From f559b33f2f12a6bb445d0ba99f4b0128a0fa41d0 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 9 Jun 2017 14:05:58 +0200 Subject: template, main topics placed --- ansible.html.markdown | 660 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 660 insertions(+) create mode 100644 ansible.html.markdown diff --git a/ansible.html.markdown b/ansible.html.markdown new file mode 100644 index 00000000..b03b04fb --- /dev/null +++ b/ansible.html.markdown @@ -0,0 +1,660 @@ +--- +category: tool +tool: git +contributors: + - ["Jakub Muszynski" , "http://github.com/sirkubax"] +filename: LearnAnsible.txt +--- + +Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. +Ansible have great integration with multiple operating systems (even Windows using Power Shell) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) + +## Main cons and pros + +### Cons + +It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) + +### Pros + +It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! +It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +Documentation is at the world-class standard! +The comunity (github, stackOverflow) would help you very fast. +Writing own modules and extension is fairly easy. + + +### Neutral +Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. + + +## Ansible naming and basic concept + +### Naming + +### ansible (run module (task)) + +### ansible-playbook (run set of tasks) + +### ansible-roles (a 'template-playbooks in right structure') + +### ansible - variables +lookup's + +### ansible-vault + +### inventory + +### dynamic inventory + +### Jinja2 and templates +jinja filters + +### ansible profiling - callback + +### facts-cache and ansible-cmdb + +### debugging ansible + +### Infrastructure as a code - what about Ansible +virtualenv + +### ansible - dynamic in AWS + +### create instance in AWS + +### create env in AWS + +## Bonus + +### writing own module + +### Python API + +### Web-UI: Ansible Tower, Jenkins, Rundeck + + +### Tips and tricks +AND,XOR +--check --diff +tags +meta +no_logs + +--- +Github template placeholder - to be removed + +### Centralized Versioning VS Distributed Versioning + +* Centralized version control focuses on synchronizing, tracking, and backing +up files. +* Distributed version control focuses on sharing changes. Every change has a +unique id. +* Distributed systems have no defined structure. You could easily have a SVN +style, centralized system, with git. + +[Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Why Use Git? + +* Can work offline. +* Collaborating with others is easy! +* Branching is easy! +* Branching is fast! +* Merging is easy! +* Git is fast. +* Git is flexible. + +## Git Architecture + +### Repository + +A set of files, directories, historical records, commits, and heads. Imagine it +as a source code data structure, with the attribute that each source code +"element" gives you access to its revision history, among other things. + +A git repository is comprised of the .git directory & working tree. + +### .git Directory (component of repository) + +The .git directory contains all the configurations, logs, branches, HEAD, and +more. +[Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Working Tree (component of repository) + +This is basically the directories and files in your repository. It is often +referred to as your working directory. + +### Index (component of .git dir) + +The Index is the staging area in git. It's basically a layer that separates +your working tree from the Git repository. This gives developers more power +over what gets sent to the Git repository. + +### Commit + +A git commit is a snapshot of a set of changes, or manipulations to your +Working Tree. For example, if you added 5 files, and removed 2 others, these +changes will be contained in a commit (or snapshot). This commit can then be +pushed to other repositories, or not! + +### Branch + +A branch is essentially a pointer to the last commit you made. As you go on +committing, this pointer will automatically update to point the latest commit. + +### Tag + +A tag is a mark on specific point in history. Typically people use this +functionality to mark release points (v1.0, and so on) + +### HEAD and head (component of .git dir) + +HEAD is a pointer that points to the current branch. A repository only has 1 +*active* HEAD. +head is a pointer that points to any commit. A repository can have any number +of heads. + +### Stages of Git +* Modified - Changes have been made to a file but file has not been committed +to Git Database yet +* Staged - Marks a modified file to go into your next commit snapshot +* Committed - Files have been committed to the Git Database + +### Conceptual Resources + +* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) +* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) + +## Commands + +### init + +Create an empty Git repository. The Git repository's settings, stored +information, and more is stored in a directory (a folder) named ".git". + +```bash +$ git init +``` + +### config + +To configure settings. Whether it be for the repository, the system itself, +or global configurations ( global config file is `~/.gitconfig` ). + +```bash +# Print & Set Some Basic Config Variables (Global) +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[Learn More About git config.](http://git-scm.com/docs/git-config) + +### help + +To give you quick access to an extremely detailed guide of each command. Or to +just give you a quick reminder of some semantics. + +```bash +# Quickly check available commands +$ git help + +# Check all available commands +$ git help -a + +# Command specific help - user manual +# git help +$ git help add +$ git help commit +$ git help init +# or git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignore files + +To intentionally untrack file(s) & folder(s) from git. Typically meant for +private & temp files which would otherwise be shared in the repository. +```bash +$ echo "temp/" >> .gitignore +$ echo "private_key" >> .gitignore +``` + +### status + +To show differences between the index file (basically your working copy/repo) +and the current HEAD commit. + +```bash +# Will display the branch, untracked files, changes and other differences +$ git status + +# To learn other "tid bits" about git status +$ git help status +``` + +### add + +To add files to the staging area/index. If you do not `git add` new files to +the staging area/index, they will not be included in commits! + +```bash +# add a file in your current working directory +$ git add HelloWorld.java + +# add a file in a nested dir +$ git add /path/to/file/HelloWorld.c + +# Regular Expression support! +$ git add ./*.java +``` + +This only adds a file to the staging area/index, it doesn't commit it to the +working directory/repo. + +### branch + +Manage your branches. You can view, edit, create, delete branches using this +command. + +```bash +# list existing branches & remotes +$ git branch -a + +# create a new branch +$ git branch myNewBranch + +# delete a branch +$ git branch -d myBranch + +# rename a branch +# git branch -m +$ git branch -m myBranchName myNewBranchName + +# edit a branch's description +$ git branch myBranchName --edit-description +``` + +### tag + +Manage your tags + +```bash +# List tags +$ git tag + +# Create a annotated tag +# The -m specifies a tagging message,which is stored with the tag. +# If you don’t specify a message for an annotated tag, +# Git launches your editor so you can type it in. +$ git tag -a v2.0 -m 'my version 2.0' + +# Show info about tag +# That shows the tagger information, the date the commit was tagged, +# and the annotation message before showing the commit information. +$ git show v2.0 + +# Push a single tag to remote +$ git push origin v2.0 + +# Push a lot of tags to remote +$ git push origin --tags +``` + +### checkout + +Updates all files in the working tree to match the version in the index, or +specified tree. + +```bash +# Checkout a repo - defaults to master branch +$ git checkout + +# Checkout a specified branch +$ git checkout branchName + +# Create a new branch & switch to it +# equivalent to "git branch ; git checkout " + +$ git checkout -b newBranch +``` + +### clone + +Clones, or copies, an existing repository into a new directory. It also adds +remote-tracking branches for each branch in the cloned repo, which allows you +to push to a remote branch. + +```bash +# Clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git + +# shallow clone - faster cloning that pulls only latest snapshot +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + +# clone only a specific branch +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Stores the current contents of the index in a new "commit." This commit +contains the changes made and a message created by the user. + +```bash +# commit with a message +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" + +# automatically stage modified or deleted files, except new files, and then commit +$ git commit -a -m "Modified foo.php and removed bar.php" + +# change last commit (this deletes previous commit with a fresh commit) +$ git commit --amend -m "Correct message" +``` + +### diff + +Shows differences between a file in the working directory, index and commits. + +```bash +# Show difference between your working dir and the index +$ git diff + +# Show differences between the index and the most recent commit. +$ git diff --cached + +# Show differences between your working dir and the most recent commit +$ git diff HEAD +``` + +### grep + +Allows you to quickly search a repository. + +Optional Configurations: + +```bash +# Thanks to Travis Jeffery for these +# Set line numbers to be shown in grep search results +$ git config --global grep.lineNumber true + +# Make search results more readable, including grouping +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Search for "variableName" in all java files +$ git grep 'variableName' -- '*.java' + +# Search for a line that contains "arrayListName" and, "add" or "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google is your friend; for more examples +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Display commits to the repository. + +```bash +# Show all commits +$ git log + +# Show only commit message & ref +$ git log --oneline + +# Show merge commits only +$ git log --merges + +# Show all commits represented by an ASCII graph +$ git log --graph +``` + +### merge + +"Merge" in changes from external commits into the current branch. + +```bash +# Merge the specified branch into the current. +$ git merge branchName + +# Always generate a merge commit when merging +$ git merge --no-ff branchName +``` + +### mv + +Rename or move a file + +```bash +# Renaming a file +$ git mv HelloWorld.c HelloNewWorld.c + +# Moving a file +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Force rename or move +# "existingFile" already exists in the directory, will be overwritten +$ git mv -f myFile existingFile +``` + +### pull + +Pulls from a repository and merges it with another branch. + +```bash +# Update your local repo, by merging in new changes +# from the remote "origin" and "master" branch. +# git pull +$ git pull origin master + +# By default, git pull will update your current branch +# by merging in new changes from its remote-tracking branch +$ git pull + +# Merge in changes from remote branch and rebase +# branch commits onto your local repo, like: "git fetch , git +# rebase /" +$ git pull origin master --rebase +``` + +### push + +Push and merge changes from a branch to a remote & branch. + +```bash +# Push and merge changes from a local repo to a +# remote named "origin" and "master" branch. +# git push +$ git push origin master + +# By default, git push will push and merge changes from +# the current branch to its remote-tracking branch +$ git push + +# To link up current local branch with a remote branch, add -u flag: +$ git push -u origin master +# Now, anytime you want to push from that same local branch, use shortcut: +$ git push +``` + +### stash + +Stashing takes the dirty state of your working directory and saves it on a +stack of unfinished changes that you can reapply at any time. + +Let's say you've been doing some work in your git repo, but you want to pull +from the remote. Since you have dirty (uncommited) changes to some files, you +are not able to run `git pull`. Instead, you can run `git stash` to save your +changes onto a stack! + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Now you can pull! + +```bash +git pull +``` +`...changes apply...` + +Now check that everything is OK + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +You can see what "hunks" you've stashed so far using `git stash list`. +Since the "hunks" are stored in a Last-In-First-Out stack, our most recent +change will be at top. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 added the index file +stash@{1}: WIP on master: c264051 Revert "added file_size" +stash@{2}: WIP on master: 21d80a5 added number to log +``` + +Now let's apply our dirty changes back by popping them off the stack. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add ..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` does the same thing + +Now you're ready to get back to work on your stuff! + +[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) + +### rebase (caution) + +Take all changes that were committed on one branch, and replay them onto +another branch. +*Do not rebase commits that you have pushed to a public repo*. + +```bash +# Rebase experimentBranch onto master +# git rebase +$ git rebase master experimentBranch +``` + +[Additional Reading.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (caution) + +Reset the current HEAD to the specified state. This allows you to undo merges, +pulls, commits, adds, and more. It's a great command but also dangerous if you +don't know what you are doing. + +```bash +# Reset the staging area, to match the latest commit (leaves dir unchanged) +$ git reset + +# Reset the staging area, to match the latest commit, and overwrite working dir +$ git reset --hard + +# Moves the current branch tip to the specified commit (leaves dir unchanged) +# all changes still exist in the directory. +$ git reset 31f2bb1 + +# Moves the current branch tip backward to the specified commit +# and makes the working dir match (deletes uncommited changes and all commits +# after the specified commit). +$ git reset --hard 31f2bb1 +``` + +### reflog (caution) + +Reflog will list most of the git commands you have done for a given time period, +default 90 days. + +This give you the a change to reverse any git commands that have gone wrong +for instance if a rebase is has broken your application. + +You can do this: + +1. `git reflog` to list all of the git commands for the rebase +``` +38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog +38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators +4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown +34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666) +ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) +2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d +``` +2. Select where to reset to, in our case its `2e6c386`, or `HEAD@{5}` +3. 'git reset --hard HEAD@{5}' this will reset your repo to that head +4. You can start the rebase again or leave it alone. + +[Additional Reading.](https://git-scm.com/docs/git-reflog) + +### revert + +Revert can be used to undo a commit. It should not be confused with reset which +restores the state of a project to a previous point. Revert will add a new +commit which is the inverse of the specified commit, thus reverting it. + +```bash +# Revert a specified commit +$ git revert +``` + +### rm + +The opposite of git add, git rm removes files from the current working tree. + +```bash +# remove HelloWorld.c +$ git rm HelloWorld.c + +# Remove a file from a nested dir +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Further Information + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [Learn Git Branching - the most visual and interactive way to learn Git on the web](http://learngitbranching.js.org/) + +* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) + +* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From d6468f27ea7abda52b9ed9fa4afa959c692aea3d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 9 Jun 2017 14:07:58 +0200 Subject: tool name :) --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b03b04fb..f28abb68 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,6 +1,6 @@ --- category: tool -tool: git +tool: ansible contributors: - ["Jakub Muszynski" , "http://github.com/sirkubax"] filename: LearnAnsible.txt -- cgit v1.2.3 From bcb1b623b1db1057085982507399c62eaa053e7b Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Fri, 23 Jun 2017 13:35:19 -0700 Subject: [scala/en] Make return value example actually demonstrate issue Previously the `return z` didn't actually have any effect on the output, since the outer function just return the anon function's result directly. Updated to make the outer function do something to demonstrate the difference. Also renamed functions to make what they're doing easier to follow, and added a couple examples of behavior w/ explanations --- scala.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5eb94986..e541f4b3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -253,16 +253,20 @@ weirdSum(2, 4) // => 16 // def that surrounds it. // WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: -def foo(x: Int): Int = { - val anonFunc: Int => Int = { z => +def addTenButMaybeTwelve(x: Int): Int = { + val anonMaybeAddTwo: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of addTenButMaybeTwelve! else z + 2 // This line is the return value of anonFunc } - anonFunc(x) // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of foo } +addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 +addTenButMaybeTwelve(7) // Returns 7: 7 > 5, return value set to z, so + // last line doesn't get called and 10 is not added + ///////////////////////////////////////////////// // 3. Flow Control -- cgit v1.2.3 From 23cee36b4c056dcd3c01676132cb9a6588fb75ad Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Thu, 29 Jun 2017 10:49:44 -0700 Subject: Update more function mentions in comments --- scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index e541f4b3..192af953 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -258,9 +258,9 @@ def addTenButMaybeTwelve(x: Int): Int = { if (z > 5) return z // This line makes z the return value of addTenButMaybeTwelve! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonMaybeAddTwo } - anonMaybeAddTwo(x) + 10 // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of addTenButMaybeTwelve } addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 -- cgit v1.2.3 From cd21e6da04a5f9fcba49093984c03ffe6c0216dd Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:44:20 +0200 Subject: add some lines --- ansible.html.markdown | 60 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index f28abb68..e074ed44 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -7,7 +7,7 @@ filename: LearnAnsible.txt --- Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -Ansible have great integration with multiple operating systems (even Windows using Power Shell) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) ## Main cons and pros @@ -15,10 +15,12 @@ Ansible have great integration with multiple operating systems (even Windows usi It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. ### Pros It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +In some way you can use it as 'bash on steroids'. It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) @@ -30,12 +32,66 @@ Writing own modules and extension is fairly easy. ### Neutral Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. +## Basics on ansible + +Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. +In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. ## Ansible naming and basic concept ### Naming -### ansible (run module (task)) +#### Inventory +Inventory is a set of objects/hosts against which we are executing our playbooks +For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts_ + +#### Module - this is name for an logical program (usaly python) that consume proper JSON input and return proper output :) +This program perform certain task/action (like manage Amazon instances, execute shell command, any of your program). +Example: Module:shell - a module that executes shell command on a delegated host(s). +Example: Module:file - performs file operations (stat, link, dir, ...) + +##### Task +Execution of a single module is called a `task` + +Example of a Task run in CLI: +###### Run a ansible module + +ansible -m shell -a 'date; whoami' + +as a contrast - please note a module `command` that allows to execute a single command only + +ansible -m command -a 'date; whoami' # FAILURE + +ansible -m command -a 'date' +ansible -m command -a 'whoami' + +##### Playbook + +A list of tasks written in a file of proper structure is called a `playbook` +Playbook must have a list (or group) of hosts that is executed against, some task(s) or role(s) that are going to be executed, and multiple optional settings. + +Example of the playbook: + +``` +hosts: all + +tasks: + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" +``` + +### Basic ansible commands + +There are few binaries you should know + +`ansible` (to run modules in CLI) +`ansible-playbook` (to run playbooks) +`ansible-vault` (to manage secrets) +`ansible-galaxy` (to install roles from github/galaxy) +and other! ### ansible-playbook (run set of tasks) -- cgit v1.2.3 From bd05f751631d71d823a197cc5a506b05a60be849 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:46:45 +0200 Subject: add some lines --- ansible.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index e074ed44..24821862 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -93,10 +93,15 @@ There are few binaries you should know `ansible-galaxy` (to install roles from github/galaxy) and other! -### ansible-playbook (run set of tasks) +### More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') +There are tasks (modules) that can be run via CLI +The execution plans of multiple tasks (with variables and logic) are called playbooks. + +Fot parts of the code, that is reusable, a concept called `role` was introduced + ### ansible - variables lookup's -- cgit v1.2.3 From 3069c1b9451768369cee30ea22c3e150dafef294 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:48:01 +0200 Subject: add some lines --- ansible.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 24821862..37c3e299 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -57,14 +57,18 @@ Execution of a single module is called a `task` Example of a Task run in CLI: ###### Run a ansible module +``` ansible -m shell -a 'date; whoami' +``` as a contrast - please note a module `command` that allows to execute a single command only +``` ansible -m command -a 'date; whoami' # FAILURE ansible -m command -a 'date' ansible -m command -a 'whoami' +``` ##### Playbook -- cgit v1.2.3 From dff02575a0a417e3d23802f4d115d52d1503232c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Tue, 15 Aug 2017 21:55:44 +0200 Subject: add some lines --- ansible.html.markdown | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 37c3e299..c0de7ac0 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -38,6 +38,8 @@ Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. +But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! + ## Ansible naming and basic concept ### Naming @@ -104,7 +106,30 @@ and other! There are tasks (modules) that can be run via CLI The execution plans of multiple tasks (with variables and logic) are called playbooks. -Fot parts of the code, that is reusable, a concept called `role` was introduced +For parts of the code, that is reusable, a concept called `role` was introduced + +Role in a way is just a structured way to keep your set of tasks, your variables, handlers, default settings, and way more (meta, files, templates). +Rele allows to reuse the same parts of code in multiple plybooks (usually with some parametisation). +It is a great way to introduce `object oriented` management for your applications. + +Role can be included in your playbook (executed in your playbook). + + +``` +hosts: all + +tasks: + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" + +role: + - some_role + +pre_tasks: + - name: some pre-task + shell: echo 'this task is the last, but would be executed before roles, and before tasks' ### ansible - variables lookup's -- cgit v1.2.3 From fa55726a683cf5bdee1d5e262f60df9042db3db6 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 6 Sep 2017 23:20:52 +0200 Subject: continue description --- ansible.html.markdown | 136 ++++++++++++++++++++++++++++++++------------------ 1 file changed, 87 insertions(+), 49 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index c0de7ac0..3234fe5c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -7,38 +7,11 @@ filename: LearnAnsible.txt --- Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) - -## Main cons and pros - -### Cons - -It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. -It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) -Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. - -### Pros +'You can think as simple as writing in bash with python API :) +Of course the rabit hole is way deeper.' -It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. -In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' -I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! -It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) -Documentation is at the world-class standard! -The comunity (github, stackOverflow) would help you very fast. -Writing own modules and extension is fairly easy. - - -### Neutral -Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. - -## Basics on ansible - -Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. -In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). -On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) -But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! ## Ansible naming and basic concept @@ -56,42 +29,54 @@ Example: Module:file - performs file operations (stat, link, dir, ...) ##### Task Execution of a single module is called a `task` +The simplest module is called `ping`. +Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. + Example of a Task run in CLI: ###### Run a ansible module -``` -ansible -m shell -a 'date; whoami' +```bash +$ ansible -m ping hostname_or_a_group_name +$ ansible -m shell -a 'date; whoami' hostname_or_a_group_name ``` -as a contrast - please note a module `command` that allows to execute a single command only +another module - `command` that allows to execute a single command only with a simple shell #JM +We should also mention a module `raw` -``` -ansible -m command -a 'date; whoami' # FAILURE +```bash +$ ansible -m command -a 'date; whoami' # FAILURE -ansible -m command -a 'date' -ansible -m command -a 'whoami' +$ ansible -m command -a 'date' +$ ansible -m command -a 'whoami' ``` ##### Playbook -A list of tasks written in a file of proper structure is called a `playbook` -Playbook must have a list (or group) of hosts that is executed against, some task(s) or role(s) that are going to be executed, and multiple optional settings. +A common way to execute tasks is called `playbook`. +You have to define a list (or group) of hosts that is executed against, some `task(s)` or `role(s)` that are going to be executed. There are also multiple optional settings (like default variables, and way more). + +You can think that it is very advanced CLI script that you are executing. Example of the playbook: -``` +```yml hosts: all tasks: - - name: "ping all" - ping: - - name: "execute a shell command" - shell: "date; whoami; df -h;" + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" +``` + +You can execute a playbook with a command: +```bash +$ ansible-playbook path/name_of_the_playbook.yml ``` ### Basic ansible commands -There are few binaries you should know +There are few commands you should know about `ansible` (to run modules in CLI) `ansible-playbook` (to run playbooks) @@ -106,16 +91,16 @@ and other! There are tasks (modules) that can be run via CLI The execution plans of multiple tasks (with variables and logic) are called playbooks. -For parts of the code, that is reusable, a concept called `role` was introduced +For parts of the code, that should be reusable, a concept called `role` was introduced -Role in a way is just a structured way to keep your set of tasks, your variables, handlers, default settings, and way more (meta, files, templates). -Rele allows to reuse the same parts of code in multiple plybooks (usually with some parametisation). +Role is a structured way to keep your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). +Role allows to reuse the same parts of code in multiple plybooks (you can parametrize this). It is a great way to introduce `object oriented` management for your applications. Role can be included in your playbook (executed in your playbook). -``` +```yml hosts: all tasks: @@ -126,10 +111,28 @@ tasks: role: - some_role + - { role: another_role, some_variable: 'learnxiny', tags: ['my_tag'] } pre_tasks: - name: some pre-task shell: echo 'this task is the last, but would be executed before roles, and before tasks' +``` + +``` +roles/ + some_role/ + defaults/ + files/ + templates/ + tasks/ + handlers/ + vars/ + meta/ +``` + +#### Role Handlers +Handlers are a task that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. +It is a best way to restart a service, check if application port is open, etc. ### ansible - variables lookup's @@ -174,6 +177,41 @@ tags meta no_logs + +## Main cons and pros + +### Cons + +It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. + +### Pros + +It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +In some way you can use it as 'bash on steroids'. +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! +It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +Documentation is at the world-class standard! +The comunity (github, stackOverflow) would help you very fast. +Writing own modules and extension is fairly easy. + + +### Neutral +Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. + +## Basics on ansible + +Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. +In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. + +But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! + + + + --- Github template placeholder - to be removed -- cgit v1.2.3 From 32b2f01d3652274f27dee4cf3d5957ac6aa7e95b Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 6 Sep 2017 23:34:29 +0200 Subject: continue --- ansible.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 3234fe5c..c1cddd35 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -54,6 +54,7 @@ $ ansible -m command -a 'whoami' A common way to execute tasks is called `playbook`. You have to define a list (or group) of hosts that is executed against, some `task(s)` or `role(s)` that are going to be executed. There are also multiple optional settings (like default variables, and way more). +Playbook script language is YAML You can think that it is very advanced CLI script that you are executing. @@ -118,6 +119,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` +Role directory structure: ``` roles/ some_role/ -- cgit v1.2.3 From 60ae84cf4123473a5685de21d1f1e5b09b52aaa5 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 6 Sep 2017 23:40:18 +0200 Subject: continue --- ansible.html.markdown | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index c1cddd35..cd619cc3 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -15,7 +15,15 @@ Ansible have great integration with multiple operating systems (even Windows) an ## Ansible naming and basic concept -### Naming +### Basic ansible commands + +There are few commands you should know about + +`ansible` (to run modules in CLI) +`ansible-playbook` (to run playbooks) +`ansible-vault` (to manage secrets) +`ansible-galaxy` (to install roles from github/galaxy) +and other! #### Inventory Inventory is a set of objects/hosts against which we are executing our playbooks @@ -23,6 +31,7 @@ For this few minutes, lets asume that we are using default ansible inventory (wh #### Module - this is name for an logical program (usaly python) that consume proper JSON input and return proper output :) This program perform certain task/action (like manage Amazon instances, execute shell command, any of your program). +The simplest module is called `ping` - it just returns a JSON with `pong` message and ansible variables. Example: Module:shell - a module that executes shell command on a delegated host(s). Example: Module:file - performs file operations (stat, link, dir, ...) @@ -75,17 +84,7 @@ You can execute a playbook with a command: $ ansible-playbook path/name_of_the_playbook.yml ``` -### Basic ansible commands - -There are few commands you should know about - -`ansible` (to run modules in CLI) -`ansible-playbook` (to run playbooks) -`ansible-vault` (to manage secrets) -`ansible-galaxy` (to install roles from github/galaxy) -and other! - -### More on ansible concept +## More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') @@ -163,6 +162,8 @@ virtualenv ### create env in AWS +### Naming + ## Bonus ### writing own module -- cgit v1.2.3 From 4076cc53c0fcb1f8b85a71e0e395407ab43a05ab Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:21:42 +0200 Subject: change the concept of paragraphs --- ansible.html.markdown | 109 +++++++++++++++++++++++++++++++++++--------------- 1 file changed, 77 insertions(+), 32 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index cd619cc3..2eb6df2e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -6,17 +6,38 @@ contributors: filename: LearnAnsible.txt --- -Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -'You can think as simple as writing in bash with python API :) -Of course the rabit hole is way deeper.' +```yaml +--- +Ansible - the easiest orchestration tool -Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) +Why Ansible and Intro - in the second part of document +``` -## Ansible naming and basic concept +## Installation +```bash +# Universal way +$ pip install ansible -### Basic ansible commands +# Debian, Ubuntu +$ apt-get install ansible +``` +* Appendix A - How do I install ansible +[Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) + +### Basic ansible commands (shell execution) +```bash +# This command ping the localhost (defined in default inventory /etc/ansible/hosts) + +$ ansible -m ping localhost +localhost | SUCCESS => { + "changed": false, + "ping": "pong" +} + +``` +### Commands There are few commands you should know about `ansible` (to run modules in CLI) @@ -25,16 +46,37 @@ There are few commands you should know about `ansible-galaxy` (to install roles from github/galaxy) and other! +```bash +$ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name +``` + +The module `command` allows to execute a single command. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work. Use shell :) +We should also mention a module `raw` that sometimes can save the day. + +```bash +$ ansible -m command -a 'date; whoami' # FAILURE + +$ ansible -m command -a 'date' +$ ansible -m command -a 'whoami' +``` + + +#### Module - program (usaly python) that execute, do some work and return proper output :) +This program perform specialized task/action (like manage instances in the cloud, execute shell command). +The simplest module is called `ping` - it just returns a JSON with `pong` message. + +Example of modules: +Module: `shell` - a module that executes shell command on a specified host(s). +Module: `file` - performs file operations (stat, link, dir, ...) + + +```yaml +``` + #### Inventory Inventory is a set of objects/hosts against which we are executing our playbooks For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts_ -#### Module - this is name for an logical program (usaly python) that consume proper JSON input and return proper output :) -This program perform certain task/action (like manage Amazon instances, execute shell command, any of your program). -The simplest module is called `ping` - it just returns a JSON with `pong` message and ansible variables. -Example: Module:shell - a module that executes shell command on a delegated host(s). -Example: Module:file - performs file operations (stat, link, dir, ...) - ##### Task Execution of a single module is called a `task` @@ -44,30 +86,22 @@ Another example of the module that allow you to execute command remotly on multi Example of a Task run in CLI: ###### Run a ansible module -```bash -$ ansible -m ping hostname_or_a_group_name -$ ansible -m shell -a 'date; whoami' hostname_or_a_group_name -``` - -another module - `command` that allows to execute a single command only with a simple shell #JM -We should also mention a module `raw` - -```bash -$ ansible -m command -a 'date; whoami' # FAILURE - -$ ansible -m command -a 'date' -$ ansible -m command -a 'whoami' -``` ##### Playbook - -A common way to execute tasks is called `playbook`. -You have to define a list (or group) of hosts that is executed against, some `task(s)` or `role(s)` that are going to be executed. There are also multiple optional settings (like default variables, and way more). +Execution plan written in a form of script file(s) is called `playbook`. +Playbook consist of multiple elements +* a list (or group) of hosts that 'the play' is executed against +* `task(s)` or `role(s)` that are going to be executed +* multiple optional settings (like default variables, and way more) Playbook script language is YAML -You can think that it is very advanced CLI script that you are executing. +You can think that playbook is very advanced CLI script that you are executing. + -Example of the playbook: +##### Example of the playbook: +This playbook would execute (on all hosts defined in the inventory) two tasks +*`ping` that would return message *pong* +* `shell` that execute three commands and return the output to our terminal ```yml hosts: all @@ -83,7 +117,7 @@ You can execute a playbook with a command: ```bash $ ansible-playbook path/name_of_the_playbook.yml ``` - +It is also possible to become a user other than root using --become-user: ## More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') @@ -138,6 +172,9 @@ It is a best way to restart a service, check if application port is open, etc. ### ansible - variables lookup's +#### templates +JINJA2 + ### ansible-vault ### inventory @@ -180,6 +217,14 @@ tags meta no_logs +## Introduction +Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. +'You can think as simple as writing in bash with python API :) +Of course the rabit hole is way deeper.' + +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) + + ## Main cons and pros -- cgit v1.2.3 From c7fbf44dd595d621fb1140d58e53c34be7494a20 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:23:09 +0200 Subject: test markdown --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 2eb6df2e..36d95532 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -8,7 +8,7 @@ filename: LearnAnsible.txt ```yaml --- -Ansible - the easiest orchestration tool +Ansible: 'the easiest orchestration tool' Why Ansible and Intro - in the second part of document -- cgit v1.2.3 From fdb26e4870ee45f9edb1e9df7abce7bf9edac878 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:24:22 +0200 Subject: test markdown --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 36d95532..94fa20a0 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -8,9 +8,9 @@ filename: LearnAnsible.txt ```yaml --- -Ansible: 'the easiest orchestration tool' +Ansible: "the easiest orchestration tool" -Why Ansible and Intro - in the second part of document +"{{ Why Ansible and Intro }}" in the second part of document ``` -- cgit v1.2.3 From 6ba6076dea7bf3b6633cdb8e0005362f4619deaa Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:25:47 +0200 Subject: test markdown --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 94fa20a0..b8d7eb70 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -6,10 +6,10 @@ contributors: filename: LearnAnsible.txt --- +## Ansible: the easiest orchestration tool + ```yaml --- -Ansible: "the easiest orchestration tool" - "{{ Why Ansible and Intro }}" in the second part of document ``` -- cgit v1.2.3 From 0601badf4f6557ead604e693a273726c282fce46 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:27:32 +0200 Subject: test markdown --- ansible.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b8d7eb70..12aefe5f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -24,17 +24,16 @@ $ apt-get install ansible ``` * Appendix A - How do I install ansible -[Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) +* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) ### Basic ansible commands (shell execution) ```bash # This command ping the localhost (defined in default inventory /etc/ansible/hosts) - $ ansible -m ping localhost -localhost | SUCCESS => { +localhost | SUCCESS => { "changed": false, "ping": "pong" -} +} ``` ### Commands -- cgit v1.2.3 From 6ade03b92abfdc30917aa0f5188e7a0ed9a70ca9 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:29:12 +0200 Subject: test markdown --- ansible.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 12aefe5f..4409422b 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -39,10 +39,10 @@ localhost | SUCCESS => { ### Commands There are few commands you should know about -`ansible` (to run modules in CLI) -`ansible-playbook` (to run playbooks) -`ansible-vault` (to manage secrets) -`ansible-galaxy` (to install roles from github/galaxy) +* `ansible` (to run modules in CLI) +* `ansible-playbook` (to run playbooks) +* `ansible-vault` (to manage secrets) +* `ansible-galaxy` (to install roles from github/galaxy) and other! ```bash @@ -50,6 +50,7 @@ $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` The module `command` allows to execute a single command. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work. Use shell :) + We should also mention a module `raw` that sometimes can save the day. ```bash -- cgit v1.2.3 From e7e43b01e66c158053acfd00d5317743f137abb4 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:30:27 +0200 Subject: test markdown --- ansible.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 4409422b..9408db18 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -43,7 +43,9 @@ There are few commands you should know about * `ansible-playbook` (to run playbooks) * `ansible-vault` (to manage secrets) * `ansible-galaxy` (to install roles from github/galaxy) -and other! +* and other! + +Example of usage - `shell` ```bash $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name -- cgit v1.2.3 From 688f9b686f70c7a0763e7e0e550b18f12bc1b7fb Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:41:27 +0200 Subject: test markdown --- ansible.html.markdown | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 9408db18..fff85563 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -45,15 +45,24 @@ There are few commands you should know about * `ansible-galaxy` (to install roles from github/galaxy) * and other! -Example of usage - `shell` + +#### Module - program (usaly python) that execute, do some work and return proper output :) +This program perform specialized task/action (like manage instances in the cloud, execute shell command). +The simplest module is called `ping` - it just returns a JSON with `pong` message. + +Example of modules: +* Module: `ping` - the simplest module that is usefull to verify host connectivity +* Module: `shell` - a module that executes shell command on a specified host(s). + +Example of usage - `ping`, `shell` ```bash +$ ansible -m ping $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` -The module `command` allows to execute a single command. It will not be processed through the shell, so variables like $HOME and operations like "<", ">", "|", ";" and "&" will not work. Use shell :) +* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME will not work -We should also mention a module `raw` that sometimes can save the day. ```bash $ ansible -m command -a 'date; whoami' # FAILURE @@ -62,14 +71,8 @@ $ ansible -m command -a 'date' $ ansible -m command -a 'whoami' ``` - -#### Module - program (usaly python) that execute, do some work and return proper output :) -This program perform specialized task/action (like manage instances in the cloud, execute shell command). -The simplest module is called `ping` - it just returns a JSON with `pong` message. - -Example of modules: -Module: `shell` - a module that executes shell command on a specified host(s). -Module: `file` - performs file operations (stat, link, dir, ...) +* Module: `file` - performs file operations (stat, link, dir, ...) +* Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) ```yaml -- cgit v1.2.3 From 2baed7cd96532f90ec7619e828e58a0115b34f20 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:42:18 +0200 Subject: test markdown --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index fff85563..389eaaa1 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -46,7 +46,8 @@ There are few commands you should know about * and other! -#### Module - program (usaly python) that execute, do some work and return proper output :) +#### Module +*program (usaly python) that execute, do some work and return proper output :)* This program perform specialized task/action (like manage instances in the cloud, execute shell command). The simplest module is called `ping` - it just returns a JSON with `pong` message. -- cgit v1.2.3 From 6f0799d6078c117a59da7cc2ada0cee583d6db56 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:42:43 +0200 Subject: test markdown --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 389eaaa1..5fc103b7 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,8 @@ There are few commands you should know about #### Module -*program (usaly python) that execute, do some work and return proper output :)* +_*program (usaly python) that execute, do some work and return proper output :)*_ + This program perform specialized task/action (like manage instances in the cloud, execute shell command). The simplest module is called `ping` - it just returns a JSON with `pong` message. -- cgit v1.2.3 From 7ba7ab471e340803e078a6cae0e24c7615dde0a2 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:43:50 +0200 Subject: test markdown --- ansible.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 5fc103b7..ea7bb47a 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,9 +47,10 @@ There are few commands you should know about #### Module -_*program (usaly python) that execute, do some work and return proper output :)*_ +_*program (usaly python) that execute, do some work and return proper JSON output :)*_ + +This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). -This program perform specialized task/action (like manage instances in the cloud, execute shell command). The simplest module is called `ping` - it just returns a JSON with `pong` message. Example of modules: -- cgit v1.2.3 From 8a1139dee670362ab4186cb9866d746f36d2d7e4 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:48:55 +0200 Subject: test markdown --- ansible.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index ea7bb47a..13afeb3b 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -26,7 +26,7 @@ $ apt-get install ansible * Appendix A - How do I install ansible * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_installation.html) -### Basic ansible commands (shell execution) +### Your first ansible command (shell execution) ```bash # This command ping the localhost (defined in default inventory /etc/ansible/hosts) $ ansible -m ping localhost @@ -36,7 +36,7 @@ localhost | SUCCESS => { } ``` -### Commands +### Shell Commands There are few commands you should know about * `ansible` (to run modules in CLI) @@ -45,8 +45,7 @@ There are few commands you should know about * `ansible-galaxy` (to install roles from github/galaxy) * and other! - -#### Module +### Module _*program (usaly python) that execute, do some work and return proper JSON output :)*_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). @@ -57,7 +56,7 @@ Example of modules: * Module: `ping` - the simplest module that is usefull to verify host connectivity * Module: `shell` - a module that executes shell command on a specified host(s). -Example of usage - `ping`, `shell` +Example of execution - `ping`, `shell` ```bash $ ansible -m ping -- cgit v1.2.3 From 7abd3b5017df4c698b8bd33a6e472483decf73a2 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 22:49:43 +0200 Subject: test markdown --- ansible.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 13afeb3b..6ef7bab7 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -30,6 +30,7 @@ $ apt-get install ansible ```bash # This command ping the localhost (defined in default inventory /etc/ansible/hosts) $ ansible -m ping localhost +# you should see this output localhost | SUCCESS => { "changed": false, "ping": "pong" -- cgit v1.2.3 From 21fb697b8899ea62bf83f11928d6f91c98c62ad1 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 22 Sep 2017 23:00:10 +0200 Subject: test markdown --- ansible.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 6ef7bab7..72a91a5c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,7 @@ There are few commands you should know about * and other! ### Module -_*program (usaly python) that execute, do some work and return proper JSON output :)*_ +_*program (usally python) that execute, do some work and return proper JSON output :)*_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). @@ -64,7 +64,7 @@ $ ansible -m ping $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` -* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME will not work +* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` will not work ```bash @@ -72,6 +72,7 @@ $ ansible -m command -a 'date; whoami' # FAILURE $ ansible -m command -a 'date' $ ansible -m command -a 'whoami' +$ ansible -m command -a 'echo $HOME' ``` * Module: `file` - performs file operations (stat, link, dir, ...) -- cgit v1.2.3 From 7b6f0757c23b2339692c9194e4e5c95614b145f1 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:43:25 +0200 Subject: test markdown --- ansible.html.markdown | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 72a91a5c..255715bd 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -64,7 +64,7 @@ $ ansible -m ping $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` -* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` will not work +* Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` `;` will not work ```bash @@ -79,17 +79,27 @@ $ ansible -m command -a 'echo $HOME' * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) -```yaml -``` +### Ansible - naming and basic concept #### Inventory -Inventory is a set of objects/hosts against which we are executing our playbooks -For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts_ +Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands +For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) -##### Task +`/etc/ansible/hosts` +``` +localhost + +[some_group] +hostA.mydomain.com +hostB.localdomain +``` +* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) + +#### Task Execution of a single module is called a `task` -The simplest module is called `ping`. +The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: @@ -180,6 +190,8 @@ It is a best way to restart a service, check if application port is open, etc. ### ansible - variables lookup's +```yaml +``` #### templates JINJA2 -- cgit v1.2.3 From 69c40ee1a2659ba9f150e04adb2822d66f18570f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:50:05 +0200 Subject: test markdown --- ansible.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 255715bd..a09c8b34 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -79,7 +79,7 @@ $ ansible -m command -a 'echo $HOME' * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) -### Ansible - naming and basic concept +### Ansible - naming and quick intro #### Inventory Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands @@ -96,11 +96,10 @@ hostB.localdomain * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) #### Task -Execution of a single module is called a `task` +Execution of a single Ansible **module** is called a **task** -The simplest module is called `ping` as you could see above - -Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. + The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: ###### Run a ansible module -- cgit v1.2.3 From e946c383fde705d20aa3342c372cc8ad22793d90 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:52:10 +0200 Subject: test markdown --- ansible.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index a09c8b34..02ee8694 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -106,12 +106,14 @@ Example of a Task run in CLI: ##### Playbook -Execution plan written in a form of script file(s) is called `playbook`. +Execution plan written in a form of script file(s) is called `playbook`.-- + Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed * multiple optional settings (like default variables, and way more) -Playbook script language is YAML +Playbook script language is YAML-- + You can think that playbook is very advanced CLI script that you are executing. -- cgit v1.2.3 From a6ea9118be2fe266ea89661b360707294b854725 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:53:10 +0200 Subject: test markdown --- ansible.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 02ee8694..44bce5b0 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -99,6 +99,7 @@ hostB.localdomain Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: @@ -106,14 +107,12 @@ Example of a Task run in CLI: ##### Playbook -Execution plan written in a form of script file(s) is called `playbook`.-- - +Execution plan written in a form of script file(s) is called `playbook`. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed * multiple optional settings (like default variables, and way more) -Playbook script language is YAML-- - +Playbook script language is YAML You can think that playbook is very advanced CLI script that you are executing. -- cgit v1.2.3 From a5bec9b8efecbbda3415289325db37c911a0969e Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:54:26 +0200 Subject: test markdown --- ansible.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 44bce5b0..1e3fc138 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -96,10 +96,9 @@ hostB.localdomain * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) #### Task -Execution of a single Ansible **module** is called a **task** + Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above - Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. Example of a Task run in CLI: -- cgit v1.2.3 From eaf3e9c46154842509e58bdcadb1a863178bb976 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:56:13 +0200 Subject: test markdown --- ansible.html.markdown | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 1e3fc138..744f6394 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -98,11 +98,8 @@ hostB.localdomain #### Task Execution of a single Ansible **module** is called a **task** - The simplest module is called `ping` as you could see above - Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. - -Example of a Task run in CLI: -###### Run a ansible module + The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. ##### Playbook -- cgit v1.2.3 From 656516a2b9c0951779b2450de24f46e8effad81c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 23 Sep 2017 11:56:50 +0200 Subject: test markdown --- ansible.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index 744f6394..27a467cc 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -99,6 +99,7 @@ hostB.localdomain Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above + Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. -- cgit v1.2.3 From 386c4882c849b423af907686a40af699cc663ce0 Mon Sep 17 00:00:00 2001 From: Jichao Ouyang Date: Sun, 24 Sep 2017 21:05:34 +0800 Subject: gnu make zh_cn --- zh-cn/make-cn.html.markdown | 261 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 zh-cn/make-cn.html.markdown diff --git a/zh-cn/make-cn.html.markdown b/zh-cn/make-cn.html.markdown new file mode 100644 index 00000000..4a58f0b6 --- /dev/null +++ b/zh-cn/make-cn.html.markdown @@ -0,0 +1,261 @@ +--- +language: make +contributors: +- ["Robert Steed", "https://github.com/robochat"] +- ["Jichao Ouyang", "https://github.com/jcouyang"] +translators: +- ["Jichao Ouyang", "https://github.com/jcouyang"] +filename: Makefile +--- + +Makefile 用于定义如何创建目标文件, 比如如何从源码到可执行文件. 创建这一工具的目标是 +减少不必要的编译或者任务.是传说中的 Stuart Feldman 在 1976 年花了一个周末写出来的, +而今仍然使用广泛, 特别是在 Unix 和 Linux 系统上. + +虽然每个语言可能都有相应的或多或少提供 make 的功能, 比如 ruby 的 rake, node 的 gulp, broccoli +, scala 的 sbt 等等. 但是 make 的简洁与高效, 和只做一件事并做到极致的风格, 使其至今仍是无可替代的, +甚至与其他构建工具一起使用也并无冲突. + +尽管有许多的分支和变体, 这篇文章针对是标准的 GNU make. + +```make +# 这行表示注释 + +# 文件名一定要交 Makefile, 大小写区分, 使用 `make ` 生成 target +# 如果想要取别的名字, 可以用 `make -f "filename" `. + +# 重要的事情 - 只认识 TAB, 空格是不认的, 但是在 GNU Make 3.82 之后, 可以通过 +# 设置参数 .RECIPEPREFIX 进行修改 + +#----------------------------------------------------------------------- +# 初级 +#----------------------------------------------------------------------- + +# 创建一个 target 的规则非常简单 +# targets : prerequisites +# recipe +# … +# prerequisites(依赖) 是可选的, recipe(做法) 也可以多个或者不给. + +# 下面这个任务没有给 prerequisites, 只会在目标文件 file0.txt 文件不存在是跑 +file0.txt: + echo "foo" > file0.txt + # 试试 `make file0.txt` + # 或者直接 `make`, 因为第一个任务是默认任务. + # 注意: 即使是这些注释, 如果前面有 TAB, 也会发送给 shell, 注意看 `make file0.txt` 输出 + +# 如果提供 prerequisites, 则只有 prerequisites 比 target 新时会执行 +# 比如下面这个任务只有当 file1.txt 比 file0.txt 新时才会执行. +file1.txt: file0.txt + cat file0.txt > file1.txt + # 这里跟shell里的命令式一毛一样的. + @cat file0.txt >> file1.txt + # @ 不会把命令往 stdout 打印. + -@echo 'hello' + # - 意思是发生错误了也没关系. + # 试试 `make file1.txt` 吧. + +# targets 和 prerequisites 都可以是多个, 以空格分割 +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# 如果声明重复的 target, make 会给一个 warning, 后面会覆盖前面的 +# 比如重复定义 file2.txt 会得到这样的 warning +# Makefile:46: warning: overriding commands for target `file2.txt' +# Makefile:40: warning: ignoring old commands for target `file2.txt' +file2.txt: file0.txt + touch file2.txt + +# 但是如果不定义任何 recipe, 就不会冲突, 只是多了依赖关系 +file2.txt: file0.txt file3.txt + +#----------------------------------------------------------------------- +# Phony(假的) Targets +#----------------------------------------------------------------------- + +# phony targets 意思是 tagets 并不是文件, 可以想象成一个任务的名字而已. +# 因为不是文件, 无法比对是否有更新, 所以每次make都会执行. +all: maker process + +# 依赖于 phony target 的 target 也会每次 make 都执行, 即使 target 是文件 +ex0.txt ex1.txt: maker + +# target 的声明顺序并不重要, 比如上面的 all 的依赖 maker 现在才声明 +maker: + touch ex0.txt ex1.txt + +# 如果定义的 phony target 与文件名重名, 可以用 .PHONY 显示的指明哪些 targets 是 phony +.PHONY: all maker process +# This is a special target. There are several others. + +# 常用的 phony target 有: all clean install ... + +#----------------------------------------------------------------------- +# 变量与通配符 +#----------------------------------------------------------------------- + +process: file*.txt | dir/a.foo.b # 可以用通配符匹配多个文件作为prerequisites + @echo $^ # $^ 是 prerequisites + @echo $@ # $@ 代表 target, 如果 target 为多个, $@ 代表当前执行的那个 + @echo $< # $< prerequisite 中的第一个 + @echo $? # $? 需要更新的 prerequisite 文件列表 + @echo $+ # $+ 所有依赖, 包括重复的 + @echo $| # $| 竖线后面的 order-only prerequisites + +a.%.b: + @echo $* # $* match 的target % 那部分, 包括路径, 比如 `make dir/a.foo.b` 会打出 `dir/foo` + +# 即便分开定义依赖, $^ 依然能拿到 +process: ex1.txt file0.txt +# 非常智能的, ex1.txt 会被找到, file0.txt 会被去重. + +#----------------------------------------------------------------------- +# 模式匹配 +#----------------------------------------------------------------------- + +# 可以让 make 知道如何转换某些文件到别格式 +# 比如 从 svg 到 png +%.png: %.svg + inkscape --export-png $^ + +# 一旦有需要 foo.png 这个任务就会运行 + +# 路径会被忽略, 所以上面的 target 能匹配所有 png +# 但是如果加了路径, make 会找到最接近的匹配, 如果 +# make small/foo.png (在这之前要先有 small/foo.svg 这个文件) +# 则会匹配下面这个规则 +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +%.png: %.svg + @echo 重复定义会覆盖前面的, 现在 inkscape 没用了 + +# make 已经有一些内置的规则, 比如从 *.c 到 *.o + +#----------------------------------------------------------------------- +# 变量 +#----------------------------------------------------------------------- +# 其实是宏 macro + +# 变量都是字符串类型, 下面这俩是一样一样的 + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # 这个会被蠢蠢的解析成 $(n)ame. + @echo \"$(name3)\" # 为声明的变量或扩展成空字符串. + @echo $(name4) + @echo $(name5) +# 你可以通过4种方式设置变量. +# 按以下顺序由高到低: +# 1: 命令行参数. 比如试试 `make echo name3=JICHAO` +# 2: Makefile 里面的 +# 3: shell 中的环境变量 +# 4: make 预设的一些变量 + +name4 ?= Jean +# 问号意思是如果 name4 被设置过了, 就不设置了. + +override name5 = David +# 用 override 可以防止命令行参数设置的覆盖 + +name4 +=grey +# 用加号可以连接 (中间用空格分割). + +# 在依赖的地方设置变量 +echo: name2 = Sara2 + +# 还有一些内置的变量 +echo_inbuilt: + echo $(CC) + echo ${CXX)} + echo $(FC) + echo ${CFLAGS)} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# 变量 2 +#----------------------------------------------------------------------- + +# 加个冒号可以声明 Simply expanded variables 即时扩展变量, 即只在声明时扩展一次 +# 之前的等号声明时 recursively expanded 递归扩展 + +var := hello +var2 := $(var) hello + +# 这些变量会在其引用的顺序求值 +# 比如 var3 声明时找不到 var4, var3 会扩展成 `and good luck` +var3 := $(var4) and good luck +# 但是一般的变量会在调用时递归扩展, 先扩展 var5, 再扩展 var4, 所以是正常的 +var5 = $(var4) and good luck +var4 := good night + +echoSEV: + @echo $(var) + @echo $(var2) + @echo $(var3) + @echo $(var4) + @echo $(var5) + +#----------------------------------------------------------------------- +# 函数 +#----------------------------------------------------------------------- + +# make 自带了一些函数. +# wildcard 会将后面的通配符变成一串文件路径 +all_markdown: + @echo $(wildcard *.markdown) +# patsubst 可以做替换, 比如下面会把所有 markdown +# 后缀的文件重命名为 md 后缀 +substitue: * + @echo $(patsubst %.markdown,%.md,$* $^) + +# 函数调用格式是 $(func arg0,arg1,arg2...) + +# 试试 +ls: * + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# 可以用 include 引入别的 Makefile 文件 +# include foo.mk + +sport = tennis +# 一些逻辑语句 if else 什么的, 顶个写 +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# 还有 ifneq, ifdef, ifndef + +foo = true + +# 不只是 recipe, 还可以写在外面哟 +ifdef $(foo) +bar = 'bar' +endif + +hellobar: + @echo bar +``` + +### 资源 + ++ GNU Make 官方文档 [HTML](https://www.gnu.org/software/make/manual/) [PDF](https://www.gnu.org/software/make/manual/make.pdf) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) -- cgit v1.2.3 From 27c3e82f12f40c75bdd08e97aead14048a080505 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 16:47:10 +0200 Subject: test markdown --- ansible.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 27a467cc..14565057 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -79,9 +79,9 @@ $ ansible -m command -a 'echo $HOME' * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) -### Ansible - naming and quick intro +## Ansible - naming and quick intro -#### Inventory +### Inventory Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) @@ -95,15 +95,15 @@ hostB.localdomain ``` * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) -#### Task +### Task Execution of a single Ansible **module** is called a **task** The simplest module is called `ping` as you could see above - Another example of the module that allow you to execute command remotly on multiple resources is called shell. It is the same as you would execute command remotely over ssh. + Another example of the module that allow you to execute command remotly on multiple resources is called `shell`. See above how you were using them already. -##### Playbook +### Playbook Execution plan written in a form of script file(s) is called `playbook`. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against @@ -114,7 +114,7 @@ Playbook script language is YAML You can think that playbook is very advanced CLI script that you are executing. -##### Example of the playbook: +#### Example of the playbook: This playbook would execute (on all hosts defined in the inventory) two tasks *`ping` that would return message *pong* * `shell` that execute three commands and return the output to our terminal -- cgit v1.2.3 From bb3e71c52957561c425999a542c0fb9f47a3c4f7 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:00:23 +0200 Subject: test markdown --- ansible.html.markdown | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 14565057..b5de971c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -10,7 +10,7 @@ filename: LearnAnsible.txt ```yaml --- -"{{ Why Ansible and Intro }}" in the second part of document +"{{ Why Ansible and detailed Intro }}" written in the second part of document ``` @@ -60,19 +60,19 @@ Example of modules: Example of execution - `ping`, `shell` ```bash -$ ansible -m ping +$ ansible -m ping all $ ansible -m shell -a 'date; whoami' localhost #hostname_or_a_group_name ``` * Module: `command` - executes a single command that will not be processed through the shell, so variables like $HOME or operands like `|` `;` will not work +#JM ```bash $ ansible -m command -a 'date; whoami' # FAILURE -$ ansible -m command -a 'date' -$ ansible -m command -a 'whoami' -$ ansible -m command -a 'echo $HOME' +$ ansible -m command -a 'date' all +$ ansible -m command -a 'whoami' all ``` * Module: `file` - performs file operations (stat, link, dir, ...) @@ -92,6 +92,11 @@ localhost [some_group] hostA.mydomain.com hostB.localdomain + +[a_group_of_a_groups:children] +some_group +some_other_group + ``` * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) @@ -104,7 +109,7 @@ hostB.localdomain ### Playbook -Execution plan written in a form of script file(s) is called `playbook`. +**Execution plan** written in a form of script file(s) is called `playbook`. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed @@ -116,7 +121,7 @@ You can think that playbook is very advanced CLI script that you are executing. #### Example of the playbook: This playbook would execute (on all hosts defined in the inventory) two tasks -*`ping` that would return message *pong* +* `ping` that would return message *pong* * `shell` that execute three commands and return the output to our terminal ```yml -- cgit v1.2.3 From c62c527f82cd6addd38fec966efed5390bf15bdc Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:06:17 +0200 Subject: test markdown --- ansible.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index b5de971c..2b997340 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -109,18 +109,19 @@ some_other_group ### Playbook -**Execution plan** written in a form of script file(s) is called `playbook`. +**Execution plan** written in a form of script file(s) is called **playbook**. Playbook consist of multiple elements * a list (or group) of hosts that 'the play' is executed against * `task(s)` or `role(s)` that are going to be executed * multiple optional settings (like default variables, and way more) -Playbook script language is YAML + +Playbook script language is YAML. You can think that playbook is very advanced CLI script that you are executing. #### Example of the playbook: -This playbook would execute (on all hosts defined in the inventory) two tasks +This example-playbook would execute (on all hosts defined in the inventory) two tasks: * `ping` that would return message *pong* * `shell` that execute three commands and return the output to our terminal @@ -134,11 +135,10 @@ tasks: shell: "date; whoami; df -h;" ``` -You can execute a playbook with a command: +You can run the playbook with the command: ```bash $ ansible-playbook path/name_of_the_playbook.yml ``` -It is also possible to become a user other than root using --become-user: ## More on ansible concept ### ansible-roles (a 'template-playbooks in right structure') @@ -232,6 +232,7 @@ virtualenv ### Web-UI: Ansible Tower, Jenkins, Rundeck +#become-user, become ### Tips and tricks AND,XOR -- cgit v1.2.3 From cbc9b5b2a5af550926f3232458432984951b5b53 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:52:48 +0200 Subject: test markdown --- ansible.html.markdown | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 2b997340..460faf82 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -139,20 +139,20 @@ You can run the playbook with the command: ```bash $ ansible-playbook path/name_of_the_playbook.yml ``` -## More on ansible concept +### More on ansible concept -### ansible-roles (a 'template-playbooks in right structure') +#### ansible-roles (a 'template-playbooks' with right structure) -There are tasks (modules) that can be run via CLI +You already know the tasks (modules) that can be run via CLI The execution plans of multiple tasks (with variables and logic) are called playbooks. -For parts of the code, that should be reusable, a concept called `role` was introduced +A concept called `role` was introduced for parts of the code that should be reusable. -Role is a structured way to keep your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). -Role allows to reuse the same parts of code in multiple plybooks (you can parametrize this). +**Role** is a structured way to manage your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). +Role allows to reuse the same parts of code in multiple plybooks (you can parametrize the role 'further' during it's execution). It is a great way to introduce `object oriented` management for your applications. -Role can be included in your playbook (executed in your playbook). +Role can be included in your playbook (executed via your playbook). ```yml @@ -173,6 +173,16 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` +Example-role + +We would clone the ready-to-use examples from additional repository +```bash +$ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git +$ cd ansible-for-learnXinYminutes +$ source environment +$(venv) ansible-playbook playbooks/role_example.yml +``` + Role directory structure: ``` roles/ -- cgit v1.2.3 From 04a88249c9ee8f1e611d67b782267289208ab310 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 17:53:42 +0200 Subject: test markdown --- ansible.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 460faf82..1f04b520 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -143,8 +143,8 @@ $ ansible-playbook path/name_of_the_playbook.yml #### ansible-roles (a 'template-playbooks' with right structure) -You already know the tasks (modules) that can be run via CLI -The execution plans of multiple tasks (with variables and logic) are called playbooks. + You already know the tasks (modules) that can be run via CLI. + The execution plans of multiple tasks (with variables and logic) are called playbooks. A concept called `role` was introduced for parts of the code that should be reusable. -- cgit v1.2.3 From da0ca8fcbda3b035fa725e7746c9ee4f084b08cc Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 18:11:20 +0200 Subject: test markdown --- ansible.html.markdown | 64 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 1f04b520..25a38283 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,4 +1,4 @@ ---- +o-- category: tool tool: ansible contributors: @@ -143,10 +143,9 @@ $ ansible-playbook path/name_of_the_playbook.yml #### ansible-roles (a 'template-playbooks' with right structure) - You already know the tasks (modules) that can be run via CLI. - The execution plans of multiple tasks (with variables and logic) are called playbooks. + You already know the tasks (modules) that can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). -A concept called `role` was introduced for parts of the code that should be reusable. +A concept called `role` was introduced for parts of the code (playbooks) that should be reusable. **Role** is a structured way to manage your set of tasks, variables, handlers, default settings, and way more (meta, files, templates). Role allows to reuse the same parts of code in multiple plybooks (you can parametrize the role 'further' during it's execution). @@ -173,7 +172,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -Example-role +Example->role We would clone the ready-to-use examples from additional repository ```bash @@ -183,30 +182,59 @@ $ source environment $(venv) ansible-playbook playbooks/role_example.yml ``` -Role directory structure: +#### Role directory structure: ``` roles/ some_role/ - defaults/ - files/ - templates/ - tasks/ - handlers/ - vars/ - meta/ + defaults/ # contains default variables + files/ # for static files + templates/ # for jinja templates + tasks/ # tasks + handlers/ # handlers + vars/ # more variables (higher priority) + meta/ # meta - package (role) info ``` #### Role Handlers -Handlers are a task that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. -It is a best way to restart a service, check if application port is open, etc. +Handlers are a tasks that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. +It is a best way to restart a service, check if application port is active (successfull deployment criteria), etc. ### ansible - variables -lookup's + +Ansible is flexible - it has 21 levels of variable precedence + +[read more] + +For now you might like to know, that CLI variables has the top priority. + +You should also know, that a nice way to pool some data is a **lookup** + +##### Lookups + +* pipe +* file +* stream +* etcd + +You can use them in CLI too ```yaml +ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" + ``` -#### templates -JINJA2 +#### Templates + +Template is a powerfull way to deliver some (partially) dynamic content. Ansible uses **Jinja2** langueage to describe the template. + +```jinja2 +Some static content + +{{ a_variable }} + +{% for item in loop_items %} + this line item is {{ item }} +{% endfor %} +``` ### ansible-vault -- cgit v1.2.3 From 05892ff7ddd69e5f01e9da6d9d602dd318d0485e Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 18:34:38 +0200 Subject: test markdown --- ansible.html.markdown | 63 ++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 57 insertions(+), 6 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 25a38283..cadf6301 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,4 +1,8 @@ -o-- +# JM inventory dynamic aws ec2 +# vault +# roles + +--- category: tool tool: ansible contributors: @@ -218,7 +222,7 @@ You should also know, that a nice way to pool some data is a **lookup** You can use them in CLI too ```yaml -ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" +ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" localhost ``` @@ -235,16 +239,63 @@ Some static content this line item is {{ item }} {% endfor %} ``` +Jinja may have some limitations, but it is a powerfull tool that you might like. -### ansible-vault - -### inventory +#### Jinja2 CLI +You can use the jinja in the CLI too +```bash +ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost +``` -### dynamic inventory ### Jinja2 and templates jinja filters + +#### ansible-vault +To maintain **ifrastructure as a code** you need to store secrets. + Ansible provides a way to encrypt the poufne files so you can store it in the repository, yet the files are decrypted in-fly during ansible execution. + +The best way to use the **ansible-vault** is to store the secret in some secure location, and configure ansible to use during runtime. + +```bash +$ echo some_very_very_long_secret > ~/.ssh/secure_located_file + +$ vi ansible.cfg + ansible_vault_password_file = ~/.ssh/secure_located_file + +#or to use env +export ANSIBLE_VAULT_PASSWORD_FILE=~/.ssh/secure_located_file + +$ ansible-playbook playbooks/vault_example.yml + + # decrypt the file +$ ansible-vault encrypt path/somefile + + # view the file +$ ansible-vault view path/somefile + + # check the file content: +$ cat path/somefile + + # decrypt the file +$ ansible-vault decrypt path/somefile +``` + +#### dynamic inventory +You might like to know, that you can build your inventory dynamically. + +(For Ansible) inventory is just a JSON with proper structure - if you can deliver that to ansible - anything is possible. + +You do not need to invent the wheel - there are plenty ready to use inventory script for most popular Cloud provicers and a lot of in-house popular usecaseses. + +```bash +$ etc/inv/ec2.py --refresh + +$ ansible -m ping all -i etc/inv/ec2.py +``` + + ### ansible profiling - callback ### facts-cache and ansible-cmdb -- cgit v1.2.3 From 3c7153633842717cb9de7a96f5cd3da5982ffe50 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Wed, 27 Sep 2017 23:57:45 +0200 Subject: test markdown --- ansible.html.markdown | 713 +++++++++----------------------------------------- 1 file changed, 119 insertions(+), 594 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index cadf6301..0023a718 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -1,7 +1,3 @@ -# JM inventory dynamic aws ec2 -# vault -# roles - --- category: tool tool: ansible @@ -247,10 +243,14 @@ You can use the jinja in the CLI too ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost ``` - -### Jinja2 and templates -jinja filters - +### Jinja2 filters +Junja is powerfull. It has built-in many usefull functions. +```jinja +# get first item of the list +{{ some_list | first() }} +# if variable is undefined - use default value +{{ some_variable | default('default_value') }} +``` #### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. @@ -295,655 +295,180 @@ $ etc/inv/ec2.py --refresh $ ansible -m ping all -i etc/inv/ec2.py ``` +#### ansible profiling - callback +It is ok that your playbook executes some time. Sometimes you may like to speed things up :) -### ansible profiling - callback - -### facts-cache and ansible-cmdb - -### debugging ansible - -### Infrastructure as a code - what about Ansible -virtualenv - -### ansible - dynamic in AWS - -### create instance in AWS - -### create env in AWS - -### Naming - -## Bonus - -### writing own module - -### Python API - -### Web-UI: Ansible Tower, Jenkins, Rundeck - -#become-user, become - -### Tips and tricks -AND,XOR ---check --diff -tags -meta -no_logs - -## Introduction -Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -'You can think as simple as writing in bash with python API :) -Of course the rabit hole is way deeper.' - -Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) - - - -## Main cons and pros - -### Cons - -It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. -It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) -Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. - -### Pros - -It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. -In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' -I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! -It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) -Documentation is at the world-class standard! -The comunity (github, stackOverflow) would help you very fast. -Writing own modules and extension is fairly easy. - - -### Neutral -Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. - -## Basics on ansible - -Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. -In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). -On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. - -But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! - - - - ---- -Github template placeholder - to be removed - -### Centralized Versioning VS Distributed Versioning - -* Centralized version control focuses on synchronizing, tracking, and backing -up files. -* Distributed version control focuses on sharing changes. Every change has a -unique id. -* Distributed systems have no defined structure. You could easily have a SVN -style, centralized system, with git. - -[Additional Information](http://git-scm.com/book/en/Getting-Started-About-Version-Control) - -### Why Use Git? - -* Can work offline. -* Collaborating with others is easy! -* Branching is easy! -* Branching is fast! -* Merging is easy! -* Git is fast. -* Git is flexible. - -## Git Architecture - -### Repository - -A set of files, directories, historical records, commits, and heads. Imagine it -as a source code data structure, with the attribute that each source code -"element" gives you access to its revision history, among other things. - -A git repository is comprised of the .git directory & working tree. - -### .git Directory (component of repository) - -The .git directory contains all the configurations, logs, branches, HEAD, and -more. -[Detailed List.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) - -### Working Tree (component of repository) - -This is basically the directories and files in your repository. It is often -referred to as your working directory. - -### Index (component of .git dir) - -The Index is the staging area in git. It's basically a layer that separates -your working tree from the Git repository. This gives developers more power -over what gets sent to the Git repository. - -### Commit - -A git commit is a snapshot of a set of changes, or manipulations to your -Working Tree. For example, if you added 5 files, and removed 2 others, these -changes will be contained in a commit (or snapshot). This commit can then be -pushed to other repositories, or not! - -### Branch - -A branch is essentially a pointer to the last commit you made. As you go on -committing, this pointer will automatically update to point the latest commit. - -### Tag - -A tag is a mark on specific point in history. Typically people use this -functionality to mark release points (v1.0, and so on) - -### HEAD and head (component of .git dir) - -HEAD is a pointer that points to the current branch. A repository only has 1 -*active* HEAD. -head is a pointer that points to any commit. A repository can have any number -of heads. - -### Stages of Git -* Modified - Changes have been made to a file but file has not been committed -to Git Database yet -* Staged - Marks a modified file to go into your next commit snapshot -* Committed - Files have been committed to the Git Database - -### Conceptual Resources - -* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) -* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) - -## Commands - -### init - -Create an empty Git repository. The Git repository's settings, stored -information, and more is stored in a directory (a folder) named ".git". - -```bash -$ git init -``` - -### config - -To configure settings. Whether it be for the repository, the system itself, -or global configurations ( global config file is `~/.gitconfig` ). +Since ansible 2.x there is bouilt-in callback for task execution profiling -```bash -# Print & Set Some Basic Config Variables (Global) -$ git config --global user.email "MyEmail@Zoho.com" -$ git config --global user.name "My Name" ``` - -[Learn More About git config.](http://git-scm.com/docs/git-config) - -### help - -To give you quick access to an extremely detailed guide of each command. Or to -just give you a quick reminder of some semantics. - -```bash -# Quickly check available commands -$ git help - -# Check all available commands -$ git help -a - -# Command specific help - user manual -# git help -$ git help add -$ git help commit -$ git help init -# or git --help -$ git add --help -$ git commit --help -$ git init --help +vi ansible.cfg +#set this to: +callback_whitelist = profile_tasks ``` -### ignore files +#### facts-cache and ansible-cmdb +You can pool some infrmations of you environment from another hosts. +If the informations does not change - you may consider using a facts_cache to speed things up. -To intentionally untrack file(s) & folder(s) from git. Typically meant for -private & temp files which would otherwise be shared in the repository. -```bash -$ echo "temp/" >> .gitignore -$ echo "private_key" >> .gitignore ``` +vi ansible.cfg -### status - -To show differences between the index file (basically your working copy/repo) -and the current HEAD commit. - -```bash -# Will display the branch, untracked files, changes and other differences -$ git status - -# To learn other "tid bits" about git status -$ git help status +# if set to a persistent type (not 'memory', for example 'redis') fact values +# from previous runs in Ansible will be stored. This may be useful when +# wanting to use, for example, IP information from one group of servers +# without having to talk to them in the same playbook run to get their +# current IP information. +fact_caching = jsonfile +fact_caching_connection = ~/facts_cache +fact_caching_timeout = 86400 ``` -### add +I like to use `jsonfile` as my backend. It allows to use another project +`ansible-cmdb` [github] that generates a HTML page of your inventory resources. A nice 'free' addition! -To add files to the staging area/index. If you do not `git add` new files to -the staging area/index, they will not be included in commits! +#### debugging ansible +When your job fails - it is good to be effective with debugging. -```bash -# add a file in your current working directory -$ git add HelloWorld.java - -# add a file in a nested dir -$ git add /path/to/file/HelloWorld.c - -# Regular Expression support! -$ git add ./*.java -``` +1. Increase verbosiy by using multiple -v **[ -vvvvv]** +2. If variable is undefined +3. If variable (dictionary or a list) is undefined +4. Jinja template debug -This only adds a file to the staging area/index, it doesn't commit it to the -working directory/repo. - -### branch - -Manage your branches. You can view, edit, create, delete branches using this -command. +#### Infrastructure as a code - what about Ansible +You already know, that ansible-vault allow you to store your poufne data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. +See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additiinal benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. You can have multiple versions of Ansible present in the same time. This is very helpfull! ```bash -# list existing branches & remotes -$ git branch -a - -# create a new branch -$ git branch myNewBranch - -# delete a branch -$ git branch -d myBranch + # recreate ansible 2.x venv +$ rm -rf venv2 +$ source environment2.sh + # execute playbook +(venv2)$ ansible-playbook playbooks/ansible1.9_playbook.yml # would fail - deprecated syntax -# rename a branch -# git branch -m -$ git branch -m myBranchName myNewBranchName + # now lets install ansible 1.9.x next to ansible 2.x +(venv2)$ deactivate +$ source environment.1.9.sh + # execute playbook +(venv1.9)$ ansible-playbook playbooks/ansible1.9_playbook.yml # works! -# edit a branch's description -$ git branch myBranchName --edit-description -``` - -### tag - -Manage your tags - -```bash -# List tags -$ git tag - -# Create a annotated tag -# The -m specifies a tagging message,which is stored with the tag. -# If you don’t specify a message for an annotated tag, -# Git launches your editor so you can type it in. -$ git tag -a v2.0 -m 'my version 2.0' - -# Show info about tag -# That shows the tagger information, the date the commit was tagged, -# and the annotation message before showing the commit information. -$ git show v2.0 - -# Push a single tag to remote -$ git push origin v2.0 - -# Push a lot of tags to remote -$ git push origin --tags -``` - -### checkout - -Updates all files in the working tree to match the version in the index, or -specified tree. - -```bash -# Checkout a repo - defaults to master branch -$ git checkout - -# Checkout a specified branch -$ git checkout branchName - -# Create a new branch & switch to it -# equivalent to "git branch ; git checkout " - -$ git checkout -b newBranch -``` - -### clone - -Clones, or copies, an existing repository into a new directory. It also adds -remote-tracking branches for each branch in the cloned repo, which allows you -to push to a remote branch. - -```bash -# Clone learnxinyminutes-docs -$ git clone https://github.com/adambard/learnxinyminutes-docs.git - -# shallow clone - faster cloning that pulls only latest snapshot -$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git - -# clone only a specific branch -$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch -``` - -### commit - -Stores the current contents of the index in a new "commit." This commit -contains the changes made and a message created by the user. - -```bash -# commit with a message -$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" - -# automatically stage modified or deleted files, except new files, and then commit -$ git commit -a -m "Modified foo.php and removed bar.php" - -# change last commit (this deletes previous commit with a fresh commit) -$ git commit --amend -m "Correct message" -``` - -### diff - -Shows differences between a file in the working directory, index and commits. - -```bash -# Show difference between your working dir and the index -$ git diff - -# Show differences between the index and the most recent commit. -$ git diff --cached - -# Show differences between your working dir and the most recent commit -$ git diff HEAD -``` - -### grep - -Allows you to quickly search a repository. - -Optional Configurations: - -```bash -# Thanks to Travis Jeffery for these -# Set line numbers to be shown in grep search results -$ git config --global grep.lineNumber true - -# Make search results more readable, including grouping -$ git config --global alias.g "grep --break --heading --line-number" -``` - -```bash -# Search for "variableName" in all java files -$ git grep 'variableName' -- '*.java' - -# Search for a line that contains "arrayListName" and, "add" or "remove" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) -``` - -Google is your friend; for more examples -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) - -### log - -Display commits to the repository. - -```bash -# Show all commits -$ git log - -# Show only commit message & ref -$ git log --oneline - -# Show merge commits only -$ git log --merges - -# Show all commits represented by an ASCII graph -$ git log --graph -``` - -### merge - -"Merge" in changes from external commits into the current branch. - -```bash -# Merge the specified branch into the current. -$ git merge branchName - -# Always generate a merge commit when merging -$ git merge --no-ff branchName -``` - -### mv - -Rename or move a file - -```bash -# Renaming a file -$ git mv HelloWorld.c HelloNewWorld.c - -# Moving a file -$ git mv HelloWorld.c ./new/path/HelloWorld.c - -# Force rename or move -# "existingFile" already exists in the directory, will be overwritten -$ git mv -f myFile existingFile -``` - -### pull - -Pulls from a repository and merges it with another branch. - -```bash -# Update your local repo, by merging in new changes -# from the remote "origin" and "master" branch. -# git pull -$ git pull origin master - -# By default, git pull will update your current branch -# by merging in new changes from its remote-tracking branch -$ git pull - -# Merge in changes from remote branch and rebase -# branch commits onto your local repo, like: "git fetch , git -# rebase /" -$ git pull origin master --rebase -``` - -### push - -Push and merge changes from a branch to a remote & branch. - -```bash -# Push and merge changes from a local repo to a -# remote named "origin" and "master" branch. -# git push -$ git push origin master - -# By default, git push will push and merge changes from -# the current branch to its remote-tracking branch -$ git push - -# To link up current local branch with a remote branch, add -u flag: -$ git push -u origin master -# Now, anytime you want to push from that same local branch, use shortcut: -$ git push + # please note that you have both venv1.9 and venv2 present - you need to (de)activate one - that is all ``` +### Naming -### stash +### Bonus -Stashing takes the dirty state of your working directory and saves it on a -stack of unfinished changes that you can reapply at any time. +### writing own module -Let's say you've been doing some work in your git repo, but you want to pull -from the remote. Since you have dirty (uncommited) changes to some files, you -are not able to run `git pull`. Instead, you can run `git stash` to save your -changes onto a stack! +### Python API -```bash -$ git stash -Saved working directory and index state \ - "WIP on master: 049d078 added the index file" - HEAD is now at 049d078 added the index file - (To restore them type "git stash apply") -``` +### Web-UI: Ansible Tower, Jenkins, Rundeck -Now you can pull! +#### Ansible Tower +Ansible provides a Web User Interface called `Ansible Tower`. +It is a convienient way to run Ansible Playbooks, have proper user management, log retention, and cron (periodic jobs). -```bash -git pull -``` -`...changes apply...` +Personaly I'm not a fan of it - it's to expensive for my cases, and the trial is 10 inventory-hosts only. -Now check that everything is OK +For my usecases I hide the 'pure ansible' commands behind other projects. -```bash -$ git status -# On branch master -nothing to commit, working directory clean -``` +#### Rundeck +This is nice, secure interface, that allows you to execute a jobs of your choice (CLI, script, execution plan). +It can perform roling-deployment (without Ansible), can integrate with clouds, etc. -You can see what "hunks" you've stashed so far using `git stash list`. -Since the "hunks" are stored in a Last-In-First-Out stack, our most recent -change will be at top. +#### Jenkins +For my 'business cases' I use Jenkins - it has a 'cron', jobs can be binded into 'pipelines'. -```bash -$ git stash list -stash@{0}: WIP on master: 049d078 added the index file -stash@{1}: WIP on master: c264051 Revert "added file_size" -stash@{2}: WIP on master: 21d80a5 added number to log -``` - -Now let's apply our dirty changes back by popping them off the stack. - -```bash -$ git stash pop -# On branch master -# Changes not staged for commit: -# (use "git add ..." to update what will be committed) -# -# modified: index.html -# modified: lib/simplegit.rb -# -``` +### become-user, become +### ansible - dynamic in AWS +### create instance in AWS +### create env in AWS -`git stash apply` does the same thing +### Tips and tricks -Now you're ready to get back to work on your stuff! +##### --check -C +Always make sure that your playbook can executes in 'dry run' mode (--check), and it's execution is not declaring 'Changed' objects. -[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) +##### --diff -D +Diff is usefull to see nice detail of the files changed -### rebase (caution) +It compare 'in memory' the files like `diff -BbruN fileA fileB` -Take all changes that were committed on one branch, and replay them onto -another branch. -*Do not rebase commits that you have pushed to a public repo*. +##### Execute hosts with 'regex' ```bash -# Rebase experimentBranch onto master -# git rebase -$ git rebase master experimentBranch +ansible -m ping web* ``` -[Additional Reading.](http://git-scm.com/book/en/Git-Branching-Rebasing) - -### reset (caution) - -Reset the current HEAD to the specified state. This allows you to undo merges, -pulls, commits, adds, and more. It's a great command but also dangerous if you -don't know what you are doing. +##### +Host groups can be joined, negated, etc ```bash -# Reset the staging area, to match the latest commit (leaves dir unchanged) -$ git reset - -# Reset the staging area, to match the latest commit, and overwrite working dir -$ git reset --hard - -# Moves the current branch tip to the specified commit (leaves dir unchanged) -# all changes still exist in the directory. -$ git reset 31f2bb1 - -# Moves the current branch tip backward to the specified commit -# and makes the working dir match (deletes uncommited changes and all commits -# after the specified commit). -$ git reset --hard 31f2bb1 +ansible -m ping web*:!backend:monitoring:&allow_change ``` -### reflog (caution) +##### Tagging +You should tag some (not all) objects - a task in a playbook, all tasks included form a role, etc. +It allwos you to execute the choosen parts of the playbook. -Reflog will list most of the git commands you have done for a given time period, -default 90 days. +##### no_logs: True +You may see, that some roles print a lot of output in verbose mode. There is also a debug module. +This is the place where credentials may leak. Use `no_log` to hide the output. -This give you the a change to reverse any git commands that have gone wrong -for instance if a rebase is has broken your application. +##### Debug module +allows to print a value to the screen -You can do this: +##### Register the output of a task +You can register the output (stdout), rc (return code), stderr of a task with the `register` command. -1. `git reflog` to list all of the git commands for the rebase -``` -38b323f HEAD@{0}: rebase -i (finish): returning to refs/heads/feature/add_git_reflog -38b323f HEAD@{1}: rebase -i (pick): Clarify inc/dec operators -4fff859 HEAD@{2}: rebase -i (pick): Update java.html.markdown -34ed963 HEAD@{3}: rebase -i (pick): [yaml/en] Add more resources (#1666) -ed8ddf2 HEAD@{4}: rebase -i (pick): pythonstatcomp spanish translation (#1748) -2e6c386 HEAD@{5}: rebase -i (start): checkout 02fb96d -``` -2. Select where to reset to, in our case its `2e6c386`, or `HEAD@{5}` -3. 'git reset --hard HEAD@{5}' this will reset your repo to that head -4. You can start the rebase again or leave it alone. +##### Conditionals: when: -[Additional Reading.](https://git-scm.com/docs/git-reflog) +##### Loop: with, with_items, with_dict, with_together -### revert -Revert can be used to undo a commit. It should not be confused with reset which -restores the state of a project to a previous point. Revert will add a new -commit which is the inverse of the specified commit, thus reverting it. +## Introduction +Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. +'You can think as simple as writing in bash with python API :) +Of course the rabit hole is way deeper.' -```bash -# Revert a specified commit -$ git revert -``` +Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) -### rm -The opposite of git add, git rm removes files from the current working tree. -```bash -# remove HelloWorld.c -$ git rm HelloWorld.c +## Main cons and pros -# Remove a file from a nested dir -$ git rm /pather/to/the/file/HelloWorld.c -``` +### Cons -## Further Information +It is an agent-less tool - every agent consumes up to 16MB ram - in some environments, it may be noticable amount. +It is agent-less - you have to verify your environment consistency 'on-demand' - there is no built-in mechanism taht would warn you about some change automatically (this can be achieved with reasonable effort - but it must be known) +Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is expensive. There is no 'small enterprice' payment plan. Easy workaround with Rundeck or Jenkins is possible with reasonable workload. -* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) +### Pros -* [Learn Git Branching - the most visual and interactive way to learn Git on the web](http://learngitbranching.js.org/) +It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +In some way you can use it as 'bash on steroids'. +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! +It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) +Documentation is at the world-class standard! +The comunity (github, stackOverflow) would help you very fast. +Writing own modules and extension is fairly easy. -* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) -* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/) +### Neutral +Migration Ansible<->Salt is failrly easy - so if you would need an event-driven agent environment - it would be a good choice to start quick with Ansible, and convert to salt when needed. -* [git-scm - Video Tutorials](http://git-scm.com/videos) +## Basics on ansible -* [git-scm - Documentation](http://git-scm.com/docs) +Ansible uses ssh or paramiko as a transport layer. In a way you can imagine that you are using a ssh with API to perform your action. +In the 'low-level' way you can use it to execute remote command in more controlled way (still using ssh). +On the other hand - in advanced scope - you can use python anible code as a library to your own python scrips! This is awesome! (if you know what you are doing). It is a bit like fabric then. -* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) +But ansible is way more! It provides an execution plans, an API, library, callbacks, not forget to mention - COMUNITY! and great support by developers! -* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf) -* [GitGuys](http://www.gitguys.com/) -* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) -* [Pro Git](http://www.git-scm.com/book/en/v2) +# JM inventory dynamic aws ec2 +# vault +# roles -* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From bb4deacd225d410e6c0b09c67cc2b889c4825ff3 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:02:01 +0200 Subject: test markdown --- ansible.html.markdown | 50 +++++++++++++++++++++++--------------------------- 1 file changed, 23 insertions(+), 27 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 0023a718..9c1b86e8 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,7 @@ There are few commands you should know about * and other! ### Module -_*program (usally python) that execute, do some work and return proper JSON output :)*_ +_*program (usally python) that execute, do some work and return proper JSON output *_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). @@ -78,28 +78,6 @@ $ ansible -m command -a 'whoami' all * Module: `file` - performs file operations (stat, link, dir, ...) * Module: `raw` - executes a low-down and dirty SSH command, not going through the module subsystem (usefull to install python2.7) - -## Ansible - naming and quick intro - -### Inventory -Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands -For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) - -`/etc/ansible/hosts` -``` -localhost - -[some_group] -hostA.mydomain.com -hostB.localdomain - -[a_group_of_a_groups:children] -some_group -some_other_group - -``` -* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) - ### Task Execution of a single Ansible **module** is called a **task** @@ -141,6 +119,24 @@ $ ansible-playbook path/name_of_the_playbook.yml ``` ### More on ansible concept +### Inventory +Inventory is a set of an objects or hosts, against which we are executing our playbooks or single tasks via shell commands +For this few minutes, lets asume that we are using default ansible inventory (which in Debian based system is placed in /etc/ansible/hosts) + +`/etc/ansible/hosts` +``` +localhost + +[some_group] +hostA.mydomain.com +hostB.localdomain + +[a_group_of_a_groups:children] +some_group +some_other_group + +``` +* [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) #### ansible-roles (a 'template-playbooks' with right structure) You already know the tasks (modules) that can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). @@ -296,7 +292,7 @@ $ ansible -m ping all -i etc/inv/ec2.py ``` #### ansible profiling - callback -It is ok that your playbook executes some time. Sometimes you may like to speed things up :) +It is ok that your playbook executes some time. Sometimes you may like to speed things up Since ansible 2.x there is bouilt-in callback for task execution profiling @@ -427,7 +423,7 @@ You can register the output (stdout), rc (return code), stderr of a task with th ## Introduction Ansible is (one of the many) orchestration tools. It allows you to controll your environment (infrastructure and a code) and automate the manual tasks. -'You can think as simple as writing in bash with python API :) +'You can think as simple as writing in bash with python API Of course the rabit hole is way deeper.' Ansible have great integration with multiple operating systems (even Windows) and some hardware (switches, Firewalls, etc). It has multiple tools that integrate with the could providers. Almost every worth-notice cloud provider is present in the ecosystem (AWS, Azure, Google, DigitalOcean, OVH, etc...) @@ -444,9 +440,9 @@ Official GUI Tool (web inferface) - Ansible Tower - is more than GUI, but it is ### Pros -It is an agent-less tools :) In most scenarios, it use ssh as a transport layer. +It is an agent-less tools In most scenarios, it use ssh as a transport layer. In some way you can use it as 'bash on steroids'. -It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible :) (almost). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' +It is very-very-very easy to start. If you are familiar with ssh concept - you already know ansible (ALMOST). My personal record is: 'I did show how to install and use ansible (for simple raspberry pi cluster management) and it tool me 30 seconds to deliver a working tool !!!)' I do provide a training services - I'm able to teach a production-ready person - in 8 hours (1 training day)! It covers all needed to work aspects! No other tool can match this ease of use! It executes when you do it - other tools (salt, puppet, chef - might execute in different scenario than you would expect) Documentation is at the world-class standard! -- cgit v1.2.3 From 6c378a858964a5c5d656e39f8fec110b584e7bd0 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:02:50 +0200 Subject: test markdown --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 9c1b86e8..1cf77033 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -47,7 +47,7 @@ There are few commands you should know about * and other! ### Module -_*program (usally python) that execute, do some work and return proper JSON output *_ +_program (usally python) that execute, do some work and return proper JSON output_ This *program* perform specialized task/action (like manage instances in the cloud, execute shell command). -- cgit v1.2.3 From c2bcf94c80e1bfc2314014a8e7dd0858c6e4207c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:05:12 +0200 Subject: test markdown --- ansible.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 1cf77033..d68eafd8 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -137,7 +137,7 @@ some_other_group ``` * [Additional Reading.](http://docs.ansible.com/ansible/latest/intro_inventory.html) -#### ansible-roles (a 'template-playbooks' with right structure) +### ansible-roles (a 'template-playbooks' with right structure) You already know the tasks (modules) that can be run via CLI. You also know the playbooks - the execution plans of multiple tasks (with variables and logic). @@ -205,7 +205,7 @@ For now you might like to know, that CLI variables has the top priority. You should also know, that a nice way to pool some data is a **lookup** -##### Lookups +### Lookups * pipe * file @@ -218,7 +218,7 @@ ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" lo ``` -#### Templates +### Templates Template is a powerfull way to deliver some (partially) dynamic content. Ansible uses **Jinja2** langueage to describe the template. @@ -233,7 +233,7 @@ Some static content ``` Jinja may have some limitations, but it is a powerfull tool that you might like. -#### Jinja2 CLI +### Jinja2 CLI You can use the jinja in the CLI too ```bash ansible -m shell -a 'echo {{ my_variable }}` -e 'my_variable=something, playbook_parameter=twentytwo" localhost @@ -248,7 +248,7 @@ Junja is powerfull. It has built-in many usefull functions. {{ some_variable | default('default_value') }} ``` -#### ansible-vault +### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. Ansible provides a way to encrypt the poufne files so you can store it in the repository, yet the files are decrypted in-fly during ansible execution. @@ -278,7 +278,7 @@ $ cat path/somefile $ ansible-vault decrypt path/somefile ``` -#### dynamic inventory +### dynamic inventory You might like to know, that you can build your inventory dynamically. (For Ansible) inventory is just a JSON with proper structure - if you can deliver that to ansible - anything is possible. @@ -291,7 +291,7 @@ $ etc/inv/ec2.py --refresh $ ansible -m ping all -i etc/inv/ec2.py ``` -#### ansible profiling - callback +### ansible profiling - callback It is ok that your playbook executes some time. Sometimes you may like to speed things up Since ansible 2.x there is bouilt-in callback for task execution profiling @@ -302,7 +302,7 @@ vi ansible.cfg callback_whitelist = profile_tasks ``` -#### facts-cache and ansible-cmdb +### facts-cache and ansible-cmdb You can pool some infrmations of you environment from another hosts. If the informations does not change - you may consider using a facts_cache to speed things up. @@ -322,7 +322,7 @@ fact_caching_timeout = 86400 I like to use `jsonfile` as my backend. It allows to use another project `ansible-cmdb` [github] that generates a HTML page of your inventory resources. A nice 'free' addition! -#### debugging ansible +### debugging ansible When your job fails - it is good to be effective with debugging. 1. Increase verbosiy by using multiple -v **[ -vvvvv]** @@ -330,7 +330,7 @@ When your job fails - it is good to be effective with debugging. 3. If variable (dictionary or a list) is undefined 4. Jinja template debug -#### Infrastructure as a code - what about Ansible +### Infrastructure as a code - what about Ansible You already know, that ansible-vault allow you to store your poufne data along with your code (in repository). You can go further - and define your ansible installation and configuration as-a-code. See `environment.sh` to learn how to install the ansible itself inside a `virtualenv` that is not attached to your operating system (can be changed by non-privilages user), and as additiinal benefit - upgrading version of ansible is as easy as installing new version in new virtualenv. You can have multiple versions of Ansible present in the same time. This is very helpfull! @@ -379,46 +379,46 @@ For my 'business cases' I use Jenkins - it has a 'cron', jobs can be binded into ### create instance in AWS ### create env in AWS -### Tips and tricks +## Tips and tricks -##### --check -C +#### --check -C Always make sure that your playbook can executes in 'dry run' mode (--check), and it's execution is not declaring 'Changed' objects. -##### --diff -D +#### --diff -D Diff is usefull to see nice detail of the files changed It compare 'in memory' the files like `diff -BbruN fileA fileB` -##### Execute hosts with 'regex' +#### Execute hosts with 'regex' ```bash ansible -m ping web* ``` -##### +#### Host groups can be joined, negated, etc ```bash ansible -m ping web*:!backend:monitoring:&allow_change ``` -##### Tagging +#### Tagging You should tag some (not all) objects - a task in a playbook, all tasks included form a role, etc. It allwos you to execute the choosen parts of the playbook. -##### no_logs: True +#### no_logs: True You may see, that some roles print a lot of output in verbose mode. There is also a debug module. This is the place where credentials may leak. Use `no_log` to hide the output. -##### Debug module +#### Debug module allows to print a value to the screen -##### Register the output of a task +#### Register the output of a task You can register the output (stdout), rc (return code), stderr of a task with the `register` command. -##### Conditionals: when: +#### Conditionals: when: -##### Loop: with, with_items, with_dict, with_together +#### Loop: with, with_items, with_dict, with_together ## Introduction -- cgit v1.2.3 From a090f8fd0af03ca558d57392a60edf6aa7184f4f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Thu, 28 Sep 2017 00:07:12 +0200 Subject: test markdown --- ansible.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ansible.html.markdown b/ansible.html.markdown index d68eafd8..699e4419 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -291,6 +291,8 @@ $ etc/inv/ec2.py --refresh $ ansible -m ping all -i etc/inv/ec2.py ``` +Read also about `dynamic inventory` below + ### ansible profiling - callback It is ok that your playbook executes some time. Sometimes you may like to speed things up -- cgit v1.2.3 From 24025fc252a3b4fff3d72572906ccfa6ba20d612 Mon Sep 17 00:00:00 2001 From: ditam Date: Sun, 15 Oct 2017 17:33:53 +0200 Subject: add Hungarian translation of Python entry --- hu-hu/python-hu.html.markdown | 816 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 816 insertions(+) create mode 100644 hu-hu/python-hu.html.markdown diff --git a/hu-hu/python-hu.html.markdown b/hu-hu/python-hu.html.markdown new file mode 100644 index 00000000..9b55f8e2 --- /dev/null +++ b/hu-hu/python-hu.html.markdown @@ -0,0 +1,816 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +filename: learnpython-hu.py +lang: hu-hu +--- + +A Python nyelvet Guido Van Rossum alkotta meg a 90-es évek elején. Manapság az +egyik legnépszerűbb programozási nyelv. Én a tiszta szintaxisa miatt szerettem +bele. Tulajdonképpen futtatható pszeudokód. + +Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh) +vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen. + +Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve +általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz +támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az +ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python3/) +ajánlott. + +Lehetséges olyan Python kódot írni, ami egyszerre kompatibilis a 2.7 és a 3.x +verziókkal is, a Python [`__future__` imports](https://docs.python.org/2/library/__future__.html) használatával. +A `__future__` import használata esetén Python 3-ban írhatod a kódot, ami +Python 2 alatt is futni fog, így ismét a fenti Python 3 bemutató ajánlott. + +```python + +# Az egysoros kommentek kettőskereszttel kezdődnek + +""" Többsoros stringeket három darab " közé + fogva lehet írni, ezeket gyakran használják + több soros kommentként. +""" + +#################################################### +# 1. Egyszerű adattípusok és operátorok +#################################################### + +# Használhatsz számokat +3 # => 3 + +# Az alapműveletek meglepetésektől mentesek +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Az osztás kicsit trükkös. Egész osztást végez, és a hányados alsó egész része +# lesz az eredmény +5 / 2 # => 2 + +# Az osztás kijavításához a (lebegőpontos) float típust kell használnunk +2.0 # Ez egy float +11.0 / 4.0 # => 2.75 áh... máris jobb + +# Az egész osztás a negatív számok esetén is az alsó egész részt eredményezi +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # floatok esetén is +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Ha importáljuk a division modult (ld. 6. Modulok rész), +# akkor a '/' jellel pontos osztást tudunk végezni. +from __future__ import division + +11 / 4 # => 2.75 ...sima osztás +11 // 4 # => 2 ...egész osztás + +# Modulo művelet +7 % 3 # => 1 + +# Hatványozás (x az y. hatványra) +2 ** 4 # => 16 + +# A precedencia zárójelekkel befolyásolható +(1 + 3) * 2 # => 8 + +# Logikai operátorok +# Megjegyzés: az "and" és "or" csak kisbetűkkel helyes +True and False # => False +False or True # => True + +# A logikai operátorok egészeken is használhatóak +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Negálni a not kulcsszóval lehet +not True # => False +not False # => True + +# Egyenlőségvizsgálat == +1 == 1 # => True +2 == 1 # => False + +# Egyenlőtlenség != +1 != 1 # => False +2 != 1 # => True + +# További összehasonlítások +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Az összehasonlítások láncolhatóak! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Stringeket " vagy ' jelek közt lehet megadni +"Ez egy string." +'Ez egy másik string.' + +# A stringek összeadhatóak! +"Hello " + "world!" # => "Hello world!" +# '+' jel nélkül is összeadhatóak +"Hello " "world!" # => "Hello world!" + +# ... illetve szorozhatóak +"Hello" * 3 # => "HelloHelloHello" + +# Kezelhető karakterek indexelhető listájaként +"This is a string"[0] # => 'T' + +# A string hosszát a len függvény adja meg +len("This is a string") # => 16 + +# String formázáshoz a % jel használható +# A Python 3.1-gyel a % már deprecated jelölésű, és később eltávolításra fog +# kerülni, de azért jó tudni, hogyan működik. +x = 'alma' +y = 'citrom' +z = "A kosárban levő elemek: %s és %s" % (x, y) + +# A string formázás újabb módja a format metódus használatával történik. +# Jelenleg ez a javasolt megoldás. +"{} egy {} szöveg".format("Ez", "helytartó") +"A {0} pedig {1}".format("string", "formázható") +# Ha nem akarsz számolgatni, nevesíthetőek a pozíciók. +"{name} kedvence a {food}".format(name="Bob", food="lasagna") + +# None egy objektum +None # => None + +# A None-nal való összehasonlításhoz ne használd a "==" jelet, +# használd az "is" kulcsszót helyette +"etc" is None # => False +None is None # => True + +# Az 'is' operátor objektum egyezést vizsgál. +# Primitív típusok esetén ez nem túl hasznos, +# objektumok esetén azonban annál inkább. + +# Bármilyen objektum használható logikai kontextusban. +# A következő értékek hamis-ra értékelődnek ki (ún. "falsey" értékek): +# - None +# - bármelyik szám típus 0 értéke (pl. 0, 0L, 0.0, 0j) +# - üres sorozatok (pl. '', (), []) +# - üres konténerek (pl., {}, set()) +# - egyes felhasználó által definiált osztályok példányai bizonyos szabályok szerint, +# ld: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# Minden egyéb érték "truthy" (a bool() függvénynek átadva igazra értékelődnek ki) +bool(0) # => False +bool("") # => False + + +#################################################### +# 2. Változók és kollekciók +#################################################### + +# Létezik egy print utasítás +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Így lehet egyszerűen bemenetet kérni a konzolról: +input_string_var = raw_input( + "Enter some data: ") # Visszatér a megadott stringgel +input_var = input("Enter some data: ") # Kiértékeli a bemenetet python kódként +# Vigyázat: a fentiek miatt az input() metódust körültekintően kell használni +# Megjegyzés: Python 3-ban az input() már deprecated, és a raw_input() lett input()-ra átnevezve + +# A változókat nem szükséges a használat előtt deklarálni +some_var = 5 # Konvenció szerint a névben kisbetu_es_alulvonas +some_var # => 5 + +# Érték nélküli változóra hivatkozás hibát dob. +# Lásd a Control Flow szekciót a kivételkezelésről. +some_other_var # name error hibát dob + +# az if használható kifejezésként +# a C nyelv '?:' ternáris operátorával egyenértékűen +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# A listákban sorozatok tárolhatóak +li = [] +# Már inicializáláskor megadhatóak elemek +other_li = [4, 5, 6] + +# A lista végére az append metódus rak új elemet +li.append(1) # li jelenleg [1] +li.append(2) # li jelenleg [1, 2] +li.append(4) # li jelenleg [1, 2, 4] +li.append(3) # li jelenleg [1, 2, 4, 3] +# A végéről a pop metódus távolít el elemet +li.pop() # => 3 és li jelenleg [1, 2, 4] +# Rakjuk vissza +li.append(3) # li jelenleg [1, 2, 4, 3], újra. + +# A lista elemeket tömb indexeléssel lehet hivatkozni +li[0] # => 1 +# A már inicializált értékekhez a = jellel lehet új értéket rendelni +li[0] = 42 +li[0] # => 42 +li[0] = 1 # csak visszaállítjuk az eredeti értékére +# Így is lehet az utolsó elemre hivatkozni +li[-1] # => 3 + +# A túlindexelés eredménye IndexError +li[4] # IndexError hibát dob + +# A lista részeit a slice szintaxissal lehet kimetszeni +# (Matekosoknak ez egy zárt/nyitott intervallum.) +li[1:3] # => [2, 4] +# A lista eleje kihagyható így +li[2:] # => [4, 3] +# Kihagyható a vége +li[:3] # => [1, 2, 4] +# Minden második elem kiválasztása +li[::2] # =>[1, 4] +# A lista egy másolata, fordított sorrendben +li[::-1] # => [3, 4, 2, 1] +# A fentiek kombinációival bonyolultabb slice parancsok is képezhetőek +# li[start:end:step] + +# Listaelemek a "del" paranccsal törölhetőek +del li[2] # li jelenleg [1, 2, 3] + +# A listák összeadhatóak +li + other_li # => [1, 2, 3, 4, 5, 6] +# Megjegyzés: az eredeti li és other_li értékei változatlanok + +# Összefőzhetőek (konkatenálhatóak) az "extend()" paranccsal +li.extend(other_li) # li jelenleg [1, 2, 3, 4, 5, 6] + +# Egy elem első előfordulásának eltávolítása +li.remove(2) # li jelenleg [1, 3, 4, 5, 6] +li.remove(2) # ValueError hibát dob, mivel a 2 nem szerepel már a listában + +# Elemek beszúrhatóak tetszőleges helyre +li.insert(1, 2) # li jelenleg [1, 2, 3, 4, 5, 6], ismét + +# Egy elem első előfordulási helye +li.index(2) # => 1 +li.index(7) # ValueError hibát dob, mivel a 7 nem szerepel a listában + +# Egy listában egy elem előfordulása az "in" szóval ellenőrizhető +1 in li # => True + +# A lista hossza a "len()" függvénnyel +len(li) # => 6 + +# Az N-esek ("tuple") hasonlítanak a listákhoz, de nem módosíthatóak +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # TypeError hibát dob + +# Az összes lista-műveletet ezeken is használható +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Az N-esek (és listák) kicsomagolhatóak külön változókba +a, b, c = (1, 2, 3) # az a így 1, a b 2 és a c pedig 3 +d, e, f = 4, 5, 6 # a zárójel elhagyható +# Ha elhagyod a zárójeleket, alapértelmezés szerint tuple képződik +g = 4, 5, 6 # => (4, 5, 6) +# Nézd, milyen egyszerű két értéket megcserélni +e, d = d, e # d most már 5 és az e 4 + +# A Dictionary típusokban hozzárendelések (kulcs-érték párok) tárolhatók +empty_dict = {} +# Ez pedig rögtön értékekkel van inicializálva +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Egy dictionary értékei [] jelek közt indexelhetőek +filled_dict["one"] # => 1 + +# A "keys()" metódus visszatér a kulcsok listájával +filled_dict.keys() # => ["three", "two", "one"] +# Megjegyzés: egy dictionary párjainak sorrendje nem garantált +# Lehet, hogy már a fenti példán is más sorrendben kaptad meg az elemeket. + +# Az értékek listája a "values()" metódussal kérhető le +filled_dict.values() # => [3, 2, 1] +# ld. a fenti megjegyzést az elemek sorrendjéről. + +# Az összes kulcs-érték pár megkapható N-esek listájaként az "items()" metódussal +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# Az "in" kulcssszóval ellenőrizhető, hogy egy kulcs szerepel-e a dictionary-ben +"one" in filled_dict # => True +1 in filled_dict # => False + +# Nem létező kulcs hivatkozása KeyError hibát dob +filled_dict["four"] # KeyError + +# A "get()" metódus használatával elkerülhető a KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# A metódusnak megadható egy alapértelmezett visszatérési érték is, hiányzó értékek esetén +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Megjegyzés: ettől még filled_dict.get("four") => None +# (vagyis a get nem állítja be az alapértelmezett értéket a dictionary-ben) + +# A kulcsokhoz értékek a listákhoz hasonló szintaxissal rendelhetőek: +filled_dict["four"] = 4 # ez után filled_dict["four"] => 4 + +# A "setdefault()" metódus csak akkor állít be egy értéket, ha az adott kulcshoz még nem volt más megadva +filled_dict.setdefault("five", 5) # filled_dict["five"] beállítva 5-re +filled_dict.setdefault("five", 6) # filled_dict["five"] még mindig 5 + +# Egy halmaz ("set") olyan, mint egy lista, de egy elemet csak egyszer tárolhat +empty_set = set() +# Inicializáljuk ezt a halmazt néhány elemmel +some_set = set([1, 2, 2, 3, 4]) # some_set jelenleg set([1, 2, 3, 4]) + +# A sorrend itt sem garantált, még ha néha rendezettnek is tűnhet +another_set = set([4, 3, 2, 2, 1]) # another_set jelenleg set([1, 2, 3, 4]) + +# Python 2.7 óta már {} jelek közt is lehet halmazt definiálni +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Új halmaz-elemek hozzáadása +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Halmaz metszés a & operátorral +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Halmaz unió | operátorral +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Halmaz különbség - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Szimmetrikus differencia ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Vizsgáljuk, hogy a bal oldali halmaz magában foglalja-e a jobb oldalit +{1, 2} >= {1, 2, 3} # => False + +# Vizsgáljuk, hogy a bal oldali halmaz részhalmaza-e a jobb oldalinak +{1, 2} <= {1, 2, 3} # => True + +# Halmazbeli elemek jelenléte az in kulcssszóval vizsgálható +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +# 3. Control Flow +#################################################### + +# Legyen egy változónk +some_var = 5 + +# Ez egy if elágazás. A behúzás mértéke (az indentáció) jelentéssel bír a nyelvben! +# Ez a kód ezt fogja kiírni: "some_var kisebb 10-nél" +if some_var > 10: + print "some_var nagyobb, mint 10." +elif some_var < 10: # Az elif kifejezés nem kötelező az if szerkezetben. + print "some_var kisebb 10-nél" +else: # Ez sem kötelező. + print "some_var kereken 10." + +""" +For ciklusokkal végigiterálhatunk listákon +a kimenet: + A(z) kutya emlős + A(z) macska emlős + A(z) egér emlős +""" +for animal in ["kutya", "macska", "egér"]: + # A {0} kifejezéssel formázzuk a stringet, ld. korábban. + print "A(z) {0} emlős".format(animal) + +""" +"range(number)" visszatér számok listájával 0-től number-ig +a kimenet: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" visszatér a lower és upper közti számok listájával +a kimenet: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +A while ciklus a feltétel hamissá válásáig fut. +a kimenet: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Rövidítés az x = x + 1 kifejezésre + +# A kivételek try/except blokkokkal kezelhetőek + +# Python 2.6-tól felfele: +try: + # A "raise" szóval lehet hibát dobni + raise IndexError("Ez egy index error") +except IndexError as e: + pass # A pass egy üres helytartó művelet. Itt hívnánk a hibakezelő kódunkat. +except (TypeError, NameError): + pass # Ha szükséges, egyszerre több hiba típus is kezelhető +else: # Az except blokk után opcionálisan megadható + print "Minden rendben!" # Csak akkor fut le, ha fentebb nem voltak hibák +finally: # Mindenképpen lefut + print "Itt felszabadíthatjuk az erőforrásokat például" + +# Az erőforrások felszabadításához try/finally helyett a with használható +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +# 4. Függvények +#################################################### + +# A "def" szóval hozhatunk létre új függvényt +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # A return szóval tudunk értékeket visszaadni + + +# Így hívunk függvényt paraméterekkel +add(5, 6) # => a konzol kimenet "x is 5 and y is 6", a visszatérési érték 11 + +# Nevesített paraméterekkel (ún. "keyword arguments") is hívhatunk egy függvényt +add(y=6, x=5) # Ez esetben a sorrendjük nem számít + + +# Változó számú paramétert fogadó függvény így definiálható. +# A * használatával a paramétereket egy N-esként kapjuk meg. +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Változó számú nevesített paramétert fogadó függvény is megadható, +# a ** használatával a paramétereket egy dictionary-ként kapjuk meg +def keyword_args(**kwargs): + return kwargs + + +# Nézzük meg, mi történik +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# A két módszer egyszerre is használható +def all_the_args(*args, **kwargs): + print args + print kwargs + + +""" +all_the_args(1, 2, a=3, b=4) kimenete: + (1, 2) + {"a": 3, "b": 4} +""" + +# Függvények hívásakor a fenti args és kwargs módszerek inverze használható +# A * karakter kifejt egy listát külön paraméterekbe, a ** egy dictionary-t nevesített paraméterekbe. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # egyenértékű: foo(1, 2, 3, 4) +all_the_args(**kwargs) # egyenértékű: foo(a=3, b=4) +all_the_args(*args, **kwargs) # egyenértékű: foo(1, 2, 3, 4, a=3, b=4) + + +# A fenti arg és kwarg paraméterek továbbadhatóak egyéb függvényeknek, +# a * illetve ** operátorokkal kifejtve +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Függvény scope +x = 5 + + +def set_x(num): + # A lokális x változó nem ugyanaz, mint a globális x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # a globális x-et 6-ra állítjuk + print x # => 6 + + +set_x(43) +set_global_x(6) + + +# A pythonban a függvény elsőrendű (ún. "first class") típus +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Névtelen függvények is definiálhatóak +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Léteznek beépített magasabb rendű függvények +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# A listaképző kifejezések ("list comprehensions") jól használhatóak a map és filter függvényekkel +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# halmaz és dictionary képzők is léteznek +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +# 5. Osztályok +#################################################### + +# Az object osztály egy alosztályát képezzük +class Human(object): + # Osztály szintű mező: az osztály összes példányában azonos + species = "H. sapiens" + + # Ez a függvény meghívódik az osztály példányosításakor. + # Megjegyzés: a dupla aláhúzás a név előtt és után egy konvenció a python + # előre definiált, a nyelv által belsőleg használt, de a felhasználó által + # is látható objektumok és mezők neveire. + # Ne vezessünk be új, ilyen elnevezési sémát használó neveket! + def __init__(self, name): + # A paramétert értékül adjuk a példány name attribútumának + self.name = name + + # Inicializálunk egy mezőt + self.age = 0 + + # Példány metódus. Minden metódus első paramétere a "self", a példány maga + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # Egy osztálymetódus az osztály összes példány közt meg van osztva. + # Hívásukkor az első paraméter mindig a hívó osztály. + @classmethod + def get_species(cls): + return cls.species + + # Egy statikus metódus osztály és példányreferencia nélkül hívódik + @staticmethod + def grunt(): + return "*grunt*" + + # Egy property jelölésű függvény olyan, mint egy getter. + # Használatával az age mező egy csak-olvasható attribútummá válik. + @property + def age(self): + return self._age + + # Így lehet settert megadni egy mezőhöz + @age.setter + def age(self, age): + self._age = age + + # Így lehet egy mező törlését engedélyezni + @age.deleter + def age(self): + del self._age + + +# Példányosítsuk az osztályt +i = Human(name="Ian") +print i.say("hi") # kimenet: "Ian: hi" + +j = Human("Joel") +print j.say("hello") # kimenet: "Joel: hello" + +# Hívjuk az osztály metódusunkat +i.get_species() # => "H. sapiens" + +# Változtassuk meg az osztály szintű attribútumot +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Hívjuk meg a statikus metódust +Human.grunt() # => "*grunt*" + +# Adjunk új értéket a mezőnek +i.age = 42 + +# Kérjük le a mező értékét +i.age # => 42 + +# Töröljük a mezőt +del i.age +i.age # => AttributeError hibát dob + +#################################################### +# 6. Modulok +#################################################### + +# Modulokat így lehet importálni +import math + +print math.sqrt(16) # => 4 + +# Lehetséges csak bizonyos függvényeket importálni egy modulból +from math import ceil, floor + +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# Egy modul összes függvénye is importálható +# Vigyázat: ez nem ajánlott. +from math import * + +# A modulok nevei lerövidíthetőek +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Meggyőződhetünk róla, hogy a függvények valóban azonosak +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# A Python modulok egyszerű fájlok. +# Írhatsz sajátot és importálhatod is. +# A modul neve azonos a tartalmazó fájl nevével. + +# Így lehet megtekinteni, milyen mezőket és függvényeket definiál egy modul. +import math + +dir(math) + + +# Ha van egy math.py nevű Python scripted a jelenleg futó scripttel azonos +# mappában, a math.py fájl lesz betöltve a beépített Python modul helyett. +# A lokális mappa prioritást élvez a beépített könyvtárak felett. + + +#################################################### +# 7. Haladóknak +#################################################### + +# Generátorok +# Egy generátor értékeket "generál" amikor kérik, a helyett, hogy előre eltárolná őket. + +# A következő metódus (ez még NEM egy generátor) megduplázza a kapott iterable elemeit, +# és eltárolja őket. Nagy méretű iterable esetén ez nagyon sok helyet foglalhat! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# A következő kód futtatásakor az összes szám kétszeresét kiszámítanánk, és visszaadnánk +# ezt a nagy listát a ciklus vezérléséhez. +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Használjunk inkább egy generátort, ami "legenerálja" a soron következő elemet, +# amikor azt kérik tőle +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# A lenti kód mindig csak a soron következő számot generálja a logikai vizsgálat előtt. +# Így amikor az érték eléri a > 5 határt, megszakítjuk a ciklust, és a lista számainak +# nagy részénél megspóroltuk a duplázás műveletet (ez sokkal gyorsabb így!). +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Feltűnt, hogy a `test_non_generator` esetén `range`, a `test_generator` esetén +# pedig `xrange` volt a segédfüggvény neve? Ahogy `double_numbers_generator` a +# generátor változata a `double_numbers` függvénynek, úgy az `xrange` a `range` +# generátor megfelelője, csak akkor generálja le a következő számot, amikor kérjük +# - esetünkben a ciklus következő iterációjakor + +# A lista képzéshez hasonlóan generátor képzőket is használhatunk +# ("generator comprehensions"). +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # kimenet: -1 -2 -3 -4 -5 + +# Egy generátor összes generált elemét listaként is elkérhetjük: +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Dekorátorok +# A dekorátor egy magasabb rendű függvény, aminek bemenete és kimenete is egy függvény. +# A lenti egyszerű példában az add_apples dekorátor a dekorált get_fruits függvény +# kimenetébe beszúrja az 'Apple' elemet. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# A kimenet tartalmazza az 'Apple' elemet: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# Ebben a példában a beg dekorátorral látjuk el a say függvényt. +# Beg meghívja say-t. Ha a say_please paraméter igaz, akkor +# megváltoztatja az eredmény mondatot. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## Még több érdekel? + +### Ingyenes online tartalmak + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) +* [Fullstack Python](https://www.fullstackpython.com/) + +### Könyvek + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 42d9ae2dd37845b4c385980f872e09ac056a93a6 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Tue, 17 Oct 2017 17:59:45 -0200 Subject: Translate awk to pt_BR --- pt-br/awk-pt.html.markdown | 376 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 pt-br/awk-pt.html.markdown diff --git a/pt-br/awk-pt.html.markdown b/pt-br/awk-pt.html.markdown new file mode 100644 index 00000000..75b73abe --- /dev/null +++ b/pt-br/awk-pt.html.markdown @@ -0,0 +1,376 @@ +--- +language: awk +filename: learnawk-pt.awk +contributors: + - ["Marshall Mason", "http://github.com/marshallmason"] +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] +lang: pt-br + +--- + +AWK é uma ferramenta padrão em todos os sistemas UNIX compatíveis com POSIX. É +como um Perl despojado, perfeito para tarefas de processamento de texto e +outras tarefas de script. Possui uma sintaxe C-like, mas sem ponto e vírgula, +gerenciamento manual de memória, ou tipagem estática. Destaca-se no +processamento de texto. Você pode chamá-lo a partir de um shell-script, ou você +pode usá-lo como uma linguagem de script autônomo. + +Por que usar AWK ao invés de Perl? Principalmente porque AWK faz parte do UNIX. +Você pode sempre contar com ele, enquanto o futuro do Perl é indefinido. AWK é +também mais fácil de ler que Perl. Para scripts simples de processamento de +texto, particularmente aqueles que leem arquivos linha por linha e fatiam texto +por delimitadores, AWK é provavelmente a ferramenta certa para a tarefa. + +```awk +#!/usr/bin/awk -f + +# Comentários são assim + +# Programas AWK consistem de uma coleção de padrões e ações. O mais +# importante padrão é chamado BEGIN. Ações estão dentro de blocos +# entre chaves. + +BEGIN { + + # O bloco BEGIN será executado no começo do programa. É onde você coloca + # todo código que prepara a execução, antes que você processe qualquer + # arquivo de texto. Se você não tem arquivos de texto, então pense no + # BEGIN como o ponto principal de entrada. + + # Variáveis são globais. Simplesmente atribua valores ou as use, sem + # necessidade de declarar. + + # Operadores são como em C e similares + a = count + 1 + b = count - 1 + c = count * 1 + d = count / 1 # divisão inteira + e = count % 1 # módulo + f = count ^ 1 # exponenciação + + a += 1 + b -= 1 + c *= 1 + d /= 1 + e %= 1 + f ^= 1 + + # Incrementando e decrementando por um + a++ + b-- + + # Como um operador pré-fixado, retorna o valor incrementado + ++a + --b + + # Perceba, não há pontuação, como ponto-e-vírgula, ao final das declarações + + # Declarações de controle + if (count == 0) + print "Começando com count em 0" + else + print "Como é que é?" + + # Ou você pode usar o operador ternário + print (count == 0) ? "Começando com count em 0" : "Como é que é?" + + # Blocos multilinhas devem usar chaves + while (a < 10) { + print "Concatenação de texto é feita" " com uma série" " de" + " textos separados por espaço" + print a + + a++ + } + + for (i = 0; i < 10; i++) + print "Uma boa opção para um loop de uma linha" + + # Quanto a comparações, eis os padrões: + a < b # Menor que + a <= b # Menor ou igual a + a != b # Não igual + a == b # Igual + a > b # Maior que + a >= b # Maior ou igual a + + # Bem como operadores lógicos + a && b # E + a || b # OU (inclusivo) + + # Em adição, há o utilíssimo operador para expressões regulares + if ("foo" ~ "^fo+$") + print "Fooey!" + if ("boo" !~ "^fo+$") + print "Boo!" + + # Matrizes + arr[0] = "foo" + arr[1] = "bar" + # Infelizmente, não há outra forma para inicializar uma matriz. Apenas + # coloque cada valor em uma linha, como mostrado acima. + + # Você também pode ter matrizes associativas + assoc["foo"] = "bar" + assoc["bar"] = "baz" + + # E matrizes multidimensionais, com algumas limitações que não mencionarei + multidim[0,0] = "foo" + multidim[0,1] = "bar" + multidim[1,0] = "baz" + multidim[1,1] = "boo" + + # Você pode testar a pertinência de um elemento em uma matriz + if ("foo" in assoc) + print "Fooey!" + + # Você pode também usar o operador 'in' para percorrer as chaves de uma + # matriz associativa + for (key in assoc) + print assoc[key] + + # Os argumentos da linha de comando estão em uma matriz especial ARGV + for (argnum in ARGV) + print ARGV[argnum] + + # Você pode remover elementos de uma matriz + # Isso é muito útil para prevenir que o AWK assuma que os argumentos são + # arquivo para ele processar + delete ARGV[1] + + # A quantidade de argumentos passados está na variável ARGC + print ARGC + + # O AWK tem várias funções nativas. Elas estão separadas em três categorias. + # Demonstrarei cada uma delas logo mais abaixo. + + return_value = arithmetic_functions(a, b, c) + string_functions() + io_functions() +} + +# Eis como você deve definir uma função +function arithmetic_functions(a, b, c, d) { + + # Provavelmente a parte mais irritante do AWK é ele não possuir variáveis + # locais. Tudo é global. Para pequenos scripts, isso não é problema, e + # pode até mesmo ser considerado útil, mas para grandes scripts, isso pode + # ser um problema. + + # Mas há como contornar isso (um hack). Os argumentos de função são locais + # para a função e o AWK permite que você defina mais argumentos de função + # do que ele precise. Então, coloque a variável local na declaração de + # função, como eu fiz acima. Como uma convenção, adicione alguns espaços + # extras para distinguir entre parâmetros de função reais e variáveis + # locais. Neste exemplo, a, b e c são parâmetros reais, enquanto d é + # meramente uma variável local. + + # Agora, serão demonstradas as funções aritméticas + + # Muitas implementações AWK possuem algumas funções trigonométricas padrão + localvar = sin(a) + localvar = cos(a) + localvar = atan2(a, b) # arco-tangente de b / a + + # E conteúdo logarítmico + localvar = exp(a) + localvar = log(a) + + # Raiz quadrada + localvar = sqrt(a) + + # Descartando a parte não inteira de um número em ponto flutuante. + localvar = int(5.34) # localvar => 5 + + # Números aleatórios + srand() # Forneça uma semente como argumento. Por padrão, ele usa a hora atual + localvar = rand() # Número aleatório entre 0 e 1. + + # Aqui mostramos como retornar um valor + return localvar +} + +function string_functions( localvar, arr) { + + # Sendo o AWK uma linguagem para processamento de texto, ele possui + # várias funções para manipulação de texto, muitas das quais + # fortemente dependentes de expressões regulares. + + # Procurar e substituir, primeira instância (sub), ou todas (gsub) + # Ambas retornam o número de instâncias substituídas + localvar = "fooooobar" + sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" + gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + + # Localiza um texto que casa com uma expressão regular + # index() faz a mesma coisa, mas não permite uma expressão regular + match(localvar, "t") # => 4, pois 't' é o quarto carácter + + # Separa por delimitador + split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] + + # Outras coisas úteis + sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" + substr("foobar", 2, 3) # => "oob" + substr("foobar", 4) # => "bar" + length("foo") # => 3 + tolower("FOO") # => "foo" + toupper("foo") # => "FOO" +} + +function io_functions( localvar) { + + # Você já viu como imprimir + print "Hello world" + + # Também há o printf + printf("%s %d %d %d\n", "Testing", 1, 2, 3) + + # O AWK não disponibiliza manipuladores de arquivo. Ele irá automaticamente + # manipular um arquivo quando você fizer algo que precise disso. O texto + # que você usou para isso pode ser usado como um manipulador de arquivo, + # para propósitos de E/S. Isso faz ele parecer com um shell script: + + print "foobar" >"/tmp/foobar.txt" + + # Agora a string "/tmp/foobar.txt" é um manipulador de arquivos. Você pode + # fechá-lo: + close("/tmp/foobar.txt") + + # Aqui está como você pode executar alguma coisa no shell + system("echo foobar") # => prints foobar + + # Lê uma linha da entrada padrão e armazena em localvar + getline localvar + + # Lê uma linha de um pipe + "echo foobar" | getline localvar # localvar => "foobar" + close("echo foobar") + + # Lê uma linha de um arquivo e armazena em localvar + getline localvar <"/tmp/foobar.txt" + close("/tmp/foobar.txt") +} + +# Como dito no início, os programas AWK consistem de uma coleção de padrões +# e ações. Você já viu o padrão BEGIN, o mais importante. Outros padrões são +# usados apenas se você estiver processando linhas de arquivos ou a entrada +# padrão. + +# Quando você passa argumentos para o AWK, eles são tratados como nomes de +# arquivos para processar. Todos serão processados, em ordem. Pense nisso como +# um implícito para loop, iterando sobre as linhas nesses arquivos. Esses +# padrões e ações são como instruções de mudança dentro do loop. + +/^fo+bar$/ { + + # Esta ação será executada para cada linha que corresponda à expressão + # regular, / ^ fo + bar $ /, e será ignorada para qualquer linha que não + # corresponda. Vamos apenas imprimir a linha: + + print + + # Opa, sem argumento! Isso ocorre pois print tem um argumento padrão: $0. + # $0 é o nome da linha atual que está sendo processada. Essa variável é + # criada automaticamente para você. + + # Você provavelmente pode adivinhar que existem outras variáveis $. Toda + # linha é implicitamente dividida antes de cada ação ser chamada, como + # o shell faz. E, como o shell, cada campo pode ser acessado com um sinal + # de cifrão + + # Isso irá imprimir o segundo e quarto campos da linha + print $2, $4 + + # O AWK automaticamente define muitas outras variáveis para ajudar você + # a inspecionar processar cada linha. A mais importante delas é NF. + + # Imprime o número de campos da linha atual + print NF + + # Imprime o último campo da linha atual + print $NF +} + +# Todo padrão é na verdade um teste verdadeiro/falso. A expressão regular no +# último padrão também é um teste verdadeiro/falso, mas parte dele estava +# escondido. Se você não informar um texto para testar, AWK assumirá $0, +# a linha que está atualmente sendo processada. Assim, a versão completa +# é a seguinte: + +$0 ~ /^fo+bar$/ { + print "Equivalente ao último padrão" +} + +a > 0 { + # Isso será executado uma vez para cada linha, quando a for positivo +} + +# Você entendeu. Processar arquivos de texto, ler uma linha de cada vez, e +# fazer algo com ela, particularmente dividir com base em um delimitador, é +# tão comum no UNIX que AWK é uma linguagem de script que faz tudo por você, +# sem você precisa perguntar. Tudo o que você precisa fazer é escrever os +# padrões e ações com base no que você espera da entrada, e o que você quer +# fazer com isso. + +# Aqui está um exemplo rápido de um script simples, o tipo de coisa que o AWK +# é perfeito para fazer. Ele irá ler um nome da entrada padrão e depois +imprimirá a média de idade de todos com esse primeiro nome. Digamos que você +forneça como argumento o nome de um arquivo com esses dados: + +# Bob Jones 32 +# Jane Doe 22 +# Steve Stevens 83 +# Bob Smith 29 +# Bob Barker 72 +# +# Eis o script: + +BEGIN { + + # Primeiro, pergunte o nome do usuário + print "Para qual nome você quer calcular a média de idade?" + + # Pega uma linha da entrada padrão, não dos arquivos indicados na + # linha de comando + getline name <"/dev/stdin" +} + +# Agora, processa cada linha em que o primeiro nome é o nome informado +$1 == name { + + # Dentro desse bloco, nós temos acesso a algumas variáveis uteis, que + # foram pré-carregadas para nós: + # $0 é a linha corrente completa + # $3 é o terceiro campo, que é o que nos interessa aqui + # NF é a quantidade de campos, que deve ser 3 + # NR é o número de registros (linhas) lidas até agora + # FILENAME é o nome do arquivo sendo processado + # FS é o delimitador em uso, que é " " aqui + # ...etc. Há muito mais, documentadas no manual. + + # Mantenha um registro do total e da quantidade de linhas encontradas + sum += $3 + nlines++ +} + +# Outro padrão especial é chamado END. Ele será executado após o processamento +# de todos os arquivos de texto. Ao contrário de BEGIN, ele só será executado +# se você tiver dado a ele dados para processar. Ele será executado depois de +# todos os arquivos terem sido lidos e processados de acordo com as regras e +# ações que você forneceu. O objetivo disso em geral é produzir algum tipo de +# relatório final, ou fazer algo com o agregado dos dados acumulados ao longo +# do script. + +END { + if (nlines) + print "A média da idade para " name " é " sum / nlines +} + +``` +Leituras adicionais (em inglês): + +* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) +* [Awk man page](https://linux.die.net/man/1/awk) +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU AWK é encontrado na maioria dos sistemas GNU/Linux. -- cgit v1.2.3 From b5a681fd6b159a5aece7e318ce01637fff3965f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20J=C3=BCrges?= Date: Wed, 18 Oct 2017 18:20:12 +0200 Subject: dynamic programming de translation --- de-de/dynamic-programming-de.html.markdown | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 de-de/dynamic-programming-de.html.markdown diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown new file mode 100644 index 00000000..d663400f --- /dev/null +++ b/de-de/dynamic-programming-de.html.markdown @@ -0,0 +1,54 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +translators: + - ["Henrik Jürges", "http://github.com/santifa"] +lang: de-de +--- + +# Dynamische Programmierung + +## Einführung +Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung einer bestimmten Klasse von Problemen verwendet wird. +Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu vermeiden, das gleiche Problem noch einmal zu lösen. + +Denken Sie immer daran! +"Diejenigen, die sich nicht an die Vergangenheit erinnern können, sind dazu verdammt, sie zu wiederholen." + +## Wege zur Lösung solcher Probleme + +1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen. Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr intuitiv. Er wird als Memoization bezeichnet. + +2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden. Dies wird als Dynamische Programmierung bezeichnet. + +## Ein Beispiel für Dynamische Programmierung + +Das Problem mit der längsten ansteigenden Subsequenz besteht darin, die längste ansteigende Subsequenz einer gegebenen Sequenz zu finden. +Gegeben die Sequenz `S= {a1, a2, a3, a3, a4,..............., an-1, an }`, müssen wir die größte Teilmenge finden, so daß für alle `j` und `i`, `j a[j] and LS[i] Date: Wed, 18 Oct 2017 18:23:39 +0200 Subject: fixed line length --- de-de/dynamic-programming-de.html.markdown | 49 ++++++++++++++++++++++-------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown index d663400f..801d2514 100644 --- a/de-de/dynamic-programming-de.html.markdown +++ b/de-de/dynamic-programming-de.html.markdown @@ -11,28 +11,51 @@ lang: de-de # Dynamische Programmierung ## Einführung -Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung einer bestimmten Klasse von Problemen verwendet wird. -Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu vermeiden, das gleiche Problem noch einmal zu lösen. +Dynamische Programmierung ist eine leistungsfähige Technik, die zur Lösung +einer bestimmten Klasse von Problemen verwendet wird. +Die Idee ist sehr einfach, wenn Sie ein Problem mit der gegebenen Eingabe +gelöst haben, dann speichern Sie das Ergebnis für die spätere Referenz, um zu +vermeiden, das gleiche Problem noch einmal zu lösen. Denken Sie immer daran! -"Diejenigen, die sich nicht an die Vergangenheit erinnern können, sind dazu verdammt, sie zu wiederholen." +"Diejenigen, die sich nicht an die Vergangenheit erinnern können, +sind dazu verdammt, sie zu wiederholen." ## Wege zur Lösung solcher Probleme -1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen. Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr intuitiv. Er wird als Memoization bezeichnet. +1. *Top-Down*: Lösen Sie das gegebene Problem, indem Sie es aufteilen. +Wenn Sie sehen, dass das Problem bereits gelöst ist, geben Sie einfach die +gespeicherte Antwort zurück. Wenn es nicht gelöst wurde, lösen Sie es und +speichern Sie die Antwort. Dieser Ansatz ist leicht zu verfolgen und sehr +intuitiv. Er wird als Memoization bezeichnet. -2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden. Dies wird als Dynamische Programmierung bezeichnet. +2. *Bottom-Up*: Analysieren Sie das Problem und beobachten Sie, in welcher +Reihenfolge die Teilprobleme gelöst werden können. Beginnen Sie mit der +Lösung vom trivialen Teilproblem bis zum gegebenen Problem. Dabei wird +sichergestellt, dass die Teilprobleme vor der Problemlösung gelöst werden. +Dies wird als Dynamische Programmierung bezeichnet. ## Ein Beispiel für Dynamische Programmierung -Das Problem mit der längsten ansteigenden Subsequenz besteht darin, die längste ansteigende Subsequenz einer gegebenen Sequenz zu finden. -Gegeben die Sequenz `S= {a1, a2, a3, a3, a4,..............., an-1, an }`, müssen wir die größte Teilmenge finden, so daß für alle `j` und `i`, `j Date: Wed, 18 Oct 2017 23:55:43 -0700 Subject: Added lambda calculus --- lambda-calculus.html.markdown | 121 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 lambda-calculus.html.markdown diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown new file mode 100644 index 00000000..6103c015 --- /dev/null +++ b/lambda-calculus.html.markdown @@ -0,0 +1,121 @@ +--- +category: Algorithms & Data Structures +name: Lambda Calculus +contributors: + - ["Max Sun", "http://github.com/maxsun"] +--- + +# Lambda Calculus + +Lambda calculus (λ-calculus), originally created by +[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), +is the world's smallest programming language. +Despite not having numbers, strings, booleans, or any non-function datatype, +lambda calculus can be used to represent any Turing Machine! + +Lambda calculus is composed of 3 elements: **variables**, **functions**, and +**applications**. + + +| Name | Syntax | Example | Explanation | +|-------------|------------------------------------|-----------|-----------------------------------------------| +| Variable | `` | `x` | a variable named "x" | +| Function | `λ.` | `λx.x` | a function with parameter "x" and body "x" | +| Application | `` | `(λx.x)a` | calling the function "λx.x" with argument "a" | + +The most basic function is the identity function: `λx.x` which is equivalent to +`f(x) = x`. The first "x" is the function's argument, and the second is the +body of the function. + +## Free vs. Bound Variables: + +- In the function `λx.x`, "x" is called a bound variable because it is both in +the body of the function and a parameter. +- In `λx.y`, "y" is called a free variable because it is never declared before hand. + +## Evaluation: + +Evaluation is done via +[β-Reduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), +which is essentially lexically-scoped substitution. + +When evaluating the +expression `(λx.x)a`, we replace all occurences of "x" in the function's body +with "a". + +- `(λx.x)a` evaluates to: `a` +- `(λx.y)a` evaluates to: `y` + +You can even create higher-order functions: + +- `(λx.(λy.x))a` evaluates to: `λy.a` + +Although lambda calculus traditionally supports only single parameter +functions, we can create multi-parameter functions using a technique called +[currying](https://en.wikipedia.org/wiki/Currying). + +- `(λx.λy.λz.xyz)` is equivalent to `f(x, y, z) = x(y(z))` + +Sometimes `λxy.` is used interchangeably with: `λx.λy.` + +---- + +It's important to recognize that traditional **lambda calculus doesn't have +numbers, characters, or any non-function datatype!** + +## Boolean Logic: + +There is no "True" or "False" in lambda calculus. There isn't even a 1 or 0. + +Instead: + +`T` is represented by: `λx.λy.x` + +`F` is represented by: `λx.λy.y` + +First, we can define an "if" function `λbtf` that +returns `t` if `b` is True and `f` if `b` is False + +`IF` is equivalent to: `λb.λt.λf.b t f` + +Using `IF`, we can define the basic boolean logic operators: + +`a AND b` is equivalent to: `λab.IF a b F` + +`a OR b` is equivalent to: `λab.IF a T b` + +`a NOT b` is equivalent to: `λa.IF a F T` + +*Note: `IF a b c` is essentially saying: `IF(a(b(c)))`* + +## Numbers: + +Although there are no numbers in lambda calculus, we can encode numbers using +[Church numerals](https://en.wikipedia.org/wiki/Church_encoding). + +For any number n: n = λf.fn so: + +`0 = λf.λx.x` + +`1 = λf.λx.f x` + +`2 = λf.λx.f(f x)` + +`3 = λf.λx.f(f(f x))` + +To increment a Church numeral, +we use the successor function `S(n) = n + 1` which is: + +`S = λn.λf.λx.f((n f) x)` + +Using successor, we can define add: + +`ADD = λab.(a S)n` + +**Challenge:** try defining your own multiplication function! + +## For more advanced reading: + +1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) +2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file -- cgit v1.2.3 From 35c2d3d242baed6a29d9d67d2db81ed0e02047ae Mon Sep 17 00:00:00 2001 From: Jeroen Deviaene Date: Thu, 19 Oct 2017 14:32:55 +0200 Subject: Added dutch translation for html --- nl-nl/html-nl.html.markdown | 97 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 nl-nl/html-nl.html.markdown diff --git a/nl-nl/html-nl.html.markdown b/nl-nl/html-nl.html.markdown new file mode 100644 index 00000000..612e9c37 --- /dev/null +++ b/nl-nl/html-nl.html.markdown @@ -0,0 +1,97 @@ +--- +language: html +filename: learnhtml.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Robert Steed", "https://github.com/robochat"] + - ["Jeroen Deviaene", "https://github.com/jerodev"] +--- + +HTML staat voor HyperText Markup Language. +Het is een taal die je toe staat pagina's te maken op het World Wide Web. +Het is een opmaak taal, dit staat de gebruiker toe om webpagina's te maken in code en zo aan te duiden hoe de pagina moet weergegeven worden. +Eigenlijk zijn html files zelfs simpele tekst bestanden. +Wat is deze opmaak? Het is een manier om de structuur en data op de pagina weer te geven met speciale html tags. +Deze tags dienen om de betekenis te geven aan de tekst die het bevat. +Zoals vele computer talen heeft html vele verschillende versies. Hier zullen we HTML5 bespreken. + +**Merk op:** Je kan de verschillende tags en elementen testen terwijl je door de tutorial gaat met een website zoals [codepen](http://codepen.io/pen/), zo kan je de effecten hier van live zien. +Dit artikel gaat vooral over de HTML syntax en enkele handige tips + + +```html + + + + + + + + + + Mijn Website + + +

Hello, world!

+ Neem een kijkje op deze link +

Dit is een paragraaf.

+

Dit is nog een paragraaf.

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

Hello, world!

+ + Neem een kijkje op deze link +

This is a paragraph.

+

This is another paragraph.

+
    + +
  • This is an item in a non-enumerated list (bullet list)
  • +
  • This is another item
  • +
  • And this is the last item on the list
  • +
+ + + +``` + +## Gebruik + +HTML wordt altijd opgeslagen in bestanden die eindigen in `.html`. + +## Meer weten + +* [wikipedia](https://nl.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 5c8c0186dcb8629396e5c82335cb7e9695ed8eec Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Thu, 19 Oct 2017 18:31:21 -0200 Subject: Translate latex to pt_BR --- pt-br/latex-pt.html.markdown | 291 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 pt-br/latex-pt.html.markdown diff --git a/pt-br/latex-pt.html.markdown b/pt-br/latex-pt.html.markdown new file mode 100644 index 00000000..a9ed566e --- /dev/null +++ b/pt-br/latex-pt.html.markdown @@ -0,0 +1,291 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] + - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] + - ["Svetlana Golubeva", "https://attillax.github.io/"] +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] +lang: pt-br +filename: learn-latex-pt.tex +--- + +```tex +% Todas as linhas de comentários começam com % +% Não existem comentários multilinhas + +$ LaTeX não é um programa processador de textos "Visual" como +% MS Word ou OpenOffice Writer + +$ Todo comando LaTeX começa com uma barra invertida (\) + +% Documentos LaTeX começam com a definição do tipo que será % compilado +% Os tipos de documento podem ser livro, relatório, apresentação, etc. +% As opções para um documento aparecem entre [] chaves. Nesse caso +% está especificado que queremos o tamanho da fonte em 12pt. +\documentclass[12pt]{article} + +% Em seguida definimos os pacotes que o documento usa. +% Se você quiser incluir gráficos, texto colorido, ou código fonte de outra +% linguagem em outro arquivo em seu documento, você precisa ampliar as +% capacidade do LaTeX. Isso é feito adicionando-se pacotes. +% Serão incluídos os pacotes float e caption para imagens e hyperref +% para links. +\usepackage{caption} +\usepackage{float} +\usepackage{hyperref} + +% Para poder usar caracteres acentuados, use o seguinte pacote: +\usepackage[utf8]{inputenc} + +% Podemos definir algumas outras propriedades do documento também! +\author{Chaitanya Krishna Ande, Colton Kohnke, Sricharan Chiruvolu \& \\ +Svetlana Golubeva} +\date{\today} +\title{Aprenda \LaTeX \hspace{1pt} em Y Minutos!} + +% Agora estamos pronto para começar o documento +% Tudo antes dessa linha é chamado "preâmbulo". +\begin{document} +% Se informarmos os campos author (autores), date (data), "title" (título), +% LaTeX poderá cria uma página inicial para nós. +\maketitle +% Se tivermos seções, poderemos criar uma tabela de conteúdo. Para isso, +% o documento deve ser compilado duas vezes, para que tudo apareça na ordem +% correta. +% É uma voa prática separar a tabela de conteúdo do corpo do documento. Para +% isso usa-se o comando \newpage +\newpage +\tableofcontents + +\newpage + +% Muitos artigos de pesquisa possuem um resumo, e pode-se isar comandos +% predefinidos para isso. +% Isso deve aparecer em sua ordem lógica, portanto, após o topo, +% mas antes das seções principais do corpo. +% Esse comando está disponível para os documentos do tipo artigo (article) +% e relatório (report). +\begin{abstract} + Documentação do \LaTeX \hspace{1pt} escrita em \LaTeX! Nada original! +\end{abstract} + +% Comandos para seções são intuitivos. +% Todos os títulos de seção são adicionados automaticamente à tabela de conteúdo. +\section{Introdução} +Olá, meu nome é Colton e juntos estamos explorando o mundo do \LaTeX! + +\section{Outra seção} +Esse é o texto para outra seção. Penso que precisamos de uma subseção. + +\subsection{Isso é uma subseção} % Subseções também são intuitivas. +Penso que precisamos de mais uma + +\subsubsection{Pythagoras} +Muito melhor agora. +\label{subsec:pythagoras} + +% Ao usar o asterisco nós impedimos a numeração automática. +% Isso funciona para outros comandos \LaTeX também. +\section*{Essa é uma seção não numerada} +Afinal nem todas as seções precisam ser numeradas! + +\section{Algumas notas sobre texto} +%\section{Espaçamento % É necessário mais informação sobre intervalos de espaço. +\LaTeX \hspace{1pt} geralmente é muito bom sobre colocar texto onde ele deve +ser posto. Se +uma linha \\ deve \\ ser \\ quebrada \\ adicione \textbackslash\textbackslash +\hspace{1pt} ao código de seu documento. \\ + +\section{Listas} +Listas são uma das coisas mais fáceis de criar no \LaTeX! Preciso fazer compras +amanhã, então façamos uma lista de compras. +\begin{enumerate} % Isso cria o bloco "enumerate". + % \item faz com que o enumerate incremente + \item Salada. + \item 27 melancias. + \item Uma lebre. + % pode-se também sobrescrever o número do item usando [] + \item[quantas?] Pistolas de água médias. + + Não é um item da lista, mas faz parte do bloco enumerate. + + \end{enumerate} % Todos os blocos devem ter um final (end{}). + +\section{Matemática} + +Um dos usos iniciais para \LaTeX \hspace{1pt} foi a produção de artigos +acadêmicos e técnicos. Usualmente nos campos da matemática e ciência. Assim, é +necessários que consigamos incluir alguns símbolos especiais em nosso texto! \\ + +A matemática tem muitos símbolos, além dos quais se pode encontrar no teclado; +símbolos para relações e conjuntos, setas, operadores, e letras gregas, apenas +para mencionar alguns.\\ + +Conjuntos e relações são essenciais em muitos textos de pesquisa em matemática. +Aqui está como você pode indicar como todo x que pertence +a X, $\forall$ x $\in$ X. \\ +% Perceba que é necessário adicionar os sinais $ antes e depois dos símbolos. +% Isso é porque quando escrevendo, estamos em modo texto. +% Mas os símbolos de matemática só existem no modo matemática. +% Podemos entrar no modo matemática a partir do modo texto com os símbolos $. +% O oposto também pode ocorrer. Variáveis podem ser renderizadas no modo +% matemática. +% Também podemos entrar no modo matemática com \[\] + +\[a^2 + b^2 = c^2 \] + +Minha letra grega favorita é $\xi$. Eu também gosto da $\beta$, $\gamma$ e $\sigma$. +Eu ainda não encontrei uma letra grega que o \LaTeX \hspace{1pt} não tenha!\\ + +Operadores são parte essencial de um documento sobre matemática: +funções trigonométricas ($\sin$, $\cos$, $\tan$), +logaritmo e exponencial ($\log$, $\exp$), +limites ($\lim$), etc. +possuem comandos pré-definidos em LaTex. +Vamos escrever uma equação para ver como se faz: +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ \\ + +Frações (numerador/denominador) podem ser escritas dessa forma: + +% 10 / 7 +$$ ^{10}/_{7} $$ + +% Frações relativamente complexas podem ser escritas como +% \frac{numerator}{denominator} +$$ \frac{n!}{k!(n - k)!} $$ \\ + +Também podemos escrever equações em um ``bloco de equação''. + +% Apresenta matemática com o 'bloco' equação +\begin{equation} % entra no modo matemática + c^2 = a^2 + b^2. + \label{eq:pythagoras} % para referência + \end{equation} % toda declaração \begin precisa de uma declaração end + +Podemos então referenciar nossa nova equação! +A equação~\ref{eq:pythagoras} é também conhecida como Teorema de Pitágoras que é +também assunto da Seção~\ref{subsec:pythagoras}. Muitas coisas podem ser +rotuladas: figuras, equações, seções, etc. + +Somatórios e Integrais são escritas com os comandos sum e int: + +% Alguns compiladores LaTeX irão reclamar se existirem linhas em branco +% em um bloco de equação. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figuras} + +Insiramos uma Figura. O local para colocar a figura pode ser difícil +de determinar. Eu tenho sempre que verificar as opções toda vez. + +\begin{figure}[H] % H aqui é uma opção para o local da figura. + \centering % centra a figura na página + % Inclui uma figura com escala de 0.8 do tamanho da página. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Comentado para propósitos de compilação. Por favor, use sua imaginação. + \caption{Triângulo retângulo com lados $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabelas} +Também podemos incluir tabelas da mesma forma que figuras. + +\begin{table}[H] + \caption{Título para a Tabela.} + % os argumentos {} abaixo descrevem como cada linha da tabela é desenhada. + % Aqui também, Preciso ver isso. Toda. E. Cada. Vez. + \begin{tabular}{c|cc} + Número & Sobrenome & Primeiro Nome \\ % Colunas são separadas por & + \hline % uma linha horizontal + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +\section{Fazendo o \LaTeX \hspace{1pt} não compilar algo (o código fonte)} +Digamos que precisamos incluir algum código dentro do nosso +documento \LaTeX \hspace{1pt}, para isso precisamos com o \LaTeX \hspace{1pt} +não tente interpretar esse texto e que apenas inclua ele no documento. Fazemos +isso com o bloco verbatim. + +% Existem outros pacotes (por exemplo, minty, lstlisting, etc.) +% mas verbatim é o básico +\begin{verbatim} + print("Hello World!") + a%b; % olha só! Podemos usar os sinais % no bloco verbatim. + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Compilando} + +Imagino que agora você esteja pensando como compilar esse fantástico documento +e visualizar a gloriosa glória que é um pdf gerado por \LaTeX \hspace{1pt} pdf. +(sim, esse documento é compilável). \\ + +Finalizando o documento usando \LaTeX \hspace{1pt} consiste nos seguintes passos: + \begin{enumerate} + \item Escrever o documento em texto puro (o ``código fonte''). + \item Compilar o código fonte para gerar um pdf. + Os passos para compilar se parecem (em Linux) com: \\ + \begin{verbatim} + > pdflatex learn-latex.tex + \end{verbatim} + \end{enumerate} + +Existem editores de \LaTeX \hspace{1pt} que combinam os passos 1 e 2 no mesmo +sistema de software. Assim, você pode ver o passo 1, mas não o passo 2 por +completo. Passo 2 estará acontecendo escondido\footnote{Por exemplo, quando usar +referências (como Equação~\ref{eq:pythagoras}), pode ser necessário executar o +passo 2 várias vezes, para gerar arquivos *.aux intermediários.}. +% É assim que você adiciona notas de rodapé em seus documentos! + +Você escreve toda a informação de formatação em texto puro, no passo 1. O +momento da compilação no passo 2 é responsável por produzir o documento no +formato que você definiu no passo 1. + +\section{Links} +Nós podemos inserir links em nosso documento. Para isso nós necessitamos incluir +o pacote hyperref no preâmbulo com o comando: +\begin{verbatim} + \usepackage{hyperref} +\end{verbatim} + +Existem dois tipos principais de links: URL visíveis \\ +\url{https://learnxinyminutes.com/docs/latex/}, ou +\href{https://learnxinyminutes.com/docs/latex/}{um texto alternativo} +% Você não pode adicionar espaços extras ou símbolos especiais no texto +% alternativo, pois isso causará problemas na compilação. + +Esse pacote também produz uma lista de thumbnails no documento pdf gerado e +ativa os links na tabela de conteúdo. + +\section{End} + +Por enquanto é isso! + +% Frequentemente você precisa de uma seção de referências em seu documento. +% A forma mais fácil de configurá-la é usando uma seção de bibliografia +\begin{thebibliography}{1} + % como em outras listas, o comando \bibitem pode ser usado para itens da lista + % cada entrada pode ser citada diretamente no corpo do texto + \bibitem{latexwiki} The amazing \LaTeX \hspace{1pt} wikibook: {\em +https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} +\end{thebibliography} + +% end the document +\end{document} +``` + +## Mais sobre LaTeX + +* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) -- cgit v1.2.3 From 1f035686ef8f6605d8e43c1c6138bae10c4f9b0d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 21:42:16 +0200 Subject: set -e - again --- ansible.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 699e4419..e17e543f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -376,10 +376,7 @@ It can perform roling-deployment (without Ansible), can integrate with clouds, #### Jenkins For my 'business cases' I use Jenkins - it has a 'cron', jobs can be binded into 'pipelines'. -### become-user, become -### ansible - dynamic in AWS -### create instance in AWS -### create env in AWS +#### become-user, become ## Tips and tricks @@ -470,3 +467,6 @@ But ansible is way more! It provides an execution plans, an API, library, callba # vault # roles +#### ansible - dynamic in AWS +#### create instance in AWS +#### create env in AWS -- cgit v1.2.3 From 66055cf822018d1c2f38b352919c5ccdc4aeb437 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 22:31:58 +0200 Subject: set -e - again --- ansible.html.markdown | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index e17e543f..c495b308 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -109,6 +109,7 @@ hosts: all tasks: - name: "ping all" ping: + - name: "execute a shell command" shell: "date; whoami; df -h;" ``` @@ -174,8 +175,12 @@ We would clone the ready-to-use examples from additional repository ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git $ cd ansible-for-learnXinYminutes -$ source environment -$(venv) ansible-playbook playbooks/role_example.yml +$ source environment.sh +(venv) u@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml + +# First lets execute the simple_playbook.yml +(venv) user@host:~/ansible-for-learnXinYminute$ ansible-playbook playbook/simple_playbook.yml + ``` #### Role directory structure: -- cgit v1.2.3 From d81ed7f3b7bfdc748b74f75debd5451cb5bbee59 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:24:45 +0200 Subject: set -e - again --- ansible.html.markdown | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index c495b308..d134c073 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -169,18 +169,23 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -Example->role - -We would clone the ready-to-use examples from additional repository +#### We would use repository with *ready to use* examples +We would clone the repository ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git $ cd ansible-for-learnXinYminutes $ source environment.sh -(venv) u@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml +$ +$# First lets execute the simple_playbook.yml +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml -# First lets execute the simple_playbook.yml -(venv) user@host:~/ansible-for-learnXinYminute$ ansible-playbook playbook/simple_playbook.yml +``` +```bash +$ source environment.sh +$ +$# Now we would run the above playbook with roles +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml ``` #### Role directory structure: -- cgit v1.2.3 From 340f30f3410602e649c224eb9804f826d2fc8e0e Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:26:03 +0200 Subject: set -e - again --- ansible.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index d134c073..d3a0fb34 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -176,15 +176,14 @@ $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git $ cd ansible-for-learnXinYminutes $ source environment.sh $ -$# First lets execute the simple_playbook.yml +$ # First lets execute the simple_playbook.yml (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml ``` ```bash $ source environment.sh -$ -$# Now we would run the above playbook with roles +$ # Now we would run the above playbook with roles (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml ``` -- cgit v1.2.3 From 1a935188969deac50f30fe356422d8003188afbb Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:29:13 +0200 Subject: set -e - again --- ansible.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index d3a0fb34..91442dbf 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -171,10 +171,12 @@ pre_tasks: #### We would use repository with *ready to use* examples We would clone the repository +This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command + ```bash $ git colone git@github.com:sirkubax/ansible-for-learnXinYminutes.git -$ cd ansible-for-learnXinYminutes -$ source environment.sh +user@host:~/$ cd ansible-for-learnXinYminutes +user@host:~/ansible-for-learnXinYminutes$ source environment.sh $ $ # First lets execute the simple_playbook.yml (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml -- cgit v1.2.3 From 738f09d92596b3c9f12477d4e0ac88f9ad9c7c76 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:30:15 +0200 Subject: set -e - again --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 91442dbf..ee313f2c 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -170,7 +170,7 @@ pre_tasks: ``` #### We would use repository with *ready to use* examples -We would clone the repository +For remaining examples we would clone the repository This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command ```bash -- cgit v1.2.3 From a3e6e2bb3b4ed325cd6fea0cc4f7590cb198849f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:31:14 +0200 Subject: set -e - again --- ansible.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index ee313f2c..57f559ef 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -169,8 +169,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -#### We would use repository with *ready to use* examples -For remaining examples we would clone the repository +#### For remaining examples we would use repository with *ready to use* examples This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command ```bash -- cgit v1.2.3 From 68eae69fb5471f645265216967044905f3471a29 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:32:41 +0200 Subject: set -e - again --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 57f559ef..04862a14 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -169,7 +169,7 @@ pre_tasks: shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` -#### For remaining examples we would use repository with *ready to use* examples +#### For remaining examples we would use additional repository This example install ansible in `virtualenv` so it is independend from a system. You need to init it with `source environment.sh` command ```bash @@ -182,6 +182,7 @@ $ # First lets execute the simple_playbook.yml ``` +Run the above playbook with roles example ```bash $ source environment.sh $ # Now we would run the above playbook with roles -- cgit v1.2.3 From ceac9628c238b8835df8d7c0154c7a91d60ac74f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 20 Oct 2017 23:45:03 +0200 Subject: set -e - again --- ansible.html.markdown | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 04862a14..bd0200f6 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -104,14 +104,14 @@ This example-playbook would execute (on all hosts defined in the inventory) two * `shell` that execute three commands and return the output to our terminal ```yml -hosts: all - -tasks: - - name: "ping all" - ping: - - - name: "execute a shell command" - shell: "date; whoami; df -h;" +- hosts: all + + tasks: + - name: "ping all" + ping: + + - name: "execute a shell command" + shell: "date; whoami; df -h;" ``` You can run the playbook with the command: @@ -152,21 +152,21 @@ Role can be included in your playbook (executed via your playbook). ```yml -hosts: all - -tasks: - - name: "ping all" - ping: - - name: "execute a shell command" - shell: "date; whoami; df -h;" - -role: - - some_role - - { role: another_role, some_variable: 'learnxiny', tags: ['my_tag'] } - -pre_tasks: - - name: some pre-task - shell: echo 'this task is the last, but would be executed before roles, and before tasks' +- hosts: all + + tasks: + - name: "ping all" + ping: + - name: "execute a shell command" + shell: "date; whoami; df -h;" + + roles: + - some_role + - { role: another_role, some_variable: 'learnxiny', tags: ['my_tag'] } + + pre_tasks: + - name: some pre-task + shell: echo 'this task is the last, but would be executed before roles, and before tasks' ``` #### For remaining examples we would use additional repository -- cgit v1.2.3 From bb31a53eb2c559d327b6bc7f58735b410ae4815f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Sat, 21 Oct 2017 00:01:29 +0200 Subject: set -e - again --- ansible.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index bd0200f6..e41d1a6a 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -225,7 +225,8 @@ You should also know, that a nice way to pool some data is a **lookup** You can use them in CLI too ```yaml -ansible -m shell -a 'echo {{ my_variable }}` -e '{{ lookup('pipe'; 'date' }}" localhost +ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "date") }}"' localhost +ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "hostname") }}"' all ``` -- cgit v1.2.3 From 2eb1aa6abdc07cf25d6706a0ed5f9963fdd60605 Mon Sep 17 00:00:00 2001 From: SmuSmu Date: Sun, 22 Oct 2017 13:52:48 +0200 Subject: Update html.html.markdown --- html.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/html.html.markdown b/html.html.markdown index 3c855b5c..6516e5dd 100644 --- a/html.html.markdown +++ b/html.html.markdown @@ -111,7 +111,7 @@ This article is concerned principally with HTML syntax and some useful tips. ## Usage -HTML is written in files ending with `.html`. +HTML is written in files ending with `.html` or `.htm`. The mime type is `text/html`. ## To Learn More -- cgit v1.2.3 From 10bd172129c2df170c6609a5d209fed8417f76b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20J=C3=BCrges?= Date: Mon, 23 Oct 2017 18:12:14 +0200 Subject: Translated LOLCODE to german --- de-de/LOLCODE-de.html.markdown | 188 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 de-de/LOLCODE-de.html.markdown diff --git a/de-de/LOLCODE-de.html.markdown b/de-de/LOLCODE-de.html.markdown new file mode 100644 index 00000000..155c5657 --- /dev/null +++ b/de-de/LOLCODE-de.html.markdown @@ -0,0 +1,188 @@ +--- +language: LOLCODE +filename: learnLOLCODE.lol +contributors: + - ["abactel", "https://github.com/abactel"] +translators: + - ["Henrik Jürges", "http://github.com/santifa"] +lang: de-de +--- + +LOLCODE ist eine esoterische Programmiersprache die die Sprache der [lolcats](https://upload.wikimedia.org/wikipedia/commons/a/ab/Lolcat_in_folder.jpg?1493656347257) nachahmt. + +``` +BTW Das ist ein Kommentar +BTW Das Programm muss mit `HAI ` beginnen und mit `KTHXBYE` enden. + +HAI 1.3 +CAN HAS STDIO? BTW Standard Header importieren + +OBTW + ========================================================================== + ============================== Grundlegendes ============================= + ========================================================================== +TLDR + +BTW Texte anzeigen: +VISIBLE "HELLO WORLD" + +BTW Variablen deklarieren: +I HAS A MESSAGE ITZ "CATZ ARE GOOD" +VISIBLE MESSAGE + +OBTW + Variablen sind dynamisch typisiert und der Typ muss nicht explizit + angegeben werden. Die möglichen Typen sind: +TLDR + +I HAS A STRING ITZ "DOGZ ARE GOOOD" BTW Typ ist YARN +I HAS A INTEGER ITZ 42 BTW Typ ist NUMBR +I HAS A FLOAT ITZ 3.1415 BTW Typ ist NUMBAR +I HAS A BOOLEAN ITZ WIN BTW Typ ist TROOF +I HAS A UNTYPED BTW Typ ist NOOB + +BTW Eingaben von Nutzern: +I HAS A AGE +GIMMEH AGE +BTW Die Variable wird als YARN gespeichert und kann in eine +BTW NUMBR konvertiert werden: +AGE IS NOW A NUMBR + +OBTW + ========================================================================== + ================================== MATHE ================================= + ========================================================================== +TLDR + +BTW LOLCODE benutzt polnische Notation für Mathe. + +BTW grundlegende mathematische Notationen: + +SUM OF 21 AN 33 BTW 21 + 33 +DIFF OF 90 AN 10 BTW 90 - 10 +PRODUKT OF 12 AN 13 BTW 12 * 13 +QUOSHUNT OF 32 AN 43 BTW 32 / 43 +MOD OF 43 AN 64 BTW 43 modulo 64 +BIGGR OF 23 AN 53 BTW max(23, 53) +SMALLR OF 53 AN 45 BTW min(53, 45) + +BTW binäre Notation: + +BOTH OF WIN AN WIN BTW und: WIN if x=WIN, y=WIN +EITHER OF FAIL AN WIN BTW oder: FAIL if x=FAIL, y=FAIL +WON OF WIN AN FAIL BTW exklusives oder: FAIL if x=y +NOT FAIL BTW unäre Negation: WIN if x=FAIL +ALL OF WIN AN WIN MKAY BTW beliebige Stelligkeit bei AND +ANY OF WIN AN FAIL MKAY BTW beliebige Stelligkeit bei OR + +BTW Vergleiche: + +BOTH SAEM "CAT" AN "DOG" BTW WIN wenn x == y +DIFFRINT 732 AN 184 BTW WIN wenn x != y +BOTH SAEM 12 AN BIGGR OF 12 AN 4 BTW x >= y +BOTH SAEM 43 AN SMALLR OF 43 AN 56 BTW x <= y +DIFFRINT 64 AN SMALLR OF 64 AN 2 BTW x > y +DIFFRINT 75 AN BIGGR OF 75 AN 643 BTW x < y + +OBTW + ========================================================================== + ============================= Flusskontrolle ============================= + ========================================================================== +TLDR + +BTW If/then Statement: +I HAS A ANIMAL +GIMMEH ANIMAL +BOTH SAEM ANIMAL AN "CAT", O RLY? + YA RLY + VISIBLE "YOU HAV A CAT" + MEBBE BOTH SAEM ANIMAL AN "MAUS" + VISIBLE "NOM NOM NOM. I EATED IT." + NO WAI + VISIBLE "AHHH IS A WOOF WOOF" +OIC + +BTW Case Statement: +I HAS A COLOR +GIMMEH COLOR +COLOR, WTF? + OMG "R" + VISIBLE "RED FISH" + GTFO + OMG "Y" + VISIBLE "YELLOW FISH" + BTW Weil hier kein `GTFO` ist wird auch das nächste Statement überprüft + OMG "G" + OMG "B" + VISIBLE "FISH HAS A FLAVOR" + GTFO + OMGWTF + VISIBLE "FISH IS TRANSPARENT OHNO WAT" +OIC + +BTW For Schleife: +I HAS A TEMPERATURE +GIMMEH TEMPERATURE +TEMPERATURE IS NOW A NUMBR +IM IN YR LOOP UPPIN YR ITERATOR TIL BOTH SAEM ITERATOR AN TEMPERATURE + VISIBLE ITERATOR +IM OUTTA YR LOOP + +BTW While Schleife: +IM IN YR LOOP NERFIN YR ITERATOR WILE DIFFRINT ITERATOR AN -10 + VISIBLE ITERATOR +IM OUTTA YR LOOP + +OBTW + ========================================================================= + ================================ Strings ================================ + ========================================================================= +TLDR + +BTW Zeilenumbrüche: +VISIBLE "FIRST LINE :) SECOND LINE" + +BTW Tabulatoren: +VISIBLE ":>SPACES ARE SUPERIOR" + +BTW Bell (macht beep): +VISIBLE "NXT CUSTOMER PLS :o" + +BTW Anführungszeichen in Strings: +VISIBLE "HE SAID :"I LIKE CAKE:"" + +BTW Doppelpunkte in Strings : +VISIBLE "WHERE I LIVE:: CYBERSPACE" + +OBTW + ========================================================================= + =============================== Funktionen ============================== + ========================================================================= +TLDR + +BTW Definieren einer neuen Funktion: +HOW IZ I SELECTMOVE YR MOVE BTW `MOVE` ist ein Argument + BOTH SAEM MOVE AN "ROCK", O RLY? + YA RLY + VISIBLE "YOU HAV A ROCK" + NO WAI + VISIBLE "OH NO IS A SNIP-SNIP" + OIC + GTFO BTW Gibt NOOB zurück +IF U SAY SO + +BTW Eine Funktion deklarieren und einen Wert zurückgeben: +HOW IZ I IZYELLOW + FOUND YR "YELLOW" +IF U SAY SO + +BTW Eine Funktion aufrufen: +I IZ IZYELLOW MKAY + +KTHXBYE +``` + +## Weiterführende Informationen: + +- [LCI compiler](https://github.com/justinmeza/lci) +- [Official spec](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md) -- cgit v1.2.3 From fc57b35478e2ba624005fdb0138c98bb4916fbf4 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Mon, 23 Oct 2017 16:16:44 -0200 Subject: Translate whip to pt_BR --- pt-br/whip-pt.html.markdown | 247 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 247 insertions(+) create mode 100644 pt-br/whip-pt.html.markdown diff --git a/pt-br/whip-pt.html.markdown b/pt-br/whip-pt.html.markdown new file mode 100644 index 00000000..989bae05 --- /dev/null +++ b/pt-br/whip-pt.html.markdown @@ -0,0 +1,247 @@ +--- +language: whip +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] +author: Tenor Biel +author_url: http://github.com/L8D +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] +lang: pt-br +filename: whip-pt.lisp +--- + +Whip é um dialeto de Lisp feito para construir scripts e trabalhar com +conceitos mais simples. +Ele também copia muitas funções e sintaxe de Haskell (uma linguagem não correlata) + +Esse documento foi escrito pelo próprio autor da linguagem. Então é isso. + +```scheme +; Comentário são como em Lisp. Pontos-e-vírgulas... + +; A maioria das declarações de primeiro nível estão dentro de "listas" +; que nada mais são que coisas entre parêntesis separadas por espaços em branco +nao_é_uma_lista +(uma lista) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 1. Números, texto e operadores + +; Whip tem um tipo numérico (que é um double de 64 bits IEE 754, do JavaScript) +3 ; => 3 +1.5 ; => 1.5 + +; Funções são chamadas se elas são o primeiro elemento em uma lista +(funcao_chamada argumentos) + +; A maioria das operações são feitas com funções +; Todas as funções aritméticas básicas são bem diretas +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 +; até mesmo o módulo +(% 9 4) ; => 1 +; Divisão não inteira ao estilo JavaScript. +(/ 5 2) ; => 2.5 + +; Aninhamento de listas funciona como esperado. +(* 2 (+ 1 3)) ; => 8 + +; Há um tipo boleano. +true +false + +; Textos são criados com ". +"Hello, world" + +; Caracteres são criados com '. +'a' + +; Para negação usa-se a função 'not'. +(not true) ; => false +(not false) ; => true + +; Mas a maioria das funções não-haskell tem atalhos +; o não atalho é um '!'. +(! (! true)) ; => true + +; Igualdade é `equal` ou `=`. +(= 1 1) ; => true +(equal 2 1) ; => false + +; Por exemplo, inigualdade pode ser verificada combinando as funções +;`not` e `equal`. +(! (= 2 1)) ; => true + +; Mais comparações +(< 1 10) ; => true +(> 1 10) ; => false +; e suas contra partes para texto. +(lesser 1 10) ; => true +(greater 1 10) ; => false + +; Texto pode ser concatenado com +. +(+ "Hello " "world!") ; => "Hello world!" + +; Você pode usar as características comparativas do JavaScript. +(< 'a' 'b') ; => true +; ... e coerção de tipos +(= '5' 5) + +; As funções `at` ou `@` acessarão caracteres de um texto, começando em 0. +(at 0 'a') ; => 'a' +(@ 3 "foobar") ; => 'b' + +; Também existem as variáveis `null` e `undefined`. +null ; usada para indicar a ausência de algum valor +undefined ; usada para indicar que um valor não foi informado + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 2. Variáveis, matrizes e dicionários + +; Variáveis são declaradas com as funções `def` ou `let`. +; Variáveis que não tiveram valor atribuído serão `undefined`. +(def some_var 5) +; `def` deixará a variável no contexto global. +; `let` deixará a variável no contexto local, e tem uma sintaxe estranha. +(let ((a_var 5)) (+ a_var 5)) ; => 10 +(+ a_var 5) ; = undefined + 5 => undefined + +; Matrizes são listas de valores de qualquer tipo. +; Elas basicamente são listas sem funções no início +(1 2 3) ; => [1, 2, 3] (sintaxe JavaScript) + +; Dicionários em Whip são o equivalente a 'object' em JavaScript ou +; 'dict' em python ou 'hash' em Ruby: eles s]ão uma coleção desordenada +de pares chave-valor. +{"key1" "value1" "key2" 2 3 3} + +; Chaves podem ser apenas identificadores, números ou texto. +(def my_dict {my_key "my_value" "my other key" 4}) +; Mas em Whip, dicionários são parceados como: valor, espaço, valor; +; com mais espaço entre cada. Então isso significa que +{"key" "value" +"another key" +1234 +} +é avaliado da mesma forma que +{"key" "value" "another key" 1234} + +; Dicionários podem ser acessados usando a função `at` +; (como em texto e listas) +(@ "my other key" my_dict) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 3. Lógica e controle de fluxo + +; A função `if` é muito simples, ainda que muito diferente do que em muitas +linguagens imperativas. +(if true "returned if first arg is true" "returned if first arg is false") +; => "returned if first arg is true" + +; E por conta do legado operador ternário +; `?` é o atalho não utilizado para `if`. +(? false true false) ; => false + +; `both` é uma declaração lógica `and`, e `either` é o `or` lógico. +(both true true) ; => true +(both true false) ; => false +(either true false) ; => true +(either false false) ; => false +; E seus atalhos são +; & => both +; ^ => either +(& true true) ; => true +(^ false true) ; => true + +;;;;;;;;; +; Lambdas + +; Lambdas em Whip são declaradas com as funções `lambda` ou `->`. +; E funções são na verdade lambdas com nomes. +(def my_function (-> (x y) (+ (+ x y) 10))) +; | | | | +; | | | valor retornado (com escopo contento argumentos) +; | | argumentos +; | declaração de funções lambda +; | +; nome do lambda a ser declarado + +(my_function 10 10) ; = (+ (+ 10 10) 10) => 30 + +; Obviamente, todos os lambdas por definição são anônimos e +; tecnicamente sempre usados anonimamente. Redundância. +((lambda (x) x) 10) ; => 10 + +;;;;;;;;;;;;;;;; +; Comprehensions + +; `range` or `..` geram uma lista dos números para +; cada número entre seus dois argumentos. +(range 1 5) ; => (1 2 3 4 5) +(.. 0 2) ; => (0 1 2) + +; `map` aplica seu primeiro argumento (que deve ser um lambda/função) +; a cada item dos argumentos seguintes (que precisa ser uma lista) +(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) + +; Reduce +(reduce + (.. 1 5)) +; equivalente a +((+ (+ (+ 1 2) 3) 4) 5) + +; Nota: map e reduce não possuem atalhos + +; `slice` ou `\` é similar ao .slice() do JavaScript +; mas veja que ele pega uma lista como primeiro argumento, não o último. +(slice (.. 1 5) 2) ; => (3 4 5) +(\ (.. 0 100) -5) ; => (96 97 98 99 100) + +; `append` ou `<<` são auto explicativos +(append 4 (1 2 3)) ; => (1 2 3 4) +(<< "bar" ("foo")) ; => ("foo" "bar") + +; Length é auto explicativo. +(length (1 2 3)) ; => 3 +(_ "foobar") ; => 6 + +;;;;;;;;;;;;;;; +; Delicadezas Haskell + +; Primeiro item de uma lista +(head (1 2 3)) ; => 1 +; Pega do segundo ao último elemento de uma lista +(tail (1 2 3)) ; => (2 3) +; Último item de uma lista +(last (1 2 3)) ; => 3 +; Contrário de `tail` +(init (1 2 3)) ; => (1 2) +; Pega do primeiro até o elemento especificado da lista +(take 1 (1 2 3 4)) ; (1 2) +; Contrário de `take` +(drop 1 (1 2 3 4)) ; (3 4) +; Menos valor em uma lista +(min (1 2 3 4)) ; 1 +; Maior valor em uma lista +(max (1 2 3 4)) ; 4 +; Verifica se o valor está em uma lista ou objeto +(elem 1 (1 2 3)) ; true +(elem "foo" {"foo" "bar"}) ; true +(elem "bar" {"foo" "bar"}) ; false +; Inverte a ordem de uma lista +(reverse (1 2 3 4)) ; => (4 3 2 1) +; Verifica se o valor é par ou ímpar +(even 1) ; => false +(odd 1) ; => true +; Separa um texto cortando por espaço em branco +(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") +; Junta lista de textos +(unwords ("foo" "bar")) ; => "foobar" +; Sucessor e predecessor +(pred 21) ; => 20 +(succ 20) ; => 21 +``` + +Para mais informação, verifique o [repositório](http://github.com/L8D/whip) -- cgit v1.2.3 From 95b5f9a4c4fa17b1d4854185a08e2a3434944de0 Mon Sep 17 00:00:00 2001 From: ksami Date: Tue, 24 Oct 2017 13:29:11 +0800 Subject: #2314 add delegates and events to csharp/en --- csharp.html.markdown | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index c98a7da9..24ce803e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -640,6 +640,54 @@ on a new line! ""Wow!"", the masses cried"; } } + + // DELEGATES AND EVENTS + public class DelegateTest + { + public static int count = 0; + public static int Increment() + { + // increment count then return it + return ++count; + } + + // A delegate is a reference to a method + // To reference the Increment method, + // first declare a delegate with the same signature + // ie. takes no arguments and returns an int + public delegate int IncrementDelegate(); + + // An event can also be used to trigger delegates + // Create an event with the delegate type + public static event IncrementDelegate MyEvent; + + static void Main(string[] args) + { + // Refer to the Increment method by instantiating the delegate + // and passing the method itself in as an argument + IncrementDelegate inc = new IncrementDelegate(Increment); + Console.WriteLine(inc()); // => 1 + + // Delegates can be composed with the + operator + IncrementDelegate composedInc = inc; + composedInc += inc; + composedInc += inc; + + // composedInc will run Increment 3 times + Console.WriteLine(composedInc()); // => 4 + + + // Subscribe to the event with the delegate + MyEvent += new IncrementDelegate(Increment); + MyEvent += new IncrementDelegate(Increment); + + // Trigger the event + // ie. run all delegates subscribed to this event + Console.WriteLine(MyEvent()); // => 6 + } + } + + // Class Declaration Syntax: // class { // //data fields, constructors, functions all inside. -- cgit v1.2.3 From be1381f6bbcedff978027c80c4a1e579748cb769 Mon Sep 17 00:00:00 2001 From: Senrion Date: Tue, 24 Oct 2017 07:52:54 +0200 Subject: [edn/de] fixing typos --- de-de/edn-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/edn-de.html.markdown b/de-de/edn-de.html.markdown index 4f452d7e..2434d1bd 100644 --- a/de-de/edn-de.html.markdown +++ b/de-de/edn-de.html.markdown @@ -41,7 +41,7 @@ false ; Charaktere werden einem Backslash vorangestellt \g \r \a \c \e -; Schlüsselwörter beginnen mit einenm Doppelpunkt. Sie verhalten sich wie Enums. +; Schlüsselwörter beginnen mit einem Doppelpunkt. Sie verhalten sich wie Enums. ; Ähnlich, wie Symbole in Ruby. :eggs :cheese @@ -79,7 +79,7 @@ false #{:a :b 88 "huat"} ;;;;;;;;;;;;;;;;;;;;;;;;; -;;; makierte Elemente ;;; +;;; markierte Elemente ;;; ;;;;;;;;;;;;;;;;;;;;;;;;; ; EDN kann erweitert werden, indem Elemente mit # Symbolen makiert werden. @@ -91,7 +91,7 @@ false (defrecord MenuItem [name rating]) ; Um EDN in clojure Werte umzuwandeln, muss ich den eingebauten EDN Leser -;edn/read-string verwenden +; edn/read-string verwenden (edn/read-string "{:eggs 2 :butter 1 :flour 5}") ; -> {:eggs 2 :butter 1 :flour 5} -- cgit v1.2.3 From 4eb33f98b47dfbf6ae0c7c2148faadab310f53c5 Mon Sep 17 00:00:00 2001 From: ksami Date: Tue, 24 Oct 2017 15:20:20 +0800 Subject: add topics for tuples to csharp/en Added explanation and examples for tuples, deconstruction of tuples and other objects, and discarding unwanted fields during deconstruction --- csharp.html.markdown | 72 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 56 insertions(+), 16 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index c98a7da9..54d5ea09 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1106,25 +1106,65 @@ namespace Learning.More.CSharp } } +//New C# 7 Feature +//Install Microsoft.Net.Compilers Latest from Nuget +//Install System.ValueTuple Latest from Nuget using System; namespace Csharp7 { - //New C# 7 Feature - //Install Microsoft.Net.Compilers Latest from Nuget - //Install System.ValueTuple Latest from Nuget - class Program - { - static void Main(string[] args) - { - //Type 1 Declaration - (string FirstName, string LastName) names1 = ("Peter", "Parker"); - Console.WriteLine(names1.FirstName); - - //Type 2 Declaration - var names2 = (First:"Peter", Last:"Parker"); - Console.WriteLine(names2.Last); - } - } + // TUPLES, DECONSTRUCTION AND DISCARDS + class TuplesTest + { + public (string, string) GetName() + { + // Fields in tuples are by default named Item1, Item2... + var names1 = ("Peter", "Parker"); + Console.WriteLine(names1.Item2); // => Parker + + // Fields can instead be explicitly named + // Type 1 Declaration + (string FirstName, string LastName) names2 = ("Peter", "Parker"); + + // Type 2 Declaration + var names3 = (First:"Peter", Last:"Parker"); + + Console.WriteLine(names2.FirstName); // => Peter + Console.WriteLine(names3.Last); // => Parker + + return names3; + } + + public string GetLastName() { + var fullName = GetName(); + + // Tuples can be deconstructed + (string firstName, string lastName) = fullName; + + // Fields in a deconstructed tuple can be discarded by using _ + var (_, last) = fullName; + return last; + } + + // Any type can be deconstructed in the same way by + // specifying a Deconstruct method + public int randomNumber = 4; + public int anotherRandomNumber = 10; + + public void Deconstruct(out int randomNumber, out int anotherRandomNumber) + { + randomNumber = this.randomNumber; + anotherRandomNumber = this.anotherRandomNumber; + } + + static void Main(string[] args) + { + var tt = new TuplesTest(); + (int num1, int num2) = tt; + Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10 + + Console.WriteLine(tt.GetLastName()); + } + } } ``` -- cgit v1.2.3 From 52324c9d0f8bd5d2d6a1167c3c6775e00c842b6b Mon Sep 17 00:00:00 2001 From: thanhpd Date: Wed, 25 Oct 2017 20:46:38 +0700 Subject: Added Vietnamese translation for Less --- vi-vn/less-vi.html.markdown | 405 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 405 insertions(+) create mode 100644 vi-vn/less-vi.html.markdown diff --git a/vi-vn/less-vi.html.markdown b/vi-vn/less-vi.html.markdown new file mode 100644 index 00000000..73940592 --- /dev/null +++ b/vi-vn/less-vi.html.markdown @@ -0,0 +1,405 @@ +--- +language: less +contributors: + - ["Saravanan Ganesh", "http://srrvnn.me"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +filename: learnless-vi.ts +lang: vi-vn +--- + +Less là một CSS pre-processor (bộ tiền xử lí CSS), nó thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Less cùng với các CSS pre-processor khác như [Sass](http://sass-lang.com/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself). + +```css + + +// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS + +/* Comment trên nhiều dòng sẽ được giữ lại */ + + + +/* Biến +==============================*/ + + +/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến. + Sử dụng ký hiệu '@' để khai báo một biến. */ + +@primary-color: #a3a4ff; +@secondary-color: #51527f; +@body-font: 'Roboto', sans-serif; + +/* You can use the variables throughout your stylesheet. + Now if you want to change a color, you only have to make the change once.*/ +/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. + Nhờ sử dụng biến ta chỉ cần thay đổi một lần + tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ + +body { + background-color: @primary-color; + color: @secondary-color; + font-family: @body-font; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ + +body { + background-color: #a3a4ff; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn + việc phải đổi giá trị mỗi lần nó xuất hiện + trong tệp stylesheet. */ + + + +/* Mixins +==============================*/ + + +/* Nếu đang viết một đoạn code cho nhiều hơn một + element, ta có thể sử dụng lại nó dễ dàng. */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Ta có thể dùng mixin chỉ bằng việc thêm selector + vào trong nội dung style của element khác */ + +div { + .center; + background-color: @primary-color; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + +/* You can omit the mixin code from being compiled by adding parenthesis + after the selector */ +/* Ta có thể ngăn không cho code mixin được biên dịch + bằng cách thêm cặp ngoặc tròn đằng sau selector */ + +.center() { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +div { + .center; + background-color: @primary-color; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #a3a4ff; +} + + + +/* Nesting - Lồng +==============================*/ + + +/* Less cho phép ta có thể lồng selector bên trong selector */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #f00; + } +} + +/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&' + với selector cha. */ +/* Ta cũng có thể lồng các pseudo-class với nhau */ +/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì. + Kinh nghiệm cho thấy không nên lồng quá 3 lần. + Ví dụ: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Biên dịch thành: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Function +==============================*/ + + +/* Less cung cấp các function có thể được dùng để hoàn thành + các công việc khác nhau. */ + +/* Function được gọi sử dụng tên của nó và truyền vào + các tham số được yêu cầu. */ + +body { + width: round(10.25px); +} + +.header { + background-color: lighten(#000, 0.5); +} + +.footer { + background-color: fadeout(#000, 0.25) +} + +/* Biên dịch thành: */ + +body { + width: 10px; +} + +.header { + background-color: #010101; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Ta có thể định nghĩa function mới. + Function khá tương tự với mixin bởi chúng đều có thể được tái + sử dụng. Khi lựa chọn giữa việc sử dụng function hay mixin, + hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi + function sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng + xuyên suốt Less code. Các ví dụ trong phần 'Toán tử' là ứng cử viên + sáng giá cho việc dùng function có thể tái sử dụng được. +*/ + +/* Function này tính giá trị trung bình của hai số: */ +.average(@x, @y) { + @average-result: ((@x + @y) / 2); +} + +div { + .average(16px, 50px); // gọi mixin + padding: @average-result; // sử dụng giá trị trả về của mixin +} + +/* Biên dịch thành: */ + +div { + padding: 33px; +} + + + +/* Mở rộng (Thừa kế) +==============================*/ + + +/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */ + +.display { + height: 50px; +} + +.display-success { + &:extend(.display); + border-color: #22df56; +} + +/* Biên dịch thành: */ +.display, +.display-success { + height: 50px; +} +.display-success { + border-color: #22df56; +} + +/* Extending a CSS statement is preferable to creating a mixin + because of the way it groups together the classes that all share + the same base styling. If this was done with a mixin, the properties + would be duplicated for each statement that + called the mixin. While it won't affect your workflow, it will + add unnecessary bloat to the files created by the Less compiler. */ +/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới + bởi cách nó nhóm các lớp có chung một style gốc. + Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp + cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó + tạo ra các đoạn code CSS thừa sau khi được biên dịch. +*/ + + +/* Partials and Imports - Chia nhỏ và nhập vào +==============================*/ + + +/* Less cho phép ta tạo các partial file (tệp con). + Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống. + Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less + và được nhập vào file Less chính để được biên dịch thành CSS */ + +/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Less cung cấp cú pháp @import cho phép nhập các partial vào một file. + Cú pháp này trong Less sẽ nhập các file và kết hợp chúng lại với + code CSS được sinh ra. Nó khác với cú pháp @import của CSS, + bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Biên dịch thành: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Toán học +==============================*/ + + +/* Less cung cấp các toán tử sau: +, -, *, / và %. + Điều này rất có ích cho việc tính toán giá trị trực tiếp + trong tệp Less thay vì phải tính toán thủ công. + Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */ + +@content-area: 960px; +@main-content: 600px; +@sidebar-content: 300px; + +@main-size: @main-content / @content-area * 100%; +@sidebar-size: @sidebar-content / @content-area * 100%; +@gutter: 100% - (@main-size + @sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: @main-size; +} + +.sidebar { + width: @sidebar-size; +} + +.gutter { + width: @gutter; +} + +/* Biên dịch thành: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + +## Tập sử dụng Less + +Nếu bạn cần xài thử Less trên trình duyệt, hãy ghé qua: +* [Codepen](http://codepen.io/) +* [LESS2CSS](http://lesscss.org/less-preview/) + +## Tính tương thích + +Less có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn. + +[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS. + +## Tìm hiểu thêm +* [Tài liệu chính thức](http://lesscss.org/features/) +* [Less CSS - Hướng dẫn cho người mới bắt đầu](http://www.hongkiat.com/blog/less-basic/) \ No newline at end of file -- cgit v1.2.3 From 4d248efdb8a927ebb14c53aa0da5d025838195a6 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Wed, 25 Oct 2017 20:48:16 +0700 Subject: Fixed minor typo for Less translation file --- vi-vn/less-vi.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vi-vn/less-vi.html.markdown b/vi-vn/less-vi.html.markdown index 73940592..f861fb0e 100644 --- a/vi-vn/less-vi.html.markdown +++ b/vi-vn/less-vi.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Saravanan Ganesh", "http://srrvnn.me"] translators: - ["Thanh Duy Phan", "https://github.com/thanhpd"] -filename: learnless-vi.ts +filename: learnless-vi.less lang: vi-vn --- -- cgit v1.2.3 From ab094ff0615d7236be17368b50795adf756f98c0 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Wed, 25 Oct 2017 22:12:24 +0700 Subject: Re-edit Less translation file --- vi-vn/less-vi.html.markdown | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/vi-vn/less-vi.html.markdown b/vi-vn/less-vi.html.markdown index f861fb0e..594ccc31 100644 --- a/vi-vn/less-vi.html.markdown +++ b/vi-vn/less-vi.html.markdown @@ -30,8 +30,6 @@ Less là một CSS pre-processor (bộ tiền xử lí CSS), nó thêm các tín @secondary-color: #51527f; @body-font: 'Roboto', sans-serif; -/* You can use the variables throughout your stylesheet. - Now if you want to change a color, you only have to make the change once.*/ /* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. Nhờ sử dụng biến ta chỉ cần thay đổi một lần tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ @@ -98,8 +96,6 @@ div { background-color: #a3a4ff; } -/* You can omit the mixin code from being compiled by adding parenthesis - after the selector */ /* Ta có thể ngăn không cho code mixin được biên dịch bằng cách thêm cặp ngoặc tròn đằng sau selector */ @@ -275,12 +271,6 @@ div { border-color: #22df56; } -/* Extending a CSS statement is preferable to creating a mixin - because of the way it groups together the classes that all share - the same base styling. If this was done with a mixin, the properties - would be duplicated for each statement that - called the mixin. While it won't affect your workflow, it will - add unnecessary bloat to the files created by the Less compiler. */ /* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới bởi cách nó nhóm các lớp có chung một style gốc. Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp -- cgit v1.2.3 From 838efd36532faf52d631bbc798b284bbc7867479 Mon Sep 17 00:00:00 2001 From: Allwin Baby Panikulam Date: Thu, 26 Oct 2017 01:12:10 +0800 Subject: Fix link to javascript docs --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 44fd791a..10f01ebc 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -9,7 +9,7 @@ TypeScript is a language that aims at easing development of large scale applicat TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. -This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](javascript.html.markdown). +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](/docs/javascript). To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. -- cgit v1.2.3 From ab84fe8cf57d42b78b4a6d441ebd47acc65bd520 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:27:36 -0200 Subject: [c#/pt-br] Small typos --- pt-br/csharp-pt.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..377ac984 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -6,23 +6,23 @@ contributors: lang: pt-br --- -C# é uma linguagem elegante e altamente tipado orientada a objetos que permite aos desenvolvedores criarem uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. +C# é uma linguagem elegante, altamente tipada e orientada a objetos que permite aos desenvolvedores criar uma variedade de aplicações seguras e robustas que são executadas no .NET Framework. -[Read more here.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) +[Leia mais aqui.](http://msdn.microsoft.com/pt-br/library/vstudio/z1zx9t92.aspx) ```c# -// Comentário de linha única começa com // +// Comentários de linha única começam com // /* -Múltipas linhas é desta forma +Comentários de múltiplas linhas são desta forma */ /// -/// Esta é uma documentação comentário XML que pode ser usado para gerar externo -/// documentação ou fornecer ajuda de contexto dentro de um IDE +/// Este é um comentário de documentação XML que pode ser usado para gerar documentação +/// externa ou para fornecer ajuda de contexto dentro de uma IDE /// //public void MethodOrClassOrOtherWithParsableHelp() {} -// Especificar qual namespace seu código irá usar -// Os namespaces a seguir são padrões do .NET Framework Class Library +// Especifica os namespaces que o código irá usar +// Os namespaces a seguir são padrões da biblioteca de classes do .NET Framework using System; using System.Collections.Generic; using System.Dynamic; @@ -33,11 +33,11 @@ using System.IO; // Mas este aqui não é : using System.Data.Entity; -// Para que consiga utiliza-lo, você precisa adicionar novas referências +// Para que consiga utilizá-lo, você precisa adicionar novas referências // Isso pode ser feito com o gerenciador de pacotes NuGet : `Install-Package EntityFramework` -// Namespaces são escopos definidos para organizar o códgo em "pacotes" or "módulos" -// Usando este código a partir de outra arquivo de origem: using Learning.CSharp; +// Namespaces são escopos definidos para organizar o código em "pacotes" ou "módulos" +// Usando este código a partir de outro arquivo de origem: using Learning.CSharp; namespace Learning.CSharp { // Cada .cs deve conter uma classe com o mesmo nome do arquivo -- cgit v1.2.3 From d1b6dda7bd074ba76c0d136d4176f358b0a94adb Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:38:59 -0200 Subject: [java/pt-br] Small typo --- pt-br/java-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index 82989502..1b9d7fc6 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -42,7 +42,7 @@ public class LearnJava { " Double: " + 3.14 + " Boolean: " + true); - // Para imprimir sem inserir uma nova lina, use o System.out.print + // Para imprimir sem inserir uma nova linha, use o System.out.print System.out.print("Olá "); System.out.print("Mundo"); -- cgit v1.2.3 From a246fb409059fce98b5f4ebf6ae17036112ce750 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:42:06 -0200 Subject: [json/pt-br] Small typo --- pt-br/json-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index fd822c03..62d9ccad 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -16,7 +16,7 @@ Como JSON é um formato de intercâmbio de dados, este será, muito provavelment JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade. -Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null. +Um valor JSON pode ser um número, uma string, um array, um objeto, um booleano (true, false) ou null. Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+. -- cgit v1.2.3 From 5a4785cac438809a714a700ad15e09518052c014 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Wed, 25 Oct 2017 23:46:29 -0200 Subject: [javascript/pt-br] Small typo --- pt-br/javascript-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 7b6729ef..ed4a6ff3 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -25,7 +25,7 @@ Feedback são muito apreciados! Você me encontrar em ```js // Comentários são como em C. Comentários de uma linha começam com duas barras, -/* e comentários de múltplas linhas começam com barra-asterisco +/* e comentários de múltiplas linhas começam com barra-asterisco e fecham com asterisco-barra */ // comandos podem ser terminados com ; -- cgit v1.2.3 From 3a41a6006ff421b45ae46a521b900216ac28daf7 Mon Sep 17 00:00:00 2001 From: SmuSmu Date: Thu, 26 Oct 2017 10:15:32 +0200 Subject: html-de.html.markdown removed a Double Point. improved usage part to follow english original --- de-de/html-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/html-de.html.markdown b/de-de/html-de.html.markdown index 2ee18129..0bf58f9c 100644 --- a/de-de/html-de.html.markdown +++ b/de-de/html-de.html.markdown @@ -9,7 +9,7 @@ lang: de-de --- HTML steht für HyperText Markup Language (Hypertext-Auszeichnungssprache). -Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben.. +Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben. Es ist eine Auszeichnugssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien. Was sind das für Auszeichnungen? Es ist eine Methode, um die Daten der Website zu organisieren mithilfe von Start- und Endtags. Diese Auszeichnung dient dazu dem Text Bedeutung zu geben, welchen sie umschließt. @@ -111,7 +111,7 @@ Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben ## Verwendung -HTML Dateien enden mit `.html`. +HTML Dateien enden mit `.html` oder mit `.htm`. Der Mime Typ ist meist `text/html`. ## Um mehr zu lernen -- cgit v1.2.3 From 5670c7381dbffa12b3d2b5e51ac9b8b1c4d9dca1 Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 11:22:40 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..800e3097 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -823,7 +823,7 @@ on a new line! ""Wow!"", the masses cried"; } } - // Interfaces only contain signatures of the members, without the implementation. + // Interfaces contêm apenas as assinaturas dos membros, sem a implementação. interface IJumpable { void Jump(int meters); // all interface members are implicitly public -- cgit v1.2.3 From 9f7322b6208a693a013df81da6b1aadd095b78fd Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 12:39:25 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..3f13f1aa 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -784,7 +784,7 @@ on a new line! ""Wow!"", the masses cried"; } // end class Bicycle - // PennyFarthing is a subclass of Bicycle + // PennyFarthing é uma subclasse de Bicycle class PennyFarthing : Bicycle { // (Penny Farthings are those bicycles with the big front wheel. -- cgit v1.2.3 From b5cac96eff8d92f9fb736d6e3e61d21d771f1e2a Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 12:44:09 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..cc3885d2 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -790,7 +790,7 @@ on a new line! ""Wow!"", the masses cried"; // (Penny Farthings are those bicycles with the big front wheel. // They have no gears.) - // calling parent constructor + // chamando construtor pai public PennyFarthing(int startCadence, int startSpeed) : base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) { -- cgit v1.2.3 From ee3f34379abd8bea7274d024571b8596c6c759d4 Mon Sep 17 00:00:00 2001 From: Fer Date: Thu, 26 Oct 2017 12:47:42 -0200 Subject: [csharp/pt-br] Missing translation --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 547f4817..a1bd980b 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -762,7 +762,7 @@ on a new line! ""Wow!"", the masses cried"; } } - //Method to display the attribute values of this Object. + //Método para exibir os valores dos atributos deste objeto. public virtual string Info() { return "Gear: " + Gear + -- cgit v1.2.3 From 18eb083fb64c77b6cf4aec36686a7058f2b03fdc Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:42:44 -0200 Subject: [css/pt-br] Missing translation --- pt-br/css-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown index b1fbd961..956b3614 100644 --- a/pt-br/css-pt.html.markdown +++ b/pt-br/css-pt.html.markdown @@ -25,7 +25,7 @@ O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais. ```css /* Comentários aparecem dentro do slash-asterisk, tal como esta linha! - não há "comentários de uma linha"; este é o único estilo de comentário * / + Não há "comentários de uma linha"; este é o único estilo de comentário * / /* #################### ## SELETORES -- cgit v1.2.3 From 12d4277200728b24c11da63d069c30ba555ac49c Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:48:09 -0200 Subject: [c++/pt-br] Small typos --- pt-br/c++-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 09bfc825..cd4adde7 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -18,9 +18,9 @@ foi concebida para - suportar programação orientada a objetos - suportar programação genérica -Embora sua sintaxe pode ser mais difícil ou complexa do que as linguagens mais -recentes, C++ é amplamente utilizado porque compila para instruções nativas que -podem ser executadas diretamente pelo processador e oferece um controle rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os +Embora sua sintaxe possa ser mais difícil ou complexa do que as linguagens mais +recentes, C++ é amplamente utilizada porque compila para instruções nativas que +podem ser executadas diretamente pelo processador e oferece um controle rígido sobre o hardware (como C), enquanto oferece recursos de alto nível, como os genéricos, exceções e classes. Esta combinação de velocidade e funcionalidade faz C++ uma das linguagens de programação mais utilizadas. -- cgit v1.2.3 From 469740c35f4059ece40887f881d27705a536e35f Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:51:16 -0200 Subject: [perl/pt-br] Missing translation --- pt-br/perl-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index cc07a2ec..ff01c31a 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -52,7 +52,7 @@ my %fruta_cor = ( banana => "amarelo", ); -# Scalars, arrays and hashes são documentados mais profundamentes em perldata. +# Scalars, arrays and hashes são documentados mais profundamente em perldata. # (perldoc perldata). # Mais tipos de dados complexos podem ser construídas utilizando referências, -- cgit v1.2.3 From e787065d76fdf9eeba2747e3b5baaadd532156da Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:52:52 -0200 Subject: [perl/pt-br] Missing translation --- pt-br/perl-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index cc07a2ec..19a72635 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -55,7 +55,7 @@ my %fruta_cor = ( # Scalars, arrays and hashes são documentados mais profundamentes em perldata. # (perldoc perldata). -# Mais tipos de dados complexos podem ser construídas utilizando referências, +# Mais tipos de dados complexos podem ser construídos utilizando referências, # o que permite que você crie listas e hashes dentro de listas e hashes. #### Condicionais e construtores de iteração -- cgit v1.2.3 From adb4fb69ad4554665d9708ca3e82b22464dbb98f Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Thu, 26 Oct 2017 13:55:43 -0200 Subject: [perl/pt-br] Missing translation --- pt-br/perl-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index cc07a2ec..c1e6e76f 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -21,7 +21,7 @@ Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada # Variáveis iniciam com um sigilo, que é um símbolo que mostra o tipo. # Um nome de variável válido começa com uma letra ou sublinhado, -# seguido por qualquer número de letras, números ou sublinhados. +# seguido por qualquer quantidade de letras, números ou sublinhados. ### Perl has three main variable types: $scalar, @array, e %hash. -- cgit v1.2.3 From 1569318bdcfea0c486cd2fa6a374446fe6ae02c0 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Thu, 26 Oct 2017 14:11:13 -0200 Subject: [c++/pt-br] Small typos --- pt-br/c-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index c0cfb0ba..0dca7ab0 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -182,7 +182,7 @@ int main() { int a, b, c; a = b = c = 0; - // Aritimética é óbvia + // Aritmética é óbvia i1 + i2; // => 3 i2 - i1; // => 1 i2 * i1; // => 2 -- cgit v1.2.3 From 189336c674856a036112b9b32a6254b07aa6aa75 Mon Sep 17 00:00:00 2001 From: daniloyamauti <33129352+daniloyamauti@users.noreply.github.com> Date: Thu, 26 Oct 2017 14:21:20 -0200 Subject: [visualbasic/pt-br] Small typos --- pt-br/visualbasic-pt.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown index 76cca567..b94ab609 100644 --- a/pt-br/visualbasic-pt.html.markdown +++ b/pt-br/visualbasic-pt.html.markdown @@ -15,9 +15,9 @@ module Module1 Sub Main () ' Uma visão geral de console de aplicativos do Visual Basic antes de - ' mergulharmos mais profundamente na linguagem + ' mergulharmos mais profundamente na linguagem. ' Aspas simples começam comentários. - ' Para Navegar este tutorial dentro do compilador do Visual Basic, + ' Para navegar neste tutorial dentro do compilador do Visual Basic, ' eu criei um sistema de navegação. ' Este sistema de navegação vai ser explicado conforme avançarmos no ' tutorial, e você vai entender o que isso significa. @@ -93,16 +93,16 @@ module Module1 Private Sub HelloWorldInput () Console.Title = " Olá Mundo YourName | Saiba X em Y Minutes" ' Variáveis - 'Os dados inseridos por um usuário precisa ser armazenada . + 'Os dados inseridos por um usuário precisam ser armazenados. ' As variáveis ​​também começar com um Dim e terminar com um Como VariableType . - ' Neste tutorial, nós queremos saber o que o seu nome, e faça o programa + ' Neste tutorial, nós queremos saber qual é o seu nome, e faça o programa ' Responder ao que é dito. Nome de usuário Dim As String " Nós usamos string como string é uma variável de texto baseado . Console.WriteLine (" Olá, Qual é o seu nome? ") ' Peça ao usuário seu nome. - username = Console.ReadLine () ' armazena o nome usuários. - Console.WriteLine (" Olá " + nome do usuário) " A saída é Olá ' Seu nome ' + username = Console.ReadLine () ' armazena o nome do usuário. + Console.WriteLine (" Olá " + username) ' A saída é "Olá < seu nome >". Console.ReadLine () ' Outsputs acima. ' O código acima irá lhe fazer uma pergunta seguiu imprimindo sua resposta. " Outras variáveis ​​incluem Integer e usamos inteiro para números inteiros. -- cgit v1.2.3 From 6d836a9fda6ea007d3393799c83f3f12df91affb Mon Sep 17 00:00:00 2001 From: ksami Date: Fri, 27 Oct 2017 14:27:14 +0800 Subject: Add more c#7 features Added pattern matching, reference locals and local functions under c#7 features --- csharp.html.markdown | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 3790747c..f27adf18 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1213,6 +1213,85 @@ namespace Csharp7 Console.WriteLine(tt.GetLastName()); } } + + // PATTERN MATCHING + class PatternMatchingTest + { + public static (string, int)? CreateLogMessage(object data) + { + switch(data) + { + // Additional filtering using when + case System.Net.Http.HttpRequestException h when h.Message.Contains("404"): + return (h.Message, 404); + case System.Net.Http.HttpRequestException h when h.Message.Contains("400"): + return (h.Message, 400); + case Exception e: + return (e.Message, 500); + case string s: + return (s, s.Contains("Error") ? 500 : 200); + case null: + return null; + default: + return (data.ToString(), 500); + } + } + } + + // REFERENCE LOCALS + // Allow you to return a reference to an object instead of just its value + class RefLocalsTest + { + // note ref in return + public static ref string FindItem(string[] arr, string el) + { + for(int i=0; i apple + } + } + + // LOCAL FUNCTIONS + class LocalFunctionTest + { + private static int _id = 0; + public int id; + public LocalFunctionTest() + { + id = generateId(); + + // This local function can only be accessed in this scope + int generateId() + { + return _id++; + } + } + + public static void AnotherMethod() + { + var lf1 = new LocalFunctionTest(); + var lf2 = new LocalFunctionTest(); + Console.WriteLine($"{lf1.id}, {lf2.id}"); // => 0, 1 + + int id = generateId(); + // error CS0103: The name 'generateId' does not exist in the current context + } + } } ``` -- cgit v1.2.3 From 5a9f042ea544776b9d1b94bdb02326006c199b72 Mon Sep 17 00:00:00 2001 From: Julien M'Poy Date: Fri, 27 Oct 2017 09:51:28 +0200 Subject: Corrected french mistakes --- fr-fr/php.html.markdown | 84 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 64 insertions(+), 20 deletions(-) diff --git a/fr-fr/php.html.markdown b/fr-fr/php.html.markdown index 823630bd..d001f1d4 100644 --- a/fr-fr/php.html.markdown +++ b/fr-fr/php.html.markdown @@ -6,11 +6,14 @@ contributors: - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["Pascal Boutin", "http://pboutin.net/"] + - ["Julien M'Poy", "https://github.com/groovytron"] lang: fr-fr --- This document describes PHP 5+. +Ce document décrit PHP 5+. + ```php // Le code PHP doit être placé à l'intérieur de balises ' '$String' // Évitez les guillemets sauf pour inclure le contenu d'une autre variable -$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' +$dbl_quotes = "Ceci est une $sgl_quotes."; // => 'Ceci est une $String.' // Les caractères spéciaux sont seulement échappés avec des guillemets -$escaped = "This contains a \t tab character."; -$unescaped = 'This just contains a slash and a t: \t'; +$escaped = "Ceci contient \t une tabulation."; +$unescaped = 'Ceci contient juste un slash et un t: \t'; // En cas de besoin, placez la variable dans des accolades -$money = "I have $${number} in the bank."; +$money = "J'ai $${number} sur mon compte en banque."; // Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes // multi-lignes non-interprétées $nowdoc = <<<'END' -Multi line -string +String +mutli-lignes END; // Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées $heredoc = << 'Cette string est concaténée' /******************************** @@ -122,7 +125,7 @@ echo 'This string ' . 'is concatenated'; define("FOO", "something"); // on peut accéder à une constante en utilisant directement son nom -echo 'This outputs '.FOO; +echo 'Ceci affiche ' . FOO; /******************************** @@ -149,6 +152,14 @@ $array[] = 'Four'; // Retrait d'un élément du tableau unset($array[3]); +// Depuis PHP 7, il est possible de déclarer des tableaux constants en +// utilisant 'define'. +define('ANIMAUX', [ + 'chien', + 'chat', + 'oiseau', +]); + /******************************** * Affichage */ @@ -159,11 +170,13 @@ echo('Hello World!'); print('Hello World!'); // Pareil à "écho" -// Pour écho, vous n'avez pas besoin des parenthèses +// 'echo' et 'print' sont des language constructs. +// Il n'ont pas besoin de parenthèses car ils sont traités comme +// des opérateurs unaires. echo 'Hello World!'; -print 'Hello World!'; // Pour print non plus +print 'Hello World!'; -$paragraph = 'paragraph'; +$paragraph = 'paragraphe'; echo 100; // Affichez un scalaire directement echo $paragraph; // ou des variables @@ -202,7 +215,8 @@ $b = '0'; $c = '1'; $d = '1'; -// assert affiche un avertissement dans son argument n'est pas vrai +// assert affiche un avertissement quand l'expression booléenne passée +// en argument n'est pas vraie. // Ces comparaisons vont toujours être vraies, même si leurs // types ne sont pas les mêmes. @@ -315,7 +329,7 @@ if ($x === '0') { switch ($x) { case '0': print 'Les switch font du transtypage implicite'; - break; // Il est important de déclaré un 'break', sinon les cas + break; // Il est important de déclarer un 'break', sinon les cas // 'two' et 'three' seront évalués case 'two': case 'three': @@ -390,9 +404,10 @@ function my_function () { echo my_function(); // => "Hello" -// Les noms de fonction débutent par le symbole $ -// Un nom de variable valide commence par une lettre ou un souligné, +// Un nom de fonction valide commence par une lettre ou un souligné, // suivi de n'importe quelle lettre, nombre ou de soulignés. +// Les noms des arguments d'une fonction doivent respecter le même format que +// celui des variables. function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1 $result = $x + $y; @@ -519,7 +534,7 @@ class MyClass public static function myStaticMethod() { - print 'I am static'; + print 'Je suis static'; } } @@ -527,7 +542,7 @@ class MyClass echo MyClass::MY_CONST; // Outputs 'value'; echo MyClass::$staticVar; // Retourne 'static'; -MyClass::myStaticMethod(); // Retourne 'I am static'; +MyClass::myStaticMethod(); // Retourne 'Je suis static'; // On peut instancier une classe en utilisant le mot clé 'new' $my_class = new MyClass('An instance property'); @@ -584,7 +599,7 @@ echo $x->property; // Va utiliser la méthode __get() $x->property = 'Something'; // Va utiliser la méthode __set() // Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou -// elle peuvent implémenter une interface (en utilisant le mot clé 'implement'). +// elle peuvent implémenter une interface (en utilisant le mot clé 'implements'). // Une interface peut être déclarée avec le mot clé 'interface' @@ -637,6 +652,35 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo } } +// Il est possible de déclarer des classes internes anonymes depuis PHP 7 + +interface Logger { + public function log(string $msg); +} + +class Application { + private $logger; + + public function getLogger(): Logger { + return $this->logger; + } + + public function setLogger(Logger $logger) { + $this->logger = $logger; + } +} + +$app = new Application; + +$app->setLogger(new class implements Logger { + public function log(string $msg) { + echo $msg; + } +}); + +var_dump($app->getLogger()); // => 'object(class@anonymous)#2 (0) {}' + + /******************************** * Espaces de noms (namespaces) */ -- cgit v1.2.3 From c14dc8fd1d0f04b90c9e5195bb21acc88f90e05b Mon Sep 17 00:00:00 2001 From: Fer Date: Fri, 27 Oct 2017 07:55:22 -0200 Subject: Update csharp-pt.html.markdown --- pt-br/csharp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 800e3097..a6e82211 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -826,7 +826,7 @@ on a new line! ""Wow!"", the masses cried"; // Interfaces contêm apenas as assinaturas dos membros, sem a implementação. interface IJumpable { - void Jump(int meters); // all interface members are implicitly public + void Jump(int meters); // todos os membros da interface são implicitamente públicos } interface IBreakable -- cgit v1.2.3 From e063c7ef3556cc3b8fc2515a8175474461c83a2d Mon Sep 17 00:00:00 2001 From: Fer Date: Fri, 27 Oct 2017 08:03:05 -0200 Subject: Update csharp-pt.html.markdown --- pt-br/csharp-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown index 3f13f1aa..8d34d772 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -787,8 +787,8 @@ on a new line! ""Wow!"", the masses cried"; // PennyFarthing é uma subclasse de Bicycle class PennyFarthing : Bicycle { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) + // (Penny Farthings são aquelas bicicletas com uma grande roda frontal. + // Elas não tem correias.) // calling parent constructor public PennyFarthing(int startCadence, int startSpeed) : -- cgit v1.2.3 From 7466732d20bc605d3c5aa8a504d2129ef26acf5a Mon Sep 17 00:00:00 2001 From: thanhpd Date: Fri, 27 Oct 2017 17:43:16 +0700 Subject: Added Vietnamese translation for Sass language --- vi-vn/sass-vi.html.markdown | 590 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 590 insertions(+) create mode 100644 vi-vn/sass-vi.html.markdown diff --git a/vi-vn/sass-vi.html.markdown b/vi-vn/sass-vi.html.markdown new file mode 100644 index 00000000..313890d4 --- /dev/null +++ b/vi-vn/sass-vi.html.markdown @@ -0,0 +1,590 @@ +--- +language: sass +filename: learnsass-vi.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] + - ["Keith Miyake", "https://github.com/kaymmm"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Less là một ngôn ngữ mở rộng CSS/ CSS pre-processor, thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Sass cùng với các CSS pre-processor khác như [Less](http://lesscss.org/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself). + +Sass có hai lựa chọn sử dụng cú pháp khác nhau. Một là SCSS, sử dụng cú pháp giống như CSS nhưng bổ sung thêm các tính năng của Sass. Hai là Sass (cú pháp nguyên bản), sử dụng thụt đầu dòng - indention thay vì ngoặc nhọn và dấu chấm phẩy. +Bài hướng dẫn này sử dụng SCSS. + +Nếu bạn đọc đã quen thuộc với CSS3 thì sẽ tương đối nhanh chóng để nắm được Sass. Nó không cung cấp thuộc tính để style CSS mới nhưng đưa ra những công cụ để có thể viết CSS hiệu quả hơn và có thể bảo trì dễ dàng hơn. + +```sass + + +// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS + +/* Comment trên nhiều dòng sẽ được giữ lại */ + + + +/* Variable - Biến +============================== */ + + + +/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến. + Sử dụng ký hiệu '$' để khai báo một biến. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. + Nhờ sử dụng biến ta chỉ cần thay đổi một lần + tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + +/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn + việc phải đổi giá trị mỗi lần nó xuất hiện + trong tệp stylesheet. */ + + + +/* Control Directive - Chỉ thị +============================== */ + + +/* Sass cho phép sử dụng @if, @else, @for, @while và @each để quản lý luồng code sinh ra CSS */ + +/* Khối điều kiện @if/@else hoạt động như các ngôn ngữ khác */ + +$debug: true !default; + +@mixin debugmode { + @if $debug { + @debug "Debug mode enabled"; + + display: inline-block; + } + @else { + display: none; + } +} + +.info { + @include debugmode; +} + +/* Trong đoạn code trên, nếu $debug được đặt là true thì class .info sẽ được sinh ra và ngược lại. + Lưu ý: @debug sẽ sinh ra thông tin debug trên dòng lệnh (command line). + Chế độ này rất có ích khi thực hiện debug trên file SCSS. */ + +.info { + display: inline-block; +} + +/* @for là khối vòng lặp trên một khoảng các giá trị. + Nó rất có ích cho việc đặt style của một tập hợp các phần tử. + Có hai cách để lặp, "through" sẽ lặp tới kể cả giá trị cuối cùng, "to" sẽ lặp tới và dừng khi đến giá trị cuối cùng. */ + +// Lặp 3 lần (không kể 4) +@for $c from 1 to 4 { + div:nth-of-type(#{$c}) { + left: ($c - 1) * 900 / 3; + } +} + +// Lặp 3 lần (kể cả 3) +@for $c from 1 through 3 { + .myclass-#{$c} { + color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3); + } +} + +/* Biên dịch thành */ + +div:nth-of-type(1) { + left: 0; +} + +div:nth-of-type(2) { + left: 300; +} + +div:nth-of-type(3) { + left: 600; +} + +.myclass-1 { + color: #555555; +} + +.myclass-2 { + color: #aaaaaa; +} + +.myclass-3 { + color: white; +// SASS tự động chuyển mã #FFFFFF thành white (trắng) +} + +/* Khối lặp @while rất cơ bản: */ + +$columns: 4; +$column-width: 80px; + +@while $columns > 0 { + .col-#{$columns} { + width: $column-width; + left: $column-width * ($columns - 1); + } + + $columns: $columns - 1; +} + +/* Sẽ được biên dịch thành: */ + +.col-4 { + width: 80px; + left: 240px; +} + +.col-3 { + width: 80px; + left: 160px; +} + +.col-2 { + width: 80px; + left: 80px; +} + +.col-1 { + width: 80px; + left: 0px; +} + +/* @each hoạt động giống như @for, nhưng sử dụng một danh sách (list) thay vì thứ tự số đếm. + List được khai báo như những biến khác, sử dụng dấu cách để làm dấu phân cách. */ + +$social-links: facebook twitter linkedin reddit; + +.social-links { + @each $sm in $social-links { + .icon-#{$sm} { + background-image: url("images/#{$sm}.png"); + } + } +} + +/* Sẽ sinh ra: */ + +.social-links .icon-facebook { + background-image: url("images/facebook.png"); +} + +.social-links .icon-twitter { + background-image: url("images/twitter.png"); +} + +.social-links .icon-linkedin { + background-image: url("images/linkedin.png"); +} + +.social-links .icon-reddit { + background-image: url("images/reddit.png"); +} + + +/* Mixin +==============================*/ + +/* Nếu đang viết một đoạn code cho nhiều hơn một + element, ta có thể sử dụng lại nó dễ dàng. + Sử dụng cú pháp '@mixin' kèm theo tên để tạo một mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Ta có thể dùng mixin bằng cú pháp '@include' kèm theo tên của mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Được biên dịch thành: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + +/* Ta có thể dùng mixin để tạo nhanh các thuộc tính. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Trong ví dụ này ta có thể tạo nhanh 2 thuộc tính width và height + bằng cách sử dụng mixin size và truyền vào tham số cho width và height. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Biên dịch thành: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Function - Hàm +============================== */ + + + +/* Less cung cấp các hàm có thể được dùng để hoàn thành + các công việc khác nhau. */ + +/* Hàm được gọi sử dụng tên của nó và truyền vào + các tham số được yêu cầu. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25); +} + +/* Biên dịch thành: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Ta có thể định nghĩa hàm mới. + hàm khá tương tự với mixin bởi chúng đều có thể được tái + sử dụng. Khi lựa chọn giữa việc sử dụng hàm hay mixin, + hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi + hàm sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng + xuyên suốt Less code. Các ví dụ trong phần 'Toán tử toán học' là ứng cử viên + sáng giá cho việc dùng hàm có thể tái sử dụng được. +*/ + +/* Hàm này sẽ tính độ tương đối giữa hai giá trị kích thước. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Biên dịch thành: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Mở rộng (Thừa kế) +============================== */ + + + +/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Biên dịch thành: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới + bởi cách nó nhóm các lớp có chung một style gốc. + Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp + cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó + tạo ra các đoạn code CSS thừa sau khi được biên dịch. +*/ + + + +/* Nesting - Lồng +============================== */ + + + +/* Sass cho phép ta có thể lồng selector bên trong selector */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&' + với selector cha. */ +/* Ta cũng có thể lồng các pseudo-class với nhau */ +/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì. + Kinh nghiệm cho thấy không nên lồng quá 3 lần. + Ví dụ: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Biên dịch thành: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials and Imports - Chia nhỏ thành tệp con và nhập vào +============================== */ + + +/* Less cho phép ta tạo các partial file (tệp con). + Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống. + Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less + và được nhập vào file Less chính để được biên dịch thành CSS. + File con không được biên dịch thành file CSS riêng. */ + +/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass cung cấp cú pháp @import cho phép nhập các partial vào một file. + Cú pháp này trong Sass sẽ nhập các file và kết hợp chúng lại với + code CSS được sinh ra. Nó khác với cú pháp @import của CSS, + bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Biên dịch thành: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Placeholder Selectors - Selector trống +============================== */ + + + +/* Khai báo trống rất hữu dụng khi ta cần tạo một khai báo CSS cần được mở rộng. + Nếu bạn cần tạo một khai báo CSS gốc cho các lần mở rộng sau ta có thể + sử dụng một khai báo trống. Khai báo trống bắt đầu với kí tự '$' thay vì + sử dụng '.' hay '#'. Khai báo trống sẽ không xuất hiện trong code CSS được biên dịch. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Biên dịch thành: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Toán tử toán học +============================== */ + + + +/* Sass cung cấp các toán tử sau: +, -, *, / và %. + Điều này rất có ích cho việc tính toán giá trị trực tiếp + trong tệp Sass thay vì phải tính toán thủ công. + Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Biên dịch thành: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS hay Sass? +Bạn đã bao giờ thắc mắc liệu Sass có phải là từ viết tắt hay không? Nhiều nguwòi lầm tưởng nó là từ viết tắt nhưng thực chất tên của ngôn ngữ này lại là một từ - Sass. +Do sự lầm tưởng như vậy và mọi người thường xuyên viết nó là "SASS", người sáng lập ra ngôn ngữ này đã đặt một cái tên hài hước cho nó là "Syntactically Awesome StyleSheets" (Thiết lập style có cú pháp một cách tuyệt vời đáng kinh ngạc). + + +## Tập sử dụng Sass +Nếu bạn muốn thử dùng Sass trên trình duyệt, hãy ghé qua [SassMeister](http://sassmeister.com/). Bạn có thể dùng cả hai cú pháp, hoặc mở cài đặt và chọn Sass hoặc SCSS. + +## Tính tương thích +Sass có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn. + +[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS. + + +## Tìm hiểu thêm +* [Tài liệu chính thức](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) cung cấp các hướng dẫn từ cơ bản đến nâng cao cùng với các tin tức. -- cgit v1.2.3 From 5a511b6e3c26d3f60fdd217c401b7c5983629838 Mon Sep 17 00:00:00 2001 From: thanhpd Date: Fri, 27 Oct 2017 17:43:16 +0700 Subject: Added Vietnamese translation for Sass language --- vi-vn/sass-vi.html.markdown | 590 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 590 insertions(+) create mode 100644 vi-vn/sass-vi.html.markdown diff --git a/vi-vn/sass-vi.html.markdown b/vi-vn/sass-vi.html.markdown new file mode 100644 index 00000000..313890d4 --- /dev/null +++ b/vi-vn/sass-vi.html.markdown @@ -0,0 +1,590 @@ +--- +language: sass +filename: learnsass-vi.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] + - ["Keith Miyake", "https://github.com/kaymmm"] +translators: + - ["Thanh Duy Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Less là một ngôn ngữ mở rộng CSS/ CSS pre-processor, thêm các tính năng như biến (variable), lồng (nesting), mixin và nhiều thứ khác. Sass cùng với các CSS pre-processor khác như [Less](http://lesscss.org/) giúp lập trình viên viết được các đoạn CSS bảo trì được và không bị lặp lại (DRY - Don't Repeat Yourself). + +Sass có hai lựa chọn sử dụng cú pháp khác nhau. Một là SCSS, sử dụng cú pháp giống như CSS nhưng bổ sung thêm các tính năng của Sass. Hai là Sass (cú pháp nguyên bản), sử dụng thụt đầu dòng - indention thay vì ngoặc nhọn và dấu chấm phẩy. +Bài hướng dẫn này sử dụng SCSS. + +Nếu bạn đọc đã quen thuộc với CSS3 thì sẽ tương đối nhanh chóng để nắm được Sass. Nó không cung cấp thuộc tính để style CSS mới nhưng đưa ra những công cụ để có thể viết CSS hiệu quả hơn và có thể bảo trì dễ dàng hơn. + +```sass + + +// Comment (chú thích) một dòng sẽ bị xóa khi Less được biên dịch thành CSS + +/* Comment trên nhiều dòng sẽ được giữ lại */ + + + +/* Variable - Biến +============================== */ + + + +/* Ta có thể lưu giá trị CSS (ví dụ như color) vào một biến. + Sử dụng ký hiệu '$' để khai báo một biến. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Sau khi khai báo biến, ta có thể sử dụng nó ở trong tệp stylesheet. + Nhờ sử dụng biến ta chỉ cần thay đổi một lần + tại 1 nơi để thay đổi tất cả những đoạn sử dụng biến */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Đoạn code trên sẽ được biên dịch thành: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + +/* Cách sử dụng này giúp ta dễ dàng bảo trì hơn + việc phải đổi giá trị mỗi lần nó xuất hiện + trong tệp stylesheet. */ + + + +/* Control Directive - Chỉ thị +============================== */ + + +/* Sass cho phép sử dụng @if, @else, @for, @while và @each để quản lý luồng code sinh ra CSS */ + +/* Khối điều kiện @if/@else hoạt động như các ngôn ngữ khác */ + +$debug: true !default; + +@mixin debugmode { + @if $debug { + @debug "Debug mode enabled"; + + display: inline-block; + } + @else { + display: none; + } +} + +.info { + @include debugmode; +} + +/* Trong đoạn code trên, nếu $debug được đặt là true thì class .info sẽ được sinh ra và ngược lại. + Lưu ý: @debug sẽ sinh ra thông tin debug trên dòng lệnh (command line). + Chế độ này rất có ích khi thực hiện debug trên file SCSS. */ + +.info { + display: inline-block; +} + +/* @for là khối vòng lặp trên một khoảng các giá trị. + Nó rất có ích cho việc đặt style của một tập hợp các phần tử. + Có hai cách để lặp, "through" sẽ lặp tới kể cả giá trị cuối cùng, "to" sẽ lặp tới và dừng khi đến giá trị cuối cùng. */ + +// Lặp 3 lần (không kể 4) +@for $c from 1 to 4 { + div:nth-of-type(#{$c}) { + left: ($c - 1) * 900 / 3; + } +} + +// Lặp 3 lần (kể cả 3) +@for $c from 1 through 3 { + .myclass-#{$c} { + color: rgb($c * 255 / 3, $c * 255 / 3, $c * 255 / 3); + } +} + +/* Biên dịch thành */ + +div:nth-of-type(1) { + left: 0; +} + +div:nth-of-type(2) { + left: 300; +} + +div:nth-of-type(3) { + left: 600; +} + +.myclass-1 { + color: #555555; +} + +.myclass-2 { + color: #aaaaaa; +} + +.myclass-3 { + color: white; +// SASS tự động chuyển mã #FFFFFF thành white (trắng) +} + +/* Khối lặp @while rất cơ bản: */ + +$columns: 4; +$column-width: 80px; + +@while $columns > 0 { + .col-#{$columns} { + width: $column-width; + left: $column-width * ($columns - 1); + } + + $columns: $columns - 1; +} + +/* Sẽ được biên dịch thành: */ + +.col-4 { + width: 80px; + left: 240px; +} + +.col-3 { + width: 80px; + left: 160px; +} + +.col-2 { + width: 80px; + left: 80px; +} + +.col-1 { + width: 80px; + left: 0px; +} + +/* @each hoạt động giống như @for, nhưng sử dụng một danh sách (list) thay vì thứ tự số đếm. + List được khai báo như những biến khác, sử dụng dấu cách để làm dấu phân cách. */ + +$social-links: facebook twitter linkedin reddit; + +.social-links { + @each $sm in $social-links { + .icon-#{$sm} { + background-image: url("images/#{$sm}.png"); + } + } +} + +/* Sẽ sinh ra: */ + +.social-links .icon-facebook { + background-image: url("images/facebook.png"); +} + +.social-links .icon-twitter { + background-image: url("images/twitter.png"); +} + +.social-links .icon-linkedin { + background-image: url("images/linkedin.png"); +} + +.social-links .icon-reddit { + background-image: url("images/reddit.png"); +} + + +/* Mixin +==============================*/ + +/* Nếu đang viết một đoạn code cho nhiều hơn một + element, ta có thể sử dụng lại nó dễ dàng. + Sử dụng cú pháp '@mixin' kèm theo tên để tạo một mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Ta có thể dùng mixin bằng cú pháp '@include' kèm theo tên của mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Được biên dịch thành: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + +/* Ta có thể dùng mixin để tạo nhanh các thuộc tính. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Trong ví dụ này ta có thể tạo nhanh 2 thuộc tính width và height + bằng cách sử dụng mixin size và truyền vào tham số cho width và height. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Biên dịch thành: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Function - Hàm +============================== */ + + + +/* Less cung cấp các hàm có thể được dùng để hoàn thành + các công việc khác nhau. */ + +/* Hàm được gọi sử dụng tên của nó và truyền vào + các tham số được yêu cầu. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25); +} + +/* Biên dịch thành: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Ta có thể định nghĩa hàm mới. + hàm khá tương tự với mixin bởi chúng đều có thể được tái + sử dụng. Khi lựa chọn giữa việc sử dụng hàm hay mixin, + hãy nhớ mixin được tối ưu cho việc tạo ra CSS trong khi + hàm sẽ được sử dụng tốt hơn cho logic sẽ được sử dụng + xuyên suốt Less code. Các ví dụ trong phần 'Toán tử toán học' là ứng cử viên + sáng giá cho việc dùng hàm có thể tái sử dụng được. +*/ + +/* Hàm này sẽ tính độ tương đối giữa hai giá trị kích thước. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Biên dịch thành: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Mở rộng (Thừa kế) +============================== */ + + + +/* Mở rộng là cách để chia sẻ thuộc tính của một selector cho selector khác */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Biên dịch thành: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Nên mở rộng một khai báo CSS có trước thay vì tạo một mixin mới + bởi cách nó nhóm các lớp có chung một style gốc. + Nếu thực hiện với mixin, các thuộc tính sẽ bị trùng lặp + cho mỗi khai báo có sử dụng mixin. Mặc dù không ảnh hưởng đến luồng công việc nhưng nó + tạo ra các đoạn code CSS thừa sau khi được biên dịch. +*/ + + + +/* Nesting - Lồng +============================== */ + + + +/* Sass cho phép ta có thể lồng selector bên trong selector */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* Selector bắt đầu bằng ký tự '&' sẽ thay thế ký tự '&' + với selector cha. */ +/* Ta cũng có thể lồng các pseudo-class với nhau */ +/* Nên lưu ý không nên lồng quá nhiều lần sẽ làm code kém tính bảo trì. + Kinh nghiệm cho thấy không nên lồng quá 3 lần. + Ví dụ: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Biên dịch thành: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials and Imports - Chia nhỏ thành tệp con và nhập vào +============================== */ + + +/* Less cho phép ta tạo các partial file (tệp con). + Sử dụng nó giúp ta có thể tổ chức code Less theo mô-đun có hệ thống. + Các tệp con thường bắt đầu với ký tự gạch dưới '_', vd: _reset.less + và được nhập vào file Less chính để được biên dịch thành CSS. + File con không được biên dịch thành file CSS riêng. */ + +/* Quan sát ví dụ sau, ta sẽ đặt đoạn code dưới đây vào tệp tên là _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass cung cấp cú pháp @import cho phép nhập các partial vào một file. + Cú pháp này trong Sass sẽ nhập các file và kết hợp chúng lại với + code CSS được sinh ra. Nó khác với cú pháp @import của CSS, + bản chất là tạo một HTTP request mới để tải về tệp tin được yêu cầu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Biên dịch thành: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Placeholder Selectors - Selector trống +============================== */ + + + +/* Khai báo trống rất hữu dụng khi ta cần tạo một khai báo CSS cần được mở rộng. + Nếu bạn cần tạo một khai báo CSS gốc cho các lần mở rộng sau ta có thể + sử dụng một khai báo trống. Khai báo trống bắt đầu với kí tự '$' thay vì + sử dụng '.' hay '#'. Khai báo trống sẽ không xuất hiện trong code CSS được biên dịch. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Biên dịch thành: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Toán tử toán học +============================== */ + + + +/* Sass cung cấp các toán tử sau: +, -, *, / và %. + Điều này rất có ích cho việc tính toán giá trị trực tiếp + trong tệp Sass thay vì phải tính toán thủ công. + Dưới đây là ví dụ về việc tạo một khung thiết kế đơn giản có hai cột. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Biên dịch thành: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS hay Sass? +Bạn đã bao giờ thắc mắc liệu Sass có phải là từ viết tắt hay không? Nhiều nguwòi lầm tưởng nó là từ viết tắt nhưng thực chất tên của ngôn ngữ này lại là một từ - Sass. +Do sự lầm tưởng như vậy và mọi người thường xuyên viết nó là "SASS", người sáng lập ra ngôn ngữ này đã đặt một cái tên hài hước cho nó là "Syntactically Awesome StyleSheets" (Thiết lập style có cú pháp một cách tuyệt vời đáng kinh ngạc). + + +## Tập sử dụng Sass +Nếu bạn muốn thử dùng Sass trên trình duyệt, hãy ghé qua [SassMeister](http://sassmeister.com/). Bạn có thể dùng cả hai cú pháp, hoặc mở cài đặt và chọn Sass hoặc SCSS. + +## Tính tương thích +Sass có thể được dùng trong bất kì dự án nào miễn là ta có chương trình để biên dịch nó thành CSS. Ta cần chắc chắn rằng đoạn CSS đang dùng tương thích với các phiên bản trình duyệt mong muốn. + +[QuirksMode CSS](http://www.quirksmode.org/css/) và [CanIUse](http://caniuse.com) là nguồn thông tin tin cậy để kiểm tra tính tương thích của mã CSS. + + +## Tìm hiểu thêm +* [Tài liệu chính thức](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) cung cấp các hướng dẫn từ cơ bản đến nâng cao cùng với các tin tức. -- cgit v1.2.3 From 8f803122808e802b8bc0bf7b2ecb057207c5f46f Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:42:44 +0200 Subject: copy into docker --- .ansible.html.markdown.swl | Bin 0 -> 36864 bytes .ansible.html.markdown.swm | Bin 0 -> 32768 bytes .ansible.html.markdown.swn | Bin 0 -> 61440 bytes ansible.html.markdown | 32 ++++++++++++++++++++++++++++++-- 4 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 .ansible.html.markdown.swl create mode 100644 .ansible.html.markdown.swm create mode 100644 .ansible.html.markdown.swn diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl new file mode 100644 index 00000000..94a17a7d Binary files /dev/null and b/.ansible.html.markdown.swl differ diff --git a/.ansible.html.markdown.swm b/.ansible.html.markdown.swm new file mode 100644 index 00000000..ff91c7a0 Binary files /dev/null and b/.ansible.html.markdown.swm differ diff --git a/.ansible.html.markdown.swn b/.ansible.html.markdown.swn new file mode 100644 index 00000000..25fce1a6 Binary files /dev/null and b/.ansible.html.markdown.swn differ diff --git a/ansible.html.markdown b/ansible.html.markdown index e41d1a6a..53ea153f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -178,7 +178,7 @@ user@host:~/$ cd ansible-for-learnXinYminutes user@host:~/ansible-for-learnXinYminutes$ source environment.sh $ $ # First lets execute the simple_playbook.yml -(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbook/simple_playbook.yml +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/simple_playbook.yml ``` @@ -186,7 +186,7 @@ Run the above playbook with roles example ```bash $ source environment.sh $ # Now we would run the above playbook with roles -(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/role_example.yml +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/simple_role.yml ``` #### Role directory structure: @@ -206,6 +206,15 @@ roles/ Handlers are a tasks that can be triggered (notified) during execution of a playbook, but they itself execute at the very end of a playbook. It is a best way to restart a service, check if application port is active (successfull deployment criteria), etc. +Please get familiar how you can use role in simple_apache_role example +``` +playbooks/roles/simple_apache_role/ +├── tasks +│   └── main.yml +└── templates + └── main.yml +``` + ### ansible - variables Ansible is flexible - it has 21 levels of variable precedence @@ -223,11 +232,29 @@ You should also know, that a nice way to pool some data is a **lookup** * stream * etcd +```bash +# read playbooks/lookup.yml +# run +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/lookup.yml +``` + You can use them in CLI too ```yaml ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "date") }}"' localhost ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe", "hostname") }}"' all +# Or use in playbook + +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/lookup.yml + +``` + +### Register +Another way to dynamicaly generate the variable content is a `register` command +`Register` is also useful to store an output of a task, and use it's value as a logic +for execution further tasks. +``` +(venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/register_and_when.yml ``` ### Templates @@ -259,6 +286,7 @@ Junja is powerfull. It has built-in many usefull functions. # if variable is undefined - use default value {{ some_variable | default('default_value') }} ``` +### ansible - tags, limmit, diff, check_mode ### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. -- cgit v1.2.3 From c56a644fb3a9acc0687746f3dfd34be0dc1408d9 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:55:16 +0200 Subject: copy into docker --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 55 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 94a17a7d..4664ca70 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 53ea153f..ae5ca01e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -249,7 +249,9 @@ ansible -m shell -a 'echo "{{ my_variable }}"' -e 'my_variable="{{ lookup("pipe" ``` -### Register +### Register and Conditional + +#### Register Another way to dynamicaly generate the variable content is a `register` command `Register` is also useful to store an output of a task, and use it's value as a logic for execution further tasks. @@ -257,6 +259,56 @@ for execution further tasks. (venv) user@host:~/ansible-for-learnXinYminutes$ ansible-playbook playbooks/register_and_when.yml ``` +```yaml +#file content +--- +- hosts: localhost + tasks: + - name: check the system capacity + shell: df -h / + register: root_size + + - name: debug root_size + debug: + msg: "{{ root_size }}" + + - name: debug root_size return code + debug: + msg: "{{ root_size.rc }}" + + + - name: Print this message when return code of 'check the system capacity' was ok + debug: + msg: "{{ root_size.rc }}" + when: root_size.rc == 0 + +``` +#### Conditionals + +You can define complex logic with ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) + + + +### ansible - tags, limmit + +You should know about a way to increase efficiency by this simple functionality + +#### TAGS + You can tag a task, role (and its tasks), include, etc... + You can then limit an execution by using + --tags tagA, other_tag,... + + There are special tags: always + + --skip-tags can be used to exclude a block of code + +#### LIMMIT + You can limmit an execution of your tasks to defined hosts + --limit my_hostname + --limit groupname + --limit some_prefix* + --limit hostname:group #JM + ### Templates Template is a powerfull way to deliver some (partially) dynamic content. Ansible uses **Jinja2** langueage to describe the template. @@ -286,7 +338,6 @@ Junja is powerfull. It has built-in many usefull functions. # if variable is undefined - use default value {{ some_variable | default('default_value') }} ``` -### ansible - tags, limmit, diff, check_mode ### ansible-vault To maintain **ifrastructure as a code** you need to store secrets. -- cgit v1.2.3 From 75379d6b672ed34b5f593c9aea60564e90a0cc3d Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:56:38 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 4664ca70..607a08ba 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index ae5ca01e..155a3b0e 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -285,7 +285,7 @@ for execution further tasks. ``` #### Conditionals -You can define complex logic with ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) +You can define complex logic with Ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) -- cgit v1.2.3 From a3bbb085b06d640b4807c296358f4569599fcd5b Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:57:54 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 3 ++- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 607a08ba..8916354d 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 155a3b0e..236fca99 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -276,7 +276,8 @@ for execution further tasks. debug: msg: "{{ root_size.rc }}" - +# when: example + - name: Print this message when return code of 'check the system capacity' was ok debug: msg: "{{ root_size.rc }}" -- cgit v1.2.3 From 6c6dfb1884d216983b685ebb2683df7d53779f5a Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:58:23 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 8916354d..4bc70c7b 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 236fca99..b076c11f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -284,7 +284,7 @@ for execution further tasks. when: root_size.rc == 0 ``` -#### Conditionals +#### Conditionals - when: You can define complex logic with Ansible and Jinja functions. Most common is usage of `when:`, with some variable (often dynamicly generated in previous playbook steps with `register` or `lookup`) -- cgit v1.2.3 From 41b345c69be430a535345b5dac0a972f85493b0c Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:59:23 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 5 +++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 4bc70c7b..57301145 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index b076c11f..a6ce656b 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -295,7 +295,8 @@ You can define complex logic with Ansible and Jinja functions. Most common is us You should know about a way to increase efficiency by this simple functionality #### TAGS - You can tag a task, role (and its tasks), include, etc... +You can tag a task, role (and its tasks), include, etc... + You can then limit an execution by using --tags tagA, other_tag,... @@ -304,7 +305,7 @@ You should know about a way to increase efficiency by this simple functionality --skip-tags can be used to exclude a block of code #### LIMMIT - You can limmit an execution of your tasks to defined hosts +You can limmit an execution of your tasks to defined hosts --limit my_hostname --limit groupname --limit some_prefix* -- cgit v1.2.3 From 8fc4b38c1010e7e85ef396ff045becc8a998c459 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 14:59:51 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 1 + 2 files changed, 1 insertion(+) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 57301145..4ffb166f 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index a6ce656b..41d9d62f 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -306,6 +306,7 @@ You can tag a task, role (and its tasks), include, etc... #### LIMMIT You can limmit an execution of your tasks to defined hosts + --limit my_hostname --limit groupname --limit some_prefix* -- cgit v1.2.3 From 844e24899e022a948c52cc68b8af33e2d8b28208 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 15:00:25 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 4ffb166f..6f152625 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 41d9d62f..a10540d3 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -290,7 +290,7 @@ You can define complex logic with Ansible and Jinja functions. Most common is us -### ansible - tags, limmit +### ansible - tags, limit You should know about a way to increase efficiency by this simple functionality @@ -304,8 +304,8 @@ You can tag a task, role (and its tasks), include, etc... --skip-tags can be used to exclude a block of code -#### LIMMIT -You can limmit an execution of your tasks to defined hosts +#### LIMIT +You can limit an execution of your tasks to defined hosts --limit my_hostname --limit groupname -- cgit v1.2.3 From 147533c849733dadc2c3db31e9365ff4b4943cbe Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 15:05:56 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 4 +++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index 6f152625..d3239470 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index a10540d3..95735e21 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -298,7 +298,7 @@ You should know about a way to increase efficiency by this simple functionality You can tag a task, role (and its tasks), include, etc... You can then limit an execution by using - --tags tagA, other_tag,... + ansible-playbook playbooks/simple_playbook.yml --tags tagA, tag_other There are special tags: always @@ -307,6 +307,8 @@ You can tag a task, role (and its tasks), include, etc... #### LIMIT You can limit an execution of your tasks to defined hosts + ansible-playbook playbooks/simple_playbook.yml --limmit localhost + --limit my_hostname --limit groupname --limit some_prefix* -- cgit v1.2.3 From c8ef9d6d874da784b3e1de7bce300f37f92292c1 Mon Sep 17 00:00:00 2001 From: sirkubax Date: Fri, 27 Oct 2017 15:08:30 +0200 Subject: update --- .ansible.html.markdown.swl | Bin 36864 -> 36864 bytes ansible.html.markdown | 10 ++++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.ansible.html.markdown.swl b/.ansible.html.markdown.swl index d3239470..259fc5a0 100644 Binary files a/.ansible.html.markdown.swl and b/.ansible.html.markdown.swl differ diff --git a/ansible.html.markdown b/ansible.html.markdown index 95735e21..0ad58d45 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -295,14 +295,16 @@ You can define complex logic with Ansible and Jinja functions. Most common is us You should know about a way to increase efficiency by this simple functionality #### TAGS -You can tag a task, role (and its tasks), include, etc... +You can tag a task, role (and its tasks), include, etc, and then run only the tagged resources - You can then limit an execution by using - ansible-playbook playbooks/simple_playbook.yml --tags tagA, tag_other + ansible-playbook playbooks/simple_playbook.yml --tags=tagA,tag_other + ansible-playbook playbooks/simple_playbook.yml -t tagA,tag_other - There are special tags: always + There are special tags: + always --skip-tags can be used to exclude a block of code + --list-tags to list available tags #### LIMIT You can limit an execution of your tasks to defined hosts -- cgit v1.2.3 From 46fab3c0be2852661fb972555a20c9f7083ad17d Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:20:32 -0200 Subject: [dynamic-programming/pt-br] - Small typos --- pt-br/dynamic-programming-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..b4ace9a4 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -22,7 +22,7 @@ Sempre se lembre!! ## Maneiras de Solucionar tais Problemas -1. Top-Down (De cima para baixo): Começe solucionando o problema quebrando-o em +1. Top-Down (De cima para baixo): Comece solucionando o problema quebrando-o em partes. Se você perceber que o problema já foi resolvido, então simplemente pegue a resposta salva. Se ainda não foi resolvido, solucione-o e salve a resposta. Isso é geralmente fácil de pensar e muito intuitivo. É geralmente -- cgit v1.2.3 From 1504f4af99ef6811158c270143e035bc6ac3eed4 Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:21:48 -0200 Subject: [dynamic-programming/pt-br] - Small typos --- pt-br/dynamic-programming-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..a90b11ec 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -29,7 +29,7 @@ resposta. Isso é geralmente fácil de pensar e muito intuitivo. É geralmente referenciado como Memorização. 2. Bottom-Up (De baixo para cima): Analise o problema e veja a ordem em que os -subproblemas são resolvidos e começe a solucionar dos problemas mais triviais, +subproblemas são resolvidos e comece a solucionar dos problemas mais triviais, até o problema dado. Neste processo, é garantido que os subproblemas são resolvidos antes de resoler o problema. Isto é referenciado como Programação Dinâmica. -- cgit v1.2.3 From 01bcf645997fbea7b5b6d8e5ffb01b9d9c5fc7a6 Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:22:50 -0200 Subject: [dynamic-programming/pt-br] - Small typos --- pt-br/dynamic-programming-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..40e6fda2 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -31,7 +31,7 @@ referenciado como Memorização. 2. Bottom-Up (De baixo para cima): Analise o problema e veja a ordem em que os subproblemas são resolvidos e começe a solucionar dos problemas mais triviais, até o problema dado. Neste processo, é garantido que os subproblemas são -resolvidos antes de resoler o problema. Isto é referenciado como Programação Dinâmica. +resolvidos antes de resolver o problema. Isto é referenciado como Programação Dinâmica. ## Exemplo de Programação Dinâmica -- cgit v1.2.3 From 5f5dd74260efd76af39262c1608cd3c3e14f5576 Mon Sep 17 00:00:00 2001 From: milenaduo <33162200+milenaduo@users.noreply.github.com> Date: Fri, 27 Oct 2017 16:29:00 -0200 Subject: [dynamic-programming/pt-br] - Better reading --- pt-br/dynamic-programming-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/dynamic-programming-pt.html.markdown b/pt-br/dynamic-programming-pt.html.markdown index 8de9bee6..45b52790 100644 --- a/pt-br/dynamic-programming-pt.html.markdown +++ b/pt-br/dynamic-programming-pt.html.markdown @@ -51,7 +51,7 @@ array antecedente e uma variável como maiorSequenciasAteAgora e seu índice ajudariam a poupar muito tempo. Um conceito similar poderia ser aplicado ao procurar o maior caminho em um grafo acíclico dirigido. ---------------------------------------------------------------------------- + ``` for i=0 to n-1 LS[i]=1 @@ -62,7 +62,7 @@ grafo acíclico dirigido. if (largest < LS[i]) ``` -### Alguns Problemas Famosos de Programação Dinâmica +## Alguns Problemas Famosos de Programação Dinâmica ``` Floyd Warshall Algorithm - Tutorial and C Program source code:http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code -- cgit v1.2.3 From 9ac6b5775bcda6d1e881825f0425ca36bc8775d9 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Fri, 27 Oct 2017 20:44:07 +0200 Subject: [go/it-it] Wording and missing translation --- it-it/go-it.html.markdown | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index e005f2dc..e49ccd79 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -26,14 +26,14 @@ Aggiunge la concorrenza in maniera diretta e semplice da capire, per far forza sulle CPU multi-core di oggigiorno. Presenta caratteristiche utili per la programmazione in larga scala. -Go comes with a great standard library and an enthusiastic community. +Go include un'ottima libreria standard e ha una community entusiasta. ```go // Commento su riga singola /* Commento su riga multipla */ -// In cima a ogni file è necessario specificare il package. +// In cima ad ogni file è necessario specificare il package. // Main è un package speciale che identifica un eseguibile anziché una libreria. package main @@ -65,19 +65,19 @@ func oltreIlCiaoMondo() { x = 3 // Assegnazione di una variabile. // E' possibile la dichiarazione "rapida" := per inferire il tipo, dichiarare e assegnare contemporaneamente. y := 4 - // Una funzione che ritorna due valori. - somma, prod := imparaMoltepliciValoriDiRitorno(x, y) + // Una funzione che restituisce due valori. + somma, prod := imparaMoltepliciValoriRestituiti(x, y) fmt.Println("somma:", somma, "prodotto:", prod) // Semplice output. imparaTipi() // < y minuti, devi imparare ancora! } /* <- commento su righe multiple -Le funzioni possono avere parametri e ritornare (molteplici!) valori. -Qua, x e y sono gli argomenti, mentre somma e prod sono i valori ritornati. +Le funzioni possono avere parametri e restituire (molteplici!) valori. +In questo esempio, x e y sono gli argomenti, mentre somma e prod sono i valori restituiti. Da notare il fatto che x e somma vengono dichiarati come interi. */ -func imparaMoltepliciValoriDiRitorno(x, y int) (somma, prod int) { - return x + y, x * y // Ritorna due valori. +func imparaMoltepliciValoriRestituiti(x, y int) (somma, prod int) { + return x + y, x * y // Restituisce due valori. } // Ecco alcuni tipi presenti in Go @@ -86,7 +86,7 @@ func imparaTipi() { str := "Impara il Go!" // Tipo stringa. s2 := `Una stringa letterale -puo' includere andata a capo.` // Sempre di tipo stringa. +può includere andata a capo.` // Sempre di tipo stringa. // Stringa letterale non ASCII. I sorgenti Go sono in UTF-8. g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode. @@ -144,20 +144,20 @@ puo' includere andata a capo.` // Sempre di tipo stringa. imparaControlloDiFlusso() // Torniamo in carreggiata. } -// In Go è possibile associare dei nomi ai valori di ritorno di una funzione. -// Assegnare un nome al tipo di dato ritornato permette di fare return in vari +// In Go è possibile associare dei nomi ai valori restituiti da una funzione. +// Assegnare un nome al tipo di dato restituito permette di fare return in vari // punti all'interno del corpo della funzione, ma anche di usare return senza -// specificare in modo esplicito che cosa ritornare. -func imparaValoriDiRitornoConNome(x, y int) (z int) { +// specificare in modo esplicito che cosa restituire. +func imparaValoriRestituitiConNome(x, y int) (z int) { z = x * y return // z è implicito, perchè compare nella definizione di funzione. } // Go è dotato di garbage collection. Ha i puntatori, ma non l'aritmetica dei -// puntatori. Puoi fare errori coi puntatori a nil, ma non puoi direttamente -// incrementare un puntatore. +// puntatori. Puoi commettere errori a causa di puntatori nulli, ma non puoi +// incrementare un puntatore direttamente. func imparaLaMemoria() (p, q *int) { - // I valori di ritorno (con nome) p e q sono puntatori a int. + // I valori restituiti (con nome) p e q sono puntatori a int. p = new(int) // La funzione new si occupa di allocare memoria. // L'int allocato viene inizializzato a 0, dunque p non è più nil. s := make([]int, 20) // Alloca 20 int come un singolo blocco di memoria. @@ -207,14 +207,14 @@ func imparaControlloDiFlusso() { } // x == 42 qua. - // Il for è l'unica istruzione per ciclare in Go, ma ha varie forme. + // Il for è l'unica istruzione per i loop in Go, ma ha varie forme. for { // Ciclo infinito. break // Scherzavo. continue // Non si arriva qua. } - // Puoi usare range per ciclare su un vettore, slice, stringa, mappa o canale. - // range ritorna uno (per i canali) o due valori (vettore, slice, stringa, mappa). + // Puoi usare range per iterare lungo un vettore, slice, stringa, mappa o canale. + // range restituisce uno (per i canali) o due valori (vettore, slice, stringa, mappa). for chiave, valore := range map[string]int{"uno": 1, "due": 2, "tre": 3} { // per ogni coppia dentro la mappa, stampa chiave e valore fmt.Printf("chiave=%s, valore=%d\n", chiave, valore) @@ -236,7 +236,7 @@ func imparaControlloDiFlusso() { // Inoltre le funzioni letterali possono essere definite e chiamate // inline, col ruolo di parametri di funzione, a patto che: // a) la funzione letterale venga chiamata subito (), - // b) il valore ritornato è in accordo con il tipo dell'argomento. + // b) il valore restituito è in accordo con il tipo dell'argomento. fmt.Println("Somma e raddoppia due numeri: ", func(a, b int) int { return (a + b) * 2 @@ -247,7 +247,7 @@ func imparaControlloDiFlusso() { goto amore amore: - imparaFabbricaDiFunzioni() // Una funzione che ritorna un'altra funzione è divertente! + imparaFabbricaDiFunzioni() // Una funzione che restituisce un'altra funzione è divertente! imparaDefer() // Un tour veloce di una parola chiave importante. imparaInterfacce() // Arriva la roba buona! } @@ -271,7 +271,7 @@ func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string { func imparaDefer() (ok bool) { // Le istruzioni dette "deferred" (rinviate) sono eseguite - // appena prima che la funzione ritorni. + // appena prima che la funzione abbia termine. defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).") defer fmt.Println("\nQuesta riga viene stampata per prima perché") // defer viene usato di solito per chiudere un file, così la funzione che -- cgit v1.2.3 From f21a5f061b757223456edc632bb807e046bc5bf8 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Fri, 27 Oct 2017 20:53:15 +0200 Subject: [rst/it] Improve wording --- it-it/rst-it.html.markdown | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/it-it/rst-it.html.markdown b/it-it/rst-it.html.markdown index 8947c738..a834e899 100644 --- a/it-it/rst-it.html.markdown +++ b/it-it/rst-it.html.markdown @@ -6,10 +6,12 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] translators: - ["Ale46", "https://github.com/Ale46"] + - ["Chris54721", "https://chris54721.net"] lang: it-it --- -RST è un formato di file formalmente creato dalla comunità Python per scrivere documentazione (e quindi fa parte di Docutils). +RST (Restructured Text) è un formato di file inizialmente creato dalla comunità Python +per la documentazione (per questo motivo appartiene a Docutils). I file RST sono semplici file di testo con una sintassi leggera (in confronto all'HTML). @@ -23,7 +25,7 @@ Per usare Restructured Text, sarà necessario installare [Python](http://www.pyt $ easy_install docutils ``` -O se il tuo sistema ha `pip`, puoi usare anche lui: +Oppure, se hai `pip` installato sul tuo sistema: ```bash $ pip install docutils @@ -32,7 +34,7 @@ $ pip install docutils ## Sintassi del file -Un semplice esempio della sintassi del file: +Ecco un semplice esempio della sintassi RST: ``` .. Le righe che iniziano con due punti sono comandi speciali. Ma se non è possibile trovare alcun comando, la riga viene considerata come un commento @@ -41,16 +43,16 @@ Un semplice esempio della sintassi del file: I titoli principali sono scritti utilizzando caratteri di uguale, sopra e sotto =============================================================================== -Si noti che devono esistere tanti caratteri di uguale quanti sono i caratteri del titolo. +Si noti che devono esserci tanti caratteri di uguale quanti caratteri del titolo. -Anche il titolo è sottolineato con caratteri di uguale -====================================================== +Anche i titoli normali usano caratteri di uguale, ma solo sotto +=============================================================== -Sottotitoli con i trattini --------------------------- +I sottotitoli usano i trattini +------------------------------ -E sotto-sottotitoli con tildi -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +E i sotto-sottotitoli le tildi +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Puoi inserire il testo in *corsivo* o in **grassetto**, puoi "contrassegnare" il testo come codice con un doppio apice ``: `` print () ``. @@ -60,13 +62,13 @@ Le liste sono semplici come in Markdown: - Secondo elemento      - Sottoelemento -o +oppure * Primo elemento * Secondo elemento      * Sottoelemento -Le tabelle sono davvero facili da scrivere: +Le tabelle sono molto semplici da inserire: =========== ======== Stato Capitale @@ -75,22 +77,21 @@ Francia Parigi Giappone Tokio =========== ======== -Le tabelle più complesse possono essere fatte facilmente (colonne e/o righe unite) ma ti suggerisco di leggere il documento completo per questo :) +Anche le tabelle più complesse possono essere inserite facilmente (colonne e/o righe unite) ma ti suggerisco di leggere la documentazione completa per questo :) Esistono diversi modi per creare collegamenti: -- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo modo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile). +- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile). - Digitando un URL completo: https://github.com/ (verrà automaticamente convertito in un collegamento) -- Facendo un collegamento simile a Markdown: `Github `_ . +- Utilizzando una sintassi simile a Markdown: `Github `_ . .. _Github https://github.com/ ``` - ## Come usarlo -RST viene fornito con docutils che dispone di `rst2html`, per esempio: +RST viene fornito con docutils, che dispone di `rst2html`, per esempio: ```bash $ rst2html miofile.rst output.html -- cgit v1.2.3 From 6800d632b179661a8902db748fea50b7012e8208 Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Fri, 27 Oct 2017 15:50:49 -0400 Subject: Cleaning up whitespace --- vim.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/vim.html.markdown b/vim.html.markdown index 7723136f..6fc52564 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -8,9 +8,9 @@ filename: LearnVim.txt [Vim](http://www.vim.org) -(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text -editor designed for speed and increased productivity, and is ubiquitous in most -unix-based systems. It has numerous keybindings for speedy navigation to +(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text +editor designed for speed and increased productivity, and is ubiquitous in most +unix-based systems. It has numerous keybindings for speedy navigation to specific points in the file, and for fast editing. ## Basics of navigating Vim @@ -51,12 +51,12 @@ specific points in the file, and for fast editing. # Jumping to characters f # Jump forward and land on - t # Jump forward and land right before + t # Jump forward and land right before - # For example, + # For example, f< # Jump forward and land on < t< # Jump forward and land right before < - + # Moving by word w # Move forward by one word @@ -77,15 +77,15 @@ specific points in the file, and for fast editing. Vim is based on the concept on **modes**. -Command Mode - vim starts up in this mode, used to navigate and write commands -Insert Mode - used to make changes in your file -Visual Mode - used to highlight text and do operations to them +Command Mode - vim starts up in this mode, used to navigate and write commands +Insert Mode - used to make changes in your file +Visual Mode - used to highlight text and do operations to them Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands ``` i # Puts vim into insert mode, before the cursor position a # Puts vim into insert mode, after the cursor position - v # Puts vim into visual mode + v # Puts vim into visual mode : # Puts vim into ex mode # 'Escapes' from whichever mode you're in, into Command mode @@ -102,18 +102,18 @@ Ex Mode - used to drop down to the bottom with the ':' prompt to enter comm ## The 'Grammar' of vim -Vim can be thought of as a set of commands in a +Vim can be thought of as a set of commands in a 'Verb-Modifier-Noun' format, where: -Verb - your action -Modifier - how you're doing your action +Verb - your action +Modifier - how you're doing your action Noun - the object on which your action acts on A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ``` # 'Verbs' - + d # Delete c # Change y # Yank (copy) @@ -135,7 +135,7 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns': s # Sentence p # Paragraph b # Block - + # Sample 'sentences' or commands d2w # Delete 2 words @@ -180,7 +180,7 @@ Here's a sample ~/.vimrc file: ``` " Example ~/.vimrc -" 2015.10 +" 2015.10 " Required for vim to be iMproved set nocompatible -- cgit v1.2.3 From 437adfa5a4f07dfbae9e54c258fb0f8815a6c2dc Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Fri, 27 Oct 2017 15:51:05 -0400 Subject: Adding help documentation --- vim.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/vim.html.markdown b/vim.html.markdown index 6fc52564..15144b8d 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -17,6 +17,7 @@ specific points in the file, and for fast editing. ``` vim # Open in vim + :help # Open up built-in help docs about if any exists :q # Quit vim :w # Save current file :wq # Save file and quit vim @@ -73,6 +74,15 @@ specific points in the file, and for fast editing. L # Move to the bottom of the screen ``` +## Help docs: + +Vim has built in help documentation that can accessed with `:help `. +For example `:help navigation` will pull up documentation about how to navigate +your workspace! + +`:help` can also be used without an option. This will bring up a default help dialog +that aims to make getting started with vim more approachable! + ## Modes: Vim is based on the concept on **modes**. -- cgit v1.2.3 From 575dc7c0184978f73c4327c5f27f1c41c090fa5a Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Fri, 27 Oct 2017 16:09:35 -0400 Subject: Adding missing semicolons --- javascript.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 85c8a52d..4ed8f849 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -103,7 +103,7 @@ false; // ... which works with more than just strings "1, 2, " + 3; // = "1, 2, 3" -"Hello " + ["world", "!"] // = "Hello world,!" +"Hello " + ["world", "!"]; // = "Hello world,!" // and are compared with < and > "a" < "b"; // = true @@ -222,7 +222,7 @@ while (true){ var input; do { input = getInput(); -} while (!isValid(input)) +} while (!isValid(input)); // The `for` loop is the same as C and Java: // initialization; continue condition; iteration. @@ -293,7 +293,7 @@ myFunction("foo"); // = "FOO" // automatic semicolon insertion. Watch out for this when using Allman style. function myFunction(){ return // <- semicolon automatically inserted here - {thisIsAn: 'object literal'} + {thisIsAn: 'object literal'}; } myFunction(); // = undefined @@ -388,7 +388,7 @@ myFunc(); // = undefined // through `this`, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); -} +}; myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" @@ -397,7 +397,7 @@ myObj.myOtherFunc(); // = "HELLO WORLD!" var anotherFunc = function(s){ return this.myString + s; -} +}; anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" // The `apply` function is nearly identical, but takes an array for an argument @@ -420,7 +420,7 @@ boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" // `bind` can also be used to partially apply (curry) a function. -var product = function(a, b){ return a * b; } +var product = function(a, b){ return a * b; }; var doubler = product.bind(this, 2); doubler(8); // = 16 @@ -430,11 +430,11 @@ doubler(8); // = 16 var MyConstructor = function(){ this.myNumber = 5; -} +}; myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Unlike most other popular object-oriented languages, JavaScript has no +// Unlike most other popular object-oriented languages, JavaScript has no // concept of 'instances' created from 'class' blueprints; instead, JavaScript // combines instantiation and inheritance into a single concept: a 'prototype'. @@ -451,7 +451,7 @@ var myObj = { var myPrototype = { meaningOfLife: 42, myFunc: function(){ - return this.myString.toLowerCase() + return this.myString.toLowerCase(); } }; @@ -515,7 +515,7 @@ MyConstructor.prototype = { }; var myNewObj2 = new MyConstructor(); myNewObj2.getMyNumber(); // = 5 -myNewObj2.myNumber = 6 +myNewObj2.myNumber = 6; myNewObj2.getMyNumber(); // = 6 // Built-in types like strings and numbers also have constructors that create @@ -540,7 +540,7 @@ if (new Number(0)){ // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0); -} +}; "abc".firstCharacter(); // = "a" // This fact is often used in "polyfilling", which is implementing newer @@ -556,7 +556,7 @@ if (Object.create === undefined){ // don't overwrite it if it exists Constructor.prototype = proto; // then use it to create a new, appropriately-prototyped object return new Constructor(); - } + }; } ``` -- cgit v1.2.3 From 56a82546e9196a94a0085eae0abd0578702a578f Mon Sep 17 00:00:00 2001 From: Andrew Gallasch Date: Sat, 28 Oct 2017 15:36:34 +1030 Subject: Improve comment about final modifier --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 7b59b085..73e4bd2e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -173,7 +173,7 @@ public class LearnJava { // Char - A single 16-bit Unicode character char fooChar = 'A'; - // final variables can't be reassigned to another object, + // final variables can't be reassigned, final int HOURS_I_WORK_PER_WEEK = 9001; // but they can be initialized later. final double E; -- cgit v1.2.3 From 32090679c2a6a79933fa94f36a7dcddd22a20897 Mon Sep 17 00:00:00 2001 From: Andrew Gallasch Date: Sat, 28 Oct 2017 16:09:07 +1030 Subject: Improve comments on abstract classes --- java.html.markdown | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 73e4bd2e..621d500c 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -703,15 +703,21 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // // Method declarations // } -// Marking a class as abstract means that it contains at least one abstract -// method that must be defined in a child class. Similar to interfaces, abstract -// classes cannot be instantiated, but instead must be extended and the abstract -// methods defined. Different from interfaces, abstract classes can contain a -// mixture of concrete and abstract methods. Methods in an interface cannot -// have a body, unless the method is static, and variables are final by default, -// unlike an abstract class. Also abstract classes CAN have the "main" method. +// Abstract Classes cannot be instantiated. +// Abstract classes may define abstract methods. +// Abstract methods have no body and are marked abstract +// Non-abstract child classes must @Override all abstract methods +// from their super-classes. +// Abstract classes can be useful when combining repetitive logic +// with customised behavior, but as Abstract classes require +// inheritance, they violate "Composition over inheritance" +// so consider other approaches using composition. +// https://en.wikipedia.org/wiki/Composition_over_inheritance + public abstract class Animal { + private int age; + public abstract void makeSound(); // Method can have a body @@ -722,17 +728,12 @@ public abstract class Animal age = 30; } - // No need to initialize, however in an interface - // a variable is implicitly final and hence has - // to be initialized. - private int age; - public void printAge() { System.out.println(age); } - // Abstract classes can have main function. + // Abstract classes can have main method. public static void main(String[] args) { System.out.println("I am abstract"); -- cgit v1.2.3 From 2e218f5dfbc2015cc429e9ae8e3a0e38c0e9098b Mon Sep 17 00:00:00 2001 From: Oleg Gromyak Date: Sat, 28 Oct 2017 20:13:12 +0300 Subject: [python/ua] Add Ukrainian translation --- uk-ua/python-ua.html.markdown | 818 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 818 insertions(+) create mode 100644 uk-ua/python-ua.html.markdown diff --git a/uk-ua/python-ua.html.markdown b/uk-ua/python-ua.html.markdown new file mode 100644 index 00000000..2406678d --- /dev/null +++ b/uk-ua/python-ua.html.markdown @@ -0,0 +1,818 @@ +--- +language: python +lang: uk-ua +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] +translators: + - ["Oleg Gromyak", "https://github.com/ogroleg"] +filename: learnpython-ua.py +--- + +Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з +найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому +синтаксису. Це майже як виконуваний псевдокод. + +З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh) +або louiedinh [at] [поштовий сервіс від Google] + +Примітка: Ця стаття стосується Python 2.7, проте має працювати і +у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну, +його підтримку припинять у 2020, тож наразі краще починати вивчення Python +з версії 3.x. +Аби вивчити Python 3.x, звертайтесь до статті по Python 3. + +```python +# Однорядкові коментарі починаються з символу решітки. + +""" Текст, що займає декілька рядків, + може бути записаний з використанням 3 знаків " і + зазвичай використовується у якості + вбудованої документації +""" + +#################################################### +## 1. Примітивні типи даних та оператори +#################################################### + +# У вас є числа +3 # => 3 + +# Математика працює досить передбачувано +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# А ось з діленням все трохи складніше. Воно цілочисельне і результат +# автоматично округлюється у меншу сторону. +5 / 2 # => 2 + +# Аби правильно ділити, спершу варто дізнатися про числа +# з плаваючою комою. +2.0 # Це число з плаваючою комою +11.0 / 4.0 # => 2.75 ох... Так набагато краще + +# Результат цілочисельного ділення округлюється у меншу сторону +# як для додатніх, так і для від'ємних чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Зверніть увагу, що ми також можемо імпортувати модуль для ділення, +# див. розділ Модулі +# аби звичне ділення працювало при використанні лише '/'. +from __future__ import division + +11 / 4 # => 2.75 ...звичне ділення +11 // 4 # => 2 ...цілочисельне ділення + +# Залишок від ділення +7 % 3 # => 1 + +# Піднесення до степеня +2 ** 4 # => 16 + +# Приорітет операцій вказується дужками +(1 + 3) * 2 # => 8 + +# Логічні оператори +# Зверніть увагу: ключові слова «and» і «or» чутливі до регістру букв +True and False # => False +False or True # => True + +# Завважте, що логічні оператори також використовуються і з цілими числами +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Для заперечення використовується not +not True # => False +not False # => True + +# Рівність — це == +1 == 1 # => True +2 == 1 # => False + +# Нерівність — це != +1 != 1 # => False +2 != 1 # => True + +# Ще трохи порівнянь +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Порівняння можуть бути записані ланцюжком! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Рядки позначаються символом " або ' +"Це рядок." +'Це теж рядок.' + +# І рядки також можна додавати! +"Привіт " + "світ!" # => "Привіт світ!" +# Рядки можна додавати і без '+' +"Привіт " "світ!" # => "Привіт світ!" + +# ... або множити +"Привіт" * 3 # => "ПривітПривітПривіт" + +# З рядком можна працювати як зі списком символів +"Це рядок"[0] # => 'Ц' + +# Ви можете дізнатися довжину рядка +len("Це рядок") # => 8 + +# Символ % використовується для форматування рядків, наприклад: +"%s можуть бути %s" % ("рядки", "інтерпольовані") + +# Новий спосіб форматування рядків — використання методу format. +# Це бажаний спосіб. +"{} є {}".format("Це", "заповнювач") +"{0} можуть бути {1}".format("рядки", "форматовані") +# Якщо ви не хочете рахувати, то можете скористатися ключовими словами. +"{name} хоче з'істи {food}".format(name="Боб", food="лазанью") + +# None - це об'єкт +None # => None + +# Не використовуйте оператор рівності '=='' для порівняння +# об'єктів з None. Використовуйте для цього «is» +"etc" is None # => False +None is None # => True + +# Оператор 'is' перевіряє ідентичність об'єктів. Він не +# дуже корисний при роботі з примітивними типами, проте +# незамінний при роботі з об'єктами. + +# None, 0 і порожні рядки/списки рівні False. +# Всі інші значення рівні True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Змінні та колекції +#################################################### + +# В Python є оператор print +print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись! + +# Отримати дані з консолі просто +input_string_var = raw_input( + "Введіть щось: ") # Повертає дані у вигляді рядка +input_var = input("Введіть щось: ") # Працює з даними як з кодом на python +# Застереження: будьте обережні при використанні методу input() + +# Оголошувати змінні перед ініціалізацією не потрібно. +some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями +some_var # => 5 + +# При спробі доступу до неініціалізованої змінної +# виникне виняткова ситуація. +# Див. розділ Потік управління, аби дізнатись про винятки більше. +some_other_var # Помилка в імені + +# if може використовуватися як вираз +# Такий запис еквівалентний тернарному оператору '?:' у мові С +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Списки зберігають послідовності +li = [] +# Можна одразу створити заповнений список +other_li = [4, 5, 6] + +# Об'єкти додаються у кінець списку за допомогою методу append +li.append(1) # li тепер дорівнює [1] +li.append(2) # li тепер дорівнює [1, 2] +li.append(4) # li тепер дорівнює [1, 2, 4] +li.append(3) # li тепер дорівнює [1, 2, 4, 3] +# І видаляються з кінця методом pop +li.pop() # => повертає 3 і li стає рівним [1, 2, 4] +# Повернемо елемент назад +li.append(3) # li тепер знову дорівнює [1, 2, 4, 3] + +# Поводьтесь зі списком як зі звичайним масивом +li[0] # => 1 +# Присвоюйте нові значення вже ініціалізованим індексам за допомогою = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення +# Звертаємось до останнього елементу +li[-1] # => 3 + +# Спроба вийти за границі масиву призводить до помилки в індексі +li[4] # помилка в індексі + +# Можна звертатися до діапазону, використовуючи так звані зрізи +# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал). +li[1:3] # => [2, 4] +# Опускаємо початок +li[2:] # => [4, 3] +# Опускаємо кінець +li[:3] # => [1, 2, 4] +# Вибираємо кожен другий елемент +li[::2] # => [1, 4] +# Перевертаємо список +li[::-1] # => [3, 4, 2, 1] +# Використовуйте суміш вищеназваного для більш складних зрізів +# li[початок:кінець:крок] + +# Видаляємо довільні елементи зі списку оператором del +del li[2] # li тепер [1, 2, 3] + +# Ви можете додавати списки +li + other_li # => [1, 2, 3, 4, 5, 6] +# Зверніть увагу: значення li та other_li при цьому не змінились. + +# Поєднувати списки можна за допомогою методу extend +li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6] + +# Видалити перше входження значення +li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6] +li.remove(2) # Помилка значення, оскільки у списку li немає 2 + +# Вставити елемент за вказаним індексом +li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6] + +# Отримати індекс першого знайденого елементу +li.index(2) # => 1 +li.index(7) # Помилка значення, оскільки у списку li немає 7 + +# Перевірити елемент на входження у список можна оператором in +1 in li # => True + +# Довжина списку обчислюється за допомогою функції len +len(li) # => 6 + +# Кортежі схожі на списки, лише незмінні +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Виникає помилка типу + +# Все те ж саме можна робити і з кортежами +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Ви можете розпаковувати кортежі (або списки) у змінні +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 +d, e, f = 4, 5, 6 # дужки можна опустити +# Кортежі створюються за замовчуванням, якщо дужки опущено +g = 4, 5, 6 # => (4, 5, 6) +# Дивіться, як легко обміняти значення двох змінних +e, d = d, e # тепер d дорівнює 5, а e дорівнює 4 + +# Словники містять асоціативні масиви +empty_dict = {} +# Ось так описується попередньо заповнений словник +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значення можна отримати так само, як і зі списку +filled_dict["one"] # => 1 + +# Можна отримати всі ключі у виді списку за допомогою методу keys +filled_dict.keys() # => ["three", "two", "one"] +# Примітка: збереження порядку ключів у словників не гарантується +# Ваші результати можуть не співпадати з цими. + +# Можна отримати і всі значення у вигляді списку, використовуйте метод values +filled_dict.values() # => [3, 2, 1] +# Те ж зауваження щодо порядку ключів діє і тут + +# Отримуйте всі пари ключ-значення у вигляді списку кортежів +# за допомогою "items()" +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# За допомогою оператору in можна перевіряти ключі на входження у словник +"one" in filled_dict # => True +1 in filled_dict # => False + +# Спроба отримати значення за неіснуючим ключем викине помилку ключа +filled_dict["four"] # помилка ключа + +# Аби уникнути цього, використовуйте метод get() +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# Метод get також приймає аргумент за замовчуванням, значення якого буде +# повернуто при відсутності вказаного ключа +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Зверніть увагу, що filled_dict.get("four") все ще => None +# (get не встановлює значення елементу словника) + +# Присвоюйте значення ключам так само, як і в списках +filled_dict["four"] = 4 # тепер filled_dict["four"] => 4 + +# Метод setdefault() вставляє пару ключ-значення лише +# за відсутності такого ключа +filled_dict.setdefault("five", 5) # filled_dict["five"] повертає 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] все ще повертає 5 + + +# Множини містять... ну, загалом, множини +# (які схожі на списки, проте в них не може бути елементів, які повторюються) +empty_set = set() +# Ініціалізація множини набором значень +some_set = set([1,2,2,3,4]) # some_set тепер дорівнює set([1, 2, 3, 4]) + +# Порядок не гарантовано, хоча інколи множини виглядають відсортованими +another_set = set([4, 3, 2, 2, 1]) # another_set тепер set([1, 2, 3, 4]) + +# Починаючи з Python 2.7, ви можете використовувати {}, аби створити множину +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Додавання нових елементів у множину +filled_set.add(5) # filled_set тепер дорівнює {1, 2, 3, 4, 5} + +# Перетин множин: & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Об'єднання множин: | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Різниця множин: - +{1,2,3,4} - {2,3,5} # => {1, 4} + +# Симетрична різниця множин: ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Перевіряємо чи множина зліва є надмножиною множини справа +{1, 2} >= {1, 2, 3} # => False + +# Перевіряємо чи множина зліва є підмножиною множини справа +{1, 2} <= {1, 2, 3} # => True + +# Перевірка на входження у множину: in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Потік управління +#################################################### + +# Для початку створимо змінну +some_var = 5 + +# Так виглядає вираз if. Відступи у python дуже важливі! +# результат: «some_var менше, ніж 10» +if some_var > 10: + print("some_var набагато більше, ніж 10.") +elif some_var < 10: # Вираз elif є необов'язковим. + print("some_var менше, ніж 10.") +else: # Це теж необов'язково. + print("some_var дорівнює 10.") + + +""" +Цикли For проходять по спискам + +Результат: + собака — це ссавець + кішка — це ссавець + миша — це ссавець +""" +for animal in ["собака", "кішка", "миша"]: + # Можете використовувати оператор {0} для інтерполяції форматованих рядків + print "{0} — це ссавець".format(animal) + +""" +"range(число)" повертає список чисел +від нуля до заданого числа +Друкує: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) +""" +"range(нижня_границя, верхня_границя)" повертає список чисел +від нижньої границі до верхньої +Друкує: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +Цикли while продовжуються до тих пір, поки вказана умова не стане хибною. +Друкує: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Короткий запис для x = x + 1 + +# Обробляйте винятки блоками try/except + +# Працює у Python 2.6 і вище: +try: + # Аби створити виняток, використовується raise + raise IndexError("Помилка у індексі!") +except IndexError as e: + pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається + # відновлення після помилки. +except (TypeError, NameError): + pass # Винятки можна обробляти групами, якщо потрібно. +else: # Необов'язковий вираз. Має слідувати за останнім блоком except + print("Все добре!") # Виконається лише якщо не було ніяких винятків +finally: # Виконується у будь-якому випадку + print "Тут ми можемо звільнити ресурси" + +# Замість try/finally для звільнення ресурсів +# ви можете використовувати вираз with +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +## 4. Функції +#################################################### + +# Використовуйте def для створення нових функцій +def add(x, y): + print "x дорівнює {0}, а y дорівнює {1}".format(x, y) + return x + y # Повертайте результат за допомогою ключового слова return + + +# Виклик функції з аргументами +add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 6» і повертає 11 + +# Інший спосіб виклику функції — виклик з іменованими аргументами +add(y=6, x=5) # Іменовані аргументи можна вказувати у будь-якому порядку + + +# Ви можете визначити функцію, яка приймає змінну кількість аргументів, +# які будуть інтерпретовані як кортеж, за допомогою * +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1,2,3) + + +# А також можете визначити функцію, яка приймає змінне число +# іменованих аргументів, котрі будуть інтерпретовані як словник, за допомогою ** +def keyword_args(**kwargs): + return kwargs + + +# Давайте подивимось що з цього вийде +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + +# Якщо хочете, можете використовувати обидва способи одночасно +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) + + +""" +all_the_args(1, 2, a=3, b=4) друкує: + (1, 2) + {"a": 3, "b": 4} +""" + +# Коли викликаєте функції, то можете зробити навпаки! +# Використовуйте символ * аби розпакувати позиційні аргументи і +# ** для іменованих аргументів +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # еквівалентно foo(1, 2, 3, 4) +all_the_args(**kwargs) # еквівалентно foo(a=3, b=4) +all_the_args(*args, **kwargs) # еквівалентно foo(1, 2, 3, 4, a=3, b=4) + +# ви можете передавати довільне число позиційних або іменованих аргументів +# іншим функціям, які їх приймають, розпаковуючи за допомогою +# * або ** відповідно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Область визначення функцій +x = 5 + + +def set_x(num): + # Локальна змінна x - не те ж саме, що глобальна змінна x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # глобальна змінна x тепер дорівнює 6 + print x # => 6 + + +set_x(43) +set_global_x(6) + +# В Python функції є об'єктами першого класу +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Також є і анонімні функції +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Присутні вбудовані функції вищого порядку +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Для зручного відображення і фільтрації можна використовувати +# включення у вигляді списків +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Ви також можете скористатися включеннями множин та словників +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Класи +#################################################### + +# Аби отримати клас, ми наслідуємо object. +class Human(object): + # Атрибут класу. Він розділяється всіма екземплярами цього класу. + species = "H. sapiens" + + # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу + # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені + # використовується для позначення об'єктів та атрибутів, + # які використовуються Python, але знаходяться у просторах імен, + # якими керує користувач. Не варто вигадувати для них імена самостійно. + def __init__(self, name): + # Присвоєння значення аргумента атрибуту класу name + self.name = name + + # Ініціалізуємо властивість + self.age = 0 + + # Метод екземпляру. Всі методи приймають self у якості першого аргументу + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Методи класу розділяються між усіма екземплярами + # Вони викликаються з вказанням викликаючого класу + # у якості першого аргументу + @classmethod + def get_species(cls): + return cls.species + + # Статичний метод викликається без посилання на клас або екземпляр + @staticmethod + def grunt(): + return "*grunt*" + + # Властивість. + # Перетворює метод age() в атрибут тільки для читання + # з таким же ім'ям. + @property + def age(self): + return self._age + + # Це дозволяє змінювати значення властивості + @age.setter + def age(self, age): + self._age = age + + # Це дозволяє видаляти властивість + @age.deleter + def age(self): + del self._age + + +# Створюємо екземпляр класу +i = Human(name="Данило") +print(i.say("привіт")) # Друкує: «Данило: привіт» + +j = Human("Меланка") +print(j.say("Привіт")) # Друкує: «Меланка: привіт» + +# Виклик методу класу +i.get_species() # => "H. sapiens" + +# Зміна розділюваного атрибуту +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Виклик статичного методу +Human.grunt() # => "*grunt*" + +# Оновлюємо властивість +i.age = 42 + +# Отримуємо значення +i.age # => 42 + +# Видаляємо властивість +del i.age +i.age # => виникає помилка атрибуту + +#################################################### +## 6. Модулі +#################################################### + +# Ви можете імпортувати модулі +import math + +print(math.sqrt(16)) # => 4 + +# Ви можете імпортувати окремі функції з модуля +from math import ceil, floor + +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Можете імпортувати всі функції модуля. +# Попередження: краще так не робіть +from math import * + +# Можете скорочувати імена модулів +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Ви також можете переконатися, що функції еквівалентні +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# Модулі в Python — це звичайні Python-файли. Ви +# можете писати свої модулі та імпортувати їх. Назва +# модуля співпадає з назвою файлу. + +# Ви можете дізнатися, які функції та атрибути визначені +# в модулі +import math + +dir(math) + + +# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що +# і ваш поточний скрипт, то файл math.py +# може бути завантажено замість вбудованого у Python модуля. +# Так трапляється, оскільки локальна папка має перевагу +# над вбудованими у Python бібліотеками. + +#################################################### +## 7. Додатково +#################################################### + +# Генератори +# Генератор "генерує" значення тоді, коли вони запитуються, замість того, +# щоб зберігати все одразу + +# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх +# в `double_arr`. При великих розмірах може знадобитися багато ресурсів! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх, +# аби перевірити умову +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Натомість ми можемо скористатися генератором, аби "згенерувати" +# подвійне значення, як тільки воно буде запитане +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по +# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються +# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми +# виходимо з циклу і більше не подвоюємо більшість значень, +# які отримали на вхід (НАБАГАТО ШВИДШЕ!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Між іншим: ви помітили використання `range` у `test_non_generator` і +# `xrange` у `test_generator`? +# Як `double_numbers_generator` є версією-генератором `double_numbers`, так +# і `xrange` є аналогом `range`, але у вигляді генератора. +# `range` поверне нам масив з 1000000 значень +# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді, +# коли ми їх запитуємо / будемо проходитись по ним. + +# Аналогічно включенням у вигляді списків, ви можете створювати включення +# у вигляді генераторів. +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # друкує -1 -2 -3 -4 -5 + +# Включення у вигляді генератора можна явно перетворити у список +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Декоратори +# Декоратор – це функція вищого порядку, яка приймає та повертає функцію. +# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в +# список fruits, який повертає цільова функція get_fruits. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# У цьому прикладі beg обертає say +# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення, +# що повертається, буде змінено. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Будь ласка! Я бідний :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Ви можете купити мені пива?" + return msg, say_please + + +print say() # Ви можете купити мені пива? +print say(say_please=True) # Ви можете купити мені пива? Будь ласка! Я бідний :( +``` + +## Готові до більшого? + +### Безкоштовні онлайн-матеріали + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Официальная документация](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +### Платні + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + -- cgit v1.2.3 From 0aaae2653cc4edef745c7f0de2b5c038097337d2 Mon Sep 17 00:00:00 2001 From: LukaxFeh <32396925+LukaxFeh@users.noreply.github.com> Date: Sun, 29 Oct 2017 13:09:01 -0200 Subject: Fix file names in french (#2984) * fix file name * fix file names * fix file names * fix file names * fix file names * fix file names --- fr-fr/d-fr.html.markdown | 264 +++++++++++++++ fr-fr/d.html.markdown | 264 --------------- fr-fr/haskell-fr.html.markdown | 431 +++++++++++++++++++++++++ fr-fr/haskell.html.markdown | 431 ------------------------- fr-fr/markdown-fr.html.markdown | 289 +++++++++++++++++ fr-fr/markdown.html.markdown | 289 ----------------- fr-fr/php-fr.html.markdown | 697 ++++++++++++++++++++++++++++++++++++++++ fr-fr/php.html.markdown | 697 ---------------------------------------- fr-fr/scala-fr.html.markdown | 460 ++++++++++++++++++++++++++ fr-fr/scala.html.markdown | 460 -------------------------- fr-fr/vim-fr.html.markdown | 239 ++++++++++++++ fr-fr/vim.html.markdown | 239 -------------- 12 files changed, 2380 insertions(+), 2380 deletions(-) create mode 100644 fr-fr/d-fr.html.markdown delete mode 100644 fr-fr/d.html.markdown create mode 100644 fr-fr/haskell-fr.html.markdown delete mode 100644 fr-fr/haskell.html.markdown create mode 100644 fr-fr/markdown-fr.html.markdown delete mode 100644 fr-fr/markdown.html.markdown create mode 100644 fr-fr/php-fr.html.markdown delete mode 100644 fr-fr/php.html.markdown create mode 100644 fr-fr/scala-fr.html.markdown delete mode 100644 fr-fr/scala.html.markdown create mode 100644 fr-fr/vim-fr.html.markdown delete mode 100644 fr-fr/vim.html.markdown diff --git a/fr-fr/d-fr.html.markdown b/fr-fr/d-fr.html.markdown new file mode 100644 index 00000000..8d98f9dc --- /dev/null +++ b/fr-fr/d-fr.html.markdown @@ -0,0 +1,264 @@ +--- +language: D +filename: learnd-fr.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +translators: + - ["Quentin Ladeveze", "aceawan.eu"] +lang: fr-fr +--- + +```c +// Commençons par un classique +module hello; + +import std.stdio; + +// args n'est pas obligatoire +void main(string[] args) { + writeln("Bonjour le monde !"); +} +``` + +Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a +de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). +D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient +des fonctionnalités aussi bien de bas niveau que de haut niveau. + +D est activement développé par de nombreuses personnes très intelligents, guidées par +[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et +[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). +Après cette petite introduction, jetons un coup d'oeil à quelques exemples. + +```c +import std.stdio; + +void main() { + //Les conditions et les boucles sont classiques. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // On peut utiliser auto pour inférer automatiquement le + // type d'une variable. + auto n = 1; + + // On peut faciliter la lecture des valeurs numériques + // en y insérant des `_`. + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For et while sont très utiles, mais en D, on préfère foreach. + // Les deux points : '..', créent un intervalle continu de valeurs + // incluant la première mais excluant la dernière. + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // On peut également utiliser foreach_reverse pour itérer à l'envers. + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("Non !"); + } + } +} +``` +On peut définir de nouveaux types avec les mots-clés `struct`, `class`, +`union` et `enum`. Ces types sont passés à la fonction par valeur (ils sont copiés) +De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. + +```c +// Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. +struct LinkedList(T) { + T data = null; + + // Utilisez '!' pour instancier un type paramétré. + // Encore une fois semblable à '' + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + + // S'il n'y a qu'un seul paramètre de template, + // on peut s'abstenir de mettre des parenthèses. + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Utilisez alias pour créer des abreviations pour les types. +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// On peut tout aussi bien créer des templates de function ! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé +// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur. +// Ici ils seront toujours passés par référence à 'swap()'. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// Avec les templates, on peut également passer des valeurs en paramètres. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // T est 'int' par défaut + +``` +À propos de classes, parlons des propriétés. Une propriété est, en gros, +une méthode qui peut se comporter comme une lvalue. On peut donc utiliser +la syntaxe des structures classiques (`struct.x = 7`) comme si il +s'agissait de méthodes getter ou setter. + +```c +// Considérons une classe paramétrée avec les types 'T' et 'U' +class MyClass(T, U) { + T _data; + U _other; +} + +// Et des méthodes "getter" et "setter" comme suit: +class MyClass(T, U) { + T _data; + U _other; + + // Les constructeurs s'appellent toujours 'this'. + this(T t, U u) { + // Ceci va appeller les setters ci-dessous. + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +// Et on l'utilise de cette façon: +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + // Importer le module 'stdio' de la bibliothèque standard permet + // d'écrire dans la console (les imports peuvent être locaux à une portée) + import std.stdio; + + // On appelle les getters pour obtenir les valeurs. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // On appelle les setter pour assigner de nouvelles valeurs. + mc.data = 8; + mc.other = "eight"; + + // On appelle les setter pour obtenir les nouvelles valeurs. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` +Avec les propriétés, on peut construire nos setters et nos getters +comme on le souhaite, tout en gardant une syntaxe très propre, +comme si on accédait directement à des membres de la classe. + +Les autres fonctionnalités orientées objets à notre disposition +incluent les interfaces, les classes abstraites, et la surcharge +de méthodes. D gère l'héritage comme Java: On ne peut hériter que +d'une seule classe et implémenter autant d'interface que voulu. + +Nous venons d'explorer les fonctionnalités objet du D, mais changeons +un peu de domaine. D permet la programmation fonctionelle, avec les fonctions +de premier ordre, les fonctions `pures` et les données immuables. +De plus, tout vos algorithmes fonctionels favoris (map, reduce, filter) +sont disponibles dans le module `std.algorithm`. + +```c +import std.algorithm : map, filter, reduce; +import std.range : iota; // construit un intervalle excluant la dernière valeur. + +void main() { + // On veut un algorithme qui affiche la somme de la liste des carrés + // des entiers paires de 1 à 100. Un jeu d'enfant ! + + // On se contente de passer des expressions lambda en paramètre à des templates. + // On peut fournir au template n'importe quelle fonction, mais dans notre + // cas, les lambdas sont pratiques. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Vous voyez qu'on a calculé `num` comme on le ferait en haskell par exemple ? +C'est grâce à une innovation de D qu'on appelle "Uniform Function Call Syntax". +Avec l'UFCS, on peut choisir d'écrire un appel à une fonction de manière +classique, ou comme un appel à une méthode. Walter Brighter a écrit un +article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +Pour faire court, on peut appeller une fonction dont le premier paramètre +est de type A, comme si c'était une méthode de A. + +J'aime le parallélisme. Vous aimez le parallélisme ? Bien sûr que vous aimez ça. +Voyons comment on le fait en D ! + +```c +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // On veut calculer la racine carrée de tous les nombres + // dans notre tableau, et profiter de tous les coeurs + // à notre disposition. + auto arr = new double[1_000_000]; + + // On utilise un index et une référence à chaque élément du tableau. + // On appelle juste la fonction parallel sur notre tableau ! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown deleted file mode 100644 index 8d98f9dc..00000000 --- a/fr-fr/d.html.markdown +++ /dev/null @@ -1,264 +0,0 @@ ---- -language: D -filename: learnd-fr.d -contributors: - - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] -translators: - - ["Quentin Ladeveze", "aceawan.eu"] -lang: fr-fr ---- - -```c -// Commençons par un classique -module hello; - -import std.stdio; - -// args n'est pas obligatoire -void main(string[] args) { - writeln("Bonjour le monde !"); -} -``` - -Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a -de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). -D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient -des fonctionnalités aussi bien de bas niveau que de haut niveau. - -D est activement développé par de nombreuses personnes très intelligents, guidées par -[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et -[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). -Après cette petite introduction, jetons un coup d'oeil à quelques exemples. - -```c -import std.stdio; - -void main() { - //Les conditions et les boucles sont classiques. - for(int i = 0; i < 10000; i++) { - writeln(i); - } - - // On peut utiliser auto pour inférer automatiquement le - // type d'une variable. - auto n = 1; - - // On peut faciliter la lecture des valeurs numériques - // en y insérant des `_`. - while(n < 10_000) { - n += n; - } - - do { - n -= (n / 2); - } while(n > 0); - - // For et while sont très utiles, mais en D, on préfère foreach. - // Les deux points : '..', créent un intervalle continu de valeurs - // incluant la première mais excluant la dernière. - foreach(i; 1..1_000_000) { - if(n % 2 == 0) - writeln(i); - } - - // On peut également utiliser foreach_reverse pour itérer à l'envers. - foreach_reverse(i; 1..int.max) { - if(n % 2 == 1) { - writeln(i); - } else { - writeln("Non !"); - } - } -} -``` -On peut définir de nouveaux types avec les mots-clés `struct`, `class`, -`union` et `enum`. Ces types sont passés à la fonction par valeur (ils sont copiés) -De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. - -```c -// Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. -struct LinkedList(T) { - T data = null; - - // Utilisez '!' pour instancier un type paramétré. - // Encore une fois semblable à '' - LinkedList!(T)* next; -} - -class BinTree(T) { - T data = null; - - // S'il n'y a qu'un seul paramètre de template, - // on peut s'abstenir de mettre des parenthèses. - BinTree!T left; - BinTree!T right; -} - -enum Day { - Sunday, - Monday, - Tuesday, - Wednesday, - Thursday, - Friday, - Saturday, -} - -// Utilisez alias pour créer des abreviations pour les types. -alias IntList = LinkedList!int; -alias NumTree = BinTree!double; - -// On peut tout aussi bien créer des templates de function ! -T max(T)(T a, T b) { - if(a < b) - return b; - - return a; -} - -// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé -// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur. -// Ici ils seront toujours passés par référence à 'swap()'. -void swap(T)(ref T a, ref T b) { - auto temp = a; - - a = b; - b = temp; -} - -// Avec les templates, on peut également passer des valeurs en paramètres. -class Matrix(uint m, uint n, T = int) { - T[m] rows; - T[n] columns; -} - -auto mat = new Matrix!(3, 3); // T est 'int' par défaut - -``` -À propos de classes, parlons des propriétés. Une propriété est, en gros, -une méthode qui peut se comporter comme une lvalue. On peut donc utiliser -la syntaxe des structures classiques (`struct.x = 7`) comme si il -s'agissait de méthodes getter ou setter. - -```c -// Considérons une classe paramétrée avec les types 'T' et 'U' -class MyClass(T, U) { - T _data; - U _other; -} - -// Et des méthodes "getter" et "setter" comme suit: -class MyClass(T, U) { - T _data; - U _other; - - // Les constructeurs s'appellent toujours 'this'. - this(T t, U u) { - // Ceci va appeller les setters ci-dessous. - data = t; - other = u; - } - - // getters - @property T data() { - return _data; - } - - @property U other() { - return _other; - } - - // setters - @property void data(T t) { - _data = t; - } - - @property void other(U u) { - _other = u; - } -} - -// Et on l'utilise de cette façon: -void main() { - auto mc = new MyClass!(int, string)(7, "seven"); - - // Importer le module 'stdio' de la bibliothèque standard permet - // d'écrire dans la console (les imports peuvent être locaux à une portée) - import std.stdio; - - // On appelle les getters pour obtenir les valeurs. - writefln("Earlier: data = %d, str = %s", mc.data, mc.other); - - // On appelle les setter pour assigner de nouvelles valeurs. - mc.data = 8; - mc.other = "eight"; - - // On appelle les setter pour obtenir les nouvelles valeurs. - writefln("Later: data = %d, str = %s", mc.data, mc.other); -} -``` -Avec les propriétés, on peut construire nos setters et nos getters -comme on le souhaite, tout en gardant une syntaxe très propre, -comme si on accédait directement à des membres de la classe. - -Les autres fonctionnalités orientées objets à notre disposition -incluent les interfaces, les classes abstraites, et la surcharge -de méthodes. D gère l'héritage comme Java: On ne peut hériter que -d'une seule classe et implémenter autant d'interface que voulu. - -Nous venons d'explorer les fonctionnalités objet du D, mais changeons -un peu de domaine. D permet la programmation fonctionelle, avec les fonctions -de premier ordre, les fonctions `pures` et les données immuables. -De plus, tout vos algorithmes fonctionels favoris (map, reduce, filter) -sont disponibles dans le module `std.algorithm`. - -```c -import std.algorithm : map, filter, reduce; -import std.range : iota; // construit un intervalle excluant la dernière valeur. - -void main() { - // On veut un algorithme qui affiche la somme de la liste des carrés - // des entiers paires de 1 à 100. Un jeu d'enfant ! - - // On se contente de passer des expressions lambda en paramètre à des templates. - // On peut fournir au template n'importe quelle fonction, mais dans notre - // cas, les lambdas sont pratiques. - auto num = iota(1, 101).filter!(x => x % 2 == 0) - .map!(y => y ^^ 2) - .reduce!((a, b) => a + b); - - writeln(num); -} -``` - -Vous voyez qu'on a calculé `num` comme on le ferait en haskell par exemple ? -C'est grâce à une innovation de D qu'on appelle "Uniform Function Call Syntax". -Avec l'UFCS, on peut choisir d'écrire un appel à une fonction de manière -classique, ou comme un appel à une méthode. Walter Brighter a écrit un -article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) -Pour faire court, on peut appeller une fonction dont le premier paramètre -est de type A, comme si c'était une méthode de A. - -J'aime le parallélisme. Vous aimez le parallélisme ? Bien sûr que vous aimez ça. -Voyons comment on le fait en D ! - -```c -import std.stdio; -import std.parallelism : parallel; -import std.math : sqrt; - -void main() { - // On veut calculer la racine carrée de tous les nombres - // dans notre tableau, et profiter de tous les coeurs - // à notre disposition. - auto arr = new double[1_000_000]; - - // On utilise un index et une référence à chaque élément du tableau. - // On appelle juste la fonction parallel sur notre tableau ! - foreach(i, ref elem; parallel(arr)) { - ref = sqrt(i + 1.0); - } -} - - -``` diff --git a/fr-fr/haskell-fr.html.markdown b/fr-fr/haskell-fr.html.markdown new file mode 100644 index 00000000..a34dc098 --- /dev/null +++ b/fr-fr/haskell-fr.html.markdown @@ -0,0 +1,431 @@ +--- +language: Haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["David Baumgartner", "http://davidbaumgartner.ch"] +lang: fr-fr +filename: learnhaskell-fr.hs +--- + +Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. + +```haskell +-- Un commentaire en une ligne commence avec deux tirets. +{- Un commentaire sur plusieurs lignes peut être contenu dans +un bloc de cette façon. +-} + +---------------------------------------------------- +-- 1. Types de données primitifs et opérateurs +---------------------------------------------------- + +-- Vous avez les nombres +3 -- 3 + +-- Les maths sont comme vous vous y attendez +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- La division n'est pas entière par défaut +35 / 4 -- 8.75 + +-- division entière +35 `div` 4 -- 8 + +-- Les booléens sont primitifs +True +False + +-- Opérations avec les booléens +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Dans les exemples plus hauts, `not` est une fonction qui prend une valeur. +-- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous +-- les arguments sont juste listés après la fonction. Le schéma général est +-- donc : +-- func arg1 arg2 arg3... +-- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. + +-- Caractères et chaînes de caractère +"Ceci est une chaîne de caractère." +'a' -- caractère +'Vous ne pouvez pas utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! + +-- Les chaînes peuvent être concaténées +"Hello " ++ "world!" -- "Hello world!" + +-- Une chaîne de caractère est *réellement* une liste +"Ceci est une chaîne." !! 0 -- 'C' + + +---------------------------------------------------- +-- 2. Listes et tuples +---------------------------------------------------- + +-- Tous les éléments d'une liste doit avoir le même type. +-- les deux lignes suivantes sont semblables +[1, 2, 3, 4, 5] +[1..5] + +-- Il y a aussi des listes infinies en Haskell ! +[1..] -- une liste de tous les nombres naturels + +-- Les listes infinies fonctionnent parce que Haskell est « paresseux »: +-- ça veut dire qu'il n'évalue que ce qui a besoin de l'être. Vous pouvez +-- donc vous demander le 1000e élément de votre liste et il vous le donnera : + +[1..] !! 999 -- 1000 + +-- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste +-- de cette liste « infinie » n'existe pas encore ! En fait, Haskell ne va jamais +-- le faire à moins qu'il ne le doive. + +-- Adjoindre deux listes +[1..5] ++ [6..10] + +-- ajouter au début de la liste +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- l'indice d'une liste +[0..] !! 5 -- 5 + +-- d'autres opérations sur les listes +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +--liste en compréhension +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +--avec un conditionnel +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Chaque élément d'un tuple peut être d'un type différent, mais un +-- tuple a une longueur fixée. +-- Un tuple : +("haskell", 1) + +-- accéder aux éléments d'un tuple +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Functions +---------------------------------------------------- +-- Une simple fonction qui prend deux paramètres +add a b = a + b + +-- Notez que si vous utilisez ghci (l'interpréteur Haskell) +-- vous devrez utiliser `let`. Par exemple : +-- let add a b = a + b + +-- Utiliser une fonction +add 1 2 -- 3 + +-- Vous pouvez également mettre le nom de la fonction entre les +-- deux arguments avec des accents graves : +1 `add` 2 -- 3 + +-- Vous pouvez également définir des fonctions qui n'ont pas de +-- lettres ! Ça vous laisse créer vos propres opérateurs ! Voilà +-- un opérateur qui fait une division entière : +(//) a b = a `div` b +35 // 4 -- 8 + +-- Gardes : Une façon de gérer la valeur de vos arguments en amont +fib x + | x < 2 = x + | otherwise = fib (x - 1) + fib (x - 2) + +-- Le filtrage par motif est similaire. Là, on a donné trois +-- définitions différentes de `fib`. Haskell appellera automatiquement +-- la première fonction qui correspond au motif de la valeur. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Filtrage par motif sur un tuple. +foo (x, y) = (x + 1, y + 2) + +-- Filtrage par motif sur des listes. Ici, `x` est le premier +-- élément de la liste, et `xs` le reste. On peut écrire notre +-- propre fonction `map` : +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Les fonctions anonymes sont créées avec des barres obliques +-- inverses, suivies de tous les arguments. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- Une utilisation de fold (appelée `inject` dans quelques autres +-- langages) avec comme paramètre une fonction anonyme. +-- `foldl1` veut dire fold left -- soit littéralement pli gauche -- +-- et utilise la première valeur de la liste comme accumulateur. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Plus de fonctions +---------------------------------------------------- + +-- curryfication : si vous n'appliquez pas tous les arguments à une +-- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne +-- une fonction qui prend le reste des arguments. + +add a b = a + b +foo = add 10 -- foo est une fonction qui prend un nombre et y ajoute 10 +foo 5 -- 15 + +-- Une autre façon de l'écrire +foo = (+10) +foo 5 -- 15 + +-- Composition de fonctions +-- la fonction (.) enchaîne deux fonctions. +-- Par exemple, on a foo qui est une fonction qui prend une valeur, y ajoute +-- 10 et multiplie ce résultat par 5, et ensuite retourne la valeur finale. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fixation de priorité +-- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité +-- de sorte que tout ce qu'il y a à sa gauche est calculé d'abord et ensuite +-- appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser `.` et `$` +-- pour vous débarrasser de beaucoup de parenthèses : + +-- avant +(even (fib 7)) -- False + +-- ensuite +even . fib $ 7 -- False + +---------------------------------------------------- +-- 5. Signature de type +---------------------------------------------------- + +-- Haskell a un système de types très strict : par exemple, tout a un type. + +-- Quelques types simples : +5 :: Integer +"hello" :: String +True :: Bool + +-- Les fonctions ont également des types. +-- `not` prend un booléen et retourne un booléen. +-- not :: Bool -> Bool + +-- Voilà une fonction qui prend deux paramètres. +-- add :: Integer -> Integer -> Integer + +-- Quand vous définissez une valeur (souvenez-vous, tout est valeur en +-- Haskell), une bonne pratique est d'écrire son type explicitement +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Flux de contrôle et structures conditionnelles +---------------------------------------------------- + +-- structure conditionnelle if +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- les structures if peuvent être écrites sur plusieurs lignes +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- les structures case : voilà comment vous pourriez analyser les arguments de +-- ligne de commande +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + + +-- Haskell n'a pas de boucles parce qu'il utilise la récursion. +-- `map` applique une fonction sur chaque élément d'une liste + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- vous pouvez créer une fonction `for` en utilisant `map` +for array func = map func array + +-- et l'utiliser +for [0..5] $ \i -> show i + +-- nous aurions pu l'écrire également ainsi +for [0..5] show + +-- vous pouvez utiliser foldl et foldr pour +-- réduire une liste +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- C'est donc la même chose que +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl évalue de gauche à droite, foldr +-- de droite à gauche +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Et c'est équivalent à +(2 * 3 + (2 * 2 + (2 * 1 + 4))) + +---------------------------------------------------- +-- 7. Types de données +---------------------------------------------------- + +-- Vous pouvez écrire vos propres types de données en Haskell + +data Couleur = Rouge | Bleu | Vert + +-- Et maintenant l'utiliser dans une fonction + + +say :: Couleur -> String +say Rouge = "Vous êtes Rouge !" +say Bleu = "Vous êtes Bleu !" +say Vert = "Vous êtes Vert !" + +-- Vos types peuvent également avoir des paramètres + +data Maybe a = Nothing | Just a + +-- Tous les exemples ci-dessous sont issus du type Maybe +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Tandis que l'IO ne peut pas être totalement expliqué pleinement +-- sans que les monades ne le soient, il n'est pas difficile +-- d'expliquer suffisamment pour commencer. + +-- Quand un programme en Haskell est exécuté, la fonction `main` +-- est appelée. Il doit retourner une valeur de type `IO ()`. +-- Par exemple : + +main :: IO () +main = putStrLn $ "Bonjour, le ciel ! " ++ (say Blue) +-- putStrLn a comme type String -> IO () + +-- La façon la plus simple pour faire de l'IO est de faire un programme +-- fonction de String vers String. La fonction +-- interact :: (String -> String) -> IO () +-- prend un texte, applique une fonction et affiche le résultat. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Vous pouvez considérer qu'une valeur de type `IO ()` représente +-- une séquence d'actions que l'ordinateur exécute, un peu comme +-- dans un langage impératif. On peut utiliser la structure `do` +-- pour enchaîner des actions. Par exemple : + +sayHello :: IO () +sayHello = do + putStrLn "Quel est ton nom ?" + name <- getLine -- prend une ligne et assigne sa valeur à `name` + putStrLn $ "Salut, " ++ name + +-- Exercice : écrire votre propre version d'`interact` qui ne fait +-- que de lire une ligne d'entrée. + +-- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule +-- action qui sera exécutée est la valeur de `main`. +-- Pour lancer `sayHello`, commentez l'ancienne définition de `main` +-- et remplacez-le par : +-- main = sayHello + +-- Essaions de mieux comprendre comment la fonction `getLine` que +-- nous venons d'utiliser. Son type est : +-- getLine :: IO String +-- vous pouvez considérer le type `IO a` comme un programme que +-- le programme va générer comme une valeur de type `a` quand +-- il sera exécuté. On peut l'enregistrer et la réutiliser en +-- utilisant `<-`. On peut aussi faire nos propres actions +-- de type `IO String` : + +action :: IO String +action = do + putStrLn "C'est une ligne. Heu" + input1 <- getLine + input2 <- getLine + -- Le type de la structure `do` est celui de sa dernière ligne. + -- `return` n'est pas un mot clef, mais simplement une fonction. + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- On peut maintenant l'utiliser comme on a utilisé `getLine` +-- tout à l'heure + +main'' = do + putStrLn "Je vais afficher deux lignes !" + result <- action + putStrLn result + putStrLn "C'était tout !" + +-- Le type `IO` est un exemple de « monade ». La façon dont Haskell utilise +-- une monade pour faire de l'IO lui permet d'être purement fonctionnel. N'importe +-- quelle fonction qui interagit avec le « monde extérieur » (c'est à dire fait de l'IO) +-- devient marqué comme `IO` dans la signature de son type. Ça nous montre +-- quelles fonctions sont « pures » (n'interagissent pas avec le monde extérieur +-- ou ne changent pas d'état) et quelles fonctions ne le sont pas. + +-- C'est une fonctionnalité très puissante, car il est facile d'exécuter +-- des fonctions pures simultanément, et donc la concurrence en Haskell +-- est très facile. + + +---------------------------------------------------- +-- 9. Le REPL de Haskell +---------------------------------------------------- + +-- Lancer le REPL en tapant `ghci`. +-- Vous pouvez maintenant taper du code Haskell. +-- Toutes les nouvelles valeurs peuvent être crées +-- avec `let` : + +let foo = 5 + +-- Vous pouvez voir le type de n'importe quelle valeur avec `:t` : + +>:t foo +foo :: Integer + +-- Vous pouvez également lancer des actions de type `IO ()` + +> sayHello +Quel est ton nom ? +Ami +Salut, Ami ! + +``` + +Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple : une implémentation de quicksort : + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell facile à installer. Téléchargez-le [ici](http://www.haskell.org/platform/). + +Vous pouvez trouver une approche beaucoup plus douce avec les excellents +[Learn you a Haskell](http://lyah.haskell.fr/) ou +[Real World Haskell (en)](http://book.realworldhaskell.org/). diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown deleted file mode 100644 index a34dc098..00000000 --- a/fr-fr/haskell.html.markdown +++ /dev/null @@ -1,431 +0,0 @@ ---- -language: Haskell -contributors: - - ["Adit Bhargava", "http://adit.io"] -translators: - - ["David Baumgartner", "http://davidbaumgartner.ch"] -lang: fr-fr -filename: learnhaskell-fr.hs ---- - -Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie. - -```haskell --- Un commentaire en une ligne commence avec deux tirets. -{- Un commentaire sur plusieurs lignes peut être contenu dans -un bloc de cette façon. --} - ----------------------------------------------------- --- 1. Types de données primitifs et opérateurs ----------------------------------------------------- - --- Vous avez les nombres -3 -- 3 - --- Les maths sont comme vous vous y attendez -1 + 1 -- 2 -8 - 1 -- 7 -10 * 2 -- 20 -35 / 5 -- 7.0 - --- La division n'est pas entière par défaut -35 / 4 -- 8.75 - --- division entière -35 `div` 4 -- 8 - --- Les booléens sont primitifs -True -False - --- Opérations avec les booléens -not True -- False -not False -- True -1 == 1 -- True -1 /= 1 -- False -1 < 10 -- True - --- Dans les exemples plus hauts, `not` est une fonction qui prend une valeur. --- Haskell n'a pas besoin de parenthèses pour appeler une fonction... tous --- les arguments sont juste listés après la fonction. Le schéma général est --- donc : --- func arg1 arg2 arg3... --- Voyez la section sur les fonctions pour savoir comment écrire les vôtres. - --- Caractères et chaînes de caractère -"Ceci est une chaîne de caractère." -'a' -- caractère -'Vous ne pouvez pas utiliser des apostrophes pour les chaînes de caractère.' -- erreur ! - --- Les chaînes peuvent être concaténées -"Hello " ++ "world!" -- "Hello world!" - --- Une chaîne de caractère est *réellement* une liste -"Ceci est une chaîne." !! 0 -- 'C' - - ----------------------------------------------------- --- 2. Listes et tuples ----------------------------------------------------- - --- Tous les éléments d'une liste doit avoir le même type. --- les deux lignes suivantes sont semblables -[1, 2, 3, 4, 5] -[1..5] - --- Il y a aussi des listes infinies en Haskell ! -[1..] -- une liste de tous les nombres naturels - --- Les listes infinies fonctionnent parce que Haskell est « paresseux »: --- ça veut dire qu'il n'évalue que ce qui a besoin de l'être. Vous pouvez --- donc vous demander le 1000e élément de votre liste et il vous le donnera : - -[1..] !! 999 -- 1000 - --- Et là, Haskell a évalué les éléments 1 à 1000 de la liste... mais le reste --- de cette liste « infinie » n'existe pas encore ! En fait, Haskell ne va jamais --- le faire à moins qu'il ne le doive. - --- Adjoindre deux listes -[1..5] ++ [6..10] - --- ajouter au début de la liste -0:[1..5] -- [0, 1, 2, 3, 4, 5] - --- l'indice d'une liste -[0..] !! 5 -- 5 - --- d'autres opérations sur les listes -head [1..5] -- 1 -tail [1..5] -- [2, 3, 4, 5] -init [1..5] -- [1, 2, 3, 4] -last [1..5] -- 5 - ---liste en compréhension -[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] - ---avec un conditionnel -[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] - --- Chaque élément d'un tuple peut être d'un type différent, mais un --- tuple a une longueur fixée. --- Un tuple : -("haskell", 1) - --- accéder aux éléments d'un tuple -fst ("haskell", 1) -- "haskell" -snd ("haskell", 1) -- 1 - ----------------------------------------------------- --- 3. Functions ----------------------------------------------------- --- Une simple fonction qui prend deux paramètres -add a b = a + b - --- Notez que si vous utilisez ghci (l'interpréteur Haskell) --- vous devrez utiliser `let`. Par exemple : --- let add a b = a + b - --- Utiliser une fonction -add 1 2 -- 3 - --- Vous pouvez également mettre le nom de la fonction entre les --- deux arguments avec des accents graves : -1 `add` 2 -- 3 - --- Vous pouvez également définir des fonctions qui n'ont pas de --- lettres ! Ça vous laisse créer vos propres opérateurs ! Voilà --- un opérateur qui fait une division entière : -(//) a b = a `div` b -35 // 4 -- 8 - --- Gardes : Une façon de gérer la valeur de vos arguments en amont -fib x - | x < 2 = x - | otherwise = fib (x - 1) + fib (x - 2) - --- Le filtrage par motif est similaire. Là, on a donné trois --- définitions différentes de `fib`. Haskell appellera automatiquement --- la première fonction qui correspond au motif de la valeur. -fib 1 = 1 -fib 2 = 2 -fib x = fib (x - 1) + fib (x - 2) - --- Filtrage par motif sur un tuple. -foo (x, y) = (x + 1, y + 2) - --- Filtrage par motif sur des listes. Ici, `x` est le premier --- élément de la liste, et `xs` le reste. On peut écrire notre --- propre fonction `map` : -myMap func [] = [] -myMap func (x:xs) = func x:(myMap func xs) - --- Les fonctions anonymes sont créées avec des barres obliques --- inverses, suivies de tous les arguments. -myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] - --- Une utilisation de fold (appelée `inject` dans quelques autres --- langages) avec comme paramètre une fonction anonyme. --- `foldl1` veut dire fold left -- soit littéralement pli gauche -- --- et utilise la première valeur de la liste comme accumulateur. -foldl1 (\acc x -> acc + x) [1..5] -- 15 - ----------------------------------------------------- --- 4. Plus de fonctions ----------------------------------------------------- - --- curryfication : si vous n'appliquez pas tous les arguments à une --- fonction, elle devient « curryfiée ». Ça veut dire qu'elle retourne --- une fonction qui prend le reste des arguments. - -add a b = a + b -foo = add 10 -- foo est une fonction qui prend un nombre et y ajoute 10 -foo 5 -- 15 - --- Une autre façon de l'écrire -foo = (+10) -foo 5 -- 15 - --- Composition de fonctions --- la fonction (.) enchaîne deux fonctions. --- Par exemple, on a foo qui est une fonction qui prend une valeur, y ajoute --- 10 et multiplie ce résultat par 5, et ensuite retourne la valeur finale. -foo = (*5) . (+10) - --- (5 + 10) * 5 = 75 -foo 5 -- 75 - --- fixation de priorité --- Haskell a une autre fonction appelée `$`. Elle peut changer la priorité --- de sorte que tout ce qu'il y a à sa gauche est calculé d'abord et ensuite --- appliqué à tout ce qu'il y a à droite. Vous pouvez utiliser `.` et `$` --- pour vous débarrasser de beaucoup de parenthèses : - --- avant -(even (fib 7)) -- False - --- ensuite -even . fib $ 7 -- False - ----------------------------------------------------- --- 5. Signature de type ----------------------------------------------------- - --- Haskell a un système de types très strict : par exemple, tout a un type. - --- Quelques types simples : -5 :: Integer -"hello" :: String -True :: Bool - --- Les fonctions ont également des types. --- `not` prend un booléen et retourne un booléen. --- not :: Bool -> Bool - --- Voilà une fonction qui prend deux paramètres. --- add :: Integer -> Integer -> Integer - --- Quand vous définissez une valeur (souvenez-vous, tout est valeur en --- Haskell), une bonne pratique est d'écrire son type explicitement -double :: Integer -> Integer -double x = x * 2 - ----------------------------------------------------- --- 6. Flux de contrôle et structures conditionnelles ----------------------------------------------------- - --- structure conditionnelle if -haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" - --- les structures if peuvent être écrites sur plusieurs lignes -haskell = if 1 == 1 - then "awesome" - else "awful" - --- les structures case : voilà comment vous pourriez analyser les arguments de --- ligne de commande -case args of - "help" -> printHelp - "start" -> startProgram - _ -> putStrLn "bad args" - - --- Haskell n'a pas de boucles parce qu'il utilise la récursion. --- `map` applique une fonction sur chaque élément d'une liste - -map (*2) [1..5] -- [2, 4, 6, 8, 10] - --- vous pouvez créer une fonction `for` en utilisant `map` -for array func = map func array - --- et l'utiliser -for [0..5] $ \i -> show i - --- nous aurions pu l'écrire également ainsi -for [0..5] show - --- vous pouvez utiliser foldl et foldr pour --- réduire une liste --- foldl -foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 - --- C'est donc la même chose que -(2 * (2 * (2 * 4 + 1) + 2) + 3) - --- foldl évalue de gauche à droite, foldr --- de droite à gauche -foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 - --- Et c'est équivalent à -(2 * 3 + (2 * 2 + (2 * 1 + 4))) - ----------------------------------------------------- --- 7. Types de données ----------------------------------------------------- - --- Vous pouvez écrire vos propres types de données en Haskell - -data Couleur = Rouge | Bleu | Vert - --- Et maintenant l'utiliser dans une fonction - - -say :: Couleur -> String -say Rouge = "Vous êtes Rouge !" -say Bleu = "Vous êtes Bleu !" -say Vert = "Vous êtes Vert !" - --- Vos types peuvent également avoir des paramètres - -data Maybe a = Nothing | Just a - --- Tous les exemples ci-dessous sont issus du type Maybe -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` - ----------------------------------------------------- --- 8. Haskell IO ----------------------------------------------------- - --- Tandis que l'IO ne peut pas être totalement expliqué pleinement --- sans que les monades ne le soient, il n'est pas difficile --- d'expliquer suffisamment pour commencer. - --- Quand un programme en Haskell est exécuté, la fonction `main` --- est appelée. Il doit retourner une valeur de type `IO ()`. --- Par exemple : - -main :: IO () -main = putStrLn $ "Bonjour, le ciel ! " ++ (say Blue) --- putStrLn a comme type String -> IO () - --- La façon la plus simple pour faire de l'IO est de faire un programme --- fonction de String vers String. La fonction --- interact :: (String -> String) -> IO () --- prend un texte, applique une fonction et affiche le résultat. - -countLines :: String -> String -countLines = show . length . lines - -main' = interact countLines - --- Vous pouvez considérer qu'une valeur de type `IO ()` représente --- une séquence d'actions que l'ordinateur exécute, un peu comme --- dans un langage impératif. On peut utiliser la structure `do` --- pour enchaîner des actions. Par exemple : - -sayHello :: IO () -sayHello = do - putStrLn "Quel est ton nom ?" - name <- getLine -- prend une ligne et assigne sa valeur à `name` - putStrLn $ "Salut, " ++ name - --- Exercice : écrire votre propre version d'`interact` qui ne fait --- que de lire une ligne d'entrée. - --- Le code de `sayHello` ne sera jamais exécuté, cependant. La seule --- action qui sera exécutée est la valeur de `main`. --- Pour lancer `sayHello`, commentez l'ancienne définition de `main` --- et remplacez-le par : --- main = sayHello - --- Essaions de mieux comprendre comment la fonction `getLine` que --- nous venons d'utiliser. Son type est : --- getLine :: IO String --- vous pouvez considérer le type `IO a` comme un programme que --- le programme va générer comme une valeur de type `a` quand --- il sera exécuté. On peut l'enregistrer et la réutiliser en --- utilisant `<-`. On peut aussi faire nos propres actions --- de type `IO String` : - -action :: IO String -action = do - putStrLn "C'est une ligne. Heu" - input1 <- getLine - input2 <- getLine - -- Le type de la structure `do` est celui de sa dernière ligne. - -- `return` n'est pas un mot clef, mais simplement une fonction. - return (input1 ++ "\n" ++ input2) -- return :: String -> IO String - --- On peut maintenant l'utiliser comme on a utilisé `getLine` --- tout à l'heure - -main'' = do - putStrLn "Je vais afficher deux lignes !" - result <- action - putStrLn result - putStrLn "C'était tout !" - --- Le type `IO` est un exemple de « monade ». La façon dont Haskell utilise --- une monade pour faire de l'IO lui permet d'être purement fonctionnel. N'importe --- quelle fonction qui interagit avec le « monde extérieur » (c'est à dire fait de l'IO) --- devient marqué comme `IO` dans la signature de son type. Ça nous montre --- quelles fonctions sont « pures » (n'interagissent pas avec le monde extérieur --- ou ne changent pas d'état) et quelles fonctions ne le sont pas. - --- C'est une fonctionnalité très puissante, car il est facile d'exécuter --- des fonctions pures simultanément, et donc la concurrence en Haskell --- est très facile. - - ----------------------------------------------------- --- 9. Le REPL de Haskell ----------------------------------------------------- - --- Lancer le REPL en tapant `ghci`. --- Vous pouvez maintenant taper du code Haskell. --- Toutes les nouvelles valeurs peuvent être crées --- avec `let` : - -let foo = 5 - --- Vous pouvez voir le type de n'importe quelle valeur avec `:t` : - ->:t foo -foo :: Integer - --- Vous pouvez également lancer des actions de type `IO ()` - -> sayHello -Quel est ton nom ? -Ami -Salut, Ami ! - -``` - -Et Haskell ne se limite pas à ça, on trouve encore par exemple les classes de types et les monades. Il y a beaucoup de raisons qui font que coder en Haskell est si *fun*. Je vous laisse avec un dernier exemple : une implémentation de quicksort : - -```haskell -qsort [] = [] -qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater - where lesser = filter (< p) xs - greater = filter (>= p) xs -``` - -Haskell facile à installer. Téléchargez-le [ici](http://www.haskell.org/platform/). - -Vous pouvez trouver une approche beaucoup plus douce avec les excellents -[Learn you a Haskell](http://lyah.haskell.fr/) ou -[Real World Haskell (en)](http://book.realworldhaskell.org/). diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown new file mode 100644 index 00000000..2e4e8461 --- /dev/null +++ b/fr-fr/markdown-fr.html.markdown @@ -0,0 +1,289 @@ +--- +language: markdown +contributors: +- ["Andrei Curelaru", "http://www.infinidad.fr"] +filename: markdown-fr.md +lang: fr-fr +--- + +Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe +facile à lire et à écrire, aisément convertible en HTML + (et beaucoup d'autres formats aussi à présent). + +Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request! + + +```markdown + + + + + + + + +# Ceci est un

+## Ceci est un

+### Ceci est un

+#### Ceci est un

+##### Ceci est un

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

-## Ceci est un

-### Ceci est un

-#### Ceci est un

-##### Ceci est un

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

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

Ceci est affiché si $x est vrai

+ +

Ceci est affiché si $x est faux

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

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

Ceci est affiché si $x est vrai

- -

Ceci est affiché si $x est faux

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

Press belo', Joe

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

Press belo', Joe

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

` cho đến `

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

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

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

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

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

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

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

Ceci est affiché si $x est vrai

+ +

Ceci est affiché si $x est faux

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

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

Ceci est affiché si $x est vrai

- -

Ceci est affiché si $x est faux

- - - 2, 'car' => 4]; - -// Les boucles 'foreach' sont utiles pour parcourir les tableaux -foreach ($wheels as $wheel_count) { - echo $wheel_count; -} // Affiche "24" - -echo "\n"; - -// Il est également possible d'accéder aux clés du tableau -foreach ($wheels as $vehicle => $wheel_count) { - echo "The $vehicle have $wheel_count wheels"; -} - -echo "\n"; - -$i = 0; -while ($i < 5) { - if ($i === 3) { - break; // Permet d'arrêter la boucle - } - echo $i++; -} // Affiche "012" - -for ($i = 0; $i < 5; $i++) { - if ($i === 3) { - continue; // Permet de passer immédiatement à l'itération suivante - } - echo $i; -} // Affiche "0124" - - -/******************************** - * Fonctions - */ - -// On peut déclarer une fonction avec le mot clé 'function' -function my_function () { - return 'Hello'; -} - -echo my_function(); // => "Hello" - - -// Un nom de fonction valide commence par une lettre ou un souligné, -// suivi de n'importe quelle lettre, nombre ou de soulignés. -// Les noms des arguments d'une fonction doivent respecter le même format que -// celui des variables. - -function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1 - $result = $x + $y; - return $result; -} - -echo add(4); // => 5 -echo add(4, 2); // => 6 - -// $result n'est pas accessible en dehors de la fonction -// print $result; // Retourne un avertissement - -// Depuis PHP 5.3 on peut déclarer des fonctions anonymes -$inc = function ($x) { - return $x + 1; -}; - -echo $inc(2); // => 3 - -function foo ($x, $y, $z) { - echo "$x - $y - $z"; -} - -// Une fonction peut retourner une fonction -function bar ($x, $y) { - // On peut utiliser 'use' pour passer des variables externes - return function ($z) use ($x, $y) { - foo($x, $y, $z); - }; -} - -$bar = bar('A', 'B'); -$bar('C'); // Affiche "A - B - C" - -// On peut exécuter une fonction par son nom en chaîne de caractères -$function_name = 'add'; -echo $function_name(1, 2); // => 3 -// Utile pour déterminer par programmation quelle fonction exécuter. - -// On peut également utiliser -call_user_func(callable $callback [, $parameter [, ... ]]); - -/******************************** - * Insertions - */ - -instanceProp = $instanceProp; - } - - // Les méthodes sont déclarés par des fonctions au sein de la classe - public function myMethod() - { - print 'MyClass'; - } - - // le mot clé 'final' rend la function impossible à surcharger - final function youCannotOverrideMe() - { - } - -/* - * Les attributs et méthodes statiques peuvent être accédés sans devoir - * instancier la classe. Les attributs statiques ne sont pas accessibles depuis - * une instance, même si les méthodes statiques le sont. - */ - - public static function myStaticMethod() - { - print 'Je suis static'; - } -} - -// Les constantes d'une classe peuvent toujours être utilisé de façon statique -echo MyClass::MY_CONST; // Outputs 'value'; - -echo MyClass::$staticVar; // Retourne 'static'; -MyClass::myStaticMethod(); // Retourne 'Je suis static'; - -// On peut instancier une classe en utilisant le mot clé 'new' -$my_class = new MyClass('An instance property'); - -// On peut accéder aux attributs/méthodes d'une instance avec -> -echo $my_class->property; // => "public" -echo $my_class->instanceProp; // => "An instance property" -$my_class->myMethod(); // => "MyClass" - - -// On peut hériter d'une classe en utilisant 'extends' -class MyOtherClass extends MyClass -{ - function printProtectedProperty() - { - echo $this->prot; - } - - // Surcharge d'une méthode - function myMethod() - { - parent::myMethod(); - print ' > MyOtherClass'; - } -} - -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Retourne "protected" -$my_other_class->myMethod(); // Retourne "MyClass > MyOtherClass" - -// On peut empêcher qu'une classe soit héritée -final class YouCannotExtendMe -{ -} - -// On peut utiliser des "méthodes magiques" pour se faire des accesseurs -class MyMapClass -{ - private $property; - - public function __get($key) - { - return $this->$key; - } - - public function __set($key, $value) - { - $this->$key = $value; - } -} - -$x = new MyMapClass(); -echo $x->property; // Va utiliser la méthode __get() -$x->property = 'Something'; // Va utiliser la méthode __set() - -// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou -// elle peuvent implémenter une interface (en utilisant le mot clé 'implements'). - -// Une interface peut être déclarée avec le mot clé 'interface' - -interface InterfaceOne -{ - public function doSomething(); -} - -interface InterfaceTwo -{ - public function doSomethingElse(); -} - -// Les interfaces peuvent hériter d'autres interfaces -interface InterfaceThree extends InterfaceTwo -{ - public function doAnotherContract(); -} - -abstract class MyAbstractClass implements InterfaceOne -{ - public $x = 'doSomething'; -} - -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo -{ - public function doSomething() - { - echo $x; - } - - public function doSomethingElse() - { - echo 'doSomethingElse'; - } -} - - -// Les classes peuvent implémenter plusieurs interfaces à la fois -class SomeOtherClass implements InterfaceOne, InterfaceTwo -{ - public function doSomething() - { - echo 'doSomething'; - } - - public function doSomethingElse() - { - echo 'doSomethingElse'; - } -} - -// Il est possible de déclarer des classes internes anonymes depuis PHP 7 - -interface Logger { - public function log(string $msg); -} - -class Application { - private $logger; - - public function getLogger(): Logger { - return $this->logger; - } - - public function setLogger(Logger $logger) { - $this->logger = $logger; - } -} - -$app = new Application; - -$app->setLogger(new class implements Logger { - public function log(string $msg) { - echo $msg; - } -}); - -var_dump($app->getLogger()); // => 'object(class@anonymous)#2 (0) {}' - - -/******************************** - * Espaces de noms (namespaces) - */ - -// Cette section est séparée, car une déclaration d'espace de nom doit être -// la première chose que l'on retrouve dans un fichier PHP, -// imaginons que c'est le cas - - Date: Mon, 13 Nov 2017 00:41:52 +0300 Subject: Comments improved --- javascript.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 75bdf1ad..199c3c09 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -186,7 +186,7 @@ someVar = myArray.shift(); // Remove first element and return it myArray.push(3); // Add as the last element someVar = myArray.pop(); // Remove last element and return it -// Join all elements of an array with a string +// Join all elements of an array with semicolon var myArray0 = [32,false,"js",12,56,90]; myArray0.join(";") // = "32;false;js;12;56;90" @@ -194,8 +194,9 @@ myArray0.join(";") // = "32;false;js;12;56;90" myArray0.slice(1,4); // = [false,"js",12] // Remove 4 elements starting from index 2, and insert there strings -// "33","34" and "35"; return removed subarray -myArray0.splice(2,4,"33","34","35"); +// "hi","wr" and "ld"; return removed subarray +myArray0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90] +// myArray0 === [32,false,"hi","wr","ld"] // JavaScript's objects are equivalent to "dictionaries" or "maps" in other // languages: an unordered collection of key-value pairs. -- cgit v1.2.3 From 96436a33de166bef190cc59abef4be4e9004f131 Mon Sep 17 00:00:00 2001 From: Stephan Fuhrmann Date: Mon, 13 Nov 2017 15:59:58 +0100 Subject: Fix for wrong/mixed parenthesis usage. --- de-de/make-de.html.markdown | 7 ++++--- make.html.markdown | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown index 22c14a69..bc5c7bcb 100644 --- a/de-de/make-de.html.markdown +++ b/de-de/make-de.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] translators: - ["Martin Schimandl", "https://github.com/Git-Jiro"] filename: Makefile-de @@ -58,7 +59,7 @@ file2.txt file3.txt: file0.txt file1.txt touch file3.txt # Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt. -# Leere Rezepte zählen nicht und können dazu verwendet werden weitere +# Leere Rezepte zählen nicht und können dazu verwendet werden weitere # Voraussetzungen hinzuzufügen. #----------------------------------------------------------------------- @@ -182,9 +183,9 @@ echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb # Ein paar Variablen die von Make automatisch definiert werden. echo_inbuilt: echo $(CC) - echo ${CXX)} + echo ${CXX} echo $(FC) - echo ${CFLAGS)} + echo ${CFLAGS} echo $(CPPFLAGS) echo ${CXXFLAGS} echo $(LDFLAGS) diff --git a/make.html.markdown b/make.html.markdown index ab128475..45d020e9 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] filename: Makefile --- @@ -11,7 +12,7 @@ target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly on Unix and Linux) despite many competitors and criticisms. -There are many varieties of make in existence, however this article +There are many varieties of make in existence, however this article assumes that we are using GNU make which is the standard on Linux. ```make @@ -168,9 +169,9 @@ echo: name2 = Sara # True within the matching rule # Some variables defined automatically by make. echo_inbuilt: echo $(CC) - echo ${CXX)} + echo ${CXX} echo $(FC) - echo ${CFLAGS)} + echo ${CFLAGS} echo $(CPPFLAGS) echo ${CXXFLAGS} echo $(LDFLAGS) -- cgit v1.2.3 From b777242fb783d57b258c18645144b273e7eb0e13 Mon Sep 17 00:00:00 2001 From: Daniel Amireh Date: Mon, 13 Nov 2017 20:33:44 +0100 Subject: Update crystal.html.markdown attr_accessor -> property --- crystal.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crystal.html.markdown b/crystal.html.markdown index 15cbc0b1..ad9cf0f8 100644 --- a/crystal.html.markdown +++ b/crystal.html.markdown @@ -422,7 +422,7 @@ class Human @name end - # The above functionality can be encapsulated using the attr_accessor method as follows + # The above functionality can be encapsulated using the propery method as follows property :name # Getter/setter methods can also be created individually like this -- cgit v1.2.3 From 990f51293b1e85bc1146b291784474c82fabba37 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Mon, 13 Nov 2017 13:45:40 -0800 Subject: Update CONTRIBUTING.markdown --- CONTRIBUTING.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown index 5fa1d03d..455c3256 100644 --- a/CONTRIBUTING.markdown +++ b/CONTRIBUTING.markdown @@ -71,3 +71,10 @@ contributors: lang: ep-ep --- ``` + +### Should I add myself as a Contributor? + +If you want to add yourself to contributors, keep in mind that contributors get +equal billing, and the first contributor usually wrote the whole article. Please +use your judgement when deciding if your contribution constitutes a substantial +addition or not. -- cgit v1.2.3 From 20af61ee8d723dd9c3b987495261a476d59eff60 Mon Sep 17 00:00:00 2001 From: Neinei0k Date: Tue, 14 Nov 2017 18:14:17 +0000 Subject: [vim/en] Add sorting, folding, change letter case. Replacing new line character to new line character is not practical but an interesting example which shows the difference between representation of new line character in search and replace patterns. --- vim.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/vim.html.markdown b/vim.html.markdown index 15144b8d..d5c4e865 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -21,6 +21,7 @@ specific points in the file, and for fast editing. :q # Quit vim :w # Save current file :wq # Save file and quit vim + ZZ # Save file and quit vim :q! # Quit vim without saving file # ! *forces* :q to execute, hence quiting vim without saving :x # Save file and quit vim, shorter version of :wq @@ -48,6 +49,7 @@ specific points in the file, and for fast editing. :%s/foo/bar/g # Change 'foo' to 'bar' on every line in the file :s/foo/bar/g # Change 'foo' to 'bar' on the current line + :%s/\n/\r/g # Replace new line characters with new line characters # Jumping to characters @@ -167,6 +169,20 @@ A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ddp # Swap position of consecutive lines, dd then p . # Repeat previous action :w !sudo tee % # Save the current file as root + :set syntax=c # Set syntax highlighting to 'c' + :sort # Sort all lines + :sort! # Sort all lines in reverse + :sort u # Sort all lines and remove duplicates + ~ # Toggle letter case of selected text + u # Selected text to lower case + U # Selected text to upper case + + # Fold text + zf # Create fold from selected text + zo # Open current fold + zc # Close current fold + zR # Open all folds + zM # Close all folds ``` ## Macros -- cgit v1.2.3 From 2dda26010ab52ecd5d54c6fa1b8701288aaaac2d Mon Sep 17 00:00:00 2001 From: Neinei0k Date: Tue, 14 Nov 2017 19:30:57 +0000 Subject: [bash/en] Add arrays and alias --- bash.html.markdown | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 0c097c27..3f3e49eb 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -83,6 +83,25 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} # This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. # Note that it only returns default value and doesn't change variable value. +# Declare an array with 6 elements +array0=(one two three four five six) +# Print first element +echo $array0 # => "one" +# Print first element +echo ${array0[0]} # => "one" +# Print all elements +echo ${array0[@]} # => "one two three four five six" +# Print number of elements +echo ${#array0[@]} # => "6" +# Print number of characters in third element +echo ${#array0[2]} # => "5" +# Print 2 elements starting from forth +echo ${array0[@]:3:2} # => "four five" +# Print all elements. Each of them on new line. +for i in "${array0[@]}"; do + echo "$i" +done + # Brace Expansion { } # Used to generate arbitrary strings echo {1..10} # => 1 2 3 4 5 6 7 8 9 10 @@ -155,6 +174,13 @@ then echo "This will run if $Name is Daniya OR Zach." fi +# Redefine command 'ping' as alias to send only 5 packets +alias ping='ping -c 5' +# Escape alias and use command with this name instead +\ping 192.168.1.1 +# Print all aliases +alias -p + # Expressions are denoted with the following format: echo $(( 10 + 5 )) # => 15 -- cgit v1.2.3 From 0e0465218542ab81dbdde347d75aab5f907b4577 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Wed, 15 Nov 2017 21:57:30 +0800 Subject: Create PCRE-tw. --- zh-tw/pcre-tw.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 zh-tw/pcre-tw.html.markdown diff --git a/zh-tw/pcre-tw.html.markdown b/zh-tw/pcre-tw.html.markdown new file mode 100644 index 00000000..01870eaf --- /dev/null +++ b/zh-tw/pcre-tw.html.markdown @@ -0,0 +1,84 @@ +--- +language: PCRE +filename: pcre.txt +contributors: + - ["Sachin Divekar", "http://github.com/ssd532"] +translators: + - ["Michael Yeh", "https://hinet60613.github.io/"] +filename: pcre-tw.py +lang: zh-tw +--- + +正規表達式(regular expression,或縮寫為regex, regexp)是一種用來表示搜尋模式的特殊字串。例如,你可以用`/^[a-z]+:/`來從網址`http://github.com`中擷取出`http:`這段http協定名稱。 + +相容Perl正規表達式(Perl Compatible Regular Expressions, PCRE)是一個實作正規表達式的C語言函式庫。此函式庫在1997年被開發出來,在當時面對複雜字串處理時大多會選擇使用Perl。也因為如此,PCRE大多的正規表達式語法都很酷似Perl。PCRE語法被廣泛運用在許多大專案中,包括PHP、Apache、R等。 + +PCRE中的超字元(metacharacter)主要可以分為以下兩類: +* 在中括號外會被辨識的字元 +``` + \ 通用跳脫字元 + ^ 字串開頭 或 行首 + $ 字串結尾 或 行尾 + . 除了換行符號外的任何字元 + [ 字元集合定義開始 + | 支流開始 + ( 子串模式定義開始 + ) 子串模式定義結束 + ? extends the meaning of ( + 同時為數量0或1配對 + also quantifier minimizer + * 量詞 至少0個 至多無限個 + + 量詞 至少1個 至多無限個 + 同時為佔有型量詞 + { 最大/最小量詞開始 +``` + +* 在中括號內會被辨識的超字元,在中括號外會被視為字元集合使用 + +``` + + \ 通用跳脫字元 + ^ 非字元集合的字,但只會抓到第一個符合的字元 + - 字元範圍 + [ POSIX字元集合(若後面接POSIX格式) + ] 字元集合定義結束 + +``` + +PCRE提供了一些通用的字元類型,可被當作字元集合使用 +``` + \d 任何數字字元 + \D 任何非數字字元 + \h 任何水平空白字元 + \H 任何非水平空白字元 + \s 任何空白字元 + \S 任何非空白至元 + \v 任何垂直空白字元 + \V 任何非垂直空白字元 + \w 任何英文字 + \W 任何非英文字 +``` + +## 範例 + +我們以字串 `66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1"` 作為範例,這是一個標準的Apache存取記錄。 + +| 正規表達式 | 結果 | 說明 | +| :---- | :-------------- | :------ | +| GET | GET | GET 抓取 GET 字串 (會分別大小寫) | +| \d+.\d+.\d+.\d+ | 66.249.64.13 | `\d+` 抓取數字字元,數量由 `+` 定義為至少一個至多無限個。 `\.` 抓取 `.` 字元 | +| (\d+\.){3}\d+ | 66.249.64.13 | `(\d+\.){3}` 會試著抓取剛好三次的 (`\d+\.`) | +| \[.+\] | [18/Sep/2004:11:07:48 +1000] | `.+` 抓取除了換行符號以外的任何字元, `.` 表示任意字元 | +| ^\S+ | 66.249.64.13 | `^` 為行首, `\S+` 抓取至少一個非空白字元 | +| \+[0-9]+ | +1000 | `\+` 抓取 `+` 字元。 `[0-9]` 字元集表示剛好一個數字字元。 可以用 `\+\d+` 達到相同效果。 | + +以上範例皆可在 https://regex101.com/ 測試,步驟如下: + +1. 複製範例字串到 `TEST STRING` 區域 +2. 複製正規表達式字串到 `Regular Expression` 區域 +3. 網頁會顯示自動表達式抓取結果 + + +## 更多資料 + + -- cgit v1.2.3 From 6c58f36fb4ebb6d1c346246c57c91940c5ea47f5 Mon Sep 17 00:00:00 2001 From: Alexandru Cazacu Date: Sat, 18 Nov 2017 23:02:50 +0100 Subject: [bf/it] Added italian translation for brainfuck --- bf-it.html.markdown | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 bf-it.html.markdown diff --git a/bf-it.html.markdown b/bf-it.html.markdown new file mode 100644 index 00000000..1f544a09 --- /dev/null +++ b/bf-it.html.markdown @@ -0,0 +1,88 @@ +--- +language: "Brainfuck" +filename: brainfuck.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] + - ["Alexandru Cazacu", "https://github.com/alexandru-cazacu"] +lang: it-it +--- + +Brainfuck (maiuscolo solo all'inizio di una frase) è un linguaggio di +programmazione Turing-completo estremamente minimalistico composto da soli 8 comandi. + +Potete provare brainfuck sul vostro browser tramite [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +```bf +Ciascun carattere tranne "><+-.,[]" (escluse le virgolette) è ignorato. + +Brainfuck è rappresentato da un array di 30,000 celle inizializzate a zero +e da un puntatore che punta alla cella corrente. + +Ci sono otto comandi: ++ : Incrementa il valore nella cella corrente di uno. +- : Decrementa il valore nella cella corrente di uno. +> : Muove il puntatore alla cella successiva (cella a destra). +< : Muove il puntatore alla cella precedente (cella a sinistra). +. : Stampa il valore ASCII nella cella corrente (es. 65 = 'A'). +, : Legge un singolo carattere in input nella cella corrente. +[ : Se il valore nella cella corrente è zero, salta al corrispondente ] . + Altrimenti vai alla prossima istruzione. +] : Se il valore nella cella corrente è zero, vai alla prossima istruzione. + Altrimenti salta al corrispondente [ . + +[ and ] formano un ciclo while. Ovviamente devono essere in numero uguale. + +Diamo un'occhiata ad alcuni programmi brainfuck basilari. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Questo programma stampa la lettera 'A'. Prima, incrementa la cella #1 a 6. +La cella #1 sarà usata per il ciclo. Poi, entra nel ciclo ([) e si sposta +alla cella #2. Incrementa la cella #2 10 volte, ritorna indietro alla cella #1 +e la decrementa. Questo ciclo avviene 6 volte (servo 6 decrementi affinchè +la cella #1 raggiunga 0, a quel punto salta al corrispondente ] e continua +l'esecuzione). + +A questo punto siamo nella cella #1, che ha un valore di 0, mentre la +cella #2 ha un valore di 60. Ci muoviamo alla cella #2, la incrementiamo +5 volte, per arrivare a 65 e poi stampiamo il valore della cella #2. +65 equivale ad 'A' in ASCII, quindi 'A' viene stampato nel terminale. + +, [ > + < - ] > . + +Questo programma legge un carattere immesso dall'utente e lo copia nella +cella #1. Poi inizi un loop. Si muove nella cella #2, incrementa il valore +della cella #2, si muove alla cella #1 e decrementa il suo valore. Questo +ciclo continua finchè la cella #1 non vale 0, e la cella #2 contiene il vecchio +valore della cella #1. Siccome siamo nella cella #1 alla fine del ciclo, +ci muoviamo alla cella #2 e stampiamo il valore ASCII. + +Tenete in mente che gli spazi sono puramente estetici. Si potrebbe benissimo +anche scrivere come: + +,[>+<-]>. + +Cercate di capire cosa fa questo programma: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Questo programma prende 2 numeri in input e li moltiplica. + +Per prima cosa prende in input 2 numeri. Poi inizia il ciclo esterno, +condizionato dalla cella #1. Poi si muove nella cella #2 e inizia il ciclo +interno, condizionato dalla cella #2, incrementando la cella #3. Però c'è +un problema: alla fine del ciclo interno la cella #2 è zero. In questo caso +il ciclo interno non funzionerà pià fino alla volta seguente. Per risolvere +il problema, incrementiamo la cella #4 e poi ricopiamo #4 in #2. La cella #3 +è il risultato. +``` +E questo è brainfuck. Non è così difficile, vero? Per passare il tempo +potreste provare a scrivere un pogramma in brainfuck, oppure potete +scrivere un interprete brainfuck in un altro linguaggio. L'interprete +è relativamente semplice da implementare, ma se siete masochisti, potete +provare a scrivere un interprete brainfuck... in brainfuck. +And that's brainfuck. Not that hard, eh? For fun, you can write your own +brainfuck programs, or you can write a brainfuck interpreter in another +language. The interpreter is fairly simple to implement, but if you're +a masochist, try writing a brainfuck interpreter… in brainfuck. -- cgit v1.2.3 From c6c6b8198818cdc6e53789ea8e11be1068c68e4c Mon Sep 17 00:00:00 2001 From: luke zhang Date: Thu, 23 Nov 2017 19:39:43 +0700 Subject: add ethfiddle --- solidity.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/solidity.html.markdown b/solidity.html.markdown index c1f910fd..0b2f5f67 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -826,6 +826,7 @@ someContractAddress.callcode('function_name'); ## Additional resources - [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. +- [EthFiddle - The JsFiddle for Solidity](https://ethfiddle.com/) - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) -- cgit v1.2.3 From 8d09ffb07020fad0d7d7c3197e0926b42b436e85 Mon Sep 17 00:00:00 2001 From: pimgeek Date: Thu, 30 Nov 2017 12:57:29 +0800 Subject: Update javascript-cn.html.markdown MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 建议修改概要部分的文字翻译。 --- zh-cn/javascript-cn.html.markdown | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index bdef0099..360f7c65 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -12,12 +12,9 @@ translators: lang: zh-cn --- -Javascript于1995年由网景公司的Brendan Eich发明。 -最初发明的目的是作为一个简单的网站脚本语言,来作为 -复杂网站应用java的补充。但由于它与网页结合度很高并且由浏览器内置支持, -所以javascript变得比java在前端更为流行了。 +Javascript 于 1995 年由网景公司的 Brendan Eich 发明。最初它作为一种简单的,用于开发网站的脚本语言而被发明出来,是用于开发复杂网站的 Java 的补充。但由于它与网页结合度很高并且在浏览器中得到内置的支持,所以在网页前端领域 Javascript 变得比 Java 更流行了。 -不过 JavaScript 可不仅仅只用于浏览器: Node.js,一个基于Google Chrome V8引擎的独立运行时环境,也越来越流行。 +不过,Javascript 不仅用于网页浏览器,一个名为 Node.js 的项目提供了面向 Google Chrome V8 引擎的独立运行时环境,它正在变得越来越流行。 很欢迎来自您的反馈,您可以通过下列方式联系到我: [@adambrenecki](https://twitter.com/adambrenecki), 或者 -- cgit v1.2.3 From 973883c57cef5caa01e60856fbd0884fff26809c Mon Sep 17 00:00:00 2001 From: Michael Hirschler Date: Sun, 3 Dec 2017 11:23:03 +0100 Subject: unifies namespace variants in exception handling --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index f82cea7d..d4fbaa32 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -841,7 +841,7 @@ try { try { // Do something -} catch (\Exception $e) { +} catch (Exception $e) { // Handle exception } -- cgit v1.2.3 From 50dbc5e7799abbf4976bd1a26e72ce470abc4423 Mon Sep 17 00:00:00 2001 From: Ilya Sosnovsky Date: Mon, 4 Dec 2017 10:13:46 +0300 Subject: Update python3-ru.html.markdown Add multiplication of rows --- ru-ru/python3-ru.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index 2b6b59a7..bf80fed2 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -106,6 +106,9 @@ False or True #=> True # И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим. "Привет " + "мир!" #=> "Привет мир!" +# Строки можно умножать. +"aa" * 4 #=> "aaaaaaaa" + # Со строкой можно работать, как со списком символов "Это строка"[0] #=> 'Э' -- cgit v1.2.3 From 3ed8f9c8afa2b84321eb0176061d860d482e96b1 Mon Sep 17 00:00:00 2001 From: Fatih Turan Date: Tue, 5 Dec 2017 00:33:15 +0300 Subject: [css/tr]Turkish translate for CSS documentation --- tr-tr/css.html.markdown | 304 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 304 insertions(+) create mode 100644 tr-tr/css.html.markdown diff --git a/tr-tr/css.html.markdown b/tr-tr/css.html.markdown new file mode 100644 index 00000000..baa47b3d --- /dev/null +++ b/tr-tr/css.html.markdown @@ -0,0 +1,304 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] + - ["Brett Taylor", "https://github.com/glutnix"] + - ["Tyler Mumford", "https://tylermumford.com"] +filename: learncss.css +translators: + - ["Fatih Turan", "http://fatihturan.com"] +lang: tr-tr +--- + +Web sayfaları bir sayfanın içeriğini belirleyen HTML ile inşa edilirler. CSS (Basamaklı Biçim Sayfaları) ise bir sayfanın **görünümünü** belirleyen ayrı bir dildir. + +CSS kodu statik *kurallardan* oluşur. Her kural bir ya da daha fazla *seçici* alır ve görsel *özelliklere* belirli *değerleri* verir. Sonrasında bu özellikler seçiciler tarafından belirlenen sayfa unsurlarına uygulanır. + +Bu rehber, CSS 3'ün yeni özellikleri ile genişletilen CSS 2 ile dikkate alınarak yazılmıştır. + +**NOT:** CSS görsel sonuçlar ürettiğinden dolayı, öğrenmek için herşeyi bir CSS oyun alanı içinde ([dabblet](http://dabblet.com) gibi) denemeniz gerekmektedir. Bu makale sözdizimi kuralları ve genel ipuçları üzerine odaklanmaktadır. + +## Sözdizimi + +```css +/* yorumlar bu satırdaki gibi taksim-yıldız içinde görünür +CSS'te "tek satırlık yorumlar" bulunmamaktadır; bu sadece tek bir yorum yazma stilidir */ + +/* #################### + ## SEÇİCİLER + #################### */ + +/* seçici bir sayfadaki unsuru hedeflemek için kullanılır. */ +seçici { özellik: değer; /* daha fazla özellikler...*/ } + +/* +İşte bir örnek: + +
+*/ + +/* */ + +/* CSS sınıflarının birini kullanarak hedefleyebilirsiniz */ +.class1 { } + +/* veya her iki sınıfı birden!*/ +.class1.class2 { } + +/* veya sadece ögenin adını yazarak */ +div { } + +/* veya onun ID adını */ +#anID { } + +/* veya onun aldığı bir özelliği kullanarak! */ +[attr] { font-size:smaller; } + +/* veya onun aldığı özelliğin belirli bir değeri varsa */ +[attr='value'] { font-size:smaller; } + +/* bir değer ile başlıyorsa (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* veya bir değer ile bitiyorsa (CSS 3)*/ +[attr$='ue'] { font-size:smaller; } + +/* veya boşlukla ayrılmış liste içinde bir değer içeriyorsa */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* veya tire ile ayrılmış bir liste içinde bir değer içeriyorsa, örneğin: "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + +/* Farklı seçicileri birleştirerek daha fazla odaklanmış bir seçici oluşturabilirsiniz. Seçiciler arasında boşluk bırakmayın. */ +div.some-class[attr$='ue'] { } + +/* Başka bir ögenin alt ögesi olan bir ögeyi seçebilirsiniz. */ +div.some-parent > .class-name { } + +/* veya bir başka ögeden türeyeni seçebilirsiniz. Alt ögeler onların ebeveynlerinin direkt türünden gelir, sadece ağacın bir alt ögeleridirler. Soyundan gelenler ağacın herhangi bir alt seviyesinde olabilir. */ + +div.some-parent .class-name { } + +/* Uyarı: Seçiciler arasında bir boşluk bırakmazsanız aynı seçicinin başka bir anlamı olur. +Ne olduğunu tahmin edebilir misiniz? */ + +div.some-parent.class-name { } + +/* Ayrıca bir ögenin bitişik kardeşini temel alarak bir ögeyi seçebilirsiniz. */ +.i-am-just-before + .this-element { } + +/* veya kendisinden önce gelen herhangi bir kardeş ögeyi */ +.i-am-any-element-before ~ .this-element { } + +/* Yalnızca belli bir durumda bir öge seçmek için kullanılan sahte sınıflar adı verilen bazı seçiciler vardır. */ + +/* Örneğin, imleç bir ögenin üzerine geldiğinde */ +selector:hover { } + +/* veya bir bağlantı ziyaret edildiğinde */ +selector:visited { } + +/* veya ziyaret edilmediğinde */ +selected:link { } + +/* veya bir ögeye odaklanıldığında */ +selected:focus { } + +/* Ebeveyninin ilk alt ögesi olan herhangi bir öge */ +selector:first-child {} + +/* Ebeveyninin son alt ögesi olan herhangi bir öge */ +selector:last-child {} + +/* Sahte sınıflar gibi sahte elementler de bir dokümanın belirli bir parçasına stil vermenize izin verir. */ + +/* Seçilen ögenin sanal ilk alt ögesiyle eşleşir. */ +selector::before {} + +/* Seçilen ögenin sanal son alt ögesiyle eşleşir. */ +selector::after {} + +/* Uygun yerlerde yıldız karakteri ile bütün ögeleri seçmek için joker olarak kullanılabilir. */ + +* { } /* Bütün ögeler */ +.parent * { } /* Tüm alt ögeler */ +.parent > * { } /* Tüm çocuk ögeler */ + +/* #################### + ## ÖZELLİKLER + #################### */ + +selector { + + /* Ölçü birimleri kesin veya göreceli olabilir.*/ + + /* Göreceli birimler */ + width: 50%; /* Ebeveyn elementin yüzdesel olarak genişliği */ + font-size: 2em; /* Öğenin özgün yazı tipi boyutunda katları */ + font-size: 2rem; /* veya kök ögenin yazı tipi boyutu */ + font-size: 2vw; /* Görüntüleme çerçevesinin genişliğinin %1 olarak katları (CSS 3) */ + font-size: 2vh; /* veya onun yüksekliğinin */ + font-size: 2vmin; /* Bir vh veya vw'nin hangisi küçükse */ + font-size: 2vmax; /* veya daha büyük... */ + + /* Kesin birimler */ + width: 200px; /* Piksel */ + font-size: 20pt; /* Nokta */ + width: 5cm; /* Santimetre */ + min-width: 50mm; /* Milimetre */ + max-width: 5in; /* İnç */ + + /* Renkler */ + color: #F6E; /* Kısa onaltılık (HEX) biçimi */ + color: #FF66EE; /* Uzun onaltılık (HEX) biçimi */ + color: tomato; /* Bir isim verilen renk */ + color: rgb(255, 255, 255); /* RGB değerleri verilen türde */ + color: rgb(10%, 20%, 50%); /* RGB yüzdeleri verilen türde */ + color: rgba(255, 0, 0, 0.3); /* RGBA değerleri verilen türde (CSS 3) Not: 0 <= a <= 1 */ + color: transparent; /* Şeffaflık değerinin sıfır olması ile eşdeğer */ + color: hsl(0, 100%, 50%); /* HSL yüzdeleri verilen türde (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* HSL ile beraber şeffaflık değeri verilen türde */ + + /* Kenarlıklar */ + border-width:5px; + border-style:solid; + border-color:red; /* background-color'ın ayarlanışına benzer şekilde */ + border: 5px solid red; /* Bu aynı şeyin kısayol ile yazılışıdır */ + border-radius:20px; /* Bu bir CSS3 özelliğidir */ + + /* Görseller ve Ögelerin Arkaplanları */ + background-image: url(/img-path/img.jpg); /* url() içindeki tırnak işaretleri isteğe bağlı */ + + /* Yazı tipleri */ + font-family: Arial; + /* Eğer yazı tipi ailesi isminde bir boşluk var ise tırnak işareti içine alınmalıdır. */ + font-family: "Courier New"; + /* Eğer ilk sıradaki bulunamazsa, tarayıcı bir sonrakini kullanır */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Kullanım + +CSS dosyasınızı `.css`uzantısı ile kaydedin. + +```html + + + + + + + +
+
+``` + +## Öncelik veya Basamak + +Bir öge birden çok seçici tarafından hedef alınabilir ve bir özellik kümesine birden fazla kez sahip olabilir. Bunun gibi durumlarda, kurallardan biri diğerlerine göre önceliklidir. Daha spesifik bir seçiciye sahip kurallar, daha az spesifik bir seçicinin önceliğini alır ve kural daha sonra stil sayfasında bir önceki kuralın üzerine yazar. + +Bu işleme geçiş denir ve olayısıyla Geçişli/Basamaklı Stil Sayfaları adı da buradan gelmiştir. + +Aşağıdaki CSS göz önüne alındığında: + +```css +/* A */ +p.class1[attr='değer'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { özellik: değer !important; } +``` + +ve aşağıdaki biçimlendirmeyi: + +```html +

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

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

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

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

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

` through `

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

## This is an

### This is an

@@ -51,7 +51,7 @@ text you want to be in that element by a number of hashes (#). ``` Markdown also provides us with two alternative ways of indicating h1 and h2. -```markdown +```md This is an h1 ============= @@ -63,7 +63,7 @@ This is an h2 Text can be easily styled as italic or bold using markdown. -```markdown +```md *This text is in italics.* _And so is this text._ @@ -78,7 +78,7 @@ __And so is this text.__ In GitHub Flavored Markdown, which is used to render markdown files on GitHub, we also have strikethrough: -```markdown +```md ~~This text is rendered with strikethrough.~~ ``` ## Paragraphs @@ -86,7 +86,7 @@ GitHub, we also have strikethrough: Paragraphs are a one or multiple adjacent lines of text separated by one or multiple blank lines. -```markdown +```md This is a paragraph. I'm typing in a paragraph isn't this fun? Now I'm in paragraph 2. @@ -99,7 +99,7 @@ I'm in paragraph three! Should you ever want to insert an HTML `
` tag, you can end a paragraph with two or more spaces and then begin a new paragraph. -```markdown +```md I end with two spaces (highlight me to see them). There's a
above me! @@ -107,7 +107,7 @@ There's a
above me! Block quotes are easy and done with the > character. -```markdown +```md > This is a block quote. You can either > manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. > It doesn't make a difference so long as they start with a `>`. @@ -121,7 +121,7 @@ Block quotes are easy and done with the > character. ## Lists Unordered lists can be made using asterisks, pluses, or hyphens. -```markdown +```md * Item * Item * Another item @@ -141,7 +141,7 @@ or Ordered lists are done with a number followed by a period. -```markdown +```md 1. Item one 2. Item two 3. Item three @@ -150,7 +150,7 @@ Ordered lists are done with a number followed by a period. You don't even have to label the items correctly and Markdown will still render the numbers in order, but this may not be a good idea. -```markdown +```md 1. Item one 1. Item two 1. Item three @@ -159,7 +159,7 @@ render the numbers in order, but this may not be a good idea. You can also use sublists -```markdown +```md 1. Item one 2. Item two 3. Item three @@ -170,7 +170,7 @@ You can also use sublists There are even task lists. This creates HTML checkboxes. -```markdown +```md Boxes below without the 'x' are unchecked HTML checkboxes. - [ ] First task to complete. - [ ] Second task that needs done @@ -183,7 +183,7 @@ This checkbox below will be a checked HTML checkbox. You can indicate a code block (which uses the `` element) by indenting a line with four spaces or a tab. -```markdown +```md This is code So is this ``` @@ -191,7 +191,7 @@ a line with four spaces or a tab. You can also re-tab (or add an additional four spaces) for indentation inside your code -```markdown +```md my_array.each do |item| puts item end @@ -199,7 +199,7 @@ inside your code Inline code can be created using the backtick character ` -```markdown +```md John didn't even know what the `go_to()` function did! ``` @@ -220,7 +220,7 @@ highlighting of the language you specify after the \`\`\` Horizontal rules (`
`) are easily added with three or more asterisks or hyphens, with or without spaces. -```markdown +```md *** --- - - - @@ -232,17 +232,17 @@ hyphens, with or without spaces. One of the best things about markdown is how easy it is to make links. Put the text to display in hard brackets [] followed by the url in parentheses () -```markdown +```md [Click me!](http://test.com/) ``` You can also add a link title using quotes inside the parentheses. -```markdown +```md [Click me!](http://test.com/ "Link to Test.com") ``` Relative paths work too. -```markdown +```md [Go to music](/music/). ``` @@ -269,7 +269,7 @@ But it's not that commonly used. ## Images Images are done the same way as links but with an exclamation point in front! -```markdown +```md ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") ``` @@ -281,20 +281,20 @@ And reference style works as expected. ## Miscellany ### Auto-links -```markdown +```md is equivalent to [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto-links for emails -```markdown +```md ``` ### Escaping characters -```markdown +```md I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. ``` @@ -304,7 +304,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. In GitHub Flavored Markdown, you can use a `` tag to represent keyboard keys. -```markdown +```md Your computer crashed? Try sending a Ctrl+Alt+Del ``` @@ -313,7 +313,7 @@ Your computer crashed? Try sending a Tables are only available in GitHub Flavored Markdown and are slightly cumbersome, but if you really want it: -```markdown +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Left-aligned | Centered | Right-aligned | @@ -321,7 +321,7 @@ cumbersome, but if you really want it: ``` or, for the same results -```markdown +```md Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index 03a7c15c..c3381824 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -19,7 +19,7 @@ Outro livro recente e popular é o [Land of Lisp](http://landoflisp.com/). -```common_lisp +```common-lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; 0. Sintaxe diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index cbeb36b5..041641d3 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnvisualbasic.vb --- -```vb +```vbnet Module Module1 Sub Main() diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 87ed46ad..e9a8aeb2 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -13,7 +13,7 @@ Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的 欢迎您多多反馈以及分支和请求合并。 -```markdown +```md +le parser( analyseur syntaxique ) Markdown. - +``` - - - +## Titres + +Vous pouvez facilement créer des éléments HTML `

` à `

en précédant le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, selon le niveau de titre souhaité. + +```md # Ceci est un

## Ceci est un

### Ceci est un

#### Ceci est un

##### Ceci est un

###### Ceci est un
+``` - +Markdown fournit également une façon alternative de marquer les h1 et h2 +```md Ceci est un h1 ============= Ceci est un h2 ------------- +``` + +## Formatage simple du texte - - + On peut facilement rendre un texte "gras" ou "italique" en Markdown +```md *Ce texte est en italique.* _Celui-ci aussi._ @@ -61,15 +77,23 @@ __Celui-là aussi.__ ***Ce texte a les deux styles.*** **_Pareil ici_** *__Et là!__* +``` + - +Dans le Markdown de GitHub, utilisé pour interpréter le Markdown +sur GitHub, on a également le strikethrough ( texte barré ) : +```md ~~Ce texte est barré avec strikethrough.~~ +``` + - +## Les paragraphes +Les Paragraphes sont représentés par une ou plusieurs lignes de texte +séparées par une ou plusieurs lignes vides. + +```md Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non? Maintenant je suis dans le paragraphe 2. @@ -77,19 +101,21 @@ Je suis toujours dans le paragraphe 2! Puis là, eh oui, le paragraphe 3! +``` - +```md J'ai deux espaces vides à la fin (sélectionnez moi pour les voir). Bigre, il y a un
au dessus de moi! +``` - +Les 'Blocs de Citations' sont générés aisément, grâce au caractère `>` +```md > Ceci est une superbe citation. Vous pouvez même > revenir à la ligne quand ça vous chante, et placer un `>` > devant chaque bout de ligne faisant partie @@ -99,11 +125,14 @@ Bigre, il y a un
au dessus de moi! > Vous pouvez aussi utiliser plus d'un niveau >> d'imbrication! > Classe et facile, pas vrai? +``` + - - +## Les listes +les Listes non ordonnées sont marquées par des asterisques, signes plus ou signes moins. + +```md * Item * Item * Un autre item @@ -119,171 +148,201 @@ ou - Item - Item - Un dernier item +``` - +les Listes Ordonnées sont générées via un nombre suivi d'un point +```md 1. Item un 2. Item deux 3. Item trois +``` - +Vous pouvez même vous passer de tout numéroter, et Markdown générera les bons chiffres. Ceci dit, cette variante perd en clarté. +```md 1. Item un 1. Item deux 1. Item trois - +``` + +(cette liste sera interprétée de la même façon que celle au-dessus) - +Vous pouvez également utiliser des sous-listes +```md 1. Item un 2. Item deux 3. Item trois * Sub-item * Sub-item 4. Item quatre +``` - - -Les [ ] ci dessous, n'ayant pas de [ x ], -deviendront des cases à cocher HTML non-cochées. +Il y a même des "listes de Taches". Elles génèrent des champs HTML de type checkbox. Les [ ] ci-dessous, n'ayant pas de [ x ], deviendront des cases à cocher HTML non-cochées. +```md - [ ] Première tache à réaliser. - [ ] Une autre chose à faire. La case suivante sera une case à cocher HTML cochée. - [x] Ça ... c'est fait! +``` + - - +## Insertion de code +Pour marquer du texte comme étant du code, il suffit de commencer +chaque ligne en tapant 4 espaces (ou un Tab). + +```md echo "Ça, c'est du Code!"; var Ça = "aussi !"; +``` - +L'indentation par tab ou série de quatre espaces fonctionne aussi à l'intérieur du bloc de code. +```md my_array.each do |item| puts item end +``` - +On peut insérer du code dans le texte des paragraphes en entourant le code par des `. +```md La fonction `run()` ne vous oblige pas à aller courir! +``` + +En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques. - -\`\`\`ruby - -def foobar -puts "Hello world!" -end -\`\`\` + ```ruby + def foobar + puts "Hello world!" + end + ``` + +Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub +va utiliser une coloration syntaxique pour le langage indiqué après les ```. -<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub -va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> +## Ligne Horizontale - - +Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets, +avec ou sans espaces entre chaque un. +```md *** --- - - - **************** +``` + +## Liens - - +Une des fonctionnalités sympathiques du Markdown est la facilité d'ajouter des liens. Le texte du lien entre [ ], l'url entre ( ), et voilà l'travail. +```md [Clic moi!](http://test.com/) +``` - +Pour ajouter un attribut Title, collez-le entre guillemets, avec le lien. +```md [Clic moi!](http://test.com/ "Lien vers Test.com") +``` - +Les Liens Relatifs marchent aussi. +```md [En avant la musique](/music/). +``` - +Les liens façon "références" sont eux aussi disponibles en Markdown. +```md [Cliquez ici][link1] pour plus d'information! [Regardez aussi par ici][foobar] si vous voulez. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" +``` - +Le titre peut aussi être entouré de guillemets simples, entre parenthèses ou absent. Les références peuvent être placées un peu où vous voulez dans le document, et les identifiants (link1, foobar, ...) pevent être n'importe quoi tant qu'ils sont uniques. - +Il y a également le "nommage implicite" qui transforme le texte du lien en identifiant. +```md [Ceci][] est un lien. [ceci]: http://ceciestunlien.com/ +``` - +mais ce n'est pas beaucoup utilisé. - - +## Images +Pour les images, la syntaxe est identique aux liens, sauf que précédée d'un point d'exclamation! + +```md ![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel") +``` - +Là aussi, on peut utiliser le mode "références". +```md ![Ceci est l'attribut ALT de l'image][monimage] [monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." +``` - - +## Divers + +### Liens Automatiques + +```md est équivalent à : [http://testwebsite.com/](http://testwebsite.com/) +``` - +### Liens Automatiques pour emails +```md +``` + +### Caractères d'échappement + +Il suffit de précéder les caractères spécifiques à ignorer par des anti slash `\`.` - -Il suffit de précéder les caractères spécifiques à ignorer par des backslash \ +```md +Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. +``` -Pour taper *ce texte* entouré d'astérisques mais pas en italique : -Tapez \*ce texte\*. +### Tableaux - - +Les Tableaux ne sont disponibles que dans le GitHub Flavored Markdown et c'est ce n'est pas super agréable d'utilisation. Mais si vous en avez besoin : +```md | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Alignement Gauche | Centé | Alignement Droite | | bla | bla | bla | +``` - +ou bien, pour un résultat équivalent : +```md Col 1 | Col2 | Col3 :-- | :-: | --: Ough que c'est moche | svp | arrêtez +``` - +*** -``` +Pour plus d'information, consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de John Gruber à propos de la syntaxe, et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. -Pour plus d'information : - consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe, - et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard. +*** + +Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request! \ No newline at end of file -- cgit v1.2.3 From 2dbfcc8faf8c5f1b144a0b0387ac545bf17a3a75 Mon Sep 17 00:00:00 2001 From: Foo Chuan Wei Date: Tue, 26 Jun 2018 17:43:39 -0400 Subject: Fix sentence mistake in fsharp.html.markdown --- fsharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index bbf477ba..dd85552d 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -306,7 +306,7 @@ module DataTypeExamples = // ------------------------------------ // Union types (aka variants) have a set of choices - // Only case can be valid at a time. + // Only one case can be valid at a time. // ------------------------------------ // Use "type" with bar/pipe to define a union type -- cgit v1.2.3 From 92022da0a6ea9417521563de9e537f337c426465 Mon Sep 17 00:00:00 2001 From: boissonnfive Date: Wed, 27 Jun 2018 14:45:10 +0200 Subject: Corrections de majuscules, sauts de lignes, guillemets, accents + reformulations. --- fr-fr/markdown-fr.html.markdown | 85 ++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 48 deletions(-) diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown index 42af1b2b..4a2ecedc 100644 --- a/fr-fr/markdown-fr.html.markdown +++ b/fr-fr/markdown-fr.html.markdown @@ -7,12 +7,13 @@ lang: fr-fr --- Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe -facile à lire et à écrire, aisément convertible en HTML - (et beaucoup d'autres formats aussi à présent). +facile à lire et à écrire, aisément convertible en HTML (et beaucoup d'autres formats aussi à présent). + +Il existe de nombreuses formes de Markdown : Markown classique, Markdown GitHub, Multi-Markdown, etc. Dans ce guide, nous signalerons quand les fonctionnalités sont spécifiques à une forme. + +_Faites moi autant de retours que vous voulez! Sentez vous libre de "forker" +et envoyer des pull request!_ -Le Markdown est implémenté de différentes manières, selon le parser. -Ce guide va alors tenter de trier les fonctionnalités universelles de celles -spécifiques à un parser. - [HTML](#html) - [Titres](#titres) @@ -28,21 +29,20 @@ spécifiques à un parser. ## HTML -Markdown est une sorte de cousin du HTML, si bien que tout document HTML -est un document Markdown valide. Autrement dit, vous pouvez utiliser des -balises HTML dans un fichier Markdown, comme la balise commentaire dans -laquelle nous sommes à présent, car celle-ci ne sera pas affectée par -le parser( analyseur syntaxique ) Markdown. +Markdown est une sorte de cousin du HTML, si bien que tout document HTML est un document Markdown valide. ```md - + ``` ## Titres -Vous pouvez facilement créer des éléments HTML `

` à `

en précédant le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six, selon le niveau de titre souhaité. +Vous pouvez facilement créer des titres HTML `

` à `

` en précédant le texte de votre futur titre par un ou plusieurs dièses (#), de un à six, selon le niveau de titre souhaité. ```md # Ceci est un

@@ -53,7 +53,7 @@ Vous pouvez facilement créer des éléments HTML `

` à `

en précédant ###### Ceci est un
``` -Markdown fournit également une façon alternative de marquer les h1 et h2 +Markdown fournit également une façon alternative de marquer les `

` et `

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