From cedb7eca42d0eec30064f77c0ab9602bfc3c0bc7 Mon Sep 17 00:00:00 2001 From: shaltaev Date: Thu, 21 Feb 2019 22:18:12 +0400 Subject: [ru-ru] SQL full translate --- ru-ru/sql-ru.html.markdown | 103 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 ru-ru/sql-ru.html.markdown diff --git a/ru-ru/sql-ru.html.markdown b/ru-ru/sql-ru.html.markdown new file mode 100644 index 00000000..78e021fc --- /dev/null +++ b/ru-ru/sql-ru.html.markdown @@ -0,0 +1,103 @@ +--- +language: SQL +filename: learnsql.sql +contributors: + - ["Bob DuCharme", "http://bobdc.com/"] +translators: + - ["Shaltaev", "https://github.com/shaltaev"] +lang: ru-ru +--- + +Язык структурированных запросов (SQL) - это стандартный язык ISO для создания и работы с базами данных, хранящимися в наборе таблиц. Реализации обычно добавляют свои собственные расширения к языку; [Сравнение различных реализаций SQL](http://troels.arvin.dk/db/rdbms/) хороший справочник по различиям в продуктах. + +Реализации обычно предоставляют приглашение командной строки, где вы можете вводить команды (описанные ниже) в интерактивном режиме, также есть способ выполнить серию этих команд, сохраненных в файле сценария. (Результат того, что вы сделали с помощью интерактивного режима, является хорошим примером того, что не стандартизировано - большинство реализаций SQL поддерживают ключевые слова QUIT, EXIT или оба.) + +Некоторый команды ниже предполагают использование [демонстрационный образец базы данных сотрудников от MySQL](https://dev.mysql.com/doc/employee/en/) доступный на [github](https://github.com/datacharmer/test_db) следовательно для повторения команд в локальном окружении он должен быть загружен. Файлы и скрипты на github, схожи с командами ниже, которые манипулируют базами, таблицами и данными. Синтаксис для запуска этих сценариев будет зависеть от используемой вами реализации SQL. Способ запуска из командной строки обычный для вашей операционной системе. + +```sql +-- Комментарии начинаются с двух дефисов. Завершите каждую команду +-- точкой с запятой. + +-- SQL не учитывает регистр ключевых слов. Образцы команд здесь +-- следуйте соглашению о написании их в верхнем регистре, потому что +-- это позволяет легче их отличить от имен баз, таблиц и колонок. + +-- Создание и удаление базы данных. Имена базы и таблицы чувствительны +-- к регистру. +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +-- Список доступных баз. +SHOW DATABASES; + +-- Выбор базы для работы. +USE employees; + +-- Выбрать все колонки и строки из таблицы текущей базы. +-- В интерактивном режиме обычно результат будет выведен на экран. +SELECT * FROM departments; + +-- Тот же запрос что и вышеБ но выбор только колонок dept_no и dept_name. +-- Разбиение команд на несколько строк допустимо. +SELECT dept_no, + dept_name FROM departments; + +-- В данном случае будут выбраны только первые 5 результатов. +SELECT * FROM departments LIMIT 5; + +-- Выбор имен депортаментов где имена содержат в себе 'en'. +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; + +-- Выбор всех колонок где имена начинаются 'S' и 4 любых символа после. +SELECT * FROM departments WHERE dept_name LIKE 'S____'; + +-- Выбор всех должностей, но без повторений. +SELECT DISTINCT title FROM titles; + +-- В дополнение к предыдущему запросу результат будет отсортирован +-- в алфавитном порядке (С учетом регистра). +SELECT DISTINCT title FROM titles ORDER BY title; + +-- Вычислить количество строк в таблице депортамента. +SELECT COUNT(*) FROM departments; + +-- Вычислить количество строк где имя депортамента содержит 'en' +-- в любой части имени. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; + +-- ОБЪЕДИНЕНИЕ информации из нескольких таблиц: должность, когда ее занимал, +-- имя и фамилия сотрудника, объединить по идентификатору сотрудника +-- вывести только 10 строк. + +SELECT employees.first_name, employees.last_name, + titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON + employees.emp_no = titles.emp_no LIMIT 10; + +-- Список всех таблиц во всех базах. Реализации обычно предоставляют +-- их собственные сокращения чтобы сделать это для текущей базы. +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +-- Создать таблицу с именем tablename1, с двумя колонками, для колонок +-- доступно множество опций вроде типа и других, конкретнее уточняйте для +-- своей реализации. +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); + +-- Вставляем строку в таблице созданную в предыдущем запросе . +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +-- В tablename1, изменить значение fname на 'John' +-- для каждой строки где lname имеет значение 'Mutt'. +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; + +-- Удалить строки из таблицы tablename1 +-- где lname начинается с 'M'. +DELETE FROM tablename1 WHERE lname like 'M%'; + +-- Удалить все строки из таблицы tablename1, в итоге получим пустую таблицу. +DELETE FROM tablename1; + +-- Удалить таблицу tablename1. +DROP TABLE tablename1; +``` -- cgit v1.2.3 From c709f1dcbbc3f21d8aca2102fd74f9304753b775 Mon Sep 17 00:00:00 2001 From: Felix Ostmann Date: Tue, 6 Aug 2019 10:44:37 +0200 Subject: Object Model example mixed old/new code/comments --- perl6.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 6b0df0d4..1304869b 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -885,7 +885,7 @@ say_dyn(); #=> 1 100 We changed the value of $*dyn_scoped_2 in class Human { has Str $.name; # `$.name` is immutable but with an accessor method. - has Str $.bcountry; # Use `$!bplace` to modify it inside the class. + has Str $.bcountry; # Use `$!bcountry` to modify it inside the class. has Str $.ccountry is rw; # This attribute can be modified from outside. has Int $!age = 0; # A private attribute with default value. @@ -911,12 +911,12 @@ class Human { } }; -## Create a new instance of Human class with $.attrib set to 5. +## Create a new instance of Human class. ## Note: you can't set private-attribute from here (more later on). my $person1 = Human.new( name => "Jord", - bcountry = "Iceland", - ccountry => "Iceland" + bcountry = "Togo", + ccountry => "Togo" ); say $person1.name; #=> Jord -- cgit v1.2.3 From e7a2c6d888c5c5da7db436eed12bac5c41474d73 Mon Sep 17 00:00:00 2001 From: Aldaschwede <32069769+Aldaschwede@users.noreply.github.com> Date: Tue, 6 Aug 2019 17:29:19 +0200 Subject: Update solidity.html.markdown added qualifier payable to the function Info, hence without it's not compileable --- solidity.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index d215180d..cc719ec7 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -483,7 +483,7 @@ for(uint x = 0; x < refundAddressList.length; x++) { // A. Calling external contract contract InfoFeed { - function info() returns (uint ret) { return 42; } + function info() payable returns (uint ret) { return 42; } } contract Consumer { -- cgit v1.2.3 From 4132daa9e5eacab90eedbc63a203b9d21ca7ae5c Mon Sep 17 00:00:00 2001 From: Aldaschwede <32069769+Aldaschwede@users.noreply.github.com> Date: Tue, 6 Aug 2019 17:34:48 +0200 Subject: Update python3-de.html.markdown spelling mistake --- de-de/python3-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown index c383d742..4ef997a1 100644 --- a/de-de/python3-de.html.markdown +++ b/de-de/python3-de.html.markdown @@ -14,7 +14,7 @@ Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist he Feedback ist herzlich willkommen! Ihr erreicht mich unter [@louiedinh](http://twitter.com/louiedinh) oder louiedinh [at] [google's email service]. -Hinweis: Dieser Beitrag bezieht sich insplizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. +Hinweis: Dieser Beitrag bezieht sich implizit auf Python 3. Falls du lieber Python 2.7 lernen möchtest, schau [hier](http://learnxinyminutes.com/docs/python/) weiter. ```python -- cgit v1.2.3 From 2f8df4fd1425eae4160570c395f7be743a11e2cb Mon Sep 17 00:00:00 2001 From: Samuel Chase Date: Thu, 8 Aug 2019 22:16:37 +0530 Subject: Fix keybinding To enter copy mode we use `[` and not `]`. --- tmux.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index b28a4f59..1c2c2da3 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -78,7 +78,7 @@ combinations called 'Prefix' keys. p # Change to the previous window { # Swap the current pane with the previous pane } # Swap the current pane with the next pane - ] # Enter Copy Mode to copy text or view history. + [ # Enter Copy Mode to copy text or view history. s # Select a new session for the attached client interactively -- cgit v1.2.3 From d03bbc18206904d8fc7f06a5243925b379a3b5ac Mon Sep 17 00:00:00 2001 From: Julian Fondren Date: Fri, 9 Aug 2019 03:39:43 -0500 Subject: Added Mercury --- mercury.html.markdown | 263 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 mercury.html.markdown diff --git a/mercury.html.markdown b/mercury.html.markdown new file mode 100644 index 00000000..76c7d1ca --- /dev/null +++ b/mercury.html.markdown @@ -0,0 +1,263 @@ +--- +language: mercury +contributors: + - ["Julian Fondren", "https://mercury-in.space/"] +--- + +Mercury is a strict, pure functional/logic programming language, with +influences from Prolog, ML, and Haskell. + +```mercury +% Percent sign starts a one-line comment. + + % foo(Bar, Baz) + % + % Documentation comments are indented before what they describe. +:- pred foo(bar::in, baz::out) is det. + +% All toplevel syntax elements end with a '.' -- a full stop. + +% Mercury terminology comes from predicate logic. Very roughly: + +% | Mercury | C | +% | | | +% | Goal | statement | +% | expression | expression | +% | predicate rule | void function | +% | function rule | function | +% | head (of a rule) | function name and parameters | +% | body (of a rule) | function body | +% | fact | (rule without a body) | +% | pred/func declaration | function signature | +% | A, B (conjunction) | A && B | +% | A ; B (disjunction) | if (A) {} else if (B) {} | + +% some facts: +man(socrates). % "it is a fact that Socrates is a man" +man(plato). +man(aristotle). + +% a rule: +mortal(X) :- man(X). % "It is a rule that X is a mortal if X is a man." +% ^^^^^^-- the body of the rule +% ^^-- an arrow <--, pointing to the head from the body +%^^^^^^^^-- the head of the rule +% this is also a single clause that defines the rule. + +% that X is capitalized is how you know it's a variable. +% that socrates is uncapitalized is how you know it's a term. + +% it's an error for 'socrates' to be undefined. It must have a type: + +% declarations begin with ':-' +:- type people + ---> socrates + ; plato + ; aristotle + ; hermes. + %<--first tab stop (using 4-space tabs) + %<--third tab stop (first after --->) + +:- pred man(people). % rules and facts also require types + +% a rule's modes tell you how it can be used. +:- mode man(in) is semidet. % man(plato) succeeds. man(hermes) fails. +:- mode man(out) is multi. % man(X) binds X to one of socrates ; plato ; aristotle + +% a semidet predicate is like a test. It doesn't return a value, but +% it can succeed or fail, triggering backtracking or the other side of +% a disjunction or conditional. + +% 'is semidet' provides the determinism of a mode. Other determinisms: +% | Can fail? | 0 solutions | 1 | more than 1 | +% | | | | | +% | no | erroneous | det | multi | +% | yes | failure | semidet | nondet | + +:- pred mortal(people::in) is semidet. % type/mode in one declaration + +% this rule's body consists of two conjunctions: A, B, C +% this rule is true if A, B, and C are all true. +% if age(P) returns 16, it fails. +% if alive(P) fails, it fails. +:- type voter(people::in) is semidet. +voter(P) :- + alive(P), + registered(P, locale(P)), + age(P) >= 18. % age/1 is a function; int.>= is a function used as an operator + +% "a P is a voter if it is alive, is registered in P's locale, and if +% P's age is 18 or older." + +% the >= used here is provided by the 'int' module, which isn't +% imported by default. Mercury has a very small 'Prelude' (the +% 'builtin' module). You even need to import the 'list' module if +% you're going to use list literals. +``` + +Complete runnable example. File in 'types.m'; compile with 'mmc --make types'. + +```mercury +:- module types. +:- interface. +:- import_module io. % required for io.io types in... +% main/2 is usually 'det'. threading and exceptions require 'cc_multi' +:- pred main(io::di, io::uo) is cc_multi. % program entry point +:- implementation. +:- import_module int, float, string, list, bool, map, exception. + +% enum. +:- type days + ---> sunday + ; monday + ; tuesday + ; wednesday + ; thursday + ; friday + ; saturday. + +% discriminated union, like datatype in ML. +:- type payment_method + ---> cash(int) + ; credit_card( + name :: string, % named fields + cc_number :: string, + cvv :: int, + expiration :: string + ) + ; crypto(coin_type, wallet, amount). + +:- type coin_type + ---> etherium + ; monero. % "other coins are available" + +% type aliases. +:- type wallet == string. +:- type amount == int. + +% !IO is the pair of io.io arguments +% pass it to anything doing I/O, in order to perform I/O. +% many otherwise-impure functions can 'attach to the I/O state' by taking !IO +main(!IO) :- + Ints = [ + 3, + 1 + 1, + 8 - 1, + 10 * 2, + 35 / 5, + 5 / 2, % truncating division + int.div(5, 2), % floored division + div(5, 2), % (module is unambiguous due to types) + 5 `div` 2, % (any binary function can be an operator with ``) + 7 `mod` 3, % modulo of floored division + 7 `rem` 3, % remainder of truncating division + 2 `pow` 4, % 2 to the 4th power + (1 + 3) * 2, % parens have their usual meaning + + 2 >> 3, % bitwise right shift + 128 << 3, % bitwise left shift + \ 0, % bitwise complement + 5 /\ 1, % bitwise and + 5 \/ 1, % bitwise or + 5 `xor` 3, % bitwise xor + + max_int, + min_int, + + 5 `min` 3, % ( if 5 > 3 then 3 else 5 ) + 5 `max` 3 + ], + Bools = [ + yes, + no + % bools are much less important in Mercury because control flow goes by + % semidet goals instead of boolean expressions. + ], + Strings = [ + "this is a string", + "strings can have "" embedded doublequotes via doubling", + "strings support \u4F60\u597D the usual escapes\n", + % no implicit concatenation of strings: "concat:" "together" + "but you can " ++ " use the string.++ operator", + + % second param is a list(string.poly_type) + % s/1 is a function that takes a string and returns a poly_type + % i/1 takes an int. f/1 takes a float. c/1 takes a char. + string.format("Hello, %d'th %s\n", [i(45), s("World")]) + ], + + % start with purely functional types like 'map' and 'list'! + % arrays and hash tables are available too, but using them + % requires knowing a lot more about Mercury + get_map1(Map1), + get_map2(Map2), + + % list.foldl has *many* variations + % this one calls io.print_line(X, !IO) for each X of the list + foldl(io.print_line, Ints, !IO), + foldl(io.print_line, Bools, !IO), + foldl(io.print_line, Strings, !IO), + io.print_line(Map1, !IO), + % ( if Cond then ThenGoal else ElseGoal ) + % I/O not allowed in Cond: I/O isn't allowed to fail! + ( if Map2^elem(42) = Elem then + io.print_line(Elem, !IO) + else % always required + true % do nothing, successfully (vs. 'fail') + ), + + % exception handling: + ( try [io(!IO)] ( % io/1 param required or no I/O allowed here + io.print_line(received(cash(1234)), !IO), + io.print_line(received(crypto(monero, "invalid", 123)), !IO) + ) then + io.write_string("all payments accepted\n", !IO) % never reached + catch "monero not yet supported" -> % extremely specific catch! + io.write_string("monero payment failed\n", !IO) + ). + +:- pred get_map1(map(string, int)::out) is det. +get_map1(!:Map) :- % !:Map in the head is the final (free, unbound) Map + !:Map = init, % !:Map in the body is the next Map + det_insert("hello", 1, !Map), % pair of Map vars + det_insert("world", 2, !Map), + + % debug print of current (bound) Map + % other [Params] can make it optional per runtime or compiletime flags + trace [io(!IO)] (io.print_line(!.Map, !IO)), + + det_insert_from_corresponding_lists(K, V, !Map), + % this code is reordered so that K and V and defined prior to their use + K = ["more", "words", "here"], + V = [3, 4, 5]. + +:- pred get_map2(map(int, bool)::out) is det. +get_map2(Map) :- + det_insert(42, yes, map.init, Map). + +:- func received(payment_method) = string. +received(cash(N)) = string.format("received %d dollars", [i(N)]). +received(credit_card(_, _, _, _)) = "received credit card". % _ is throwaway +received(crypto(Type, _Wallet, Amount)) = S :- % _Wallet is named throwaway + ( % case/switch structure + Type = etherium, + S = string.format("receiving %d ETH", [i(Amount)]) + ; + Type = monero, + throw("monero not yet supported") % exception with string as payload + ). +``` + +## That was quick! Want more? + +### More Tutorials + +* [Mercury Tutorial](https://mercurylang.org/documentation/papers/book.pdf) (pdf link) - a more traditional tutorial with a more relaxed pace +* [Mercury Crash Course](https://mercury-in.space/crash.html) - a dense example-driven tutorial with Q&A format +* [Github Wiki Tutorial](https://github.com/Mercury-Language/mercury/wiki/Tutorial) +* [Getting Started with Mercury](https://bluishcoder.co.nz/2019/06/23/getting-started-with-mercury.html) - installation and your first steps + +### Documentation + +* Language manual, user's guide, and library reference are all at + [mercurylang.org](https://mercurylang.org/documentation/documentation.html) -- cgit v1.2.3 From e8dd50b85e93f1baf0c909f2716177e052672ff5 Mon Sep 17 00:00:00 2001 From: Dimitri Kokkonis Date: Sat, 10 Aug 2019 19:56:02 +0200 Subject: [bash/gr] Translate Bash to greek (#3595) * Add greek translation for the HTML language * Correct typo in source file name * Translate Bash to greek --- bash.html.markdown | 18 +- el-gr/bash-gr.html.markdown | 528 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 538 insertions(+), 8 deletions(-) create mode 100644 el-gr/bash-gr.html.markdown diff --git a/bash.html.markdown b/bash.html.markdown index 0385c46d..856db706 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -11,13 +11,15 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] - ["Etan Reisner", "https://github.com/deryni"] - - ["Jonathan Wang", "https://github.com/Jonathansw"] + - ["Jonathan Wang", "https://github.com/Jonathansw"] - ["Leo Rudberg", "https://github.com/LOZORD"] - ["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 +translators: + - ["Dimitri Kokkonis", "https://github.com/kokkonisd"] --- Bash is a name of the unix shell, which was also distributed as the shell @@ -67,7 +69,7 @@ echo '$Variable' # => $Variable # Parameter expansion ${ }: echo ${Variable} # => Some string # This is a simple usage of parameter expansion -# Parameter Expansion gets a value from a variable. +# Parameter Expansion gets a value from a variable. # It "expands" or prints the value # During the expansion time the value or parameter can be modified # Below are other modifications that add onto this expansion @@ -87,7 +89,7 @@ echo ${Variable: -5} # => tring echo ${#Variable} # => 11 # Default value for variable -echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} # => 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. @@ -244,7 +246,7 @@ cp -r srcDirectory/ dst/ # recursively copy # `mv` is also useful for renaming files! mv s0urc3.txt dst.txt # sorry, l33t hackers... -# Since bash works in the context of a current directory, you might want to +# Since bash works in the context of a current directory, you might want to # run your command in some other directory. We have cd for changing location: cd ~ # change to home directory cd # also goes to home directory @@ -280,7 +282,7 @@ for line in sys.stdin: EOF # Variables will be expanded if the first "EOF" is not quoted -# Run the hello.py Python script with various stdin, stdout, and +# Run the hello.py Python script with various stdin, stdout, and # stderr redirections: python hello.py < "input.in" # pass input.in as input to the script @@ -322,7 +324,7 @@ rm -r tempDir/ # recursively delete # current directory. echo "There are $(ls | wc -l) items here." -# The same can be done using backticks `` but they can't be nested - +# The same can be done using backticks `` but they can't be nested - #the preferred way is to use $( ). echo "There are `ls | wc -l` items here." @@ -442,8 +444,8 @@ grep "^foo.*bar$" file.txt | grep -v "baz" # and not the regex, use fgrep (or grep -F) fgrep "foobar" file.txt -# The `trap` command allows you to execute a command whenever your script -# receives a signal. Here, `trap` will execute `rm` if it receives any of the +# The `trap` command allows you to execute a command whenever your script +# receives a signal. Here, `trap` will execute `rm` if it receives any of the # three listed signals. trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM diff --git a/el-gr/bash-gr.html.markdown b/el-gr/bash-gr.html.markdown new file mode 100644 index 00000000..2989969d --- /dev/null +++ b/el-gr/bash-gr.html.markdown @@ -0,0 +1,528 @@ +--- +category: tool +tool: bash +contributors: + - ["Dimitri Kokkonis", "https://github.com/kokkonisd"] +filename: LearnBash-gr.sh +lang: el-gr +--- + +Η λέξη «bash» είναι ένα από τα ονόματα του unix shell (τερματικός), το οποίο +διανέμεται επίσης ως προεπιλεγμένος τερματικός για το λειτουργικό σύστημα GNU, τα Linux και τα Mac OS X. +Σχεδόν όλα τα παραδείγματα που ακολουθούν μπορούν να αποτελέσουν μέρος ενός +προγράμματος τερματικού (shell script) ή να εκτελεσθούν απευθείας από τον +τερματικό. + +[Διαβάστε περισσότερα εδώ.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/usr/bin/env bash +# Η πρώτη γραμμή του προγράμματος είναι το shebang που υποδεικνύει στο σύστημα +# πώς να εκτελέσει το πρόγραμμα: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Όπως ήδη θα καταλάβατε, τα σχόλια ξεκινούν με τον χαρακτήρα #. Το shebang +# είναι επίσης ένα σχόλιο. +# ΣτΜ.: Τα ονόματα των μεταβλητών είναι γραμμένα σε greeklish καθώς η Bash δεν +# επιτρέπει την χρήση unicode χαρακτήρων. + +# Ένα απλό παράδειγμα τύπου «hello world»: +echo Καλημέρα, Κόσμε! # => Καλημέρα, Κόσμε! + +# Κάθε εντολή ξεκινά σε μια νέα γραμμή, ή μετά από ένα ελληνικό ερωτηματικό: +echo 'Αυτή είναι η πρώτη γραμμή'; echo 'Αυτή είναι η δεύτερη γραμμή' +# => Αυτή είναι η πρώτη γραμμή +# => Αυτή είναι η δεύτερη γραμμή + +# Ορίζουμε μεταβλητές ως εξής: +Metavliti="Κάποιο αλφαριθμητικό" + +# Αλλά όχι ως εξής: +Metavliti = "Κάποιο αλφαριθμητικό" # => επιστρέφει το λάθος +# «Metavliti: command not found» +# Η Bash θα καταλάβει πως η Metavliti είναι κάποια εντολή που πρέπει να +# εκτελέσει και θα επιστρέψει ένα λάθος γιατί δεν μπορεί να την βρει. + +# Ούτε έτσι μπορούμε να δηλώσουμε μεταβλητές: +Metavliti= 'Κάποιο αλφαριθμητικό' # => επιστρέφει το λάθος: «Κάποιο + # αλφαριθμητικό: command not found» +# Η Bash θα καταλάβει πως το αλφαριθμητικό «Κάποιο αλφαριθμητικό» είναι μια +# εντολή που πρέπει να εκτελέσει και θα επιστρέψει ένα λάθος γιατί δεν μπορεί +# να την βρει. (Σε αυτή την περίπτωση το τμήμα της εντολής «Metavliti=» θα +# ερμηνευθεί ως ορισμός μεταβλητής ισχύων μόνο στο πλαίσιο της εντολής +# «Κάποιο αλφαριθμητικό».) + +# Ας χρησιμοποιήσουμε την μεταβλητή: +echo $Metavliti # => Κάποιο αλφαριθμητικό +echo "$Metavliti" # => Κάποιο αλφαριθμητικό +echo '$Metavliti' # => $Metavliti +# Όταν χρησιμοποιούμε την ίδια την μεταβλητή - είτε είναι για να της δώσουμε +# μια νέα αξία, για να την εξάγουμε ή για οτιδήποτε άλλο - γράφουμε το όνομά +# της χωρίς τον χαρακτήρα $. Αν θέλουμε να χρησιμοποιήσουμε την αξία της +# μεταβλητής, πρέπει να χρησιμοποιήσουμε τον χαρατήρα $. +# Να σημειωθεί πώς ο χαρακτήρας ' δεν θα μετατρέψει τις μεταβλητές στις αξίες +# τους! + +# Επέκταση παραμέτρων ${ }: +echo ${Metavliti} # => Κάποιο αλφαριθμητικό +# Αυτή είναι μια απλή χρήση της επέκτασης παραμέτρων. +# Η επέκταση παραμέτρων εξάγει μια αξία από μια μεταβλητή. +# Κατά την επέκταση η τιμή ή η παράμετρος μπορεί να τροποποιηθεί. +# Ακολουθούν άλλες μετατροπές που μπορούν να προστεθούν σε αυτή την επέκταση. + +# Αντικατάσταση αλφαριθμητικών μέσα σε μεταβλητές +echo ${Metavliti/Κάποιο/Ένα} # => Ένα αλφαριθμητικό +# Αυτή η τροποποίηση θα αντικαταστήσει την πρώτη εμφάνιση της λέξης «Κάποιο» +# με την λέξη «Ένα». + +# Υποαλφαριθμητικό μιας μεταβλητής +Mikos=7 +echo ${Metavliti:0:Mikos} # => Κάποιο +# Αυτή η τροποποίηση θα επιστρέψει μόνο τους πρώτους 7 χαρακτήρες της τιμής +# της μεταβλητής. +echo ${Metavliti: -5} # => ητικό +# Αυτή η τροποποίηση θα επιστρέψει τους τελευταίους 5 χαρακτήρες (προσοχή στο +# κενό πριν το -5). + +# Μήκος αλφαριθμητικού +echo ${#Metavliti} # => 20 + +# Προεπιλεγμένη αξία για μια μεταβλητή +echo ${Foo:-"ΠροεπιλεγμένηΑξίαΑνΤοFooΕίναιΑόριστοΉΆδειο"} +# => ΠροεπιλεγμένηΑξίαΑνΤοFooΕίναιΑόριστοΉΆδειο +# Αυτό δουλεύει στην περίπτωση που το Foo είναι αόριστο (Foo=) ή άδειο +# (Foo="")· το μηδέν (Foo=0) επιστρέφει 0. +# Να σημειωθεί πως αυτή η εντολή απλώς επιστρέφει την προεπιλεγμένη αξία και +# δεν τροποποιεί την αξία της μεταβλητής. + +# Ορισμός ενός πίνακα με 6 στοιχεία +pinakas0=(ένα δύο τρία τέσσερα πέντε έξι) +# Εντολή που τυπώνει το πρώτο στοιχείο +echo $pinakas0 # => "ένα" +# Εντολή που τυπώνει το πρώτο στοιχείο +echo ${pinakas0[0]} # => "ένα" +# Εντολή που τυπώνει όλα τα στοιχεία +echo ${pinakas0[@]} # => "ένα δύο τρία τέσσερα πέντε έξι" +# Εντολή που τυπώνει τον αριθμό των στοιχείων +echo ${#pinakas0[@]} # => "6" +# Εντολή που τυπώνει τον αριθμό των χαρακτήρων στο τρίτο στοιχείο +echo ${#pinakas0[2]} # => "4" +# Εντολή που τυπώνει δύο στοιχεία ξεκινώντας από το τέταρτο +echo ${pinakas0[@]:3:2} # => "τέσσερα πέντε" +# Εντολή που τυπώνει όλα τα στοιχεία, το καθένα σε διαφορετική γραμμή +for i in "${pinakas0[@]}"; do + echo "$i" +done + +# Επέκταση αγκίστρων { } +# Χρησιμοποιείται για την παραγωγή αλφαριθμητικών +echo {1..10} # => 1 2 3 4 5 6 7 8 9 10 +echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z +# Η εντολή θα τυπώσει όλο το εύρος, από την πρώτη μέχρι την τελευταία αξία + +# Ενσωματωμένες μεταβλητές +# Υπάρχουν κάποιες χρήσιμες ενσωματωμένες μεταβλητές, όπως: +echo "Η τιμή την οποία επέστρεψε το τελευταίο πρόγραμμα: $?" +echo "Ο αριθμός PID αυτού του script: $$" +echo "Ο αριθμός των παραμέτρων που περάστηκαν σε αυτό το script: $#" +echo "Όλες οι παράμετροι που περάστηκαν σε αυτό το script: $@" +echo "Οι παράμετροι του script διαχωρισμένες σε μεταβλητές: $1 $2..." + +# Τώρα που γνωρίζουμε πως να τυπώνουμε (echo) και να χρησιμοποιούμε μεταβλητές, +# ας μάθουμε κάποια από τα υπόλοιπα βασικά στοιχεία της Bash! + +# Ο τρέχων κατάλογος (ή αλλιώς, φάκελος) μπορεί να βρεθεί μέσω της εντολής +# `pwd`. +# `pwd` σημαίνει «print working directory». +# Μπορούμε επίσης να χρησιμοποιούμε την ενσωματωμένη μεταβλητή `$PWD`. +# Παρακολουθήστε πως οι δύο εντολές που ακολουθούν είναι ισοδύναμες: +echo "Είμαι στον κατάλογο $(pwd)" # εκτελεί την εντολή `pwd` και τυπώνει το + # αποτέλεσμα +echo "Είμαι στον κατάλογο $PWD" # τυπώνει την αξία της μεταβλητής + +# Αν έχετε πολλά μηνύματα στον τερματικό, η εντολή `clear` μπορεί να +# «καθαρίσει» την οθόνη σας +clear +# Η συντόμευση Ctrl-L δουλεύει επίσης όσον αφορά το «καθάρισμα» + +# Ας διαβάσουμε μια αξία από κάποια είσοδο: +echo "Πώς σε λένε;" +read Onoma # Προσέξτε πως δεν χρειάστηκε να ορίσουμε μια νέα μεταβλητή +echo Καλημέρα, $Onoma! + +# Η δομή των if statements έχει ως εξής: +# (μπορείτε να εκτελέσετε την εντολή `man test` για περισσότερες πληροφορίες +# σχετικά με τα conditionals) +if [ $Onoma != $USER ] +then + echo "Το όνομά σου δεν είναι το όνομα χρήστη σου" +else + echo "Το όνομά σου είναι το όνομα χρήστη σου" +fi +# Η συνθήκη είναι αληθής αν η τιμή του $Onoma δεν είναι ίδια με το τρέχον +# όνομα χρήστη στον υπολογιστή + +# ΣΗΜΕΙΩΣΗ: Αν το $Onoma είναι άδειο, η Bash βλέπει την συνθήκη ως: +if [ != $USER ] +# το οποίο αποτελεί συντακτικό λάθος +# οπότε ο «ασφαλής» τρόπος να χρησιμοποιούμε εν δυνάμει άδειες μεταβλητές στην +# Bash είναι ο εξής: +if [ "$Onoma" != $USER ] ... +# ο οποίος, όταν το $Onoma είναι άδειο, θα ερμηνευθεί από την Bash ως: +if [ "" != $USER ] ... +# το οποίο και δουλεύει όπως θα περιμέναμε. + +# Υπάρχει επίσης η εκτέλεση εντολών βάσει συνθηκών +echo "Εκτελείται πάντα" || echo "Εκτελείται μόνο αν η πρώτη εντολή αποτύχει" +# => Εκτελείται πάντα +echo "Εκτελείται πάντα" && echo "Εκτελείται μόνο αν η πρώτη εντολή ΔΕΝ αποτύχει" +# => Εκτελείται πάντα +# => Εκτελείται μόνο αν η πρώτη εντολή ΔΕΝ αποτύχει + + +# Για να χρησιμοποιήσουμε τους τελεστές && και || με τα if statements, +# χρειαζόμαστε πολλαπλά ζευγάρια αγκύλων: +if [ "$Onoma" == "Σταύρος" ] && [ "$Ilikia" -eq 15 ] +then + echo "Αυτό θα εκτελεστεί αν το όνομα ($Onoma) είναι Σταύρος ΚΑΙ η ηλικία ($Ilikia) είναι 15." +fi + +if [ "$Onoma" == "Δανάη" ] || [ "$Onoma" == "Ζαχαρίας" ] +then + echo "Αυτό θα εκτελεστεί αν το όνομα ($Onoma) είναι Δανάη Ή Ζαχαρίας." +fi + +# Υπάρχει επίσης ο τελεστής `=~`, που εκτελεί ένα regex πάνω σε ένα +# αλφαριθμητικό: +Email=me@example.com +if [[ "$Email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]] +then + echo "Η διεύθυνση email είναι σωστά διατυπωμένη!" +fi +# Να σημειωθεί πως ο τελεστής `=~` δουλεύει μόνο με διπλές αγκύλες [[ ]], +# που είναι ωστόσο διαφορετικές από τις μονές [ ]. +# Δείτε το http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs +# για περισσότερες πληροφορίες σχετικά με αυτό. + +# Επαναπροσδιορισμός της εντολής `ping` ως alias (ψευδώνυμο) για την αποστολή 5 +# πακέτων +alias ping='ping -c 5' +# Ακύρωση του alias και χρήση της εντολής όπως είναι κανονικά ορισμένη +\ping 192.168.1.1 +# Εκτύπωση όλων των aliases +alias -p + +# Οι μαθηματικές εκφράσεις ορίζονται ως εξής: +echo $(( 10 + 5 )) # => 15 + +# Αντίθετα με άλλες γλώσσες προγραμματισμού, η Bash είναι επίσης ένα shell, άρα +# δουλεύει στο πλαίσιο ενός «τρέχοντος καταλόγου». Μπορούμε να δούμε μια λίστα +# αρχείων και καταλόγων στον τρέχων κατάλογο με την εντολή ls: +ls # Τυπώνει μια λίστα των αρχείων και υποκαταλόγων που περιέχονται στον τρέχων + # κατάλογο + +# Αυτή η εντολή έχει επιλογές που ελέγχουν την εκτέλεσή της: +ls -l # Τυπώνει κάθε αρχείο και κατάλογο σε διαφορετική γραμμή +ls -t # Ταξινομεί τα περιεχόμενα του καταλόγου με βάσει την ημερομηνία + # τελευταίας τροποποίησης (σε φθίνουσα σειρά) +ls -R # Εκτελεί την εντολή `ls` αναδρομικά στον τρέχων κατάλογο και σε όλους + # τους υποκαταλόγους του. + +# Τα αποτελέσματα μιας εντολής μπορούν να μεταβιβαστούν σε μιαν άλλη. +# Η εντολή `grep` φιλτράρει τα δεδομένα που δέχεται βάσει μοτίβων. +# Έτσι, μπορούμε να τυπώσουμε μια λίστα αρχείων κειμένου (.txt) στον τρέχων +# κατάλογο: +ls -l | grep "\.txt" + +# Μπορούμε να χρησιμοποιήσουμε την εντολή `cat` για να τυπώσουμε το περιεχόμενο +# ενός ή περισσότερων αρχείων στην προεπιλεγμένη έξοδο (stdout): +cat file.txt + +# Μπορούμε επίσης να διαβάσουμε το αρχείο μέσω της `cat`: +Periexomena=$(cat file.txt) +echo "ΑΡΧΗ ΤΟΥ ΑΡΧΕΙΟΥ\n$Periexomena\nΤΕΛΟΣ ΤΟΥ ΑΡΧΕΙΟΥ" # Ο χαρακτήρας "\n" + # δημιουργεί μια νέα + # γραμμή +# => ΑΡΧΗ ΤΟΥ ΑΡΧΕΙΟΥ +# => [περιεχόμενα του αρχείου file.txt] +# => ΤΕΛΟΣ ΤΟΥ ΑΡΧΕΙΟΥ + +# Μπορούμε να χρησιμοποιήσουμε την εντολή `cp` για να αντιγράψουμε αρχεία ή +# καταλόγους από ένα σημείο σε ένα άλλο. +# Η εντολή `cp` δημιουργεί ΝΕΕΣ εκδοχές των πρωτοτύπων, το οποίο σημαίνει ότι +# μια τροποποίηση του αντιγράφου δεν θα επηρεάσει το πρωτότυπο (και +# αντιστρόφως). +# Να σημειωθεί πως αν υπάρχει ήδη αρχείο ή κατάλογος με το ίδιο όνομα στην ίδια +# θέση με το αντίγραφο, το αντίγραφο θα αντικαταστήσει το αρχείο/κατάλογο και +# άρα τα δεδομένα του θα χαθούν. +cp prototipo.txt antigrafo.txt +cp -r prototipo/ antigrafo/ # Αναδρομική αντιγραφή (αντιγραφή όλων των + # περιεχομένων του καταλόγου prototipo/) + +# Ενημερωθείτε σχετικά με τις εντολές `scp` και `sftp` αν σχεδιάζετε να +# αντιγράψετε αρχεία από έναν υπολογιστή σε έναν άλλο. +# Η εντολή `scp` μοιάζει πολύ με την `cp`, ενώ η `sftp` είναι πιο διαδραστική. + +# Μπορούμε να χρησιμοποιήσουμε την εντολή `mv` για να μετακινήσουμε αρχεία ή +# καταλόγους από μια θέση σε μια άλλη. +# Η εντολή `mv` μοιάζει με την `cp`, με τη διαφορά ότι διαγράφει το πρωτότυπο. +# Η `mv` χρησιμοποιείται επίσης για τη μετονομασία αρχείων! +mv prototipo.txt prototipo2.txt + +# Δεδομένου του ότι η Bash δουλεύει στο πλαίσιο του τρέχοντος καταλόγου, +# μπορεί να θελήσουμε να τρέξουμε κάποια εντολή σε κάποιον άλλο κατάλογο. +# Η εντολή `cd` (Change Directory) μας επιτρέπει να αλλάξουμε θέση μέσα στο +# σύστημα αρχείων: +cd ~ # Μετατόπιση στον κατάλογο «home» +cd # Αυτή η εντολή μας μετατοπίζει επίσης στον κατάλογο «home» +cd .. # Μετατόπιση προς τα πάνω κατά έναν κατάλογο + # (για παράδειγμα, μετατόπιση από τη θέση /home/username/Downloads + # στη θέση /home/username) +cd /home/username/Documents # Μετατόπιση προς έναν συγκεκριμένο κατάλογο +cd ~/Documents/.. # Μετατόπιση προς τον κατάλογο «home»... σωστά; +cd - # Μετατόπιση προς τον προηγούμενο κατάλογο +# => /home/username/Documents + +# Μπορούμε να χρησιμοποιήσουμε subshells για να δουλέψουμε σε πολλούς +# διαφορετικούς καταλόγους: +(echo "Πρώτα, είμαι εδώ: $PWD") && (cd kapoiosKatalogos; echo "Έπειτα, είμαι εδώ: $PWD") +pwd # Εδώ θα είμαστε στον πρώτο κατάλογο + +# Μπορούμε να χρησιμοποιήσουμε την εντολή `mkdir` για να δημιουργήσουμε νέους +# καταλόγους. +mkdir neosKatalogos +# Η επιλογή `-p` επιτρέπει σε ενδιάμεσους καταλόγους να δημιουργηθούν αν +# χρειάζεται. +mkdir -p neosKatalogos/me/epipleon/katalogous +# Αν οι ενδιάμεσοι κατάλογοι δεν υπήρχαν ήδη, η παραπάνω εντολή χωρίς την +# επιλογή `-p` θα είχε επιστρέψει κάποιο λάθος. + +# Μπορούμε να διευθύνουμε τις εισόδους και εξόδους των εντολών (χρησιμοποιώντας +# τα κανάλια stdin, stdout και stderr). +# Για παράδειγμα, μπορούμε να «διαβάσουμε» από το stdin μέχρι να βρεθεί ένα +# ^EOF$ (End Of File) και να αντικαταστήσουμε το περιεχόμενο του αρχείου +# hello.py με τις γραμμές που διαβάσαμε έως και πριν το "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 + +# Μπορούμε να τρέξουμε το πρόγραμμα Python «hello.py» με διάφορες +# ανακατευθύνσεις χρησιμοποιώντας τα stdin, stdout και stderr: +python hello.py < "eisodos.in" # Περνάμε το eisodos.in ως είσοδο στο πρόγραμμα + +python hello.py > "eksodos.out" # Ανακατευθύνουμε την έξοδο του προγράμματος + # προς το αρχείο eksodos.out + +python hello.py 2> "lathos.err" # ανακατευθύνουμε την έξοδο λάθους (stderr) + # προς το αρχείο lathos.err + +python hello.py > "eksodos-kai-lathos.log" 2>&1 +# Ανακατευθύνουμε την κανονική έξοδο (stdout) και την έξοδο λάθους (stderr) +# προς το αρχείο eksodos-kai-lathos.log + +python hello.py > /dev/null 2>&1 +# Ανακατευθύνουμε όλες τις εξόδους προς τη «μαύρη τρύπα» που λέγεται /dev/null, +# δηλαδή τίποτα δεν θα τυπωθεί στον τερματικό + +# Αν θέλετε να προσθέσετε την έξοδο σε κάποιο αρχείο αντί να διαγράψετε τα +# περιεχόμενά του με τη νέα έξοδο, μπορείτε να χρησιμοποιήσετε τον τελεστή +# `>>` αντί στη θέση του `>`: +python hello.py >> "eksodos.out" 2>> "lathos.err" + +# Αντικατάσταση του αρχείου eksodos.out, προσθήκη στο αρχείο lathos.err, και +# καταμέτρηση των γραμμών τους: +info bash 'Basic Shell Features' 'Redirections' > eksodos.out 2>> lathos.err +wc -l eksodos.out lathos.err + +# Μπορούμε να εκτελέσουμε μια εντολή και να τυπώσουμε τον file descriptor της +# (https://en.wikipedia.org/wiki/File_descriptor) +# Για παράδειγμα: /dev/fd/123 +# Δείτε επίσης: man fd +echo <(echo "#καλημέρακόσμε") + +# Αντικατάσταση του περιεχομένου του αρχείου eksodos.out με το αλφαριθμητικό +# «#καλημέρακόσμε»: +cat > eksodos.out <(echo "#καλημέρακόσμε") +echo "#καλημέρακόσμε" > eksodos.out +echo "#καλημέρακόσμε" | cat > eksodos.out +echo "#καλημέρακόσμε" | tee eksodos.out >/dev/null + +# Εκκαθάριση προσωρινών αρχείων με την επιλογή `-v` (verbose) (προσθέστε την +# επιλογή `-i` για περισσότερη διάδραση) +# ΠΡΟΣΟΧΗ: τα αποτελέσματα της εντολής `rm` είναι μόνιμα. +rm -v eksodos.out lathos.err eksodos-kai-lathos.log +rm -r tempDir/ # Αναδρομική διαγραφή + +# Οι εντολές μπορούν να αντικατασταθούν μέσα σε άλλες εντολές χρησιμοποιώντας +# το μοτίβο $( ). +# Το παράδειγμα που ακολουθεί τυπώνει τον αριθμό των αρχείων και των καταλόγων +# στον τρέχων κατάλογο. +echo "Υπάρχουν $(ls | wc -l) αντικείμενα εδώ." + +# Μπορούμε να επιτύχουμε το ίδιο αποτέλεσμα με τους χαρακτήρες ``, αλλά δεν +# μπορούμε να τους χρησιμοποιήσουμε αναδρομικά (δηλαδή `` μέσα σε ``). +# Ο προτεινόμενος τρόπος από την Bash είναι το μοτίβο $( ). +echo "Υπάρχουν `ls | wc -l` αντικείμενα εδώ." + +# Η Bash έχει επίσης τη δομή `case` που δουλεύει παρόμοια με τη δομή switch +# όπως στην Java ή την C++ για παράδειγμα: +case "$Metavliti" in + # Λίστα μοτίβων για τις συνθήκες που θέλετε να ορίσετε: + 0) echo "Η μεταβλητή έχει ένα μηδενικό.";; + 1) echo "Η μεταβλητή έχει έναν άσσο.";; + *) echo "Η μεταβλητή δεν είναι αόριστη (null).";; +esac + +# Οι βρόγχοι `for` εκτελούνται τόσες φορές όσο είναι το πλήθος των παραμέτρων +# που τους δίνονται: +# Το περιεχόμενο της μεταβλητής $Metavliti τυπώνεται τρεις φορές. +for Metavliti in {1..3} +do + echo "$Metavliti" +done +# => 1 +# => 2 +# => 3 + +# Μπορούμε επίσης να το γράψουμε πιο «παραδοσιακά»: +for ((a=1; a <= 3; a++)) +do + echo $a +done +# => 1 +# => 2 +# => 3 + +# Μπορούμε επίσης να περάσουμε αρχεία ως παραμέτρους. +# Το παράδειγμα που ακολουθεί θα τρέξει την εντολή `cat` με τα αρχεία file1 +# και file2: +for Metavliti in file1 file2 +do + cat "$Metavliti" +done + +# Μπορούμε ακόμα να χρησιμοποιήσουμε την έξοδο μας εντολής. +# Το παράδειγμα που ακολουθεί θα τρέξει την εντολή `cat` με την έξοδο της +# εντολής `ls`. +for Output in $(ls) +do + cat "$Output" +done + +# Ο βρόγχος `while` έχει ως εξής: +while [ true ] +do + echo "το «σώμα» του βρόγχου μπαίνει εδώ..." + break +done +# => το «σώμα» του βρόγχου μπαίνει εδώ... + +# Μπορούμε επίσης να ορίσουμε συναρτήσεις, ως εξής: +function synartisi () +{ + echo "Οι παράμετροι συναρτήσεων δουλεύουν όπως αυτές των προγραμμάτων: $@" + echo "Και: $1 $2..." + echo "Αυτή είναι μια συνάρτηση" + return 0 +} +# Ας καλέσουμε την συνάρτηση `synartisi` με δύο παραμέτρους, param1 και param2 +synartisi param1 param2 +# => Οι παράμετροι συναρτήσεων δουλεύουν όπως αυτές των προγραμμάτων: param1 param2 +# => Και: param1 param2... +# => Αυτή είναι μια συνάρτηση + +# Ή επίσης: +synartisi2 () +{ + echo "Ένας άλλος τρόπος να ορίσουμε συναρτήσεις!" + return 0 +} +# Ας καλέσουμε την συνάρτηση `synartisi2` χωρίς παραμέτρους: +synartisi2 # => Ένας άλλος τρόπος να ορίσουμε συναρτήσεις! + +# Ας καλέσουμε την πρώτη συνάρτηση: +synartisi "Το όνομά μου είναι" $Onoma + +# Υπάρχουν πολλές χρήσιμες εντολές που μπορείτε να μάθετε. +# Για παράδειγμα, αυτή που ακολουθεί τυπώνει τις 10 τελευταίες γραμμές του +# αρχείου file.txt: +tail -n 10 file.txt + +# Ενώ αυτή τυπώνει τις 10 πρώτες: +head -n 10 file.txt + +# Αυτή ταξινομεί τις γραμμές: +sort file.txt + +# Αυτή αναφέρει ή παραλείπει τις γραμμές που επαναλαμβάνονται (η επιλογή +# -d τις αναφέρει): +uniq -d file.txt + +# Αυτή τυπώνει μόνο ό,τι βρίσκεται πριν τον πρώτο χαρακτήρα «,» σε κάθε γραμμή: +cut -d ',' -f 1 file.txt + +# Αυτή αντικαθιστά κάθε εμφάνιση της λέξης «οκ» με τη λέξη «τέλεια» στο αρχείο +# file.txt (δέχεται επίσης μοτίβα regex): +sed -i 's/οκ/τέλεια/g' file.txt + +# Αυτή τυπώνει στο stdout όλες τις γραμμές που είναι συμβατές με κάποιο +# συγκεκριμένο μοτίβο regex. +# Για παράδειγμα, όλες τις γραμμές που ξεκινούν με «καλημέρα» και τελειώνουν με +# «καληνύχτα»: +grep "^καλημέρα.*καληνύχτα$" file.txt + +# Η επιλογή `-c` θα τυπώσει τον αριθμό των γραμμών που περιέχουν το μοτίβο: +grep -c "^καλημέρα.*καληνύχτα$" file.txt + +# Άλλες χρήσιμες επιλογές: +grep -r "^καλημέρα.*καληνύχτα$" someDir/ # Αναδρομική εκτέλεση μέσα σε κάποιο κατάλογο +grep -n "^καλημέρα.*καληνύχτα$" file.txt # Τυπώνει επίσης τον αριθμό των γραμμών +grep -rI "^καλημέρα.*καληνύχτα$" someDir/ # Αναδρομική εκτέλεση αγνοώντας τα αρχεία binary + +# Η ίδια εντολή, αλλά τώρα αγνοώντας τις γραμμές που περιέχουν «αντίο» +grep "^καλημέρα.*καληνύχτα$" file.txt | grep -v "αντίο" + +# Αν θέλετε να ψάξετε κυριολεκτικά για ένα αλφαριθμητικό, και όχι για κάποιο +# μοτίβο, μπορείτε να χρησιμοποιήσετε την εντολή `fgrep` (ή `grep -F`): +fgrep "καλημέρα" file.txt + +# Η εντολή `trap` επιτρέπει την εκτέλεση μιας εντολής μόλις το πρόγραμμά μας +# λάβει κάποιο σήμα. Στο παράδειγμα που ακολουθεί, η εντολή `trap` θα +# εκτελέσει την εντολή `rm` αν λάβει κάποιο από τα τρία σήματα που ακολουθούν +# (SIGHUP, SIGINT, SIGTERM): +trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM + +# Η εντολή `sudo` (SuperUser Do) χρησιμοποιείται για να εκτελέσουμε εντολές +# με προνόμια υπερχρήστη (superuser): +ONOMA1=$(whoami) +ONOMA2=$(sudo whoami) +echo "Ήμουν ο $ONOMA1, και έπειτα έγινα ο πιο ισχυρός $ONOMA2" + +# Διαβάστε την ενσωματωμένη documentation της Bash χρησιμοποιώντας την εντολή +# `help`: +help +help help +help for +help return +help source +help . + +# Διαβάστε τα manpages με την εντολή `man`: +apropos bash +man 1 bash +man bash + +# Διαβάστε επίσης την info documentation με την εντολή `info`: +apropos info | grep '^info.*(' +man info +info info +info 5 info +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From b1f25adeb59ea5f90feb3fa427104e07864a3f51 Mon Sep 17 00:00:00 2001 From: Worajedt Sitthidumrong Date: Tue, 13 Aug 2019 14:21:09 +0700 Subject: translate all paragraphs to Thai. --- th-th/typescript.th.html.markdown | 228 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 228 insertions(+) create mode 100644 th-th/typescript.th.html.markdown diff --git a/th-th/typescript.th.html.markdown b/th-th/typescript.th.html.markdown new file mode 100644 index 00000000..94305c14 --- /dev/null +++ b/th-th/typescript.th.html.markdown @@ -0,0 +1,228 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] + - ["Worajedt Sitthidumrong", "https://bitbucket.org/wrj"] +filename: learntypescript.ts +lang: th-th +--- + +TypeScript เป็นภาษาที่มีเป้าหมายเพื่อทำให้การพัฒนาซอฟต์แวร์ขนาดใหญ่ด้วย JavaScript ทำได้ง่ายขึ้น โดยที่ TypeScript ได้เพิ่มแนวคิดที่พบทั่วไป อาทิ classes, modules, interfaces, generics และ static typing (ไม่บังคับ) เข้าไปในภาษา JavaScript ดังนั้น TypeScript ก็เลยเป็น Super Set ของ JavaScript อีกที โค้ด JavaScript ทุกส่วน ก็คือโค้ดที่ทำงานได้ถูกต้องใน TypeScript ทำให้เราเพิ่ม TypeScript เข้าไปใช้ในโปรเจคการพัฒนาของเราได้ไม่ยากเลย เพราะ TypeScript คอมไพล์ผลลัพธ์ออกมาเป็น JavaScript ในท้ายสุดอยู่ดี + +บทความนี้จะเน้นเฉพาะ syntax ส่วนขยายของ TypeScript ซึ่งจะไม่รวมกับที่มีใน [JavaScript](/docs/javascript). + +การทดสอบเขียน TypeScript เริ่มได้ง่าย ๆ โดยเข้าไปที่ +[Playground] (http://www.typescriptlang.org/Playground) ซึ่งคุณจะเขียนโค้ดพร้อม autocomplete และเห็นเลยว่ามันจะแปลงมาเป็นผลลัพธ์แบบ JavaScript อย่างไร + +```ts +// There are 3 basic types in TypeScript +let isDone: boolean = false; +let lines: number = 42; +let name: string = "Anders"; + +// But you can omit the type annotation if the variables are derived +// from explicit literals +let isDone = false; +let lines = 42; +let name = "Anders"; + +// When it's impossible to know, there is the "Any" type +let notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // okay, definitely a boolean + +// Use const keyword for constants +const numLivesForCat = 9; +numLivesForCat = 1; // Error + +// For collections, there are typed arrays and generic arrays +let list: number[] = [1, 2, 3]; +// Alternatively, using the generic array type +let list: Array = [1, 2, 3]; + +// For enumerations: +enum Color { Red, Green, Blue }; +let c: Color = Color.Green; + +// Lastly, "void" is used in the special case of a function returning nothing +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Functions are first class citizens, support the lambda "fat arrow" syntax and +// use type inference + +// The following are equivalent, the same signature will be inferred by the +// compiler, and same JavaScript will be emitted +let f1 = function (i: number): number { return i * i; } +// Return type inferred +let f2 = function (i: number) { return i * i; } +// "Fat arrow" syntax +let f3 = (i: number): number => { return i * i; } +// "Fat arrow" syntax with return type inferred +let f4 = (i: number) => { return i * i; } +// "Fat arrow" syntax with return type inferred, braceless means no return +// keyword needed +let f5 = (i: number) => i * i; + +// Interfaces are structural, anything that has the properties is compliant with +// the interface +interface Person { + name: string; + // Optional properties, marked with a "?" + age?: number; + // And of course functions + move(): void; +} + +// Object that implements the "Person" interface +// Can be treated as a Person since it has the name and move properties +let p: Person = { name: "Bobby", move: () => { } }; +// Objects that have the optional property: +let validPerson: Person = { name: "Bobby", age: 42, move: () => { } }; +// Is not a person because age is not a number +let invalidPerson: Person = { name: "Bobby", age: true }; + +// Interfaces can also describe a function type +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Only the parameters' types are important, names are not important. +let mySearch: SearchFunc; +mySearch = function (src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - members are public by default +class Point { + // Properties + x: number; + + // Constructor - the public/private keywords in this context will generate + // the boiler plate code for the property and the initialization in the + // constructor. + // In this example, "y" will be defined just like "x" is, but with less code + // Default values are also supported + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Static members + static origin = new Point(0, 0); +} + +// Classes can be explicitly marked as implementing an interface. +// Any missing properties will then cause an error at compile-time. +class PointPerson implements Person { + name: string + move() {} +} + +let p1 = new Point(10, 20); +let p2 = new Point(25); //y will be 0 + +// Inheritance +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Explicit call to the super class constructor is mandatory + } + + // Overwrite + dist() { + let d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modules, "." can be used as separator for sub modules +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +let s1 = new Geometry.Square(5); + +// Local alias for referencing a module +import G = Geometry; + +let s2 = new G.Square(10); + +// Generics +// Classes +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Pair { + item1: T; + item2: T; +} + +// And functions +let pairToTuple = function (p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +let tuple = pairToTuple({ item1: "hello", item2: "world" }); + +// Including references to a definition file: +/// + +// Template Strings (strings that use backticks) +// String Interpolation with Template Strings +let name = 'Tyrone'; +let greeting = `Hi ${name}, how are you?` +// Multiline Strings with Template Strings +let multiline = `This is an example +of a multiline string`; + +// READONLY: New Feature in TypeScript 3.1 +interface Person { + readonly name: string; + readonly age: number; +} + +var p1: Person = { name: "Tyrone", age: 42 }; +p1.age = 25; // Error, p1.x is read-only + +var p2 = { name: "John", age: 60 }; +var p3: Person = p2; // Ok, read-only alias for p2 +p3.x = 35; // Error, p3.x is read-only +p2.x = 45; // Ok, but also changes p3.x because of aliasing + +class Car { + readonly make: string; + readonly model: string; + readonly year = 2018; + + constructor() { + this.make = "Unknown Make"; // Assignment permitted in constructor + this.model = "Unknown Model"; // Assignment permitted in constructor + } +} + +let numbers: Array = [0, 1, 2, 3, 4]; +let moreNumbers: ReadonlyArray = numbers; +moreNumbers[5] = 5; // Error, elements are read-only +moreNumbers.push(5); // Error, no push method (because it mutates array) +moreNumbers.length = 3; // Error, length is read-only +numbers = moreNumbers; // Error, mutating methods are missing +``` + +## อ่านเพิ่มเติมที่ + * [TypeScript Official website] (http://www.typescriptlang.org/) + * [TypeScript language specifications] (https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From e616d439632bf17e76685de8298247ee58b01067 Mon Sep 17 00:00:00 2001 From: Worajedt Sitthidumrong Date: Tue, 13 Aug 2019 14:44:19 +0700 Subject: translate to Thai up to interface topic --- th-th/typescript.th.html.markdown | 42 ++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/th-th/typescript.th.html.markdown b/th-th/typescript.th.html.markdown index 94305c14..ce1d3bb8 100644 --- a/th-th/typescript.th.html.markdown +++ b/th-th/typescript.th.html.markdown @@ -15,63 +15,59 @@ TypeScript เป็นภาษาที่มีเป้าหมายเพ [Playground] (http://www.typescriptlang.org/Playground) ซึ่งคุณจะเขียนโค้ดพร้อม autocomplete และเห็นเลยว่ามันจะแปลงมาเป็นผลลัพธ์แบบ JavaScript อย่างไร ```ts -// There are 3 basic types in TypeScript +// TypeScript มี data type พื้นฐาน 3 แบบ let isDone: boolean = false; let lines: number = 42; let name: string = "Anders"; -// But you can omit the type annotation if the variables are derived -// from explicit literals +// แต่เราก็สามารถละการบอกชนิดได้ โดยชนิดตัวแปรก็จะปรับชนิดของเขาจากข้อมูลที่กำหนดให้โดยตรง let isDone = false; let lines = 42; let name = "Anders"; -// When it's impossible to know, there is the "Any" type +// ถ้าไม่รู้ ก็กำหนดเป็นชนิด "Any" ได้ let notSure: any = 4; notSure = "maybe a string instead"; -notSure = false; // okay, definitely a boolean +notSure = false; // โอเค ตอนนี้เป็น Boolean แน่ ๆ -// Use const keyword for constants +// ใช้ const สำหรับสร้าง ค่าคงที่ const numLivesForCat = 9; numLivesForCat = 1; // Error -// For collections, there are typed arrays and generic arrays +// สำหรับ collections มี typed arrays และ generic arrays +// ก็คือ อะเรย์บอกชนิด และ อะเรย์เจเนอริก ตามลำดับ let list: number[] = [1, 2, 3]; -// Alternatively, using the generic array type +// ในอีกทางหนึ่ง สร้างเป็นอะเรย์ชนิด generic array let list: Array = [1, 2, 3]; -// For enumerations: +// และสำหรับ enumerations: enum Color { Red, Green, Blue }; let c: Color = Color.Green; -// Lastly, "void" is used in the special case of a function returning nothing +// สุดท้าย, "void" ใช้เมื่อเป็นกรณีพิเศษที่ฟังก์ชันไม่ส่งค่ากลับ function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -// Functions are first class citizens, support the lambda "fat arrow" syntax and -// use type inference +// ฟังก์ชั่น (Functions) เป็นสิ่งที่มีความสำคัญมาเป็นอันดับหนึ่ง รองรับการใช้ "fat arrow" ในการสร้าง lambda function และ type inference -// The following are equivalent, the same signature will be inferred by the -// compiler, and same JavaScript will be emitted +// สไตล์ต่อไปนี้มีค่าเท่ากันกับบรรทัดที่ยกตัวอย่างด้านล่าง เพราะคอมไพเลอร์จะมองเหมือนกัน และได้ JavaScript แบบเดียวกัน let f1 = function (i: number): number { return i * i; } -// Return type inferred +// อนุมานชนิดที่ส่งกลับ หรือ type inferred let f2 = function (i: number) { return i * i; } -// "Fat arrow" syntax +// เขียนแบบ "Fat arrow" แต่บอกชนิดส่งกลับ let f3 = (i: number): number => { return i * i; } -// "Fat arrow" syntax with return type inferred +// เขียนแบบ "Fat arrow" แต่อนุมานชนิดส่งกลับ let f4 = (i: number) => { return i * i; } -// "Fat arrow" syntax with return type inferred, braceless means no return -// keyword needed +// เขียนแบบ "Fat arrow" อนุมานชนิดส่งกลับ พร้อมกับไม่มีวงเล็บ แปลว่าไม่ต้องมี return keyword ด้วย let f5 = (i: number) => i * i; -// Interfaces are structural, anything that has the properties is compliant with -// the interface +// Interfaces นั้นเป็นเหมือนเราออกแบบโครงสร้าง คุณสมบัติต่าง ๆ ตอนเอาไปใช้ จะต้องเป็นไปตาม interface นั้น ๆ interface Person { name: string; - // Optional properties, marked with a "?" + // Optional properties กำหนดด้วย "?" age?: number; - // And of course functions + // และมี function พร้อมชนิดได้ใน interface move(): void; } -- cgit v1.2.3 From 121627522d97be99958b9c18e77a47e77cf12a76 Mon Sep 17 00:00:00 2001 From: Worajedt Sitthidumrong Date: Tue, 13 Aug 2019 16:02:01 +0700 Subject: finish translate TypeScript to Thai language --- th-th/typescript.th.html.markdown | 84 +++++++++++++++++++-------------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/th-th/typescript.th.html.markdown b/th-th/typescript.th.html.markdown index ce1d3bb8..29f9b16e 100644 --- a/th-th/typescript.th.html.markdown +++ b/th-th/typescript.th.html.markdown @@ -9,10 +9,10 @@ lang: th-th TypeScript เป็นภาษาที่มีเป้าหมายเพื่อทำให้การพัฒนาซอฟต์แวร์ขนาดใหญ่ด้วย JavaScript ทำได้ง่ายขึ้น โดยที่ TypeScript ได้เพิ่มแนวคิดที่พบทั่วไป อาทิ classes, modules, interfaces, generics และ static typing (ไม่บังคับ) เข้าไปในภาษา JavaScript ดังนั้น TypeScript ก็เลยเป็น Super Set ของ JavaScript อีกที โค้ด JavaScript ทุกส่วน ก็คือโค้ดที่ทำงานได้ถูกต้องใน TypeScript ทำให้เราเพิ่ม TypeScript เข้าไปใช้ในโปรเจคการพัฒนาของเราได้ไม่ยากเลย เพราะ TypeScript คอมไพล์ผลลัพธ์ออกมาเป็น JavaScript ในท้ายสุดอยู่ดี -บทความนี้จะเน้นเฉพาะ syntax ส่วนขยายของ TypeScript ซึ่งจะไม่รวมกับที่มีใน [JavaScript](/docs/javascript). +บทความนี้จะเน้นเฉพาะ syntax ส่วนขยายของ TypeScript ซึ่งจะไม่รวมกับที่มีใน [JavaScript](/docs/javascript) การทดสอบเขียน TypeScript เริ่มได้ง่าย ๆ โดยเข้าไปที่ -[Playground] (http://www.typescriptlang.org/Playground) ซึ่งคุณจะเขียนโค้ดพร้อม autocomplete และเห็นเลยว่ามันจะแปลงมาเป็นผลลัพธ์แบบ JavaScript อย่างไร +[Playground](http://www.typescriptlang.org/Playground) ซึ่งคุณจะเขียนโค้ดพร้อม autocomplete และเห็นเลยว่ามันจะแปลงมาเป็นผลลัพธ์แบบ JavaScript อย่างไร ```ts // TypeScript มี data type พื้นฐาน 3 แบบ @@ -62,7 +62,7 @@ let f4 = (i: number) => { return i * i; } // เขียนแบบ "Fat arrow" อนุมานชนิดส่งกลับ พร้อมกับไม่มีวงเล็บ แปลว่าไม่ต้องมี return keyword ด้วย let f5 = (i: number) => i * i; -// Interfaces นั้นเป็นเหมือนเราออกแบบโครงสร้าง คุณสมบัติต่าง ๆ ตอนเอาไปใช้ จะต้องเป็นไปตาม interface นั้น ๆ +// Interfaces นั้นเป็นเหมือนเราออกแบบโครงสร้าง คุณสมบัติต่าง ๆ ตอนเอาไปใช้ จะต้องเป็นไปตาม interface นั้น ๆ เหมือนกับเป็นการกำหนดสเป็คของ "ชนิดข้อมูล" interface Person { name: string; // Optional properties กำหนดด้วย "?" @@ -71,70 +71,70 @@ interface Person { move(): void; } -// Object that implements the "Person" interface -// Can be treated as a Person since it has the name and move properties +// Object นี้ implements "Person" interface ทำให้มันเป็นชนิด Person และมันก็มี property name และ function move() let p: Person = { name: "Bobby", move: () => { } }; -// Objects that have the optional property: +// Objects นี้เป็นชนิด Person ด้วย และมี optional property หรือ age?: นั่นเอง let validPerson: Person = { name: "Bobby", age: 42, move: () => { } }; -// Is not a person because age is not a number +// ไม่ใช่ Person เพราะ age: ต้องเป็น number เท่านั้น ตามข้อกำหนดใน interface Person let invalidPerson: Person = { name: "Bobby", age: true }; -// Interfaces can also describe a function type +// Interfaces ยังนำมาใช้ในลักษณะของ function ได้อีกด้วย interface SearchFunc { (source: string, subString: string): boolean; } -// Only the parameters' types are important, names are not important. +// เฉพาะชนิด parameters เท่านั้นที่สำคัญ ชื่อของมันไม่จำเป็นต้องเหมือน let mySearch: SearchFunc; mySearch = function (src: string, sub: string) { return src.search(sub) != -1; } -// Classes - members are public by default +// สมาชิกใน class จะเข้าถึงได้แบบ public เป็นค่าปริยาย class Point { // Properties + // ตั้งค่า Properties ของ class นี้ x: number; - // Constructor - the public/private keywords in this context will generate - // the boiler plate code for the property and the initialization in the - // constructor. - // In this example, "y" will be defined just like "x" is, but with less code - // Default values are also supported + // Constructor + // เราใส่ public/private keywords ตรงนี้ได้ มีผลเหมือนกันกับกำหนด x ด้านบน + // ในตัวอย่าง y มีการกำหนดเช่นเดียวกับ x แต่พิมพ์สั้นกว่า + // สังเกตว่า มีการกำหนดค่าปริยายให้ parameters ได้ด้วย constructor(x: number, public y: number = 0) { this.x = x; } // Functions - dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + dist() { return Math.sqrt(this.x*this.x + this.y*this.y); } // Static members static origin = new Point(0, 0); } -// Classes can be explicitly marked as implementing an interface. -// Any missing properties will then cause an error at compile-time. +// Classes สามารถระบุชนิด interface ที่ต้องการได้ตรง ๆ ด้วยเช่นโค้ดด้านล่าง +// แต่อะไรที่จะ implement มานั้น ถ้าไม่ได้กำหนดไว้ใน constructor ก็จะเกิดข้อผิดพลาดตอนคอมไพล์ class PointPerson implements Person { - name: string + name: string // ตรงนี้จะผิด แก้ไขโดยการไปสร้างตัวรับค่าเข้ามาผ่านทาง constructor move() {} } let p1 = new Point(10, 20); -let p2 = new Point(25); //y will be 0 +let p2 = new Point(25); //y เป็น 0 เพราะกำหนดค่าปริยายไว้ให้แล้ว -// Inheritance +// Inheritance การสืบทอดคุณสมบัติ class Point3D extends Point { constructor(x: number, y: number, public z: number = 0) { - super(x, y); // Explicit call to the super class constructor is mandatory + super(x, y); // เราจะต้องเรียกใช้ super class constructor โดยตรง } - // Overwrite + // Overwrite ฟังก์ชั่นที่มีอยู่เดิมใน Point dist() { let d = super.dist(); return Math.sqrt(d * d + this.z * this.z); } } -// Modules, "." can be used as separator for sub modules +// Modules ใช้เป็นกลุ่มของ class เราใช้ "." เป็นตัวแบ่ง sub modules +// อย่างกรณีนี้จะเป็น Module.Class เช่น Geometry.Square module Geometry { export class Square { constructor(public sideLength: number = 0) { @@ -147,7 +147,7 @@ module Geometry { let s1 = new Geometry.Square(5); -// Local alias for referencing a module +// เราทำให้เรียกใช้ง่ายขึ้นโดยการใช้ alias มาอ้างชื่อ module แบบเดียวกับบางภาษา เช่น Python import G = Geometry; let s2 = new G.Square(10); @@ -165,37 +165,37 @@ interface Pair { item2: T; } -// And functions +// และ functions let pairToTuple = function (p: Pair) { return new Tuple(p.item1, p.item2); }; let tuple = pairToTuple({ item1: "hello", item2: "world" }); -// Including references to a definition file: +// เราเรียกใช้ไฟล์ definition แบบนี้: /// -// Template Strings (strings that use backticks) -// String Interpolation with Template Strings +// Template Strings ( คือ strings ที่ใช้ backticks ครอบ — "`" ปุ่มบนซ้ายคีย์บอร์ด ) +// แทรกข้อความใน String ด้วย Template Strings let name = 'Tyrone'; let greeting = `Hi ${name}, how are you?` -// Multiline Strings with Template Strings +// Strings หลายบรรทัดก็ทำได้ใน Template Strings let multiline = `This is an example of a multiline string`; -// READONLY: New Feature in TypeScript 3.1 +// READONLY: ความสามารถใหม่ใน TypeScript 3.1 interface Person { readonly name: string; readonly age: number; } var p1: Person = { name: "Tyrone", age: 42 }; -p1.age = 25; // Error, p1.x is read-only +p1.age = 25; // Error แน่นอน เพราะ p1.x ถูกกำหนดเป็น read-only -var p2 = { name: "John", age: 60 }; -var p3: Person = p2; // Ok, read-only alias for p2 -p3.x = 35; // Error, p3.x is read-only -p2.x = 45; // Ok, but also changes p3.x because of aliasing +var p2 = { name: "John", age: 60 }; // สังเกตว่า p2 ไม่ได้กำหนดเป็น Person +var p3: Person = p2; // ทำได้ เป็น read-only alias ของ p2 และกำหนดเป็น Person +p3.x = 35; // Error p3.x ก็เป็น read-only +p2.x = 45; // Ok ทำได้แต่ก็จะเปลี่ยนค่า p3.x ด้วย เพราะ p3 เป็น alias ของ p2 class Car { readonly make: string; @@ -203,17 +203,17 @@ class Car { readonly year = 2018; constructor() { - this.make = "Unknown Make"; // Assignment permitted in constructor - this.model = "Unknown Model"; // Assignment permitted in constructor + this.make = "Unknown Make"; // อนุญาตให้กำหนดค่าได้ใน constructor แม้ว่าจะ read-only + this.model = "Unknown Model"; // อนุญาตให้กำหนดค่าได้ใน constructor แม้ว่าจะ read-only } } let numbers: Array = [0, 1, 2, 3, 4]; let moreNumbers: ReadonlyArray = numbers; -moreNumbers[5] = 5; // Error, elements are read-only -moreNumbers.push(5); // Error, no push method (because it mutates array) -moreNumbers.length = 3; // Error, length is read-only -numbers = moreNumbers; // Error, mutating methods are missing +moreNumbers[5] = 5; // Error, สมาชิกอะเรย์เป็น read-only แปลว่า ห้ามแก้ไข +moreNumbers.push(5); // Error, push method ใช้ไม่ได้ เพราะมันจะไปแก้ไข read-only array +moreNumbers.length = 3; // Error, เพราะ length ก็ต้อง read-only +numbers = moreNumbers; // Error, method ที่ทำให้อะเรย์เปลี่ยนได้จะไม่อนุญาต ``` ## อ่านเพิ่มเติมที่ -- cgit v1.2.3 From 55ec5c541476ec9faf51226f5e901a766fa88776 Mon Sep 17 00:00:00 2001 From: Fasermaler <41094233+Fasermaler@users.noreply.github.com> Date: Tue, 13 Aug 2019 17:22:11 +0800 Subject: [mercurial/en] Fix mercurial workflow link --- mercurial.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mercurial.html.markdown b/mercurial.html.markdown index 330beb35..98658f83 100644 --- a/mercurial.html.markdown +++ b/mercurial.html.markdown @@ -350,6 +350,6 @@ $ hg remove *.txt ## Further information -* [Learning Mercurial in Workflows](https://www.mercurial-scm.org/guid) +* [Learning Mercurial in Workflows](https://www.mercurial-scm.org/guide) * [Mercurial Quick Start](https://www.mercurial-scm.org/wiki/QuickStart) -* [Mercurial: The Definitive Guide by Bryan O'Sullivan](http://hgbook.red-bean.com/) \ No newline at end of file +* [Mercurial: The Definitive Guide by Bryan O'Sullivan](http://hgbook.red-bean.com/) -- cgit v1.2.3 From 7e06e77a44cba2695157ba1edaeb7c24561d0def Mon Sep 17 00:00:00 2001 From: Worajedt Sitthidumrong Date: Tue, 13 Aug 2019 16:22:32 +0700 Subject: additional translation for Iterators, Generators --- th-th/typescript.th.html.markdown | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/th-th/typescript.th.html.markdown b/th-th/typescript.th.html.markdown index 29f9b16e..88b0fc0b 100644 --- a/th-th/typescript.th.html.markdown +++ b/th-th/typescript.th.html.markdown @@ -214,6 +214,41 @@ moreNumbers[5] = 5; // Error, สมาชิกอะเรย์เป็ moreNumbers.push(5); // Error, push method ใช้ไม่ได้ เพราะมันจะไปแก้ไข read-only array moreNumbers.length = 3; // Error, เพราะ length ก็ต้อง read-only numbers = moreNumbers; // Error, method ที่ทำให้อะเรย์เปลี่ยนได้จะไม่อนุญาต + +// Tagged Union Types สำหรับโมเดลสเตท ที่อาจจะมีได้หลายๆ สเตท +type State = + | { type: "loading" } + | { type: "success", value: number } + | { type: "error", message: string }; + +ประกาศ const state: State; +if (state.type === "success") { + console.log(state.value); +} else if (state.type === "error") { + console.error(state.message); +} + +// Iterators และ Generators + +// ประโยคแบบ for..of +// การทำซ้ำกับ ลิสต์ของค่าในออปเจ็คต์ +let arrayOfAnyType = [1, "string", false]; +for (const val of arrayOfAnyType) { + console.log(val); // 1, "string", false +} + +let list = [4, 5, 6]; +for (const i of list) { + console.log(i); // 4, 5, 6 +} + +// ประโยคแบบ for..in +// การทำซ้ำกับ ลิสต์ของคีย์ในออปเจ็คต์ +for (const i in list) { + console.log(i); // 0, 1, 2 +} + + ``` ## อ่านเพิ่มเติมที่ -- cgit v1.2.3 From 0b5245e2d83453f23e13195ea164a35603c4855a Mon Sep 17 00:00:00 2001 From: Ben Landry Date: Tue, 13 Aug 2019 06:35:13 -0400 Subject: [python3/en] Added enumerate function (#3601) * Added enumerate function * adjusted spacing --- python3.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index ecdbd932..ef78ce37 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -462,8 +462,19 @@ prints: """ for i in range(4, 8, 2): print(i) + +""" +To loop over a list, and retrieve both the index and the value of each item in the list +prints: + 0 dog + 1 cat + 2 mouse """ +list = ["dog", "cat", "mouse"] +for i, value in enumerate(list): + print(i, value) +""" While loops go until a condition is no longer met. prints: 0 -- cgit v1.2.3 From 65ab14ca41d58670e73874ea31c8574637d8e749 Mon Sep 17 00:00:00 2001 From: Worajedt Sitthidumrong Date: Wed, 14 Aug 2019 02:34:53 +0700 Subject: fix file name per request 'learntypescript-th.ts' --- th-th/typescript.th.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/th-th/typescript.th.html.markdown b/th-th/typescript.th.html.markdown index 88b0fc0b..fc2a823b 100644 --- a/th-th/typescript.th.html.markdown +++ b/th-th/typescript.th.html.markdown @@ -3,7 +3,7 @@ language: TypeScript contributors: - ["Philippe Vlérick", "https://github.com/pvlerick"] - ["Worajedt Sitthidumrong", "https://bitbucket.org/wrj"] -filename: learntypescript.ts +filename: learntypescript-th.ts lang: th-th --- -- cgit v1.2.3 From 91f1f4f936f13e7363d832771acb6f5b2cd14879 Mon Sep 17 00:00:00 2001 From: Seth Corker Date: Tue, 13 Aug 2019 22:55:18 +0100 Subject: Apply some spelling and ordering suggested by @amartincolby --- reason.html.markdown | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/reason.html.markdown b/reason.html.markdown index 45633cf5..62d809cf 100644 --- a/reason.html.markdown +++ b/reason.html.markdown @@ -2,13 +2,13 @@ language: reason filename: reason.re contributors: - - ["Seth Corker", "https://sethcorker.com"] + - ["Seth Corker", "https://sethcorker.com"] --- Reason is a syntax over OCaml that is easier to get started for programmers who are familiar with C-style syntax like JavaScript. BuckleScript is part of the toolchain which compiles Reason to JavaScript so you can write statically typed code for anywhere that JavaScript runs. ```javascript -/* Comments start with slash-star, and end with slash-star */ +/* Comments start with slash-star, and end with star-slash */ /*---------------------------------------------- * Variable and function declaration @@ -18,7 +18,7 @@ Reason is a syntax over OCaml that is easier to get started for programmers who */ let x = 5; -/* - Notice we didn't add a type, Reason will infer it's an int */ +/* - Notice we didn't add a type, Reason will infer x is an int */ /* A function like this, take two arguments and add them together */ let add = (a, b) => a + b; @@ -27,7 +27,7 @@ let add = (a, b) => a + b; /*---------------------------------------------- * Type annotation *---------------------------------------------- - * Types don't need tp be explicitly annotated in most cases but when you need + * Types don't need to be explicitly annotated in most cases but when you need * to, you can add the type after the name */ @@ -85,7 +85,7 @@ let lastLetter = 'z'; /* > Boolean */ -/* A boolean be either true or false */ +/* A boolean can be either true or false */ let isLearning = true; true && false; /* - : bool = false; Logical and */ @@ -445,11 +445,11 @@ switch (driveToTown(evan)) { }; /* Alternatively, a try block can be used */ +/* - With Reason exceptions can be avoided with optionals and are seldom used */ let messageToEvan = try (driveToTown(evan)) { | Under_Age => evan.firstName ++ " is too young to drive!" }; -/* - With Reason exceptions can be avoided with optionals and are seldom used */ /*---------------------------------------------- * Object @@ -488,7 +488,7 @@ house#temperature; /* - : float = 22. */ /*---------------------------------------------- * Module *---------------------------------------------- - * Modules are used to organize your code and provide namespacing, + * Modules are used to organize your code and provide namespacing. * Each file is a module by default */ @@ -537,6 +537,7 @@ module SpecializedStaff = { ``` ## Further Reading + - [Official Reason Docs](https://reasonml.github.io/docs/en/what-and-why) - [Official BuckleScript Docs](https://bucklescript.github.io/docs/en/what-why) - [Try Reason](https://reasonml.github.io/en/try) -- cgit v1.2.3 From ed63ebcd618561d56554ef208cca1067511e40c1 Mon Sep 17 00:00:00 2001 From: Julian Fondren Date: Fri, 16 Aug 2019 14:10:39 -0500 Subject: use Prolog syntax highlighting for Mercury code --- mercury.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mercury.html.markdown b/mercury.html.markdown index 76c7d1ca..f749bac4 100644 --- a/mercury.html.markdown +++ b/mercury.html.markdown @@ -7,7 +7,7 @@ contributors: Mercury is a strict, pure functional/logic programming language, with influences from Prolog, ML, and Haskell. -```mercury +```prolog % Percent sign starts a one-line comment. % foo(Bar, Baz) @@ -97,7 +97,7 @@ voter(P) :- Complete runnable example. File in 'types.m'; compile with 'mmc --make types'. -```mercury +```prolog :- module types. :- interface. :- import_module io. % required for io.io types in... -- cgit v1.2.3 From 75d207ce173107e71aae43acde4721e48b1f6262 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Metin=20Yal=C3=A7=C4=B1nkaya?= Date: Sat, 17 Aug 2019 16:06:03 +0300 Subject: Sql file added for Turkish Sql file created and added for Turkish language --- tr-tr/sql-tr.html.markdown | 125 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 tr-tr/sql-tr.html.markdown diff --git a/tr-tr/sql-tr.html.markdown b/tr-tr/sql-tr.html.markdown new file mode 100644 index 00000000..54007d32 --- /dev/null +++ b/tr-tr/sql-tr.html.markdown @@ -0,0 +1,125 @@ +--- +language: SQL +contributors: + - ["Metin Yalçınkaya", "https://github.com/mtnylnky"] +lang: tr-tr +filename: learnsql-tr.sql +--- + + +```sql +-- Yorumlar iki tire ile başlar + +-- KISITLAR +Not null -- Bir kolon asla boş olamaz +default -- Boş olan yerlere varsayılan bir değer atar +unique -- Bir kolondaki tüm değerlerin farklı olması kısıtlaması +primary key -- Bir tablodaki her veri için kimlik bilgisi niteliğindedir +check -- Bir kolondaki değerlerin belli bir kısıtlamayı sağlamasını sağlar + +-- Tablo oluşturulur +CREATE TABLE tablo1 (); + +-- Tabloyu içerisinde kolonlar ile oluşturma +CREATE TABLE tablo1(id INTEGER PRIMARY KEY NOT NULL UNIQUE, ad TEXT, soyad TEXT, yas INTEGER); + +-- TABLO varlığını kontrol eder +.table + +-- Veri tabanında olan bütün tabloları görüntüler. +.schema + +-- Satır ekle +INSERT INTO tablo1 ( ad, soyad) VALUES ("Deger1","Deger2"); + +-- Veritabanında tablo üzerindeki verileri görüntüle +-- Sadece 'ad' gibi sınırlı bir veri için +SELECT ad FROM tablo1; +-- Bütün veriler için +SELECT * FROM tablo1; + +-- Veri güncelleme +UPDATE tablo1 SET ad = "deger1-2"; WHERE name = "Deger1"; + +-- Satır sil +DELETE FROM tablo1 WHERE id = 1; +DELETE FROM tablo1 WHERE ad = "Deger1" OR ad = "Deger2"; + +-- Tabloya sonradan kolon ekleme +ALTER TABLE tablo1 ADD COLUMN email TEXT; + +-- Tablodaki kolon adı değiştirme +EXEC sp_rename ' tablo1.[ad]', Ad, 'COLUMN'; + +-- Tablo adı değiştirme +ALTER TABLE table1 RENAME TO Table1; + +-- Tabloyu silme +DROP TABLE Table1; + +-- BİR TABLOYU BAŞKA TABLO KULLANARAK DOLDURMAK +INSERT INTO Tablo2 SELECT id,ad, soyad, email from Tablo1; + +-- LIKE KOMUTU +-- Belirli bir kritere göre arama yaparken kullanılır +-- Adı 'A' ile başlayan veriler +SELECT * FROM tablo1 WHERE adi LIKE "A%"; +-- İçinde 'A' olan veriler +SELECT * FROM tablo1 WHERE adi LIKE "%A%"; + +-- LIMIT KOMUTU +-- Gösterilen satır sayısını sınırlamak için +SELECT * FROM Tablo1 LIMIT 6; +-- Gösterilen satırları belirli bir noktadan başlamak üzere sınırlamak için +SELECT * FROM Tablo1 LIMIT 6 OFFSET 3; + +-- ORDER BY KOMUTU +-- Herhangi bir kolona göre gösterilen değerleri azalan veya artan şekilde sıralamak için +SELECT kolon FROM tablo1 WHERE yas ORDER BY column1, column2, .. columnN] [ASC | DESC]; +SELECT * FROM Tablo1 ORDER BY yas ASC +SELECT * FROM Tablo1 ORDER BY yas DESC + +-- DISTINCT ANAHTAR SÖZCÜĞÜ +-- Bu anahtar sözcükle sadece farklı değerler gösterilir. +SELECT DISTINCT yas FROM tablo1; + +-- JOIN KOMUTU +-- CROSS JOIN +-- Cross join bir tablodaki her satırı ikinci tablodaki bir satır ile eşleştirmek için kulanılır. +-- Eğer birinci tabloda x satır ikinci tabloda y satır varsa sonuçta x*y satır olur. +SELECT ... FROM table1 CROSS JOIN table2 … +SELECT ad, yas FROM Tablo1 CROSS JOIN Tablo2; + +-- INNER JOIN +-- Inner join iki tablodaki ortak kolon değerlerini kullanarak bir sonuç üretir. +SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression … +SELECT ad, yas FROM Tablo1 INNER JOIN Tablo2 ON Tablo1.ad = Tablo2.soyad; + +-- OUTER JOIN +-- Outer join iki tablodaki ortak kolon değerlerinin dışında kalanları kullanarak bir sonuç üretir. +SELECT isci_num, isim, dept FROM Tablo1 LEFT OUTER JOIN Tablo2 ON Tablo1.id = Tablo2.isci_num; + +-- ÇEKİRDEK FONKSİYONLAR +COUNT -- Sayma +AVG -- Ortalama +ABS -- Mutlak değer +SUM -- Toplam +RANDOM -- Rastgele +ROUND -- Yuvarlama +MAX -- Maksimim +MIN -- Minimum +UPPER -- Büyük Harf +LOWER -- Küçük Harf +LENGTH -- Uzunluk +CURRENT_TIMESTAMP -- Zaman + +SELECT max(yas) FROM Table1; +SELECT min(yas) FROM Table1; +SELECT avg(yas) FROM Table1; +SELECT * From Table1 WHERE yas ==18; +SELECT sum(yas) FROM Table1; +SELECT random() AS Random; +SELECT upper(ad) FROM Table1; +SELECT lower(ad) FROM Table1; +SELECT ad, length(ad) FROM Table1; +``` \ No newline at end of file -- cgit v1.2.3 From 92d9ba9b61641760ce125cb64f06d659e5089e6c Mon Sep 17 00:00:00 2001 From: SimonDei Date: Mon, 19 Aug 2019 14:54:31 +0200 Subject: [directx9/en, opengl/en] Add basic DirectX 9 and rename OpenGL (#3599) * Add files via upload * Rename learnopengl.html.markdown to opengl.html.markdown * Fix broken links and change category * Update opengl.html.markdown * Fixed some typos * Replace tab by spaces * Update opengl.html.markdown * Update opengl.html.markdown - More uniforms info - Handling VBO's - Better description of Functions * Update opengl.html.markdown * Added Matrix Transformation section * Update opengl.html.markdown * Update opengl.html.markdown * Added geometry shader section * Update opengl.html.markdown Fix newline issues * Fix typo * Create directx9.html.markdown * Update directx9.html.markdown * Update directx9.html.markdown * Update directx9.html.markdown * Update directx9.html.markdown * Vertex declarations and shaders * Update directx9.html.markdown * Basic texturing * Update directx9.html.markdown - Fix site rendering issues with newlines as required - Fix YAML frontmatter issues --- directx9.html.markdown | 827 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 827 insertions(+) create mode 100644 directx9.html.markdown diff --git a/directx9.html.markdown b/directx9.html.markdown new file mode 100644 index 00000000..b51f418d --- /dev/null +++ b/directx9.html.markdown @@ -0,0 +1,827 @@ +--- +category: tool +tool: DirectX 9 +filename: learndirectx9.cpp +contributors: + - ["Simon Deitermann", "s.f.deitermann@t-online.de"] +--- + +**Microsoft DirectX** is a collection of application programming interfaces (APIs) for handling tasks related to +multimedia, especially game programming and video, on Microsoft platforms. Originally, the names of these APIs +all began with Direct, such as Direct3D, DirectDraw, DirectMusic, DirectPlay, DirectSound, and so forth. [...] +Direct3D (the 3D graphics API within DirectX) is widely used in the development of video games for Microsoft +Windows and the Xbox line of consoles.[1] + +In this tutorial we will be focusing on DirectX 9, which is not as low-level as it's sucessors, which are aimed at programmers very familiar with how graphics hardware works. It makes a great starting point for learning Direct3D. In this tutorial I will be using the Win32-API for window handling and the DirectX 2010 SDK. + +## Window creation + +```cpp +#include + +bool _running{ false }; + +LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { + // Handle incoming message. + switch (msg) { + // Set running to false if the user tries to close the window. + case WM_DESTROY: + _running = false; + PostQuitMessage(0); + break; + } + // Return the handled event. + return DefWindowProc(hWnd, msg, wParam, lParam); +} + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, + LPSTR lpCmdLine, int nCmdShow) { + // Set window properties we want to use. + WNDCLASSEX wndEx{ }; + wndEx.cbSize = sizeof(WNDCLASSEX); // structure size + wndEx.style = CS_VREDRAW | CS_HREDRAW; // class styles + wndEx.lpfnWndProc = WndProc; // window procedure + wndEx.cbClsExtra = 0; // extra memory (struct) + wndEx.cbWndExtra = 0; // extra memory (window) + wndEx.hInstance = hInstance; // module instance + wndEx.hIcon = LoadIcon(nullptr, IDI_APPLICATION); // icon + wndEx.hCursor = LoadCursor(nullptr, IDC_ARROW); // cursor + wndEx.hbrBackground = (HBRUSH) COLOR_WINDOW; // background color + wndEx.lpszMenuName = nullptr; // menu name + wndEx.lpszClassName = "DirectXClass"; // register class name + wndEx.hIconSm = nullptr; // small icon (taskbar) + // Register created class for window creation. + RegisterClassEx(&wndEx); + // Create a new window handle. + HWND hWnd{ nullptr }; + // Create a new window handle using the registered class. + hWnd = CreateWindow("DirectXClass", // registered class + "directx window", // window title + WS_OVERLAPPEDWINDOW, // window style + 50, 50, // x, y (position) + 1024, 768, // width, height (size) + nullptr, // parent window + nullptr, // menu + hInstance, // module instance + nullptr); // struct for infos + // Check if a window handle has been created. + if (!hWnd) + return -1; + // Show and update the new window. + ShowWindow(hWnd, nCmdShow); + UpdateWindow(hWnd); + // Start the game loop and send incoming messages to the window procedure. + _running = true; + MSG msg{ }; + while (_running) { + while (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + return 0; +} +``` + +This should create a window, that can the moved, resized and closed. + +## Direct3D initialization + +```cpp +// Includes DirectX 9 structures and functions. +// Remember to link "d3d9.lib" and "d3dx9.lib". +// For "d3dx9.lib" the DirectX SDK (June 2010) is needed. +// Don't forget to set your subsystem to Windows. +#include +#include +// Includes the ComPtr, a smart pointer automatically releasing COM objects. +#include +using namespace Microsoft::WRL; +// Next we define some Direct3D9 interface structs we need. +ComPtr _d3d{ }; +ComPtr _device{ }; +``` + +With all interfaces declared we can now initialize Direct3D. + +```cpp +bool InitD3D(HWND hWnd) { + // Store the size of the window rectangle. + RECT clientRect{ }; + GetClientRect(hWnd, &clientRect); + // Initialize Direct3D + _d3d = Direct3DCreate9(D3D_SDK_VERSION); + // Get the display mode which format will be the window format. + D3DDISPLAYMODE displayMode{ }; + _d3d->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, // use default graphics card + &displayMode); // display mode pointer + // Next we have to set some presentation parameters. + D3DPRESENT_PARAMETERS pp{ }; + pp.BackBufferWidth = clientRect.right; // width is window width + pp.BackBufferHeight = clientRect.bottom; // height is window height + pp.BackBufferFormat = displayMode.Format; // use adapter format + pp.BackBufferCount = 1; // 1 back buffer (default) + pp.SwapEffect = D3DSWAPEFFECT_DISCARD; // discard after presentation + pp.hDeviceWindow = hWnd; // associated window handle + pp.Windowed = true; // display in window mode + pp.Flags = 0; // no special flags + // Variable to store results of methods to check if everything succeded. + HRESULT result{ }; + result = _d3d->CreateDevice(D3DADAPTER_DEFAULT, // use default graphics card + D3DDEVTYPE_HAL, // use hardware acceleration + hWnd, // the window handle + D3DCREATE_HARDWARE_VERTEXPROCESSING, + // vertices are processed by the hardware + &pp, // the present parameters + &_device); // struct to store the device + // Return false if the device creation failed. + // It is helpful to set breakpoints at the return line. + if (FAILED(result)) + return false; + // Create a viewport which hold information about which region to draw to. + D3DVIEWPORT9 viewport{ }; + viewport.X = 0; // start at top left corner + viewport.Y = 0; // .. + viewport.Width = clientRect.right; // use the entire window + viewport.Height = clientRect.bottom; // .. + viewport.MinZ = 0.0f; // minimun view distance + viewport.MaxZ = 100.0f; // maximum view distance + // Apply the created viewport. + result = _device->SetViewport(&viewport); + // Always check if something failed. + if (FAILED(result)) + return false; + // Everything was successful, return true. + return true; +} +// ... +// Back in our WinMain function we call our initialization function. +// ... +// Check if Direct3D initialization succeded, else exit the application. +if (!InitD3D(hWnd)) + return -1; + +MSG msg{ }; +while (_running) { + while (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + // Clear to render target to a specified color. + _device->Clear(0, // number of rects to clear + nullptr, // indicates to clear the entire window + D3DCLEAR_TARGET, // clear all render targets + D3DXCOLOR{ 1.0f, 0.0f, 0.0f, 1.0f }, // color (red) + 0.0f, // depth buffer clear value + 0); // stencil buffer clear value + // ... + // Drawing operations go here. + // ... + // Flip the front- and backbuffer. + _device->Present(nullptr, // no source rectangle + nullptr, // no destination rectangle + nullptr, // don't change the current window handle + nullptr); // pretty much always nullptr +} +// ... +``` + +Now the window should be displayed in a bright red color. + +## Vertex Buffer + +Let's create a vertex buffer to store the vertices for our triangle + +```cpp +// At the top of the file we need to add a include. +#include +// First we declare a new ComPtr holding a vertex buffer. +ComPtr _vertexBuffer{ }; +// Lets define a funtion to calculate the byte size of a std::vector +template +unsigned int GetByteSize(const std::vector& vec) { + return sizeof(vec[0]) * vec.size(); +} +// Define "flexible vertex format" describing the content of our vertex struct. +// Use the defined color as diffuse color. +const unsigned long VertexStructFVF = D3DFVF_XYZ | D3DFVF_DIFFUSE; +// Define a struct representing the vertex data the buffer will hold. +struct VStruct { + float x, y, z; // store the 3D position + D3DCOLOR color; // store a color +}; +// Declare a new function to create a vertex buffer. +IDirect3DVertexBuffer9* CreateBuffer(const std::vector& vertices) { + // Declare the buffer to be returned. + IDirect3DVertexBuffer9* buffer{ }; + HRESULT result{ }; + result = _device->CreateVertexBuffer( + GetByteSize(vertices), // vector size in bytes + 0, // data usage + VertexStructFVF, // FVF of the struct + D3DPOOL_DEFAULT, // use default pool for the buffer + &buffer, // receiving buffer + nullptr); // special shared handle + // Check if buffer was created successfully. + if (FAILED(result)) + return nullptr; + // Create a data pointer for copying the vertex data + void* data{ }; + // Lock the buffer to get a buffer for data storage. + result = buffer->Lock(0, // byte offset + GetByteSize(vertices), // size to lock + &data, // receiving data pointer + 0); // special lock flags + // Check if buffer was locked successfully. + if (FAILED(result)) + return nullptr; + // Copy the vertex data using C standard libraries memcpy. + memcpy(data, vertices.data(), GetByteSize(vertices)); + buffer->Unlock(); + // Set the FVF Direct3D uses for rendering. + _device->SetFVF(VertexStructFVF); + // If everything was successful return the filled vertex buffer. + return buffer; +} +``` + +In our **WinMain** we can now call the new function after the Direct3D initialization. + +```cpp +// ... +if (!InitD3D(hWnd)) + return -1; +// Define the vertices we need to draw a triangle. +// Values are declared in a clockwise direction else Direct3D would cull them. +// If you want to diable culling just call: +// _device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); +std::vector vertices { + // Bottom left + VStruct{ -1.0f, -1.0f, 1.0f, D3DXCOLOR{ 1.0f, 0.0f, 0.0f, 1.0f } }, + // Top left + VStruct{ -1.0f, 1.0f, 1.0f, D3DXCOLOR{ 0.0f, 1.0f, 0.0f, 1.0f } }, + // Top right + VStruct{ 1.0f, 1.0f, 1.0f, D3DXCOLOR{ 0.0f, 0.0f, 1.0f, 1.0f } } +}; +// Try to create the vertex buffer else exit the application. +if (!(_vertexBuffer = CreateBuffer(vertices))) + return -1; +// ... +``` + +## Transformations + +Before we can use the vertex buffer to draw our primitives, we first need to set up the matrices. + +```cpp +// Lets create a new funtions for the matrix transformations. +bool SetupTransform() { + // Create a view matrix that transforms world space to + // view space. + D3DXMATRIX view{ }; + // Use a left-handed coordinate system. + D3DXMatrixLookAtLH( + &view, // receiving matrix + &D3DXVECTOR3{ 0.0f, 0.0f, -20.0f }, // "camera" position + &D3DXVECTOR3{ 0.0f, 0.0f, 0.0f }, // position where to look at + &D3DXVECTOR3{ 0.0f, 1.0f, 0.0f }); // positive y-axis is up + HRESULT result{ }; + result = _device->SetTransform(D3DTS_VIEW, &view); // apply the view matrix + if (FAILED(result)) + return false; + // Create a projection matrix that defines the view frustrum. + // It transforms the view space to projection space. + D3DXMATRIX projection{ }; + // Create a perspective projection using a left-handed coordinate system. + D3DXMatrixPerspectiveFovLH( + &projection, // receiving matrix + D3DXToRadian(60.0f), // field of view in radians + 1024.0f / 768.0f, // aspect ratio (width / height) + 0.0f, // minimum view distance + 100.0f); // maximum view distance + result = _device->SetTransform(D3DTS_PROJECTION, &projection); + if (FAILED(result)) + return false; + // Disable lighting for now so we can see what we want to render. + result = _device->SetRenderState(D3DRS_LIGHTING, false); + // View and projection matrix are successfully applied, return true. + return true; +} +// ... +// Back in the WinMain function we can now call the transformation function. +// ... +if (!(_vertexBuffer = CreateVertexBuffer(vertices))) + return -1; +// Call the transformation setup function. +if (!SetupTransform()) + return -1; +// ... +``` + +## Rendering + +Now that everything is setup we can start drawing our first 2D triangle in 3D space. + +```cpp +// ... +if (!SetupTransform()) + return -1; +// First we have to bind our vertex buffer to the data stream. +HRESULT result{ }; +result = _device->SetStreamSource(0, // use the default stream + _vertexBuffer.Get(), // pass the vertex buffer + 0, // no offset + sizeof(VStruct)); // size of vertex struct +if (FAILED(result)) + return -1; + +// Create a world transformation matrix and set it to an identity matrix. +D3DXMATRIX world{ }; +D3DXMatrixIdentity(&world); +// Create a scalation matrix scaling our primitve by 10 in the x, +// 10 in the y and keeping the z direction. +D3DXMATRIX scaling{ }; +D3DXMatrixScaling(&scaling, // matrix to scale + 10, // x scaling + 10, // y scaling + 1); // z scaling +// Create a rotation matrix storing the current rotation of our primitive. +// We set the current rotation matrix to an identity matrix for now. +D3DXMATRIX rotation{ }; +D3DXMatrixIdentity(&rotation); +// Now we multiply the scalation and rotation matrix and store the result +// in the world matrix. +D3DXMatrixMultiply(&world, // destination matrix + &scaling, // matrix 1 + &rotation); // matrix 2 +// Apply the current world matrix. +_device->SetTransform(D3DTS_WORLD, &world); +// Disable culling so we can see the back of our primitive when it rotates. +_device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); +// The default cullmode is D3DCULL_CW. +// After we used our the rotation matrix for multiplication we can set it +// to rotate a small amount. +// D3DXToRadian() function converts degree to radians. +D3DXMatrixRotationY(&rotation, // matrix to rotate + D3DXToRadian(0.5f)); // rotation angle in radians + +MSG msg{ }; + while (_running) { + // ... + _device->Clear(0, nullptr, D3DCLEAR_TARGET, + D3DXCOLOR{ 0.0f, 0.0f, 0.0f, 1.0f }, 0.0f, 0); + // With everything setup we can call the draw function. + _device->BeginScene(); + _device->DrawPrimitive(D3DPT_TRIANGLELIST, // primitive type + 0, // start vertex + 1); // primitive count + _device->EndScene(); + + _device->Present(nullptr, nullptr, nullptr, nullptr); + // We can keep multiplying the world matrix with our rotation matrix + // to add it's rotation to the world matrix. + D3DXMatrixMultiply(&world, &world, &rotation); + // Update the modified world matrix. + _device->SetTransform(D3DTS_WORLD, &world); + // ... +``` + +You should now be viewing a 10x10 units colored triangle from 20 units away, rotating around its origin.
+You can find the complete working code here: [DirectX - 1](https://pastebin.com/YkSF2rkk) + +## Indexing + +To make it easier to draw primitives sharing a lot of vertices we can use indexing, so we only have to declare the unique vertices and put the order they are called in another array. + +```cpp +// First we declare a new ComPtr for our index buffer. +ComPtr _indexBuffer{ }; +// ... +// Declare a function creating a index buffer from a std::vector +IDirect3DIndexBuffer9* CreateIBuffer(std::vector& indices) { + IDirect3DIndexBuffer9* buffer{ }; + HRESULT result{ }; + result = _device->CreateIndexBuffer( + GetByteSize(indices), // vector size in bytes + 0, // data usage + D3DFMT_INDEX32, // format is 32 bit int + D3DPOOL_DEFAULT, // default pool + &buffer, // receiving buffer + nullptr); // special shared handle + if (FAILED(result)) + return nullptr; + // Create a data pointer pointing to the buffer data. + void* data{ }; + result = buffer->Lock(0, // byte offset + GetByteSize(indices), // byte size + &data, // receiving data pointer + 0); // special lock flag + if (FAILED(result)) + return nullptr; + // Copy the index data and unlock after copying. + memcpy(data, indices.data(), GetByteSize(indices)); + buffer->Unlock(); + // Return the filled index buffer. + return buffer; +} +// ... +// In our WinMain we can now change the vertex data and create new index data. +// ... +std::vector vertices { + VStruct{ -1.0f, -1.0f, 1.0f, D3DXCOLOR{ 1.0f, 0.0f, 0.0f, 1.0f } }, + VStruct{ -1.0f, 1.0f, 1.0f, D3DXCOLOR{ 0.0f, 1.0f, 0.0f, 1.0f } }, + VStruct{ 1.0f, 1.0f, 1.0f, D3DXCOLOR{ 0.0f, 0.0f, 1.0f, 1.0f } }, + // Add a vertex for the bottom right. + VStruct{ 1.0f, -1.0f, 1.0f, D3DXCOLOR{ 1.0f, 1.0f, 0.0f, 1.0f } } +}; +// Declare the index data, here we build a rectangle from two triangles. +std::vector indices { + 0, 1, 2, // the first triangle (b,left -> t,left -> t,right) + 0, 2, 3 // the second triangle (b,left -> t,right -> b,right) +}; +// ... +// Now we call the "CreateIBuffer" function to create a index buffer. +// ... +if (!(_indexBuffer = CreateIBuffer(indices))) + return -1; +// ... +// After binding the vertex buffer we have to bind the index buffer to +// use indexed rendering. +result = _device->SetStreamSource(0, _vertexBuffer.Get(), 0, sizeof(VStruct)); +if (FAILED(result)) + return -1; +// Bind the index data to the default data stream. +result = _device->SetIndices(_indexBuffer.Get()) +if (FAILED(result)) + return -1; +// ... +// Now we replace the "DrawPrimitive" function with an indexed version. +_device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, // primitive type + 0, // base vertex index + 0, // minimum index + indices.size(), // amount of vertices + 0, // start in index buffer + 2); // primitive count +// ... +``` + +Now you should see a colored rectangle made up of 2 triangles. If you set the primitive count in the "DrawIndexedPrimitive" method to 1 only the first triangle should be rendered and if you set the start of the index buffer to 3 and the primitive count to 1 only the second triangle should be rendered.
+You can find the complete working code here: [DirectX - 2](https://pastebin.com/yWBPWPRG) + +## Vertex declaration + +Instead of using the old "flexible vertex format" we should use vertex declarations instead, as the FVF declarations get converted to vertex declarations internally anyway. + +```cpp +// First we have to REMOVE the following lines: +const unsigned long VertexStructFVF = D3DFVF_XYZ | D3DFVF_DIFFUSE; +// and +_device->SetFVF(VertexStructFVF); +// ... +// We also have to change the vertex buffer creation FVF-flag. +result = _device->CreateVertexBuffer( + GetByteSize(vertices), + 0, + 0, // <- 0 indicates we use vertex declarations + D3DPOOL_DEFAULT, + &buffer, + nullptr); +// Next we have to declare a new ComPtr. +ComPtr _vertexDecl{ }; +// ... +result = _device->SetIndices(_indexBuffer.Get()); +if (FAILED(result)) + return -1; +// Now we have to declare and apply the vertex declaration. +// Create a vector of vertex elements making up the vertex declaration. +std::vector vertexDeclDesc { + { 0, // stream index + 0, // byte offset from the struct beginning + D3DDECLTYPE_FLOAT3, // data type (3d float vector) + D3DDECLMETHOD_DEFAULT, // tessellator operation + D3DDECLUSAGE_POSTION, // usage of the data + 0 }, // index (multiples usage of the same type) + { 0, + 12, // byte offset (3 * sizeof(float) bytes) + D3DDECLTYPE_D3DCOLOR, + D3DDECLMETHOD_DEFAULT, + D3DDECLUSAGE_COLOR, + 0 }, + D3DDECL_END() // marks the end of the vertex declaration +}; +// After having defined the vector we can create a vertex declaration from it. +result = _device->CreateVertexDeclaration( + vertexDeclDesc.data(), // the vertex element array + &_vertexDecl); // receiving pointer +if (FAILED(result)) + return -1; +// Apply the created vertex declaration. +_device->SetVertexDeclaration(_vertexDecl.Get()); +// ... +``` + +## Shader + +The maximum shader model for Direct3D 9 is shader model 3.0. Even though every modern graphics card should support it, it is best to check for capabilities. + +```cpp +// ... +_device->SetVertexDeclaration(_vertexDecl.Get()); +// First we have to request the device capabilities. +D3DCAPS9 deviceCaps{ }; +_device->GetDeviceCaps(&deviceCaps); +// Now we check if shader model 3.0 is supported for the vertex shader. +if (deviceCaps.VertexShaderVersion < D3DVS_VERSION(3, 0)) + return -1; +// And the same for the pixel shader. +if (deviceCaps.PixelShaderVersion < D3DPS_VERSION(3, 0)) + return -1; +``` + +Now that we are sure shader model 3.0 is supported let's create the vertex and pixel shader files. +DirectX 9 introduced the HLSL (**High Level Shading Language**), a C-like shader language, which +simplified the shader programming a lot, as you could only write shaders in shader assembly in DirectX 8. +Let's create a simple vertex- and pixel shader. + +**Vertex Shader** + +```cpp +// 3 4x4 float matrices representing the matrices we set in the fixed-function +// pipeline by using the SetTransform() method. +float4x4 projectionMatrix; +float4x4 viewMatrix; +float4x4 worldMatrix; +// The input struct to the vertex shader. +// It holds a 3d float vector for the position and a 4d float vector +// for the color. +struct VS_INPUT { + float3 position : POSITION; + float4 color : COLOR; +}; +// The output struct of the vertex shader, that is passed to the pixel shader. +struct VS_OUTPUT { + float4 position : POSITION; + float4 color : COLOR; +}; +// The main function of the vertex shader returns the output it sends to the +// pixel shader and receives it's input as a parameter. +VS_OUTPUT main(VS_INPUT input) { + // Declare a empty struct, that the vertex shader returns. + VS_OUTPUT output; + // Set the output position to the input position and set + // the w-component to 1, as the input position is a 3d vector and + // the output position a 4d vector. + output.position = float4(input.position, 1.0f); + // Multiply the output position step by step with the world, view and + // projection matrices. + output.position = mul(output.position, worldMatrix); + output.position = mul(output.position, viewMatrix); + output.position = mul(output.position, projectionMatrix); + // Pass the input color unchanged to the pixel shader. + output.color = input.color; + // Return the output struct to the pixel shader. + // The position value is automatically used as the vertex position. + return output; +} +``` + +**Pixel Shader** + +```cpp +// The pixel shader input struct must be the same as the vertex shader output! +struct PS_INPUT { + float4 position : POSITION; + float4 color : COLOR; +}; +// The pixel shader simply returns a 4d vector representing the vertex color. +// It receives it's input as a parameter just like the vertex shader. +// We have to declare the output semantic as color to it gets interpreted +// correctly. +float4 main(PS_INPUT input) : COLOR { + return input.color; +} +``` + +For more on semantics: [DirectX - Semantics](https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics#vertex-shader-semantics) + +Now we have to do quite some changes to the code. + +```cpp +ComPtr _device{ }; +ComPtr _vertexBuffer{ }; +ComPtr _indexBuffer{ }; +ComPtr _vertexDecl{ }; +// We have to add a ComPtr for the vertex- and pixel shader, aswell as one +// for the constants (matrices) in our vertex shader. +ComPtr _vertexShader{ }; +ComPtr _pixelShader{ }; +ComPtr _vertexTable{ }; +// Declare the world and rotation matrix as global, because we use them in +// WinMain and SetupTransform now. +D3DXMATRIX _worldMatrix{ }; +D3DXMATRIX _rotationMatrix{ }; +// ... +bool SetupTransform() { + // Set the world and rotation matrix to an identity matrix. + D3DXMatrixIdentity(&_worldMatrix); + D3DXMatrixIdentity(&_rotationMatrix); + + D3DXMATRIX scaling{ }; + D3DXMatrixScaling(&scaling, 10, 10, 1); + D3DXMatrixMultiply(&_worldMatrix, &scaling, &_rotationMatrix); + // After multiplying the scalation and rotation matrix the have to pass + // them to the shader, by using a method from the constant table + // of the vertex shader. + HRESULT result{ }; + result = _vertexTable->SetMatrix( + _device.Get(), // direct3d device + "worldMatrix", // matrix name in the shader + &_worldMatrix); // pointer to the matrix + if (FAILED(result)) + return false; + + D3DXMATRIX view{ }; + D3DXMatrixLookAtLH(&view, &D3DXVECTOR3{ 0.0f, 0.0f, -20.0f }, + &D3DXVECTOR3{ 0.0f, 0.0f, 0.0f }, &D3DXVECTOR3{ 0.0f, 1.0f, 0.0f }); + // Do the same for the view matrix. + result = _vertexTable->SetMatrix( + _device.Get(), // direct 3d device + "viewMatrix", // matrix name + &view); // matrix + if (FAILED(result)) + return false; + + D3DXMATRIX projection{ }; + D3DXMatrixPerspectiveFovLH(&projection, D3DXToRadian(60.0f), + 1024.0f / 768.0f, 0.0f, 100.0f); + // And also for the projection matrix. + result = _vertexTable->SetMatrix( + _device.Get(), + "projectionMatrix", + &projection); + if (FAILED(result)) + return false; + + D3DXMatrixRotationY(&_rotationMatrix, D3DXToRadian(0.5f)); + return true; +} +// ... +// Vertex and index buffer creation aswell as initialization stay unchanged. +// ... +// After checking that shader model 3.0 is available we have to compile and +// create the shaders. +// Declare two temporary buffers storing the compiled shader code. +ID3DXBuffer* vertexShaderBuffer{ }; +ID3DXBuffer* pixelShaderBuffer{ }; +result = D3DXCompileShaderFromFile("vertex.hlsl", // shader name + nullptr, // macro definitions + nullptr, // special includes + "main", // entry point name + "vs_3_0", // shader model version + 0, // special flags + &vertexShaderBuffer, // code buffer + nullptr, // error message + &_vertexTable); // constant table +if (FAILED(result)) + return -1; +// After the vertex shader compile the pixel shader. +result = D3DXCompileShaderFromFile("pixel.hlsl", + nullptr, + nullptr, + "main", + "ps_3_0", // pixel shader model 3.0 + 0, + &pixelShaderBuffer, + nullptr, + nullptr); // no need for a constant table +if (FAILED(result)) + return -1; +// Create the vertex shader from the code buffer. +result = _device->CreateVertexShader( + (DWORD*)vertexShaderBuffer->GetBufferPointer(), // code buffer + &_vertexShader); // vertex shader pointer +if (FAILED(result)) + return -1; + +result = _device->CreatePixelShader( + (DWORD*)pixelShaderBuffer->GetBufferPointer(), + &_pixelShader); +if (FAILED(result)) + return -1; +// Release the temporary code buffers after the shaders are created. +vertexShaderBuffer->Release(); +pixelShaderBuffer->Release(); +// Apply the vertex- and pixel shader. +_device->SetVertexShader(_vertexShader.Get()); +_device->SetPixelShader(_pixelShader.Get()); +// Apply the transform after the shaders have been set. +if (!SetupTransform()) + return -1; +// You can also REMOVE the call so set the lighting render state. +_device->SetRenderState(D3DRS_LIGHTING, false); +``` + +You can find the complete code here: [DirectX - 3](https://pastebin.com/y4NrvawY) + +## Texturing + +```cpp +// First we need to declare a ComPtr for the texture. +ComPtr _texture{ }; +// Then we have to change the vertex struct. +struct VStruct { + float x, y, z; + float u, v; // Add texture u and v coordinates + D3DCOLOR color; +}; +// In the vertex declaration we have to add the texture coordinates. +// the top left of the texture is u: 0, v: 0. +std::vector vertices { + VStruct{ -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, ... }, // bottom left + VStruct{ -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, ... }, // top left + VStruct{ 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, ... }, // top right + VStruct{ 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, ... } // bottom right +}; +// Next is the vertex declaration. +std::vector vertexDecl{ + {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0}, + // Add a 2d float vector used for texture coordinates. + {0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0}, + // The color offset is not (3 + 2) * sizeof(float) = 20 bytes + {0, 20, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0}, + D3DDECL_END() +}; +// Now we have to load the texture and pass its to the shader. +// ... +_device->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); +// Create a Direct3D texture from a png file. +result = D3DXCreateTextureFromFile(_device.Get(), // direct3d device + "texture.png", // texture path + &_texture); // receiving texture pointer +if (FAILED(result)) + return -1; +// Attach the texture to shader stage 0, which is equal to texture register 0 +// in the pixel shader. +_device->SetTexture(0, _texture.Get()); +``` + +With the main code ready we now have to adjust the shaders to these changes. + +**Vertex Shader** + +```cpp +float4x4 projectionMatrix; +float4x4 viewMatrix; +float4x4 worldMatrix; +// Add the texture coordinates to the vertex shader in- and output. +struct VS_INPUT { + float3 position : POSITION; + float2 texcoord : TEXCOORD; + float4 color : COLOR; +}; + +struct VS_OUTPUT { + float4 position : POSITION; + float2 texcoord : TEXCOORD; + float4 color : COLOR; +}; + +VS_OUTPUT main(VS_INPUT input) { + VS_OUTPUT output; + + output.position = float4(input.position, 1.0f); + output.position = mul(output.position, worldMatrix); + output.position = mul(output.position, viewMatrix); + output.position = mul(output.position, projectionMatrix); + + output.color = input.color; + // Set the texcoord output to the input. + output.texcoord = input.texcoord; + + return output; +} +``` + +**Pixel Shader** + +```cpp +// Create a sampler called "sam0" using sampler register 0, which is equal +// to the texture stage 0, to which we passed the texture. +sampler sam0 : register(s0); + +struct PS_INPUT { + float4 position : POSITION; + float2 texcoord : TEXCOORD; + float4 color : COLOR; +}; + +float4 main(PS_INPUT input) : COLOR{ + // Do a linear interpolation between the texture color and the input color + // using 75% of the input color. + // tex2D returns the texture data at the specified texture coordinate. + return lerp(tex2D(sam0, input.texcoord), input.color, 0.75f); +} +``` + +## Quotes +[1][DirectX - Wikipedia](https://en.wikipedia.org/wiki/DirectX) -- cgit v1.2.3 From ec3d3f91ea91cd5c6b6569af194dbafb5635c4c4 Mon Sep 17 00:00:00 2001 From: Profpatsch Date: Mon, 19 Aug 2019 14:57:50 +0200 Subject: [dhall/de]: add German translation (#3600) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [dhall/en] Typo & highlight terms Template and package are referencing concepts from other languages, so let’s highlight them to clarify. * [dhall/de] Translate to German The translation leaves (most) of the code as-is, only changing the comments and some string contents. The `philadelphia` and `john` fields are changed to `augsburg` and `bernd` respectively, as an in-joke for German programmers. --- de-de/dhall-de.html.markdown | 380 +++++++++++++++++++++++++++++++++++++++++++ dhall.html.markdown | 6 +- 2 files changed, 383 insertions(+), 3 deletions(-) create mode 100644 de-de/dhall-de.html.markdown diff --git a/de-de/dhall-de.html.markdown b/de-de/dhall-de.html.markdown new file mode 100644 index 00000000..385c88be --- /dev/null +++ b/de-de/dhall-de.html.markdown @@ -0,0 +1,380 @@ +--- +language: Dhall +contributors: + - ["Gabriel Gonzalez", "http://www.haskellforall.com/"] +translators: + - ["Profpatsch", "http://profpatsch.de"] +filename: learndhall-de.py +lang: de-de +--- + +Dhall ist eine programmierbare Konfigurationssprache und bietet eine +nicht-repetetive Alternative zu YAML. + +Man kann Dhall sehen als: JSON + Funktionen + Typen + Importsystem + +Obwohl Dhall programmierbar ist, ist die Sprache nicht +turingvollständig. Viele von Dhalls Features benutzen diese +Einschränkung, um stärkere Sicherheitsgarantien zu bieten und besseres +Tooling zu ermöglichen. + +```haskell +-- einzeiliger Kommentar + +{- mehrzeiliger Kommentar + + Unicode funktioniert 🙂 + + Diese Datei ist eine valide Dhall-Expression und evaluiert zu einem + großen Record, welcher die Ergebnisse jedes Schritts beinhaltet. + + Das Ergebnis kann angezeigt werden, indem man die Datei evaluiert: + + $ dhall --file learndhall.dhall + + {- Kommentare können verschachtelt sein -} +-} + +let greeting = "Hallo, Welt!" + +let fruits = "🍋🍓🍍🍉🍌" + +let interpolation = "Ein paar leckere Früchte: ${fruits}" + +let multilineText {- Inline-Kommentare funktionieren ebenfalls -} = + '' + In Multiline-Text-Literals wird Whitespace am Anfang der Zeile + entfernt. + + Das bedeutet Text kann frei eingerückt oder ausgerückt werden, + ohne dass sich der Inhalt des Strings ändert. + + Relative Einrückungen bleiben erhalten. + + Ansonsten wird das Text-Literal verbatim erhalten, ähnlich + zu “literal”-Multiline-Strings in YAML. + '' + +let bool = True + +-- Typannotationen für Bindings sind optional, aber hilfreich, also +-- benutzen wir sie hier. +let annotation : Bool = True + +let renderedBool : Text = if bool then "True" else "False" + +-- Natürliche Zahlen sind nicht-negativ und vorzeichenlos. +let naturalNumber : Natural = 42 + +-- Integer können negativ sein, brauchen aber ein explizites Vorzeichen. +let positiveInteger : Integer = +1 + +let negativeInteger : Integer = -12 + +let pi : Double = 3.14159265359 + +{- Identifier dürfen eine große Anzahl an verschiedenen Zeichen + beinhalten (wie z.B. Anführungszeichen oder Whitespace), wenn man + sie mit Backticks umschließt. +-} +let `Avogadro's Number` : Double = 6.0221409e+23 + +let origin : { x : Double, y : Double } = { x = 0.0, y = 0.0 } + +let somePrimes : List Natural = [ 2, 3, 5, 7, 11 ] + +{- Ein Schema ist das gleiche wie ein Typ. + + Typnamen beginnen konventionell mit einem Großbuchstaben, was + jedoch nicht erzwungen wird. +-} +let Profile : Type + = { person : + { name : Text + , age : Natural + } + , address : + { country : Text + , state : Text + , city : Text + } + } + +let bernd : Profile = + { person = + { name = "Bernd Lauert" + , age = 67 + } + , address = + { country = "Deutschland" + , state = "Bayern" + , city = "Augsburg" + } + } + +let augsburg : Text = bernd.address.city + +{- Enum-Alternativen beginnen konventionell auch mit einem + Großbuchstaben. Das wird ebenfalls nicht erzwungen. +-} +let DNA : Type = < Adenine | Cytosine | Guanine | Thymine > + +let dnaSequence : List DNA = [ DNA.Thymine, DNA.Guanine, DNA.Guanine ] + +let compactDNASequence : List DNA = + let a = DNA.Adenine + let c = DNA.Cytosine + let g = DNA.Guanine + let t = DNA.Thymine + in [ c, t, t, a, t, c, g, g, c ] + +-- Enums werden transformiert, indem man einen Record mit einem Feld +-- pro Alternative angibt. +let theLetterG : Text = + merge + { Adenine = "A" + , Cytosine = "C" + , Guanine = "G" + , Thymine = "T" + } + DNA.Guanine + +let presentOptionalValue : Optional Natural = Some 1 + +let absentOptionalValue : Optional Natural = None Natural + +let points : List { x : Double, y : Double } = + [ { x = 1.1, y = -4.2 } + , { x = 4.4, y = -3.0 } + , { x = 8.2, y = -5.5 } + ] + +{- `Natural -> List Natural` ist der Funktionstyp mit Eingabetyp + `Natural` und Ausgabetyp `List Natural`. + + Alle Funktionen in Dhall sind Anonyme Funktionen (aka. „Lambdas“), + denen man optional einen Namen geben kann. + + Die folgende Funktion beispielsweise ist äquivalent zu diesem + Python Code: + + lambda n : [ n, n + 1 ] + + ... und diesem Javascript Code: + + function (n) { return [ n, n + 1 ]; } +-} +let exampleFunction : Natural -> List Natural = + \(n : Natural) -> [ n, n + 1 ] + +-- Dhall unterstützt auch Unicode-Syntax, aber dieses Tutorial nutzt +-- die ASCII-Syntax. +let unicodeFunction : Natural → List Natural = + λ(n : Natural) → [ n, n + 1 ] + +-- Funktionsargumente brauchen keine Klammern. +let exampleFunctionApplication : List Natural = + exampleFunction 2 + +let functionOfMultipleArguments : Natural -> Natural -> List Natural = + \(x : Natural) -> \(y : Natural) -> [ x, y ] + +let functionAppliedToMultipleArguments : List Natural = + functionOfMultipleArguments 2 3 + +{- Wie `exampleFunction`, aber wir geben dem Eingabetypen + einen Namen, `n`. +-} +let namedArgumentType : forall (n : Natural) -> List Natural = + \(n : Natural) -> [ n, n + 1 ] + +{- Bekommt der Eingabetyp einen Namen, kann man ihn weiter hinten in + der gleichen Typdefinition wiederverwenden. + + Das ermöglicht Funktionen, die mit mehr als einem Eingabetypen + arbeiten können (aka. „polymorphe“ Funktionen). +-} +let duplicate : forall (a : Type) -> a -> List a = + \(a : Type) -> \(x : a) -> [ x, x ] + +let duplicatedNumber : List Natural = + duplicate Natural 2 + +let duplicatedBool : List Bool = + duplicate Bool False + +{- Die Sprache hat auch eine handvoll eingebauter polymorpher + Funktionen, wie zum Beispiel: + + List/head : forall (a : Type) -> List a -> Optional a +-} +let firstPrime : Optional Natural = List/head Natural somePrimes + +let functionOfARecord : { x : Natural, y : Natural } -> List Natural = + \(args : { x : Natural, y : Natural }) -> [ args.x, args.y ] + +let functionAppliedToARecord : List Natural = + functionOfARecord { x = 2, y = 5 } + +{- Alle Typkonversionen sind explizit. + + `Natural/show` ist eine eingebaute Funktion mit dem Typ: + + Natural/show : Natural -> Text + + ... welche `Natural`s in ihre `Text`-Repräsentation konvertiert. +-} +let typeConversion : Natural -> Text = + \(age : Natural) -> "Ich bin ${Natural/show age} Jahre alt!" + +-- Ein „Template“ ist einfach eine Funktion mit Ausgabetyp `Text`. +let mitLicense : { year : Natural, copyrightHolder : Text } -> Text = + \(args : { year : Natural, copyrightHolder : Text }) -> +'' +Copyright ${Natural/show args.year} ${args.copyrightHolder} + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +'' + +-- Template-Instanziierung ist das gleiche wie Funktionsanwendung. +let templatedLicense : Text = + mitLicense { year = 2019, copyrightHolder = "Jane Smith" } + +{- Expressions können via URL importiert werden. + + Ähnlich wie in Bash kann man Code aus dem lokalen Dateisystem + importieren (wird nicht gezeigt). + + Sicherheitsbewusste Nutzer können via URLs importierte Expressions + mit einem semantischen Integritätscheck versehen („pinnen“). + Für gepinnte Imports wird der Dhall-Interpreter jeden Versuch + vereiteln, auf der Remote-Seite die Expression zu manipulieren. + Jedoch werden Änderungen, die den Inhalt der importierten + Expression nicht verändern trotzdem akzeptiert. + + Auf diese Weise gepinnte Expressions werden auch in einem + Content-Adressable Store lokal gecached (standardmäßig in + `~/.cache/dhall`). +-} +let Natural/sum : List Natural -> Natural = + https://prelude.dhall-lang.org/Natural/sum + sha256:33f7f4c3aff62e5ecf4848f964363133452d420dcde045784518fb59fa970037 + +let twentyEight : Natural = Natural/sum somePrimes + +-- Ein „Paket“ ist einfach ein (möglicherweise verschachtelter) +-- Record, den man importiert. +let Prelude = https://prelude.dhall-lang.org/package.dhall + +let false : Bool = Prelude.Bool.not True + +-- Durch das Anhängen von `as Text` wird eine Datei verbatim +-- importiert und nicht als Dhall-Code interpretiert. +let sourceCode : Text = https://prelude.dhall-lang.org/Bool/not as Text + +-- Environment-Variablen können auch imortiert werden. +let presentWorkingDirectory = env:PWD as Text + +-- Mit `?` kann man eine “Fallback-Expression” angeben, für den Fall +-- dass ein Import fehlschlägt. +let home : Optional Text = Some env:HOME ? None Text + +-- Fallback-Expressions können auch alternative Imports enthalten. +let possiblyCustomPrelude = + env:DHALL_PRELUDE + ? https://prelude.dhall-lang.org/package.dhall + +{- Ein ausführliches Beispiel, welches mithilfe der + `generate`-Funktion eine Konfiguration für 10 Build-User generiert: + + Prelude.List.generate + : Natural -> forall (a : Type) -> (Natural -> a) -> List a +-} +let buildUsers = + let makeUser = \(user : Text) -> + let home = "/home/${user}" + let privateKey = "${home}/.ssh/id_ed25519" + let publicKey = "${privateKey}.pub" + in { home = home + , privateKey = privateKey + , publicKey = publicKey + } + + let buildUser = + \(index : Natural) -> makeUser "build${Natural/show index}" + + let Config = + { home : Text + , privateKey : Text + , publicKey : Text + } + + in Prelude.List.generate 10 Config buildUser + +-- Alle Ergebnisse in einem großen Record +in { greeting = greeting + , fruits = fruits + , interpolation = interpolation + , multilineText = multilineText + , bool = bool + , annotation = annotation + , renderedBool = renderedBool + , naturalNumber = naturalNumber + , positiveInteger = positiveInteger + , negativeInteger = negativeInteger + , pi = pi + , `Avogadro's Number` = `Avogadro's Number` + , origin = origin + , somePrimes = somePrimes + , bernd = bernd + , augsburg = augsburg + , dnaSequence = dnaSequence + , compactDNASequence = compactDNASequence + , theLetterG = theLetterG + , presentOptionalValue = presentOptionalValue + , absentOptionalValue = absentOptionalValue + , points = points + , exampleFunction = exampleFunction + , unicodeFunction = unicodeFunction + , exampleFunctionApplication = exampleFunctionApplication + , functionOfMultipleArguments = functionOfMultipleArguments + , functionAppliedToMultipleArguments = functionAppliedToMultipleArguments + , namedArgumentType = namedArgumentType + , duplicate = duplicate + , duplicatedNumber = duplicatedNumber + , duplicatedBool = duplicatedBool + , firstPrime = firstPrime + , functionOfARecord = functionOfARecord + , functionAppliedToARecord = functionAppliedToARecord + , typeConversion = typeConversion + , mitLicense = mitLicense + , templatedLicense = templatedLicense + , twentyEight = twentyEight + , false = false + , sourceCode = sourceCode + , presentWorkingDirectory = presentWorkingDirectory + , home = home + , buildUsers = buildUsers + } +``` + +Mehr Infos und Lernmaterialien gibt es auf der offiziellen Website +(Englisch), auf der man Dhall auf im Browser ausprobieren kann: + +* [https://dhall-lang.org](http://dhall-lang.org/) diff --git a/dhall.html.markdown b/dhall.html.markdown index 21126c8a..704a94ee 100644 --- a/dhall.html.markdown +++ b/dhall.html.markdown @@ -11,7 +11,7 @@ alternative to YAML. You can think of Dhall as: JSON + functions + types + imports Note that while Dhall is programmable, Dhall is not Turing-complete. Many -of Dhall's features take advantage of this restriction to provider stronger +of Dhall's features take advantage of this restriction to provide stronger safety guarantees and more powerful tooling. ```haskell @@ -216,7 +216,7 @@ let functionAppliedToARecord : List Natural = let typeConversion : Natural -> Text = \(age : Natural) -> "I am ${Natural/show age} years old!" --- A template is the same thing as a function whose output type is `Text` +-- A "template" is the same thing as a function whose output type is `Text` let mitLicense : { year : Natural, copyrightHolder : Text } -> Text = \(args : { year : Natural, copyrightHolder : Text }) -> '' @@ -263,7 +263,7 @@ let Natural/sum : List Natural -> Natural = let twentyEight : Natural = Natural/sum somePrimes --- A package is the same thing as a (possibly nested) record that you can import +-- A "package" is the same thing as a (possibly nested) record that you can import let Prelude = https://prelude.dhall-lang.org/package.dhall let false : Bool = Prelude.Bool.not True -- cgit v1.2.3 From 8f3261822430ff60c00ccf573dc2aadd41b3a5c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Se=C3=A7kin=20K=C3=BCkrer?= Date: Tue, 20 Aug 2019 06:45:22 +0000 Subject: [Clojure/tr-tr] Fix on Contributors field. (#3608) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Added myself as a Contributor because this documentation is not just translation. Thank you for notice! * Same old pit-fall. 🤦 --- tr-tr/clojure-tr.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/tr-tr/clojure-tr.html.markdown b/tr-tr/clojure-tr.html.markdown index 64970945..5ebe5ce6 100644 --- a/tr-tr/clojure-tr.html.markdown +++ b/tr-tr/clojure-tr.html.markdown @@ -4,6 +4,7 @@ lang: tr-tr filename: learnclojure-tr.clj contributors: - ["Adam Bard", "http://adambard.com/"] + - ["Seçkin KÜKRER", "https://leavenha.github.io"] translators: - ["Seçkin KÜKRER", "https://leavenha.github.io"] --- -- cgit v1.2.3 From c257831c3ab2bf73f8f2bb08707f52560369c672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Se=C3=A7kin=20K=C3=BCkrer?= Date: Wed, 21 Aug 2019 09:34:19 +0300 Subject: [Edn/tr-tr] (#3607) * Added EDN documentation in Turkish * Contribution field added. Translation field added. Fixed file name. * Contributor field fixed, again. Added lang meta information. --- tr-tr/edn-tr.html.markdown | 157 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 tr-tr/edn-tr.html.markdown diff --git a/tr-tr/edn-tr.html.markdown b/tr-tr/edn-tr.html.markdown new file mode 100644 index 00000000..9a2ac1ff --- /dev/null +++ b/tr-tr/edn-tr.html.markdown @@ -0,0 +1,157 @@ +--- +language: edn +filename: learnedn-tr.edn +lang: tr-tr +contributors: + - ["Seçkin KÜKRER", "https://github.com/LeaveNhA"] +--- + +# Y = 20 Dakika. + +### Genişletilebilir Veri Notasyonu (EDN, Extensible Data Notation). + +### Okunuşu: (Türkçe: ey-di-en), (English: eed-n) + +### Kodlama Türü: UTF-8 + +EDN Clojure sözdiziminin bir alt kümesidir. Bu alt küme, amacı gereği kod barındırmaz. Ve kendisi bir tip sistemi değildir. Bir şeması da yoktur. En basit tabirle; Genişletilebilir Veri Notasyonu kabul edilebilir elemanların bir kümesidir. + +EDN elementleri, akışları ve dosyaları UTF-8 kullanılarak kodlanmalıdır. Üstelik, dökümanı çevreleyen işaretçiler de olmadığı için akış, dağıtık programlama mesaj arayüzü ve diğer dinamik sistemler için idealdir. + + +```clojure +; Yorumlar, yorumlarımız, noktalı virgül ile başlıyor. +;; Genellikle ikili olarak kullanılıyorlar. + +;; |--------------------------------| +; |--------- Genel Yapısı ---------| +;; |--------------------------------| + +;; Boşluklar --whitespaces--, elementler için en yaygın ayıraçtır. +"Mustafa" "Kemal" "ATATÜRK" +;; Fakat okunuşu arttırdığı gerekçesiyle "," (virgüller --commas--) EDN yorumlayıcısı tarafından görmezden gelinir ve boşluk olarak nitelendirilir. +"Mustafa","Kemal","PAŞA" +;; Üstelik bu yenilikçi sözdizimsel kurala rağmen, {}, [] () gibi koleksiyon karakterlerini ayırmak için boşluğa ya da boşluğa çözümlenen virgüle ihtiyacınız yoktur. +[["MUSTAFA"] ["KEMAL"] [[{"ATA" "ATATÜRK"}]]] +;; Üst düzey vektör elemanlarını birbirinden ayıran boşlukları da kaldırabilirsiniz. +;; Fakat bu size, okunması zor bir vektör dışında hiç bir şey vermeyecektir. + +;; |--------------------------------| +; |-------- Atomik Yapılar --------| +;; |--------------------------------| + +; Mantıksal Değerler +;; Mantıksal Doğru, çoğu teknolojide aynı gösterimi var. +true +;; Mantıksal Yanlış. +false + +; Karakter Katarları +;; Karakter katarları, --SADECE-- çift tırnak ile belirtilebilir. +"İzmirin dağlarında çiçekler açar!" +;; C, C++, Java v.b. gibi dillerin desteklediği kaçış sekanslarını da destekler. +"Altın güneş orda sırmalar saçar.\nBozulmuş düşmanlar yel gibi kaçar." +;; Kaçış sekansları için bknz: $!$ + +; Karakter Sabitleri +;; Karakter sabitleri önlerinde bir ters eğik çizgi ile temsil edilirler. +\T \Ü \R \K +;; Üstelik, belirli kaçıl sekanslarının da karşılığı Karakter Sabiti olarak var. +\newline \return + +; Anahtar Kelimeler +;; Anahtar Kelimeler, önlerinde bir ":" iki nokta --colon-- +:yımırta +:kaşar +:bıngıl + +; Semboller +;; Semboller tanımlayıcıları temsil etmek için kullanılır. +;; "/" karakteri, Sembol Sabitlerinde isim-uzayı ayıracı olarak kullanılıyor. +izmir/kızları +;; "mutfak" isim uzayındaki "ekmek-bıçağı" isimli sembole çözümlenir. + +banyo/fayans +parke +laminat + +; Sayısal Değerler +;; Tam Sayı sabiti. +1991 +;; Kayan Noktalı Sabiti. +19.67 + +; Listeler +;; Listeler, yukarıdaki temel tiplerin ardışıklanmasıdır. +(bomba :bomba nokta \c \o \m) + +; Vektörler +;; Vektörler bir bakıma Listelere benzeseler de, bir çok açıdan farklıdırlar. +;; Mesela Listenin aksine Vektörler, Rastgele Erişime imkan verir. +[[] "şimdi" "asker"] + +; Eşlemeler +;; Sıfır veya daha fazla Anahtar-Değer çifti kabul eder. +;; Not: Clojure Veri Yapıları Soyutlaması ile Eşlemeler de, teknik olarak ardışık olarak işlenebilir. +{:canı :neler-ister? + :uykuda "mevlam"} +;; Bu ve diğer tüm Veri Yapıları Homojendir, birbirilerini barındırabilir, kapsayabilir, içerebilirler. +;; Ayrıca okunurluk gibi farklı sebeplerle virgül kullanımında özgürsünüz. +{{:id_ "129u391824981237981237" :kim "BEN"}, göster!} + +; Kümeler +;; Kümeler eşsiz eleman barındıran bir yapıdır. +;; Matematikteki karşılığını veriyor dersek yanlış olmaz. +#{:sen 3 milyar 750 milyon} + +;; |--------------------------------| +; |------ Etiketli Elemanlar ------| +;; |--------------------------------| + +;; EDN (Genişletilebilir Veri Notasyonu), # sembolü ile genişletilebilir. + +#benimuygulamam/bağlantı {:içerik "Y dakikada EDN Öğren" :url "https://learnxinyminutes.com/docs/tr-tr/edn-tr" :tıhlama-aksiyonu yırrttılll!} + +;; Ve bu yapıyı yorumlayacak bir de yapı gerekiyor. +(defn ->bağlantı [props] + (str "" + (:içerik props) + "")) + +;; Bu örnekte yorumlayıcıya, basit bir fonksiyon veriyoruz. +;; `clojure.edn/read-string` aslında bir ayarlar Eşlemesi kabul ediyor. +;; (Bu tür fonksiyon genişlemeleri, Clojure ekosisteminde yaygındır.) + +(clojure.edn/read-string + {:readers {'benimuygulamam/bağlantı ->bağlantı}} + "#benimuygulamam/bağlantı {:içerik \"Y dakikada EDN Öğren\" :url \"https://learnxinyminutes.com/docs/tr-tr/edn-tr\" :tıhlama-aksiyonu yırrttılll!}") +;=> "Y dakikada EDN Öğren" + +;; |--------------------------------| +; |--- Ön Tanımlı Genişletmeler ---| +;; |--------------------------------| + +; Tarih Etiketi +;; Bu etiket `inst` ön-ekinden sonra bir RFC-3339 formatında bir karakter katarı beklemektedir. +#inst "2013-10-21T14:50:00+00:00" ; => Formatlanmış bir şekilde: 21/10/2013 14:50:00 + +; UUID Etiketi +;; Bu etiket `uuid` ön-ekinden sonra bir UUID karşılığını karakter katarı olarak kabul eder. +#uuid "11k12fae-7d3c-11k0-a765-0010ckke6hgk" + +``` + +# Son Ek +Bu içerik, EDN'i tanıtmakta kısıtlı bir açıyla, özet bilgiler sunmaktadır. +Fakat, Clojure ve diğer Veri Odaklı dillerde, Verinin yolculuğunu anlamak için önemli bir rol oynamaktadır. +EDN'in var olan probleme çözümü ve artı/eksilerinin doğru şekilde kavranması mühimdir. +Ben bu dökümanı hazırlarken, EDN ve gerçek dünya kullanımını anlatan yoktu. Fakat ümidim, Clojure ve diğer teknolojiler üzerinde kullanımının artmasından sonra birinin bu ihtiyacı giderecek özgün kaynak çıkarmasıdır. + +Başarılar! + +# Referanslar + +- [EDN Formatı Standardı](https://github.com/edn-format/edn) +- [Gerçeklemeler](https://github.com/edn-format/edn/wiki/Implementations) +- [Etiketlenmiş Elementler](http://www.compoundtheory.com/clojure-edn-walkthrough/) +- [Clojure.Docs EDN İçeriği](https://clojuredocs.org/clojure.edn) -- cgit v1.2.3 From 6f3c29b6065e612806878247c4d656611a2a74b1 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Wed, 21 Aug 2019 12:17:17 +0530 Subject: Update sql-ru.html.markdown --- ru-ru/sql-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/sql-ru.html.markdown b/ru-ru/sql-ru.html.markdown index 78e021fc..64b7ab71 100644 --- a/ru-ru/sql-ru.html.markdown +++ b/ru-ru/sql-ru.html.markdown @@ -1,6 +1,6 @@ --- language: SQL -filename: learnsql.sql +filename: learnsql-ru.sql contributors: - ["Bob DuCharme", "http://bobdc.com/"] translators: -- cgit v1.2.3 From 77ab89a4b3ead12172230781e61bed629e12f7b5 Mon Sep 17 00:00:00 2001 From: Ben Landry Date: Wed, 21 Aug 2019 21:14:03 -0400 Subject: Added write to and read from a file syntax --- python3.html.markdown | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index ef78ce37..4cabb27b 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -505,6 +505,26 @@ with open("myfile.txt") as f: for line in f: print(line) +# Writing to a file +contents = {"aa": 12, "bb": 21} +with open("myfile1.txt", "w+") as file: + file.write(str(contents)) # writes a string to a file + +with open("myfile2.txt", "w+") as file: + file.write(json.dumps(contents)) # writes an object to a file + +# Reading from a file +with open('myfile1.txt', "r+") as file: + contents = file.read() # reads a string from a file +print(contents) +# print: {"aa": 12, "bb": 21} + +with open('myfile2.txt', "r+") as file: + contents = json.load(file) # reads a json object from a file +print(contents) +# print: {"aa": 12, "bb": 21} + + # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. # The object returned by the range function, is an iterable. -- cgit v1.2.3 From f0f161981f2e3d35967878b6a7a2c71de75b2b64 Mon Sep 17 00:00:00 2001 From: Amans Tofu Date: Fri, 30 Aug 2019 17:22:27 +0800 Subject: [Perl6/en]Modify an error about the Range constructor (#3612) [Perl6/en] Modify an error about the Range constructor --- perl6.html.markdown | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1304869b..c7fde218 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -499,10 +499,19 @@ say False ~~ True; #=> True ## Range constructor ##------------------ -3 .. 7; # 3 to 7, both included +3 .. 7; # 3 to 7, both included. 3 ..^ 7; # 3 to 7, exclude right endpoint. -3 ^.. 7; # 3 to 7, exclude left endpoint. Same as `4..7`. -3 ^..^ 7; # 3 to 7, exclude both endpoints. Same as `4..6`. +3 ^.. 7; # 3 to 7, exclude left endpoint. +3 ^..^ 7; # 3 to 7, exclude both endpoints. + # 3 ^.. 7 almost like 4 .. 7 when we only consider integers. + # But when we consider decimals : +3.5 ~~ 4 .. 7; # False +3.5 ~~ 3 ^.. 7; # True, This Range also contains decimals greater than 3. + # We describe it like this in some math books: 3.5 ∈ (3,7] + # If you don’t want to understand the concept of interval + # for the time being. At least we should know: +3 ^.. 7 ~~ 4 .. 7; # False + ## This also works as a shortcut for `0..^N`: ^10; # means 0..^10 -- cgit v1.2.3 From ec1090d7a8758cb3759ba903b946594257e309f7 Mon Sep 17 00:00:00 2001 From: Muhammad Usama Date: Fri, 30 Aug 2019 19:58:06 +0500 Subject: Optional parameters in methods --- groovy.html.markdown | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/groovy.html.markdown b/groovy.html.markdown index efbb2b32..89ca973a 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -180,6 +180,21 @@ class Foo { def lastName } +/* + Methods with optional parameters +*/ + +// A mthod can have default values for parameters +def say(msg = 'Hello', name = 'world') { + "$msg $name!" +} + +// It can be called in 3 different ways +assert 'Hello world!' == say() +// Right most parameter with default value is eliminated first. +assert 'Hi world!' == say('Hi') +assert 'learn groovy' == say('learn', 'groovy') + /* Logical Branching and Looping */ -- cgit v1.2.3 From 5e7c4f2f78247212d9bdfafa01b39a4dd8b7f4f6 Mon Sep 17 00:00:00 2001 From: Javier Candeira Date: Sat, 31 Aug 2019 23:59:33 +1000 Subject: Nixify so it can be easily developed on Nix --- CONTRIBUTING.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown index 18a5a5d7..79d6838a 100644 --- a/CONTRIBUTING.markdown +++ b/CONTRIBUTING.markdown @@ -103,3 +103,11 @@ You can buid the site locally to test your changes. Follow the steps below. these commands at `learnxinyminutes-site/`). * Build - `bundle exec middleman build` * Dev server - `bundle exec middleman --force-polling --verbose` + +## Building the site locally, for Nix users + +You can buid the site locally to test your changes too: + +* Clone or zip download the [learnxinyminutes-site](https://github.com/adambard/learnxinyminutes-site) repo. +* Get the source in place following the instructions above +* Install all site dependencies and start a dev server by running `nix-shell` at the `learnxinyminutes-site/` root directory. -- cgit v1.2.3 From 43fc3289dcf623779a30f1002a58748fe3998812 Mon Sep 17 00:00:00 2001 From: Ollin Boer Bohan Date: Sat, 31 Aug 2019 08:11:27 -0700 Subject: Minor fixes to C++ Smart Pointer section * Fix minor spelling / grammar problems ("tp de-allocate", "refences", "dont"...) * Remove filler words ("Basically", "As a matter of fact"...) * Remove spaces before parens in smart pointer initialization code sample (consistent with the other sections, e.g. the `Tuples` section) * Clarify `std::weak_ptr` use case --- c++.html.markdown | 46 +++++++++++++++++++++++----------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 176ea1a8..f3dc8e20 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -818,51 +818,51 @@ void doSomethingWithAFile(const std::string& filename) // Smart Pointer ///////////////////// -// Generally a smart pointer is a class, which wraps a "raw pointer" (usage of "new" +// Generally a smart pointer is a class which wraps a "raw pointer" (usage of "new" // respectively malloc/calloc in C). The goal is to be able to -// manage the lifetime of the object being point to without explicitly deleting +// manage the lifetime of the object being pointed to without ever needing to explicitly delete // the object. The term itself simply describes a set of pointers with the // mentioned abstraction. -// Basically smart pointers should preferred over raw pointers, to prevent -// risky memory leaks, which happens if you forget to delete the object. +// Smart pointers should preferred over raw pointers, to prevent +// risky memory leaks, which happen if you forget to delete an object. // Usage of a raw pointer: Dog* ptr = new Dog(); ptr->bark(); delete ptr; -// With the usage of smart pointers you dont have to worry about the deletion -// of a object anymore. -// A smart pointer describes a policy, to count the references on the -// pointer. As matter of fact the objects gets destroyed when the last -// reference on the object gets destroyed. +// By using a smart pointer, you don't have to worry about the deletion +// of the object anymore. +// A smart pointer describes a policy, to count the references to the +// pointer. The object gets destroyed when the last +// reference to the object gets destroyed. // Usage of "std::shared_ptr": void foo() { -// Its not longer necessary to delete the Dog. +// It's no longer necessary to delete the Dog. std::shared_ptr doggo(new Dog()); doggo->bark(); } // Beware of possible circular references!!! // There will be always a reference, so it will be never destroyed! -std::shared_ptr doggo_one (new Dog()); -std::shared_ptr doggo_two (new Dog()); +std::shared_ptr doggo_one(new Dog()); +std::shared_ptr doggo_two(new Dog()); doggo_one = doggo_two; // p1 references p2 doggo_two = doggo_one; // p2 references p1 -// As mentioned before there is a set of smart pointers. The way you have to -// use it, is always the same. -// This leads us to question, when to use which one? -// std::unique_ptr - use it when you just want to hold one reference on -// the same object. -// std::shared_ptr - use it when you want to hold multiple references on the -// same object and want to make sure that it´s de-allocated -// when all refences are gone. -// std::weak_ptr - use it when you want to hold multiple references from -// different places for references for which it´s no problem -// tp de-allocate. +// There are several kinds of smart pointers. +// The way you have to use them is always the same. +// This leads us to the question: when should we use each kind of smart pointer? +// std::unique_ptr - use it when you just want to hold one reference to +// the object. +// std::shared_ptr - use it when you want to hold multiple references to the +// same object and want to make sure that it's deallocated +// when all references are gone. +// std::weak_ptr - use it when you want to access +// the underlying object of a std::shared_ptr without causing that object to stay allocated. +// Weak pointers are used to prevent circular referencing. ///////////////////// -- cgit v1.2.3 From efcd37612d58baadf8821f70305e77201b5f0260 Mon Sep 17 00:00:00 2001 From: Javier Candeira Date: Sat, 31 Aug 2019 22:56:08 +1000 Subject: [nix/en] Updates for Nix 2.2.0 - nix-repl now deprecated, Nix 2 has `nix repl` - nix language now has floats, and type-preserving arithmetic - add note about immutable sets' attributes being un-redefinable - descendant sets can now have attributes added to them - fix editing loose ene in the Impurity section --- nix.html.markdown | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/nix.html.markdown b/nix.html.markdown index d078395a..5941f0e6 100644 --- a/nix.html.markdown +++ b/nix.html.markdown @@ -4,6 +4,7 @@ filename: learn.nix contributors: - ["Chris Martin", "http://chris-martin.org/"] - ["Rommel Martinez", "https://ebzzry.io"] + - ["Javier Candeira", "https://candeira.com/"] --- Nix is a simple functional language developed for the @@ -12,7 +13,7 @@ Nix is a simple functional language developed for the You can evaluate Nix expressions using [nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate) -or [`nix-repl`](https://github.com/edolstra/nix-repl). +or [`nix repl`](https://nixos.org/nix/manual/#ssec-relnotes-2.0). ``` with builtins; [ @@ -39,18 +40,26 @@ with builtins; [ #=> "a" - # Integers + # Integers and Floats #========================================= - # Integers are the only numeric type. + # There are two numeric types: integers and floats 1 0 42 (-3) # Some integers + 123.43 .27e13 # A couple of floats + + # Operations will preserve numeric type + (4 + 6 + 12 - 2) # Addition #=> 20 + (4 - 2.5) + #=> 1.5 (7 / 2) # Division #=> 3 + (7 / 2.0) + #=> 3.5 # Strings @@ -238,13 +247,20 @@ with builtins; [ }.a.c #=> { d = 2; e = 3; } - # An attribute's descendants cannot be assigned in this - # way if the attribute itself has been directly assigned. + # Sets are immutable, so you can't redefine an attribute: + { + a = { b = 1; }; + a.b = 2; + } + #=> attribute 'a.b' at (string):3:5 already defined at (string):2:11 + + # However, an attribute's set members can also be defined piecewise + # way even if the attribute itself has been directly assigned. { a = { b = 1; }; a.c = 2; } - #=> error: attribute ‘a’ already defined + #=> { a = { b = 1; c = 2; }; } # With @@ -321,8 +337,8 @@ with builtins; [ #========================================= # Because repeatability of builds is critical to the Nix package - # manager, in which, functional purity is emphasized in the Nix - # language. But there are a few impurities. + # manager, functional purity is emphasized in the Nix language + # used to describe Nix packages. But there are a few impurities. # You can refer to environment variables. (getEnv "HOME") -- cgit v1.2.3 From 10405c42fdbcfa97f856c1de5237cfc5e313cf2d Mon Sep 17 00:00:00 2001 From: Volodymyr Korniichuk <9173519@gmail.com> Date: Sun, 1 Sep 2019 10:55:27 +0300 Subject: Added translation for [Rust/uk-ua] (#3613) * Added uk-ua tranlation for Rust * fixed lang * fixed "80-symbols per line" limit * Fix filename --- uk-ua/rust-ua.html.markdown | 331 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 331 insertions(+) create mode 100644 uk-ua/rust-ua.html.markdown diff --git a/uk-ua/rust-ua.html.markdown b/uk-ua/rust-ua.html.markdown new file mode 100644 index 00000000..4ec2b7c9 --- /dev/null +++ b/uk-ua/rust-ua.html.markdown @@ -0,0 +1,331 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Volodymyr Korniichuk", "https://github.com/ezhikus"] +filename: learnrust-uk.rs +lang: uk-ua +--- + +Rust - це мова програмування, що розрабляється спільнотою Mozilla Research +Rust поєднує в собі низькорівневий контроль швидкодії з високорівневими +інструментами забезпечення гарантій цілісності та безпеки. + +Rust досягає своїх цілей без автоматичного збирання сміття і не вимагає +наявності певного середовища виконання, що робить можливим пряму заміну +бібліотек, написаних на мові С на бібліотеки, написані на Rust. + +Перший реліз Rust (версія 0.1) вийшла в січні 2012 року і з тих пір оновлення +виходили так часто, що загальною порадою розробникам було не чекати якоїсь +стабільної версії, а використовувати нічні збірки компілятора. + +15 травня 2015 року вийшла версія Rust 1.0. Для цієї версії була дана гарантія +зворотної сумісності. Подальші нічні збірки покращили швидкість компіляції та +деякі інші аспекти. На даний момент оновлення Rust виходять кожні 6 тижнів. +Бета-версія Rust 1.1 вийшла одночасно з релізом Rust 1.0. + +Не зважаючи на те, що Rust є відносно низькорівневою мовою програмування, в +ній є деякі концепти, притаманні високорівневим мовам. Це робить Rust не лише +швидким, але й досить зручним та ефективним інструментом розробки. + +```rust +// Це коментар. Він починається в цьому рядку... +// і продовжується в цьому + +/// Цей коментар включає в себе документацію і підтримує markdown. +/// # Приклади +/// +/// ``` +/// let five = 5 +/// ``` + +/////////////// +// 1. Основи // +/////////////// + +#[allow(dead_code)] +// Функції +// `i32` - це 32-бітний цілочислений знаковий тип даних +fn add2(x: i32, y: i32) -> i32 { + // неявне повернення результату (в кінці рядку немає крапки з комою) + x + y +} + +#[allow(unused_variables)] +#[allow(unused_assignments)] +#[allow(dead_code)] +// Головна функція +fn main() { + // Числа // + + // Незмінне число + let x: i32 = 1; + + // суфікси для позначення цілого числа та числа з плаваючою змінною + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Вивід типів + // Як правило, Rust може самостійно визначити тип змінної, отож + // ви можете не прописувати його явно + // В даному документі типи явно прописані в багатьох місцях, це зроблено + // виключно в навчальних цілях. В реальному коді вивід типів спрацює + // в більшості випадків + let implicit_x = 1; + let implicit_f = 1.3; + + // арифметика + let sum = x + y + 13; + + // Змінні + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // Строки // + + // Строкові літерали + let x: &str = "Привіт, світ!"; + + // Друк на екран + println!("{} {}", f, x); // 1.3 Привіт, світ! + + // `String` – строка, що розміщується в "купі" + let s: String = "hello world".to_string(); + + // Строковий зріз - це незмінне відображення якоїсь строки (або її частини) + // Зріз можна розглядати як константну пару покажчиків (на початок та кінець + // якоїсь строки) + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // Привіт, світ! Привіт, світ! + + // Вектори/масиви // + + // Масив фіксованого розміру + let four_ints: [i32; 4] = [1, 2, 3, 4]; + + // Масив змінного розміру (вектор) + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // Зріз - незмінне відображення масиву + // Це схоже на строковий зріз, але в даному випадку мова йде про вектори + let slice: &[i32] = &vector; + + // Використовуйте `{:?}` щоб вивести щось в цілях відлагодження + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Кортеж // + + // Кортеж - це набір фіксованого розміру, що включає значення кількох типів + let x: (i32, &str, f64) = (1, "привіт", 3.4); + + // розбираємо кортеж "х" на окремі змінні "a", "b" та "с" + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 привіт 3.4 + + // доступ по індексу + println!("{}", x.1); // привіт + + ////////////// + // 2. Типи // + ////////////// + + // Структура + struct Point { + x: i32, + y: i32, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // Структура з безіменними полями, "кортежна структура" + struct Point2(i32, i32); + + let origin2 = Point2(0, 0); + + // перелічуваний тип даних + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Direction::Up; + + // перелічуваний тип даних з полями + enum OptionalI32 { + AnI32(i32), + Nothing, + } + + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; + + // Узагальнене програмування // + + struct Foo { bar: T } + + // Ось так стандартна бібліотека Rust оголошує `Option` + enum Optional { + SomeVal(T), + NoVal, + } + + // Методи // + + impl Foo { + // Методи приймають неявний параметр `self` + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // Типажі (в інших мовах програмування схожою сутністю є інтерфейси) // + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) + + ///////////////////////// + // 3. Відповідність шаблону // + ///////////////////////// + + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::AnI32(n) => println!("Це тип i32: {}", n), + OptionalI32::Nothing => println!("Це ніщо!"), + } + + // Складніший приклад + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; + + match bar { + FooBar { x: 0, y: OptionalI32::AnI32(0) } => + println!("Числа рівні нулю!"), + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => + println!("Числа однакові"), + FooBar { x: n, y: OptionalI32::AnI32(m) } => + println!("Числа різні: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nothing } => + println!("Друге число - ніщо!"), + } + + ///////////////////// + // 4. Потік керування // + ///////////////////// + + // Цикл `for` + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Діапазони + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // друкує `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Математика працює!"); + } else { + println!("Ой, лишенько..."); + } + + // `if` як вираз + let value = if true { + "добре" + } else { + "погано" + }; + + // Цикл `while` + while 1 == 1 { + println!("Всесвіт функціонує стабільно."); + // Вираз break перериває цикл + break + } + + // Нескінченний цикл + loop { + println!("Привіт!"); + // Вираз break перериває цикл + break + } + + ///////////////////////////////// + // 5. Вказівники і безпека пам'яті // + ///////////////////////////////// + + // Володіючий вказівник - тільки хтось один може "володіти" вказівником в + // будь-який момент. Це означає, що коли "Box" вийде за межі області + // видимості - його можна безпечно звільнити + let mut mine: Box = Box::new(3); + *mine = 5; // розіменування `mine` з присвоєнням йому нового значення + // `now_its_mine` перебирає на себе володіння над `mine`. Іншими словами, + // `mine` переміщується. + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", mine); // цей код не скомпілюється, оскільки тепер + // покажчиком на дані володіє `now_its_mine` + + // Посилання – незмінний вказівник на дані + // При створенні посилання на якесь значення, ми говоримо, що значення + // було "запозичене". Поки значення є запозиченим - воно не може бути + // змінене або переміщене. Запозичення пропадає, як тільки стається вихід з + // області видимості, де було створене посилання + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // На відміну від `mine`, `var` можна використати + println!("{}", *ref_var); + // var = 5; // цей код не скомпілюється, оскільки `var` зараз є запозиченим + // *ref_var = 6; // цей код також не зкомпілюється, оскільки `ref_var` + // є незмінним посиланням + + // Змінне посилання + // Значення можна запозичити з можливістю зміни. У цьому випадку доступ до + // оригінального значення втрачається. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' використовується для доступу до змінного посилання + + println!("{}", *ref_var2); // 6 , // при заміні на var2 код не зкомпілюється + // ref_var2 має тип &mut i32, отож зберігає посилання на i32, а не значення + // var2 = 2; // цей рядок не зкомпілюється, оскільки `var2` є запозиченим. +} +``` + +## Матеріали для самовдосконалення + +В даному матеріалі ми оглянули лише основи Rust. Більше матеріалу ви можете +знайти на сайті +[The Rust Programming Language](http://doc.rust-lang.org/book/index.html) +Також існує Reddit-розділ [/r/rust](http://reddit.com/r/rust). Люди на каналі +irc.mozilla.org також завжди раді допомогти новачкам. + +Ви можете спробувати можливості Rust за допомогою онлайн-компілятора на сторінці +[Rust playpen](http://play.rust-lang.org) або +[Rust website](http://rust-lang.org). -- cgit v1.2.3 From c5f6427b6001aa0bb260d1636641c5edf01d8998 Mon Sep 17 00:00:00 2001 From: Emerentius Date: Sun, 1 Sep 2019 11:54:15 +0200 Subject: rust: improve explanation of string slices --- rust.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 71bc16b5..f8f6c5e4 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -92,10 +92,8 @@ fn main() { let s: String = "hello world".to_string(); // A string slice – an immutable view into another string - // This is basically an immutable pair of pointers to a string – it doesn’t - // actually contain the contents of a string, just a pointer to - // the begin and a pointer to the end of a string buffer, - // statically allocated or contained in another object (in this case, `s`) + // The string buffer can be statically allocated like in a string literal + // or contained in another object (in this case, `s`) let s_slice: &str = &s; println!("{} {}", s, s_slice); // hello world hello world -- cgit v1.2.3 From fdd278fde1fc7e5c26a853200cade201bb86e48f Mon Sep 17 00:00:00 2001 From: Emerentius Date: Sun, 1 Sep 2019 11:54:40 +0200 Subject: rust: update explanation of borrow system With the introduction of non-lexical lifetimes, borrows no longer last until the end of scope. This has always been active in the 2018 edition and is now also true in the 2015 edition as of Rust 1.36 --- rust.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index f8f6c5e4..92794e69 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -288,7 +288,7 @@ fn main() { // Reference – an immutable pointer that refers to other data // When a reference is taken to a value, we say that the value has been ‘borrowed’. // While a value is borrowed immutably, it cannot be mutated or moved. - // A borrow lasts until the end of the scope it was created in. + // A borrow is active until the last use of the borrowing variable. let mut var = 4; var = 3; let ref_var: &i32 = &var; @@ -297,6 +297,8 @@ fn main() { println!("{}", *ref_var); // var = 5; // this would not compile because `var` is borrowed // *ref_var = 6; // this would not either, because `ref_var` is an immutable reference + ref_var; // no-op, but counts as a use and keeps the borrow active + var = 2; // ref_var is no longer used after the line above, so the borrow has ended // Mutable reference // While a value is mutably borrowed, it cannot be accessed at all. @@ -307,6 +309,7 @@ fn main() { println!("{}", *ref_var2); // 6 , // var2 would not compile. // ref_var2 is of type &mut i32, so stores a reference to an i32, not the value. // var2 = 2; // this would not compile because `var2` is borrowed. + ref_var2; // no-op, but counts as a use and keeps the borrow active until here } ``` -- cgit v1.2.3 From 6d38bf6af9d82ede7a2e34081eb180acd52a7a21 Mon Sep 17 00:00:00 2001 From: WeJie Date: Wed, 4 Sep 2019 12:25:38 +0800 Subject: [yaml/zh-cn]Update yaml-cn.html.markdown --- zh-cn/yaml-cn.html.markdown | 62 ++++++++++++++++++++++++--------------------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown index bbda20e9..de933d12 100644 --- a/zh-cn/yaml-cn.html.markdown +++ b/zh-cn/yaml-cn.html.markdown @@ -23,12 +23,12 @@ YAML 根本不容许文字制表符。 ################ # 我们的根对象 (它们在整个文件里延续) 将会是一个映射, -# 它等价于在别的语言里的一个字典,哈西表或对象。 +# 它等价于在别的语言里的一个字典,哈希表或对象。 key: value another_key: Another value goes here. a_number_value: 100 -# 如果你想将数字 1 作为值,你必须要将它括在引号中。 -# 不然 YAML 解析器会假定它是一个布尔值 true。 +# 数字 1 会被解释为数值,而不是一个布尔值。 +# 如果你想要的是一个布尔值,使用 true。 scientific_notation: 1e+12 boolean: true null_value: null @@ -60,17 +60,17 @@ folded_style: > # 集合类型 # #################### -# 嵌套是通过缩进完成的。 +# 嵌套是通过缩进完成的。推荐使用 2 个空格的缩进(但非必须) 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 -# 映射的键值不必是字符串。 +# 映射的键不必是字符串。 0.25: a float key -# 键值也可以是复合型的,比如多行对象 +# 键也可以是复合型的,比如多行对象 # 我们用 ? 后跟一个空格来表示一个复合键的开始。 ? | This is a key @@ -86,19 +86,20 @@ a_nested_map: # 序列 (等价于列表或数组) 看起来像这样: a_sequence: - - Item 1 - - Item 2 - - 0.5 # 序列可以包含不同类型。 - - Item 4 - - key: value - another_key: another_value - - - - This is a sequence - - inside another sequence + - Item 1 + - Item 2 + - 0.5 # 序列可以包含不同类型。 + - Item 4 + - key: value + another_key: another_value + - + - This is a sequence + - inside another sequence # 因为 YAML 是 JSON 的超集,你也可以写 JSON 风格的映射和序列: json_map: {"key": "value"} json_seq: [3, 2, 1, "takeoff"] +and quotes are optional: {key: [3, 2, 1, takeoff]} ####################### # 其余的 YAML 特性 # @@ -111,15 +112,18 @@ other_anchor: *anchor_name # 锚也可被用来复制/继承属性 base: &base - name: Everyone has same name + name: Everyone has same name + +# The regexp << is called Merge Key Language-Independent Type. +# 它表明指定映射的所有键值会插入到当前的映射中。 foo: &foo - <<: *base - age: 10 + <<: *base + age: 10 bar: &bar - <<: *base - age: 20 + <<: *base + age: 20 # foo 和 bar 将都含有 name: Everyone has same name @@ -146,10 +150,10 @@ date: 2002-12-14 # 这个 !!binary 标签表明这个字符串实际上 # 是一个用 base64 编码表示的二进制 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 还有一个集合类型,它看起来像这样: set: @@ -157,7 +161,7 @@ set: ? item2 ? item3 -# 像 Python 一样,集合仅是值为 null 的映射;上面的集合等价于: +# 集合只是值为 null 的映射;上面的集合等价于: set2: item1: null item2: null -- cgit v1.2.3 From 4a14d54eb520f9776710102bfec740467b549745 Mon Sep 17 00:00:00 2001 From: Ilya Vorontsov Date: Thu, 5 Sep 2019 11:06:51 +0300 Subject: [ruby/ru] [ruby/en] added notes about postfix-if and about --- ru-ru/ruby-ru.html.markdown | 10 ++++++++++ ruby.html.markdown | 8 ++++++++ 2 files changed, 18 insertions(+) diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index e69c6d94..b1fd04e1 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -231,6 +231,7 @@ new_hash.value?(3) #=> true # Управление ходом выполнения (Управляющие структуры) +# Условия if true 'Если истина' elsif false @@ -239,6 +240,15 @@ else 'Во всех других случаях (тоже опционально)' end +# Если условие контролирует выполнение не блока кода, а единственного выражения, +# можно использовать постфиксную запись условного оператора +warnings = ['Отсутствует отчество', 'Слишком короткий адрес'] +puts("Обратите внимание:\n" + warnings.join("\n")) if !warnings.empty? + +# Иногда условие лучше звучит с `unless`, чем с `if` +puts("Обратите внимание:\n" + warnings.join("\n")) unless warnings.empty? + +# Циклы for counter in 1..5 puts "итерация #{counter}" end diff --git a/ruby.html.markdown b/ruby.html.markdown index 2595d1d5..d77672ab 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -247,6 +247,14 @@ else 'else, also optional' end +# If a condition controls invokation of a single statement rather than a block of code +# you can use postfix-if notation +warnings = ['Patronimic is missing', 'Address too short'] +puts("Some warnings occurred:\n" + warnings.join("\n")) if !warnings.empty? + +# Rephrase condition if `unless` sounds better than `if` +puts("Some warnings occurred:\n" + warnings.join("\n")) unless warnings.empty? + # Loops # In Ruby, traditional `for` loops aren't very common. Instead, these # basic loops are implemented using enumerable, which hinges on `each`. -- cgit v1.2.3 From 8a4aeb0fd38d67d5780c11bc013bbbf32fe68f8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mart=C3=ADn=20del=20R=C3=ADo?= <11744462+Lartu@users.noreply.github.com> Date: Sun, 8 Sep 2019 22:21:12 -0300 Subject: LDPL example documentation added. --- ldpl.html.markdown | 183 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 ldpl.html.markdown diff --git a/ldpl.html.markdown b/ldpl.html.markdown new file mode 100644 index 00000000..cc95f5fb --- /dev/null +++ b/ldpl.html.markdown @@ -0,0 +1,183 @@ +--- +language: LDPL +filename: learnLDPL.ldpl +contributors: + - ["Martín del Río", "https://github.com/lartu"] +--- + +**LDPL** is a powerful, C++ transpiled, open-source programming language designed +from the ground up to be excessively expressive, readable, fast and easy to learn. +It mimics plain English, in the likeness of older programming languages like COBOL, +with the desire that it can be understood by anybody. It's very portable and runs on a +plethora of different architectures and operating systems and it even supports UTF-8 +out of the box. + +[Read more here.](https://github.com/lartu/ldpl) + +```coffeescript +# This is a single line comment in LDPL. +# LDPL doesn't have multi-line comments. + +# LDPL is a case-insensitive language: dIsPlaY and DISPLAY are the same +# statement, and foo and FOO name the same variable. + +# An LDPL source file is divided in two sections, the DATA section and +# the PROCEDURE section. + +DATA: +# Within the DATA section, variables are declared. + +myNumber is number # Defines a real number. +myString is text # Defines a string. +myList is number list # Defines a list of numbers. +myMap is number map # Defines a map of numbers. + +# LDPL understands four data types: two scalar types (NUMBER, TEXT) +# and two container types (LISTs and MAPs). +# LISTs can be TEXT LISTs or NUMBER LISTs, while MAPs can be +# TEXT MAPs and NUMBER MAPs. You can also chain many containers +# to create larger data types: +textListList is text list list +myMulticontainer is number list list map +# Defines a map of lists of lists of numbers. + +PROCEDURE: +# Within the PROCEDURE section, your code is written. + +store -19.2 in myNumber # Use the STORE statement to assign values +store "Hi there" in myString # to variables. +push 890 to myList # Use PUSH - TO to append values to lists. +push 100 to myList +push 500 to myList +store 45 in myMap:"someIndex" # Use the : operator to index containers. + +push list to textListList # Push an empty list into a list of lists. +push "LDPL is nice!" to textListList:0 #Push text to the pushed list. + +display "Hello World!" # Use the DISPLAY statement to print values. +# The display statement can receive multiple values separated by spaces. +display crlf "How are you today?" myNumber myString crlf +# CRLF is the standard line break value in LDPL. +display textListList:0:0 " Isn't it?" crlf + +# IF statements in LDPL are extremely verbose: +if myNumber is equal to -19.2 and myList:0 is less than 900 then + display "Yes!" crlf +else if myMap:"someIndex" is not equal to 45 then + display "This is an else if!" crlf +else + display "Else!" crlf +end if +# Valid LDPL comparisson operators are +# - IS EQUAL TO +# - IS NOT EQUAL TO +# - IS LESS THAN +# - IS GREATER THAN +# - IS LESS THAN OR EQUAL TO +# - IS GREATER THAN OR EQUAL TO +if "Hi there!" is not equal to "Bye bye!" then + display "Yep, those weren't equal." crlf +end if +# LDPL normally doesn't understand inline expressions, so you +# cannot do stuff like: +# if myNumber - 9 * 2 is equal to 10 then +# LDPL will set your computer on fire and burst your screen if you do so. + +# WHILE loops follow the same rules +store 0 in myNumber +while myNumber is less than 10 do + display "Loop number " myNumber "..." crlf + in myNumber solve myNumber + 1 # You can do math like this. +repeat +# You can use 'break' and 'continue' inside loops just like any other language. + +# LDPL also has FOR loops and FOR EACH loops +for myNumber from 0 to 100 step 2 do + display myNumber crlf +repeat + +for each myNumber in myList do + display myNumber +repeat + +display "Enter your name: " +accept myString # Use ACCEPT to let the user input values. +display "Hi there, " myString crlf +display "How old are you?: " +accept myNumber +if myNumber is greater than 200 then + display "Woah, you are so old!" crlf +end if + +wait 1000 milliseconds # Pause the program for a whole second. + +# Let's do some math +store 1.2 in myNumber +in myNumber solve myNumber * (10 / 7.2) # Operators are separated by spaces. +floor myNumber +display myNumber crlf +get random in myNumber # get a random number between 0 and 1 + # and store it in myNumber + +# Functions in LDPL are called sub-procedures. Sub-procedures, like source +# files, are divided in sections. The sections found in sub-procedures are +# the PARAMETERS section, the LOCAL DATA section and the PROCEDURE section. +# All sections except the PROCEDURE section can be skipped if they aren't +# used. If no PARAMTERS nor LOCAL DATA sections are used, the PROCEDURE +# keyword may be omited. +sub myFunction + parameters: + a is number # LDPL is pass by reference + b is number + result is number # Thus you can return values through a parameter. + local data: + c is number + procedure: + get random in c + in result solve a + b * c +end sub + +sub sayHello + display "Hi there!" crlf + return + display "This won't be displayed :(" +end sub + +call myFunction with 1 2 myNumber +display myNumber crlf +call sayHello +call sayBye # sub-procedures may be called before they are declared + +sub sayBye + display "Bye!" +end sub + +# One of the greatest features of LDPL is the ability to create your +# own statements. + +create statement "say hi" executing sayHello +say hi + +create statement "random add $ and $ in $" executing myFunction +random add 1 and 2 in myNumber +display myNumber crlf + +exit +``` + +## Topics Not Covered + + * [Command line arguments](https://docs.ldpl-lang.org/variables-in-ldpl/command-line-arguments) + * [Error variables](https://docs.ldpl-lang.org/variables-in-ldpl/errorcode-and-errortext) + * [Import other files](https://docs.ldpl-lang.org/structure-of-ldpl-source-code/importing-other-sources) + * [Identifier naming schemes](https://docs.ldpl-lang.org/naming-rules) + * [Text Statements](https://docs.ldpl-lang.org/text-statements/join-and-in) + * [List Statements](https://docs.ldpl-lang.org/list-statements/push-to) + * [Map Statements](https://docs.ldpl-lang.org/vector-statements/clear) + * [File loading / writing](https://docs.ldpl-lang.org/i-o-statements/load-file-in) + * [Executing commands](https://docs.ldpl-lang.org/i-o-statements/execute) + * [Extending LDPL with C++](https://docs.ldpl-lang.org/extensions/c++-extensions) + +## Further Reading + + * [LDPL Docs](https://docs.ldpl-lang.org) -- cgit v1.2.3 From aaea037ba47492d0b4f475eb3b5986930081a812 Mon Sep 17 00:00:00 2001 From: fighou Date: Wed, 18 Sep 2019 10:46:17 +0200 Subject: Update 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 24044d76..064a9fdd 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -14,7 +14,7 @@ The syntax of F# is different from C-style languages: * Curly braces are not used to delimit blocks of code. Instead, indentation is used (like Python). * Whitespace is used to separate parameters rather than commas. -If you want to try out the code below, you can go to [tryfsharp.org](http://www.tryfsharp.org/Create) and paste it into an interactive REPL. +If you want to try out the code below, you can go to [https://try.fsharp.org](https://try.fsharp.org) and paste it into an interactive REPL. ```csharp -- cgit v1.2.3 From edcfd31759594ec55ccbedaae7a763fafbb17805 Mon Sep 17 00:00:00 2001 From: carl Date: Fri, 20 Sep 2019 14:12:41 +1000 Subject: Tweak markdown to properly render html --- it-it/pcre-it.html.markdown | 13 +++++++++---- pcre.html.markdown | 25 +++++++++++++++++-------- zh-tw/pcre-tw.html.markdown | 9 +++++---- 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/it-it/pcre-it.html.markdown b/it-it/pcre-it.html.markdown index 68233858..704392ef 100644 --- a/it-it/pcre-it.html.markdown +++ b/it-it/pcre-it.html.markdown @@ -11,7 +11,7 @@ lang: it-it Un'espressione regolare (regex o regexp in breve) è una speciale stringa utilizzata per definire un pattern, ad esempio per cercare una sequenza di caratteri; ad esempio, `/^[a-z]+:/` può essere usato per estrarre `http:` -dall'URL `http://github.com/`. +dall'URL `http://github.com/`. PCRE (Perl Compatible Regular Expressions) è una libreria per i regex in C. La sintassi utilizzata per le espressioni è molto simile a quella di Perl, da @@ -19,7 +19,9 @@ cui il nome. Si tratta di una delle sintassi più diffuse per la scrittura di regex. Esistono due tipi di metacaratteri (caratteri con una funzione speciale): + * Caratteri riconosciuti ovunque tranne che nelle parentesi quadre + ``` \ carattere di escape ^ cerca all'inizio della stringa (o della riga, in modalità multiline) @@ -36,16 +38,17 @@ Esistono due tipi di metacaratteri (caratteri con una funzione speciale): ``` * Caratteri riconosciuti nelle parentesi quadre + ``` \ carattere di escape ^ nega la classe se è il primo carattere - indica una serie di caratteri [ classe caratteri POSIX (se seguita dalla sintassi POSIX) ] termina la classe caratteri - -``` +``` + +PCRE fornisce inoltre delle classi di caratteri predefinite: -PCRE fornisce inoltre delle classi di caratteri predefinite: ``` \d cifra decimale \D NON cifra decimale @@ -62,9 +65,11 @@ PCRE fornisce inoltre delle classi di caratteri predefinite: ## Esempi Utilizzeremo la seguente stringa per i nostri test: + ``` 66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1" ``` + Si tratta di una riga di log del web server Apache. | Regex | Risultato | Commento | diff --git a/pcre.html.markdown b/pcre.html.markdown index 3e877a35..9e091721 100644 --- a/pcre.html.markdown +++ b/pcre.html.markdown @@ -3,16 +3,18 @@ language: PCRE filename: pcre.txt contributors: - ["Sachin Divekar", "http://github.com/ssd532"] - + --- -A regular expression (regex or regexp for short) is a special text string for describing a search pattern. e.g. to extract domain name from a string we can say `/^[a-z]+:/` and it will match `http:` from `http://github.com/`. +A regular expression (regex or regexp for short) is a special text string for describing a search pattern. e.g. to extract domain name from a string we can say `/^[a-z]+:/` and it will match `http:` from `http://github.com/`. PCRE (Perl Compatible Regular Expressions) is a C library implementing regex. It was written in 1997 when Perl was the de-facto choice for complex text processing tasks. The syntax for patterns used in PCRE closely resembles Perl. PCRE syntax is being used in many big projects including PHP, Apache, R to name a few. There are two different sets of metacharacters: + * Those that are recognized anywhere in the pattern except within square brackets + ``` \ general escape character with several uses ^ assert start of string (or line, in multiline mode) @@ -32,18 +34,19 @@ There are two different sets of metacharacters: ``` * Those that are recognized within square brackets. Outside square brackets. They are also called as character classes. - + ``` - + \ general escape character ^ negate the class, but only if the first character - indicates character range [ POSIX character class (only if followed by POSIX syntax) ] terminates the character class - -``` -PCRE provides some generic character types, also called as character classes. +``` + +PCRE provides some generic character types, also called as character classes. + ``` \d any decimal digit \D any character that is not a decimal digit @@ -59,7 +62,13 @@ PCRE provides some generic character types, also called as character classes. ## Examples -We will test our examples on following string `66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1"`. It is a standard Apache access log. +We will test our examples on the following string: + +``` +66.249.64.13 - - [18/Sep/2004:11:07:48 +1000] "GET /robots.txt HTTP/1.0" 200 468 "-" "Googlebot/2.1" +``` + + It is a standard Apache access log. | Regex | Result | Comment | | :---- | :-------------- | :------ | diff --git a/zh-tw/pcre-tw.html.markdown b/zh-tw/pcre-tw.html.markdown index c9cdc537..5f681d46 100644 --- a/zh-tw/pcre-tw.html.markdown +++ b/zh-tw/pcre-tw.html.markdown @@ -13,7 +13,9 @@ lang: zh-tw 相容Perl正規表達式(Perl Compatible Regular Expressions, PCRE)是一個實作正規表達式的C語言函式庫。此函式庫在1997年被開發出來,在當時面對複雜字串處理時大多會選擇使用Perl。也因為如此,PCRE大多的正規表達式語法都很酷似Perl。PCRE語法被廣泛運用在許多大專案中,包括PHP、Apache、R等。 PCRE中的超字元(metacharacter)主要可以分為以下兩類: + * 在中括號外會被辨識的字元 + ``` \ 通用跳脫字元 ^ 字串開頭 或 行首 @@ -33,18 +35,17 @@ PCRE中的超字元(metacharacter)主要可以分為以下兩類: ``` * 在中括號內會被辨識的超字元,在中括號外會被視為字元集合使用 - + ``` - \ 通用跳脫字元 ^ 非字元集合的字,但只會抓到第一個符合的字元 - 字元範圍 [ POSIX字元集合(若後面接POSIX格式) ] 字元集合定義結束 - -``` +``` PCRE提供了一些通用的字元類型,可被當作字元集合使用 + ``` \d 任何數字字元 \D 任何非數字字元 -- cgit v1.2.3 From f1a7e8f8b2553bfa4ecfcf67a16e4a5e37859194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Bed=C5=99ich?= Date: Fri, 20 Sep 2019 16:27:27 +0200 Subject: [python/cs-cz] Update examples: bool + generators --- cs-cz/python3.html.markdown | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 2cbf52e6..bd3690a8 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -137,12 +137,14 @@ None # => None "něco" is None # => False None is None # => True -# None, 0, a prázdný řetězec/seznam/slovník se vyhodnotí jako False +# None, 0, a prázdný řetězec/seznam/N-tice/slovník/množina se vyhodnotí jako False # Vše ostatní se vyhodnotí jako True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False +bool(0) # => False +bool("") # => False +bool([]) # => False +bool(tuple()) # => False +bool({}) # => False +bool(set()) # => False #################################################### @@ -602,18 +604,21 @@ dir(math) # Generátory jsou funkce, které místo return obsahují yield def nasobicka_2(sekvence): for i in sekvence: + print("Zpracovávám číslo {}".format(i)) yield 2 * i # Generátor generuje hodnoty postupně, jak jsou potřeba. Místo toho, aby vrátil # celou sekvenci s prvky vynásobenými dvěma, provádí jeden výpočet v každé iteraci. -# To znamená, že čísla větší než 15 se v metodě nasobicka_2 vůbec nezpracují. +for nasobek in nasobicka_2([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]): + # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" + if nasobek >= 10: + break # Funkce range() je také generátor - vytváření seznamu 900000000 prvků by zabralo # hodně času i paměti, proto se místo toho čísla generují postupně. - -for i in nasobicka_2(range(900000000)): - print(i) # Vypíše čísla 0, 2, 4, 6, 8, ... 30 - if i >= 30: +for nasobek in nasobicka_2(range(900000000)): + # Vypíše postupně: "Zpracovávám číslo 1", ..., "Zpracovávám číslo 5" + if nasobek >= 10: break @@ -633,7 +638,7 @@ def nekolikrat(puvodni_funkce): def pozdrav(jmeno): print("Měj se {}!".format(jmeno)) -pozdrav("Pepo") # Vypíše 3x: Měj se Pepo! +pozdrav("Pepo") # Vypíše 3x: "Měj se Pepo!" ``` ## Co dál? -- cgit v1.2.3 From 0731b18cb75968e3e844e72069ca97c5ace22a85 Mon Sep 17 00:00:00 2001 From: Auledas Date: Sat, 21 Sep 2019 18:14:09 +0100 Subject: [html/ca-es] Catalan translation of HTML --- ca-es/html-ca.html.markdown | 176 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 ca-es/html-ca.html.markdown diff --git a/ca-es/html-ca.html.markdown b/ca-es/html-ca.html.markdown new file mode 100644 index 00000000..933b9046 --- /dev/null +++ b/ca-es/html-ca.html.markdown @@ -0,0 +1,176 @@ +--- +language: html +filename: learnhtml-ca.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Marc Auledas", "https://github.com/Auledas"] +lang: ca-es +--- + +HTML significa llenguatge de marques d'hipertext (HyperText Markup Language). + +És un llenguatge que permet escriure pàgines pel sistema web (World Wide Web). +És un llenguatge de marques que permet escriure pàgines web fent servir codi per indicar +com s'ha de visualitzar el text i les dades. De fet, els fitxers html són simples +fitxers de text. + +Què són les 'marques'? Són un mètode d'organitzar les dades d'una pàgina mitjançant +etiquetes d'obertura i tancament. Aquestes marques serveixen per donar +significat al text que hi ha entre les etiquetes. Com d'altres llenguatges de marques, +hi ha moltes versions de l'HTML. Aquí es desenvoluparà l'HTML5. + +**NOTA:** Pots provar les diferents etiquetes i elements a mesura que progressis a través +del tutorial a pàgines web com [codepen](http://codepen.io/pen/). D'aquesta manera podràs +veure'n els efectes, entendre com funcionen i familiaritzar-te amb el llenguatge. Aquest +article tracta principalment la sintaxi de l'HTML i alguns consells útils. + + +```html + + + + + + + + + + + + + El meu lloc web + + +

Hola, món!

+ + Fes una ullada a com es veu això. + +

Això és un paràgraf.

+

Això és un altre paràgraf.

+
    +
  • Això és un element d'una llista no enumerada (llista de punts).
  • +
  • Això és un altre element.
  • +
  • I aquest és l'últim element de la llista.
  • +
+ + + + + + + + + + + + + + + + + + + + + + El meu lloc web + + + + + + + + +

Hola, món!

+ + + + + Fes una ullada a com es veu això. + + + +

Això és un paràgraf.

+

Això és un altre paràgraf.

+ + + +
    +
  • Això és un element d'una llista no enumerada (llista de punts).
  • +
  • Això és un altre element.
  • +
  • I aquest és l'últim element de la llista.
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Primera capçaleraSegona capçalera
Primera fila, primera columnaPrimera fila, segona columna
Segona fila, primera columnaSegona fila, segona columna
+ +``` + +## Ús + +Els arxius HTML acaben amb les extensions `.html` o `.htm`. El tipus MIME és `text/html`. + +**HTML NO és un llenguatge de programació** + +## Per aprendre'n més + +* [Viquipèdia](https://ca.wikipedia.org/wiki/Hyper_Text_Markup_Language) +* [Tutorial HTML](https://developer.mozilla.org/ca/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 473d432e5723e1a7b07b5309d2bff60f1e7b150b Mon Sep 17 00:00:00 2001 From: Auledas Date: Sun, 22 Sep 2019 14:28:43 +0100 Subject: Fixed filename --- ca-es/html-ca.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ca-es/html-ca.html.markdown b/ca-es/html-ca.html.markdown index 933b9046..7600cf24 100644 --- a/ca-es/html-ca.html.markdown +++ b/ca-es/html-ca.html.markdown @@ -1,6 +1,6 @@ --- language: html -filename: learnhtml-ca.html +filename: html-ca.html contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: -- cgit v1.2.3 From 1e4af002ce9418f0ebbb8cf761503024b48d18b9 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sun, 22 Sep 2019 23:33:55 +0530 Subject: Fix filename --- ca-es/html-ca.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ca-es/html-ca.html.markdown b/ca-es/html-ca.html.markdown index 7600cf24..351eb722 100644 --- a/ca-es/html-ca.html.markdown +++ b/ca-es/html-ca.html.markdown @@ -1,6 +1,6 @@ --- language: html -filename: html-ca.html +filename: html-ca.md contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: -- cgit v1.2.3 From 80096795e04d66bde02535775f66224f98a7a17f Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Tue, 24 Sep 2019 10:17:02 +0530 Subject: Fix explanation for slices --- python3.html.markdown | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 4cabb27b..430927a9 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -228,15 +228,11 @@ li[4] # Raises an IndexError # You can look at ranges with slice syntax. # 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 beginning and return the list -li[2:] # => [4, 3] -# Omit the end and return the list -li[:3] # => [1, 2, 4] -# Select every second entry -li[::2] # =>[1, 4] -# Return a reversed copy of the list -li[::-1] # => [3, 4, 2, 1] +li[1:3] # Return list from index 1 to 3 => [2, 4] +li[2:] # Return list starting from index 2 => [4, 3] +li[:3] # Return list from beginning uptil index 3 => [1, 2, 4] +li[::2] # Return list selecting every second entry => [1, 4] +li[::-1] # Return list in reverse order => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] -- cgit v1.2.3 From 1371efe157ac337e68091a7e5dc8652ac29497eb Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Sun, 29 Sep 2019 22:42:01 -0400 Subject: general-purpose, not specifically web-oriented Although Haxe has a great JS target, it has many other targets as well, and is a general-purpose language, and not strictly web-oriented. --- haxe.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index a31728e1..235a9b74 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -6,8 +6,8 @@ contributors: - ["Dan Korostelev", "https://github.com/nadako/"] --- -Haxe is a web-oriented language that provides platform support for C++, C#, -Swf/ActionScript, Javascript, Java, PHP, Python, Lua, HashLink, and Neko byte code +[Haxe](https://haxe.org/) is a general-purpose language that provides platform support for C++, C#, +Swf/ActionScript, JavaScript, Java, PHP, Python, Lua, HashLink, and Neko bytecode (the latter two being also written by the Haxe author). Note that this guide is for Haxe version 3. Some of the guide may be applicable to older versions, but it is recommended to use other references. @@ -668,7 +668,7 @@ class TypedefsAndStructuralTypes { That would give us a single "Surface" type to work with across all of those platforms. - */ + */ } } @@ -700,8 +700,7 @@ class UsingExample { instance, and the compiler still generates code equivalent to a static method. */ - } - + } } ``` -- cgit v1.2.3 From 5129c2acd17f8f548d2f5b9c514387e60f7d8c1e Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Sun, 29 Sep 2019 22:57:33 -0400 Subject: Space between `switch` and `(` --- haxe.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 235a9b74..6a50b88b 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -338,7 +338,7 @@ class LearnHaxe3 { */ var my_dog_name = "fido"; var favorite_thing = ""; - switch(my_dog_name) { + switch (my_dog_name) { case "fido" : favorite_thing = "bone"; case "rex" : favorite_thing = "shoe"; case "spot" : favorite_thing = "tennis ball"; @@ -366,7 +366,7 @@ class LearnHaxe3 { trace("k equals ", k); // outputs 10 - var other_favorite_thing = switch(my_dog_name) { + var other_favorite_thing = switch (my_dog_name) { case "fido" : "teddy"; case "rex" : "stick"; case "spot" : "football"; @@ -559,7 +559,7 @@ class SimpleEnumTest { // You can specify the "full" name, var e_explicit:SimpleEnum = SimpleEnum.Foo; var e = Foo; // but inference will work as well. - switch(e) { + switch (e) { case Foo: trace("e was Foo"); case Bar: trace("e was Bar"); case Baz: trace("e was Baz"); // comment this line to throw an error. @@ -572,7 +572,7 @@ class SimpleEnumTest { You can also specify a default for enum switches as well: */ - switch(e) { + switch (e) { case Foo: trace("e was Foo again"); default : trace("default works here too"); } @@ -595,21 +595,21 @@ class ComplexEnumTest { var e1:ComplexEnum = IntEnum(4); // specifying the enum parameter // Now we can switch on the enum, as well as extract any parameters // it might have had. - switch(e1) { + switch (e1) { case IntEnum(x) : trace('$x was the parameter passed to e1'); default: trace("Shouldn't be printed"); } // another parameter here that is itself an enum... an enum enum? var e2 = SimpleEnumEnum(Foo); - switch(e2){ + switch (e2){ case SimpleEnumEnum(s): trace('$s was the parameter passed to e2'); default: trace("Shouldn't be printed"); } // enums all the way down var e3 = ComplexEnumEnum(ComplexEnumEnum(MultiEnum(4, 'hi', 4.3))); - switch(e3) { + switch (e3) { // You can look for certain nested enums by specifying them // explicitly: case ComplexEnumEnum(ComplexEnumEnum(MultiEnum(i,j,k))) : { -- cgit v1.2.3 From a8d9e066eae5f48b27c93df3d0bbb53cd232a63a Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Sun, 29 Sep 2019 23:21:42 -0400 Subject: decrements too --- haxe.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 6a50b88b..05fa59bf 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -234,10 +234,9 @@ class LearnHaxe3 { ^ Bitwise exclusive OR | Bitwise inclusive OR */ - - // increments + var i = 0; - trace("Increments and decrements"); + trace("Pre-/Post- Increments and Decrements"); trace(i++); // i = 1. Post-Increment trace(++i); // i = 2. Pre-Increment trace(i--); // i = 1. Post-Decrement -- cgit v1.2.3 From a22ba3395320bbd266aad71e73e8059fc84f45a7 Mon Sep 17 00:00:00 2001 From: John Gabriele Date: Sun, 29 Sep 2019 23:29:13 -0400 Subject: whitespace --- haxe.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 05fa59bf..e086dd7a 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -189,7 +189,7 @@ class LearnHaxe3 { trace(m.get('bar') + " is the value for m.get('bar')"); trace(m['bar'] + " is the value for m['bar']"); - var m2 = ['foo' => 4, 'baz' => 6]; // Alternative map syntax + var m2 = ['foo' => 4, 'baz' => 6]; // Alternative map syntax trace(m2 + " is the value for m2"); // Remember, you can use type inference. The Haxe compiler will @@ -286,7 +286,7 @@ class LearnHaxe3 { } // do-while loop - var l = 0; + var l = 0; do { trace("do statement always runs at least once"); } while (l > 0); -- cgit v1.2.3 From 19a377def003d9992f631ff0727add5263eee824 Mon Sep 17 00:00:00 2001 From: Chris Zimmerman Date: Mon, 30 Sep 2019 17:55:50 -0400 Subject: Adds documentation for some basic ES6 features. --- javascript.html.markdown | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index c466c09b..ce9772ca 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -586,6 +586,48 @@ if (Object.create === undefined){ // don't overwrite it if it exists return new Constructor(); }; } + +// ES6 Additions + +// The "let" keyword allows you to define variables in a lexical scope, +// as opposed to a block scope like the var keyword does. +let name = "Billy"; + +// Variables defined with let can be reassigned new values. +name = "William"; + +// The "const" keyword allows you to define a variable in a lexical scope +// like with let, but you cannot reassign the value once one has been assigned. + +const pi = 3.14; + +pi = 4.13; // You cannot do this. + +// There is a new syntax for functions in ES6 known as "lambda syntax". +// This allows functions to be defined in a lexical scope like with variables +// defined by const and let. + +const isEven = (number) => { + return number % 2 === 0; +}; + +isEven(7); // false + +// The "equivalent" of this function in the traditional syntax would look like this: + +function isEven(number) { + return number % 2 === 0; +}; + +// I put the word "equivalent" in double quotes because a function defined +// using the lambda syntax cannnot be called before the definition. +// The following is an example of invalid usage: + +add(1, 8); + +const add = (firstNumber, secondNumber) => { + return firstNumber + secondNumber; +}; ``` ## Further Reading -- cgit v1.2.3 From 3ade005c37a40c8e1712f6c68c81ebc9682a36c1 Mon Sep 17 00:00:00 2001 From: Chris Zimmerman Date: Mon, 30 Sep 2019 18:11:43 -0400 Subject: Fixes the spacing of comments in the English C# documentation --- csharp.html.markdown | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index df6544d3..0cf59762 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -18,16 +18,18 @@ C# is an elegant and type-safe object-oriented language that enables developers ```c# // Single-line comments start with // + /* Multi-line comments look like this */ + /// /// This is an XML documentation comment which can be used to generate external /// documentation or provide context help within an IDE /// /// This is some parameter documentation for firstParam /// Information on the returned value of a function -//public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {} +public void MethodOrClassOrOtherWithParsableHelp(string firstParam) {} // Specify the namespaces this source code will be using // The namespaces below are all part of the standard .NET Framework Class Library @@ -254,7 +256,7 @@ on a new line! ""Wow!"", the masses cried"; int fooWhile = 0; while (fooWhile < 100) { - //Iterated 100 times, fooWhile 0->99 + // Iterated 100 times, fooWhile 0->99 fooWhile++; } @@ -273,10 +275,10 @@ on a new line! ""Wow!"", the masses cried"; } while (fooDoWhile < 100); - //for loop structure => for(; ; ) + // for loop structure => for(; ; ) for (int fooFor = 0; fooFor < 10; fooFor++) { - //Iterated 10 times, fooFor 0->9 + // Iterated 10 times, fooFor 0->9 } // For Each Loop @@ -287,7 +289,7 @@ on a new line! ""Wow!"", the masses cried"; // (The ToCharArray() could be removed, because a string also implements IEnumerable) foreach (char character in "Hello World".ToCharArray()) { - //Iterated over all the characters in the string + // Iterated over all the characters in the string } // Switch Case @@ -329,7 +331,7 @@ on a new line! ""Wow!"", the masses cried"; // Convert String To Integer // this will throw a FormatException on failure - int.Parse("123");//returns an integer version of "123" + int.Parse("123"); // returns an integer version of "123" // try parse will default to type default on failure // in this case: 0 @@ -373,7 +375,7 @@ on a new line! ""Wow!"", the masses cried"; Console.Read(); } // End main method - // CONSOLE ENTRY A console application must have a main method as an entry point + // CONSOLE ENTRY - A console application must have a main method as an entry point public static void Main(string[] args) { OtherInterestingFeatures(); @@ -404,7 +406,7 @@ on a new line! ""Wow!"", the masses cried"; ref int maxCount, // Pass by reference out int count) { - //the argument passed in as 'count' will hold the value of 15 outside of this function + // the argument passed in as 'count' will hold the value of 15 outside of this function count = 15; // out param must be assigned before control leaves the method } @@ -564,11 +566,11 @@ on a new line! ""Wow!"", the masses cried"; } ); - //Running this will produce different outputs - //since each thread finishes at different times. - //Some example outputs are: - //cat dog horse pony - //dog horse pony cat + // Running this will produce different outputs + // since each thread finishes at different times. + // Some example outputs are: + // cat dog horse pony + // dog horse pony cat // DYNAMIC OBJECTS (great for working with other languages) dynamic student = new ExpandoObject(); @@ -865,7 +867,7 @@ on a new line! ""Wow!"", the masses cried"; } } - //Method to display the attribute values of this Object. + // Method to display the attribute values of this Object. public virtual string Info() { return "Gear: " + Gear + @@ -1069,7 +1071,7 @@ on a new line! ""Wow!"", the masses cried"; { private static bool LogException(Exception ex) { - /* log exception somewhere */ + // log exception somewhere return false; } @@ -1117,12 +1119,12 @@ on a new line! ""Wow!"", the masses cried"; [Obsolete("Use NewMethod instead", false)] public static void ObsoleteMethod() { - /* obsolete code */ + // obsolete code } public static void NewMethod() { - /* new code */ + // new code } public static void Main() @@ -1154,9 +1156,9 @@ namespace Learning.More.CSharp } } -//New C# 7 Feature -//Install Microsoft.Net.Compilers Latest from Nuget -//Install System.ValueTuple Latest from Nuget +// New C# 7 Feature +// Install Microsoft.Net.Compilers Latest from Nuget +// Install System.ValueTuple Latest from Nuget using System; namespace Csharp7 { -- cgit v1.2.3 From 3e1fe4dc0077817c8946fc8644c29d2ba585b0e1 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Tue, 1 Oct 2019 11:55:55 -0300 Subject: [php/pt-br] Small typo --- pt-br/php-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown index 8a1c956e..e55f1100 100644 --- a/pt-br/php-pt.html.markdown +++ b/pt-br/php-pt.html.markdown @@ -20,7 +20,7 @@ Este documento descreve PHP 5+. // Duas barras iniciam o comentário de uma linha. -# O hash (aka pound symbol) também inicia, mas // é mais comum. +# O hash (conhecido como "pound symbol") também inicia, mas // é mais comum. /* O texto envolto por barra-asterisco e asterisco-barra -- cgit v1.2.3 From 4df895568d5600f20636e88b58cdfd74e7df4410 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Tue, 1 Oct 2019 11:58:32 -0300 Subject: [cypher/pt-br] Small typo --- pt-br/cypher-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/cypher-pt.html.markdown b/pt-br/cypher-pt.html.markdown index 9b60f771..d4400148 100644 --- a/pt-br/cypher-pt.html.markdown +++ b/pt-br/cypher-pt.html.markdown @@ -101,7 +101,7 @@ path = shortestPath( (user)-[:KNOWS*..5]-(other) ) Crie consultas --- -Create a new node +Crie um novo nó ``` CREATE (a:Person {name:"Théo Gauchoux"}) RETURN a -- cgit v1.2.3 From 09e6e2d6c4839c25564dc9fce42555bf7658ff14 Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Tue, 1 Oct 2019 12:04:06 -0300 Subject: [groovy/pt-br] Small typo --- pt-br/groovy-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown index aed23df1..f3a7699e 100644 --- a/pt-br/groovy-pt.html.markdown +++ b/pt-br/groovy-pt.html.markdown @@ -17,7 +17,7 @@ Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http: Prepara-se: 1) Instale a máquina virtual de Groovy - http://gvmtool.net/ - 2) Intalse o Groovy: gvm install groovy + 2) Intale o Groovy: gvm install groovy 3) Inicie o console groovy digitando: groovyConsole */ -- cgit v1.2.3 From ffd1fed725668b48ec8c11cbe419bd1e8d136ae3 Mon Sep 17 00:00:00 2001 From: Fer Date: Tue, 1 Oct 2019 12:06:10 -0300 Subject: Update markdown-pt.html.markdown Translation adjustments --- pt-br/markdown-pt.html.markdown | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown index f22093f9..53049c13 100644 --- a/pt-br/markdown-pt.html.markdown +++ b/pt-br/markdown-pt.html.markdown @@ -11,17 +11,17 @@ filename: learnmarkdown-pt.md Markdown foi criado por John Gruber in 2004. Originado para ser fácil de ler e escrever sintaxe que converte facilmente em HTML (hoje, suporta outros formatos também). -Dê-me feedback tanto quanto você quiser! / Sinta-se livre para a garfar (fork) e +Dê-me feedback tanto quanto você quiser! / Sinta-se livre para fazer uma bifurcação (fork) e puxar o projeto (pull request) ```markdown +de marcação. No entanto, se você criar um elemento HTML em seu arquivo Markdown, você +não pode usar sintaxe de marcação dentro desse conteúdo do elemento.--> - @@ -77,19 +77,20 @@ Termino com dois espaços (destacar-me para vê-los). Há um
acima de mim! - - + + > Este é um bloco de citação. Você pode -> Enrolar manualmente suas linhas e colocar um `>` antes de cada linha ou você pode -> deixar suas linhas ficarem muito longas e enrolar por conta própria. Não faz diferença, +> Quebrar manualmente suas linhas e colocar um `>` antes de cada linha ou você pode +> deixar suas linhas ficarem muito longas e quebrarem por conta própria. Não faz diferença, > desde que eles começam com um `>`. + > Você também pode usar mais de um nível >> De recuo? > Como pura é isso? - + * Item * Item @@ -113,8 +114,8 @@ ou 2. Item dois 3. Tem três - + 1. Item um 1. Item dois @@ -137,14 +138,14 @@ uma linha com quatro espaços ou uma guia --> Isto é código É assim, sacou? - my_array.each do |item| puts item end - + John não sabia nem o que o função 'goto()' fazia! @@ -155,13 +156,13 @@ ruby! --> def foobar puts "Hello world!" end -\`\`\` +\`\`\` <-- O texto acima não requer recuo, mas o GitHub vai usar a sintaxe destacando do idioma que você especificar após a ``` --> - *** @@ -175,7 +176,7 @@ o texto a ser exibido entre parênteses rígidos [] seguido pela url em parênte [Click aqui!](http://test.com/) - + [Click aqui!](http://test.com/ "Link para Test.com") -- cgit v1.2.3 From 1e17f8e3c7c3e7c3bf287af242dc4311f5cda615 Mon Sep 17 00:00:00 2001 From: Antonio Roberto Furlaneto Date: Tue, 1 Oct 2019 12:07:14 -0300 Subject: [csharp/pt-br] Missing translation --- 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 2ff59296..3bdbcdb1 100644 --- a/pt-br/csharp-pt.html.markdown +++ b/pt-br/csharp-pt.html.markdown @@ -85,8 +85,8 @@ namespace Learning.CSharp // Long - 64-bit integer long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) - // Numbers default to being int or uint depending on size. - // L is used to denote that this variable value is of type long or ulong + // Números por padrão são int ou uint dependendo do tamanho. + // L é usado para denotar que o valor da variável é do tipo long ou ulong. // Double - Double-precision 64-bit IEEE 754 Floating Point double fooDouble = 123.4; // Precision: 15-16 digits -- cgit v1.2.3 From 1ccbe647ede9c36aa1d789811826e43341b7911f Mon Sep 17 00:00:00 2001 From: Victor Bastos Date: Tue, 1 Oct 2019 12:10:38 -0300 Subject: [typescript/pt-br] Small typo --- pt-br/typescript-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/typescript-pt.html.markdown b/pt-br/typescript-pt.html.markdown index 077aa2cc..e8ed6a7f 100644 --- a/pt-br/typescript-pt.html.markdown +++ b/pt-br/typescript-pt.html.markdown @@ -22,7 +22,7 @@ var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -// Quando é impossível saber, há o "Qualquer" tipo +// Quando é impossível saber, há o tipo "Qualquer" var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // Ok, definitivamente um boolean @@ -65,7 +65,7 @@ interface Person { move(): void; } -// Objeto que implementa a "Pessoa" Interface +// Objeto que implementa a Interface "Pessoa" // Pode ser tratado como uma pessoa desde que tem o nome e mover propriedades var p: Person = { name: "Bobby", move: () => {} }; // Os objetos que têm a propriedade opcional: -- cgit v1.2.3 From 0e5203510bcd6500d707e0a03f30cb9f90b93cac Mon Sep 17 00:00:00 2001 From: Fer Date: Tue, 1 Oct 2019 12:16:59 -0300 Subject: [css/pt-br] Translation adjustments --- pt-br/css-pt.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown index c73669d0..1c4be746 100644 --- a/pt-br/css-pt.html.markdown +++ b/pt-br/css-pt.html.markdown @@ -14,15 +14,15 @@ translators: lang: pt-br --- -Nos primeiros dias da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornou comum. +No início da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornara comum. -CSS ajuda a manter a separação entre o conteúdo (HTML) e o look-and-feel de uma página web. +CSS ajuda a manter a separação entre o conteúdo (HTML) e o visual de uma página web. CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles. -Este guia foi escrito para CSS2, embora CSS3 está rapidamente se tornando popular. +Este guia foi escrito para CSS2, embora CSS3 esteja rapidamente se tornando popular. -**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa tentar de tudo em um playground CSS como [dabblet](http://dabblet.com/). +**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa treinar em um playground CSS como [dabblet](http://dabblet.com/). O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais. ```css @@ -42,7 +42,7 @@ Abaixo um elemento de exemplo:
*/ -/* Você pode direciona-lo usando uma das suas classes CSS */ +/* Você pode direcioná-lo usando uma das suas classes CSS */ .class1 { } /* ou ambas as classes! */ @@ -82,9 +82,9 @@ classe div.some [attr $ = 'ue'] {} /* Você pode selecionar um elemento que é filho de outro elemento */ div.some-parent> .class-name {} -/* Ou um descendente de um outro elemento. As crianças são os descendentes diretos de -   seu elemento pai, apenas um nível abaixo da árvore. Pode ser qualquer descendentes -   nivelar por baixo da árvore. */ +/* Ou um descendente de um outro elemento. Os filhos são os descendentes diretos de +   seu elemento pai, apenas um nível abaixo da árvore. Pode ser quaisquer descendentes +   nivelados por baixo da árvore. */ div.some-parent class-name {} /* Atenção: o mesmo seletor sem espaço tem um outro significado. @@ -118,7 +118,7 @@ seletor:first-child {} /* Qualquer elemento que é o último filho de seu pai */ seletor:last-child {} -/* Assim como pseudo classes, pseudo elementos permitem que você estilo certas partes de um documento */ +/* Assim como pseudo classes, pseudo elementos permitem que você estilize certas partes de um documento */ /* Corresponde a um primeiro filho virtual do elemento selecionado */ seletor::before {} @@ -127,7 +127,7 @@ seletor::before {} seletor::after {} /* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos -   elemento */ +   os elementos */ * {} /* */ Todos os elementos .parent * {} /* */ todos os descendentes .parent> * {} /* */ todas as crianças @@ -181,7 +181,7 @@ seletor { ## Uso -Guardar uma folha de estilo CSS com a extensão `.css`. +Salvar uma folha de estilo CSS com a extensão `.css`. ```xml 1 list(filled_dict.keys()) TypeError: 'list' object is not callable ``` solution: use another variable name instead of list --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 430927a9..8ef53ad1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -466,8 +466,8 @@ prints: 1 cat 2 mouse """ -list = ["dog", "cat", "mouse"] -for i, value in enumerate(list): +animals = ["dog", "cat", "mouse"] +for i, value in enumerate(animals): print(i, value) """ -- cgit v1.2.3 From cdf90f01bedc085c257ebaea3485c89c1fa071ab Mon Sep 17 00:00:00 2001 From: Andre Polykanine Date: Sat, 5 Oct 2019 19:09:59 +0300 Subject: [sql/ru] Fix translation --- ru-ru/sql-ru.html.markdown | 89 +++++++++++++++++++++++++++------------------- 1 file changed, 53 insertions(+), 36 deletions(-) diff --git a/ru-ru/sql-ru.html.markdown b/ru-ru/sql-ru.html.markdown index 64b7ab71..7353a175 100644 --- a/ru-ru/sql-ru.html.markdown +++ b/ru-ru/sql-ru.html.markdown @@ -5,25 +5,41 @@ contributors: - ["Bob DuCharme", "http://bobdc.com/"] translators: - ["Shaltaev", "https://github.com/shaltaev"] + - ["Andre Polykanine", "https://github.com/Menelion"] lang: ru-ru --- -Язык структурированных запросов (SQL) - это стандартный язык ISO для создания и работы с базами данных, хранящимися в наборе таблиц. Реализации обычно добавляют свои собственные расширения к языку; [Сравнение различных реализаций SQL](http://troels.arvin.dk/db/rdbms/) хороший справочник по различиям в продуктах. - -Реализации обычно предоставляют приглашение командной строки, где вы можете вводить команды (описанные ниже) в интерактивном режиме, также есть способ выполнить серию этих команд, сохраненных в файле сценария. (Результат того, что вы сделали с помощью интерактивного режима, является хорошим примером того, что не стандартизировано - большинство реализаций SQL поддерживают ключевые слова QUIT, EXIT или оба.) - -Некоторый команды ниже предполагают использование [демонстрационный образец базы данных сотрудников от MySQL](https://dev.mysql.com/doc/employee/en/) доступный на [github](https://github.com/datacharmer/test_db) следовательно для повторения команд в локальном окружении он должен быть загружен. Файлы и скрипты на github, схожи с командами ниже, которые манипулируют базами, таблицами и данными. Синтаксис для запуска этих сценариев будет зависеть от используемой вами реализации SQL. Способ запуска из командной строки обычный для вашей операционной системе. +Язык структурированных запросов (SQL) — это стандартный язык ISO для создания +и работы с базами данных, хранящимися в наборе таблиц. Реализации обычно +добавляют свои собственные расширения к языку; +[Сравнение различных реализаций SQL](http://troels.arvin.dk/db/rdbms/) — хороший справочник по различиям в продуктах. + +Реализации обычно предоставляют приглашение командной строки, где вы можете +вводить команды, описанные ниже, в интерактивном режиме, также есть способ +выполнить серию таких команд, сохранённых в файле скрипта. +(Результат того, что вы сделали с помощью интерактивного режима, является +хорошим примером того, что не стандартизировано, — большинство реализаций SQL +поддерживают ключевые слова QUIT, EXIT или оба). + +Некоторые команды ниже предполагают использование +[демонстрационного образца базы данных сотрудников от MySQL](https://dev.mysql.com/doc/employee/en/), доступного на [Github](https://github.com/datacharmer/test_db). +Следовательно, для повторения команд в локальном окружении он должен быть загружен. +Файлы на github — это скрипты с командами, которые схожи с командами ниже, +которые создают и манипулируют таблицами и данными о сотрудниках вымышленной +компании. Синтаксис для запуска этих скриптов будет зависеть от используемой +вами реализации SQL. Обычно используется утилита, запускаемая из командной +строки в вашей операционной системе. ```sql --- Комментарии начинаются с двух дефисов. Завершите каждую команду +-- Комментарии начинаются с двух дефисов. Завершайте каждую команду -- точкой с запятой. --- SQL не учитывает регистр ключевых слов. Образцы команд здесь --- следуйте соглашению о написании их в верхнем регистре, потому что --- это позволяет легче их отличить от имен баз, таблиц и колонок. +-- SQL не учитывает регистр букв для ключевых слов. Примеры команд здесь +-- следуют соглашению о написании в верхнем регистре, потому что +-- это позволяет легче отличить их от имён баз, таблиц и колонок. -- Создание и удаление базы данных. Имена базы и таблицы чувствительны --- к регистру. +-- к регистру букв. CREATE DATABASE someDatabase; DROP DATABASE someDatabase; @@ -33,71 +49,72 @@ SHOW DATABASES; -- Выбор базы для работы. USE employees; --- Выбрать все колонки и строки из таблицы текущей базы. --- В интерактивном режиме обычно результат будет выведен на экран. +-- Выбрать все строки и колонки из таблицы «departments» (отделы) текущей базы. +-- В интерактивном режиме обыч но результат будет выведен на экран. SELECT * FROM departments; --- Тот же запрос что и вышеБ но выбор только колонок dept_no и dept_name. +-- Тот же запрос, что и выше, но выбор только колонок «dept_no» и «dept_name». -- Разбиение команд на несколько строк допустимо. SELECT dept_no, dept_name FROM departments; --- В данном случае будут выбраны только первые 5 результатов. +-- В данном случае будут выбраны все колонки, но только первые 5 строк. SELECT * FROM departments LIMIT 5; --- Выбор имен депортаментов где имена содержат в себе 'en'. +-- Выбор названий отделов, содержащих подстроку «en». SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; --- Выбор всех колонок где имена начинаются 'S' и 4 любых символа после. +-- Выбор всех колонок, где названия отделов начинаются на «S», +-- после которой идёт ровно четыре символа. SELECT * FROM departments WHERE dept_name LIKE 'S____'; --- Выбор всех должностей, но без повторений. +-- Выбор всех должностей из таблицы «titles», но без повторений. SELECT DISTINCT title FROM titles; -- В дополнение к предыдущему запросу результат будет отсортирован --- в алфавитном порядке (С учетом регистра). +-- в алфавитном порядке (с учётом регистра). SELECT DISTINCT title FROM titles ORDER BY title; --- Вычислить количество строк в таблице депортамента. +-- Показать число строк в таблице отделов. SELECT COUNT(*) FROM departments; --- Вычислить количество строк где имя депортамента содержит 'en' --- в любой части имени. +-- Показать число строк, где название отдела содержит подстроку «en» SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; --- ОБЪЕДИНЕНИЕ информации из нескольких таблиц: должность, когда ее занимал, --- имя и фамилия сотрудника, объединить по идентификатору сотрудника --- вывести только 10 строк. - +-- Объединение информации из нескольких таблиц: +-- В таблице «titles» перечислены должности, кто их занимал по номеру сотрудника, +-- а также с какой даты по какую. Получим эту информацию, но используем номера +-- сотрудников как ссылку на таблицу «employees», чтобы получить имя и фамилию +-- каждого сотрудника. Выводим только 10 строк. SELECT employees.first_name, employees.last_name, titles.title, titles.from_date, titles.to_date FROM titles INNER JOIN employees ON employees.emp_no = titles.emp_no LIMIT 10; -- Список всех таблиц во всех базах. Реализации обычно предоставляют --- их собственные сокращения чтобы сделать это для текущей базы. +-- собственные сокращения, чтобы показать все таблицы текущей базы. SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'; --- Создать таблицу с именем tablename1, с двумя колонками, для колонок --- доступно множество опций вроде типа и других, конкретнее уточняйте для --- своей реализации. +-- Создать таблицу с именем tablename1 и двумя колонками в текущей базе. +-- Для колонок имеется множество параметров, таких как тип данных. CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); --- Вставляем строку в таблице созданную в предыдущем запросе . +-- Вставляем строку данных в таблицу «tablename1». Предполагаем, что таблица +-- настроена таким образом, чтобы принимать эти значения. INSERT INTO tablename1 VALUES('Richard','Mutt'); --- В tablename1, изменить значение fname на 'John' --- для каждой строки где lname имеет значение 'Mutt'. +-- В таблице «tablename1» изменить значение fname на «John» +-- для каждой строки, где колонка lname равна «Mutt». UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; --- Удалить строки из таблицы tablename1 --- где lname начинается с 'M'. +-- Удалить из таблицы «tablename1» строки, +-- где значение колонки lname начинается с «M». DELETE FROM tablename1 WHERE lname like 'M%'; --- Удалить все строки из таблицы tablename1, в итоге получим пустую таблицу. +-- Удалить все строки из таблицы «tablename1». В итоге получим пустую таблицу. DELETE FROM tablename1; --- Удалить таблицу tablename1. +-- Удалить таблицу «tablename1» полностью. DROP TABLE tablename1; ``` -- cgit v1.2.3 From bcefaaf7b7048f07bb27a4aa920a43e242141c3d Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sat, 5 Oct 2019 21:19:37 +0200 Subject: Add explanation of `=~` and `alias` inside bash/it-it --- it-it/bash-it.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index efc47969..099cc681 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -140,6 +140,25 @@ then echo "Questo verrà eseguito se $Nome è Daniya O Zach." fi +# C'è anche l'operatore `=~`, che serve per confrontare una stringa con un'espressione regolare: +Email=me@example.com +if [[ "$Email" =~ [a-z]+@[a-z]{2,}\.(com|net|org) ]] +then + echo "Email valida!" +fi +# L'operatore =~ funziona solo dentro alle doppie parentesi quadre [[ ]], +# che hanno un comportamento leggermente diverso rispetto alle singole [ ]. +# Se vuoi approfondire, visita questo link (in inglese): +# http://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs + +# Usando `alias`, puoi definire nuovi comandi o modificare quelli già esistenti. +# Ad esempio, così puoi ridefinire il comando ping per inviare solo 5 pacchetti +alias ping='ping -c 5' +# "Scavalca" l'alias e usa il comando vero, utilizzando il backslash +\ping 192.168.1.1 +# Stampa la lista di tutti gli alias +alias -p + # Le espressioni sono nel seguente formato: echo $(( 10 + 5 )) -- cgit v1.2.3 From b7a5d8f8e085383f198c090e35bddf8936219786 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sat, 5 Oct 2019 21:30:24 +0200 Subject: Add section about pipes, and fix docs here and there for elixir/it-it --- it-it/elixir-it.html.markdown | 52 +++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown index 60301b1a..48afe0c8 100644 --- a/it-it/elixir-it.html.markdown +++ b/it-it/elixir-it.html.markdown @@ -24,7 +24,7 @@ e molte altre funzionalità. # Per usare la shell di elixir usa il comando `iex`. # Compila i tuoi moduli con il comando `elixirc`. -# Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato +# Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato # elixir correttamente. ## --------------------------- @@ -65,7 +65,7 @@ coda #=> [2,3] # le tuple hanno dimensione differente. # {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} -# Ci sono anche i binari +# Ci sono anche i binari <<1,2,3>> # binari (Binary) # Stringhe e liste di caratteri @@ -80,7 +80,7 @@ multi-linea. #=> "Sono una stringa\nmulti-linea.\n" # Le stringhe sono tutte codificate in UTF-8: -"cìaò" +"cìaò" #=> "cìaò" # le stringhe in realtà sono dei binari, e le liste di caratteri sono liste. @@ -124,10 +124,11 @@ rem(10, 3) #=> 1 # Questi operatori si aspettano un booleano come primo argomento. true and true #=> true false or true #=> true -# 1 and true #=> ** (ArgumentError) argument error +# 1 and true +#=> ** (BadBooleanError) expected a boolean on left-side of "and", got: 1 # Elixir fornisce anche `||`, `&&` e `!` che accettano argomenti -# di qualsiasi tipo. +# di qualsiasi tipo. # Tutti i valori tranne `false` e `nil` saranno valutati come true. 1 || true #=> 1 false && 1 #=> false @@ -147,7 +148,7 @@ nil && 20 #=> nil 1 < :ciao #=> true # L'ordine generale è definito sotto: -# numeri < atomi < riferimenti < funzioni < porte < pid < tuple < liste +# numeri < atomi < riferimenti < funzioni < porte < pid < tuple < liste # < stringhe di bit # Per citare Joe Armstrong su questo: "L'ordine non è importante, @@ -171,7 +172,7 @@ else "Questo sì" end -# Ti ricordi il pattern matching? +# Ti ricordi il pattern matching? # Moltre strutture di controllo di flusso in elixir si basano su di esso. # `case` ci permette di confrontare un valore a diversi pattern: @@ -214,7 +215,7 @@ cond do "Questa sì! (essenzialmente funziona come un else)" end -# `try/catch` si usa per gestire i valori lanciati (throw), +# `try/catch` si usa per gestire i valori lanciati (throw), # Supporta anche una clausola `after` che è invocata in ogni caso. try do throw(:ciao) @@ -235,7 +236,7 @@ quadrato = fn(x) -> x * x end quadrato.(5) #=> 25 # Accettano anche guardie e condizioni multiple. -# le guardie ti permettono di perfezionare il tuo pattern matching, +# le guardie ti permettono di perfezionare il tuo pattern matching, # sono indicate dalla parola chiave `when`: f = fn x, y when x > 0 -> x + y @@ -265,13 +266,13 @@ end Matematica.somma(1, 2) #=> 3 Matematica.quadrato(3) #=> 9 -# Per compilare il modulo 'Matematica' salvalo come `matematica.ex` e usa +# Per compilare il modulo 'Matematica' salvalo come `matematica.ex` e usa # `elixirc`. # nel tuo terminale: elixirc matematica.ex # All'interno di un modulo possiamo definire le funzioni con `def` e funzioni # private con `defp`. -# Una funzione definita con `def` è disponibile per essere invocata anche da +# Una funzione definita con `def` è disponibile per essere invocata anche da # altri moduli, una funziona privata può essere invocata solo localmente. defmodule MatematicaPrivata do def somma(a, b) do @@ -286,7 +287,11 @@ end MatematicaPrivata.somma(1, 2) #=> 3 # MatematicaPrivata.esegui_somma(1, 2) #=> ** (UndefinedFunctionError) -# Anche le dichiarazioni di funzione supportano guardie e condizioni multiple: +# Anche le dichiarazioni di funzione supportano guardie e condizioni multiple. +# Quando viene chiamata una funzione dichiarata con più match, solo la prima +# che matcha viene effettivamente invocata. +# Ad esempio: chiamando area({:cerchio, 3}) vedrà invocata la seconda definizione +# di area mostrata sotto, non la prima: defmodule Geometria do def area({:rettangolo, w, h}) do w * h @@ -322,16 +327,25 @@ defmodule Modulo do Questo è un attributo incorporato in un modulo di esempio. """ - @miei_dati 100 # Questo è un attributo personalizzato . + @miei_dati 100 # Questo è un attributo personalizzato. IO.inspect(@miei_dati) #=> 100 end +# L'operatore pipe |> permette di passare l'output di una espressione +# come primo parametro di una funzione. +# Questo facilita operazioni quali pipeline di operazioni, composizione di +# funzioni, ecc. +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] + ## --------------------------- ## -- Strutture ed Eccezioni ## --------------------------- -# Le Strutture (Structs) sono estensioni alle mappe che portano +# Le Strutture (Structs) sono estensioni alle mappe che portano # valori di default, garanzia alla compilazione e polimorfismo in Elixir. defmodule Persona do defstruct nome: nil, eta: 0, altezza: 0 @@ -367,7 +381,7 @@ end ## -- Concorrenza ## --------------------------- -# Elixir si basa sul modello degli attori per la concorrenza. +# Elixir si basa sul modello degli attori per la concorrenza. # Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in elixir # sono tre primitive: creare processi, inviare messaggi e ricevere messaggi. @@ -379,12 +393,12 @@ spawn(f) #=> #PID<0.40.0> # `spawn` restituisce un pid (identificatore di processo). Puoi usare questo # pid per inviare messaggi al processo. # Per passare messaggi si usa l'operatore `send`. -# Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi, +# Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi, # oltre ad inviarli. Questo è realizzabile con `receive`: # Il blocco `receive do` viene usato per mettersi in ascolto di messaggi # ed elaborarli quando vengono ricevuti. Un blocco `receive do` elabora -# un solo messaggio ricevuto: per fare elaborazione multipla di messaggi, +# un solo messaggio ricevuto: per fare elaborazione multipla di messaggi, # una funzione con un blocco `receive do` al suo intero dovrà chiamare # ricorsivamente sé stessa per entrare di nuovo nel blocco `receive do`. defmodule Geometria do @@ -405,7 +419,7 @@ pid = spawn(fn -> Geometria.calcolo_area() end) #=> #PID<0.40.0> # Alternativamente pid = spawn(Geometria, :calcolo_area, []) -# Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive +# Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive send pid, {:rettangolo, 2, 3} #=> Area = 6 # {:rettangolo,2,3} @@ -421,7 +435,7 @@ self() #=> #PID<0.27.0> ## Referenze * [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di elixir](http://elixir-lang.org) -* [Documentazione Elixir](http://elixir-lang.org/docs/master/) +* [Documentazione Elixir](https://elixir-lang.org/docs.html) * ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) di Dave Thomas * [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) * ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) di Fred Hebert -- cgit v1.2.3 From 4fafc4a432ff9008db111d5f269464d5c67ce5a5 Mon Sep 17 00:00:00 2001 From: Oleh Hromiak Date: Mon, 7 Oct 2019 17:18:34 +0300 Subject: Add [wasm/uk-ua] and update name in [python/uk-ua] --- uk-ua/python-ua.html.markdown | 2 +- uk-ua/wasm.html.markdown | 225 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 uk-ua/wasm.html.markdown diff --git a/uk-ua/python-ua.html.markdown b/uk-ua/python-ua.html.markdown index 23bc1796..4091e433 100644 --- a/uk-ua/python-ua.html.markdown +++ b/uk-ua/python-ua.html.markdown @@ -9,7 +9,7 @@ contributors: - ["asyne", "https://github.com/justblah"] - ["habi", "http://github.com/habi"] translators: - - ["Oleg Gromyak", "https://github.com/ogroleg"] + - ["Oleh Hromiak", "https://github.com/ogroleg"] filename: learnpython-ua.py --- diff --git a/uk-ua/wasm.html.markdown b/uk-ua/wasm.html.markdown new file mode 100644 index 00000000..b5a1f4dd --- /dev/null +++ b/uk-ua/wasm.html.markdown @@ -0,0 +1,225 @@ +--- +language: WebAssembly +filename: learnwasm-ua.wast +contributors: + - ["Dean Shaff", "http://dean-shaff.github.io"] +translators: + - ["Oleh Hromiak", "https://github.com/ogroleg"] +--- + +``` +;; learnwasm-ua.wast + +(module + ;; У WebAssembly весь код знаходиться в модулях. Будь-яка операція + ;; може бути записана за допомогою s-виразу. Також існує синтаксис "стек машини", + ;; втім, він не сумісний з проміжним бінарним представленням коду. + + ;; Формат бінарного проміжного представлення майже повністю сумісний + ;; з текстовим форматом WebAssembly. + ;; Деякі відмінності: + ;; local_set -> local.set + ;; local_get -> local.get + + ;; Код розміщується у функціях + + ;; Типи даних + (func $data_types + ;; WebAssembly має чотири типи даних: + ;; i32 - ціле число, 32 біти + ;; i64 - ціле число, 64 біти (не підтримується у JavaScript) + ;; f32 - число з плаваючою комою, 32 біти + ;; f64 - число з плаваючою комою, 64 біти + + ;; Створити локальну змінну можна за допомогою ключового слова "local". + ;; Змінні потрібно оголошувати на початку функції. + + (local $int_32 i32) + (local $int_64 i64) + (local $float_32 f32) + (local $float_64 f64) + + ;; Змінні, оголошені вище, ще не ініціалізовані, себто, не мають значення. + ;; Давайте присвоїмо їм значення за допомогою <тип даних>.const: + + (local.set $int_32 (i32.const 16)) + (local.set $int_32 (i64.const 128)) + (local.set $float_32 (f32.const 3.14)) + (local.set $float_64 (f64.const 1.28)) + ) + + ;; Базові операції + (func $basic_operations + + ;; Нагадаємо, у WebAssembly будь-що є s-виразом, включно + ;; з математичними виразами або зчитуванням значень змінних + + (local $add_result i32) + (local $mult_result f64) + + (local.set $add_result (i32.add (i32.const 2) (i32.const 4))) + ;; тепер add_result дорівнює 6! + + ;; Для кожної операції потрібно використовувати правильний тип: + ;; (local.set $mult_result (f32.mul (f32.const 2.0) (f32.const 4.0))) ;; Ніт! mult_result має тип f64! + (local.set $mult_result (f64.mul (f64.const 2.0) (f64.const 4.0))) ;; Ніт! mult_result має тип f64! + + ;; У WebAssembly є вбудовані функції накшталт математики та побітових операцій. + ;; Варто зазначити, що тут відсутні вбудовані тригонометричні функції. + ;; Тож нам потрібно: + ;; - написати їх самостійно (не найкраща ідея) + ;; - звідкись їх імпортувати (як саме - побачимо згодом) + ) + + ;; Функції + ;; Параметри вказуються ключовим словом `param`, значення, що повертається - `result` + ;; Поточне значення стеку і є значенням функції, що повертається + + ;; Ми можемо викликати інші функції за допомогою `call` + + (func $get_16 (result i32) + (i32.const 16) + ) + + (func $add (param $param0 i32) (param $param1 i32) (result i32) + (i32.add + (local.get $param0) + (local.get $param1) + ) + ) + + (func $double_16 (result i32) + (i32.mul + (i32.const 2) + (call $get_16)) + ) + + ;; Досі ми не могли що-небудь вивести на консоль і не мали доступу + ;; до високорівневої математики (степеневі функції, обрахунок експоненти або тригонометрія). + ;; Більше того, ми навіть не могли викликати WASM функції у Javascript! + ;; Виклик цих функцій у WebAssembly залежить від того, + ;; де ми знаходимось - чи це Node.js, чи середовище браузера. + + ;; Якщо ми у Node.js, то потрібно виконати два кроки. По-перше, ми маємо сконвертувати + ;; текстове представлення WASM у справжній код webassembly. + ;; Наприклад, ось так (Binaryen): + + ;; wasm-as learn-wasm.wast -o learn-wasm.wasm + + ;; Давай також застосуємо оптимізації: + + ;; wasm-opt learn-wasm.wasm -o learn-wasm.opt.wasm -O3 --rse + + ;; Тепер наш скомпільований WebAssembly можна завантажити у Node.js: + ;; const fs = require('fs') + ;; const instantiate = async function (inFilePath, _importObject) { + ;; var importObject = { + ;; console: { + ;; log: (x) => console.log(x), + ;; }, + ;; math: { + ;; cos: (x) => Math.cos(x), + ;; } + ;; } + ;; importObject = Object.assign(importObject, _importObject) + ;; + ;; var buffer = fs.readFileSync(inFilePath) + ;; var module = await WebAssembly.compile(buffer) + ;; var instance = await WebAssembly.instantiate(module, importObject) + ;; return instance.exports + ;; } + ;; + ;; const main = function () { + ;; var wasmExports = await instantiate('learn-wasm.wasm') + ;; wasmExports.print_args(1, 0) + ;; } + + ;; Цей код зчитує функції з importObject + ;; (вказано у асинхронній JavaScript функції instantiate), а потім експортує функцію + ;; "print_args", яку ми викликаємо у Node.js + + (import "console" "log" (func $print_i32 (param i32))) + (import "math" "cos" (func $cos (param f64) (result f64))) + + (func $print_args (param $arg0 i32) (param $arg1 i32) + (call $print_i32 (local.get $arg0)) + (call $print_i32 (local.get $arg1)) + ) + (export "print_args" (func $print_args)) + + ;; Завантаження даних з пам'яті WebAssembly. + ;; Наприклад, ми хочемо порахувати cos для елементів Javascript масиву. + ;; Нам потрібно отримати доступ до масиву і можливість ітерувати по ньому. + ;; У прикладі нижче ми змінимо існуючий масив. + ;; f64.load і f64.store приймають адресу числа у пам'яті *у байтах*. + ;; Для того, щоб отримати доступ до 3-го елементу масиву, ми маємо передати щось + ;; накшталт (i32.mul (i32.const 8) (i32.const 2)) у функцію f64.store. + + ;; У JavaScript ми викличемо `apply_cos64` таким чином + ;; (використаємо функцію instantiate з попереднього прикладу): + ;; + ;; const main = function () { + ;; var wasm = await instantiate('learn-wasm.wasm') + ;; var n = 100 + ;; const memory = new Float64Array(wasm.memory.buffer, 0, n) + ;; for (var i=0; i Date: Mon, 7 Oct 2019 22:35:03 +0300 Subject: Fix [wasm/ua] filename --- uk-ua/wasm-ua.html.markdown | 225 ++++++++++++++++++++++++++++++++++++++++++++ uk-ua/wasm.html.markdown | 225 -------------------------------------------- 2 files changed, 225 insertions(+), 225 deletions(-) create mode 100644 uk-ua/wasm-ua.html.markdown delete mode 100644 uk-ua/wasm.html.markdown diff --git a/uk-ua/wasm-ua.html.markdown b/uk-ua/wasm-ua.html.markdown new file mode 100644 index 00000000..b5a1f4dd --- /dev/null +++ b/uk-ua/wasm-ua.html.markdown @@ -0,0 +1,225 @@ +--- +language: WebAssembly +filename: learnwasm-ua.wast +contributors: + - ["Dean Shaff", "http://dean-shaff.github.io"] +translators: + - ["Oleh Hromiak", "https://github.com/ogroleg"] +--- + +``` +;; learnwasm-ua.wast + +(module + ;; У WebAssembly весь код знаходиться в модулях. Будь-яка операція + ;; може бути записана за допомогою s-виразу. Також існує синтаксис "стек машини", + ;; втім, він не сумісний з проміжним бінарним представленням коду. + + ;; Формат бінарного проміжного представлення майже повністю сумісний + ;; з текстовим форматом WebAssembly. + ;; Деякі відмінності: + ;; local_set -> local.set + ;; local_get -> local.get + + ;; Код розміщується у функціях + + ;; Типи даних + (func $data_types + ;; WebAssembly має чотири типи даних: + ;; i32 - ціле число, 32 біти + ;; i64 - ціле число, 64 біти (не підтримується у JavaScript) + ;; f32 - число з плаваючою комою, 32 біти + ;; f64 - число з плаваючою комою, 64 біти + + ;; Створити локальну змінну можна за допомогою ключового слова "local". + ;; Змінні потрібно оголошувати на початку функції. + + (local $int_32 i32) + (local $int_64 i64) + (local $float_32 f32) + (local $float_64 f64) + + ;; Змінні, оголошені вище, ще не ініціалізовані, себто, не мають значення. + ;; Давайте присвоїмо їм значення за допомогою <тип даних>.const: + + (local.set $int_32 (i32.const 16)) + (local.set $int_32 (i64.const 128)) + (local.set $float_32 (f32.const 3.14)) + (local.set $float_64 (f64.const 1.28)) + ) + + ;; Базові операції + (func $basic_operations + + ;; Нагадаємо, у WebAssembly будь-що є s-виразом, включно + ;; з математичними виразами або зчитуванням значень змінних + + (local $add_result i32) + (local $mult_result f64) + + (local.set $add_result (i32.add (i32.const 2) (i32.const 4))) + ;; тепер add_result дорівнює 6! + + ;; Для кожної операції потрібно використовувати правильний тип: + ;; (local.set $mult_result (f32.mul (f32.const 2.0) (f32.const 4.0))) ;; Ніт! mult_result має тип f64! + (local.set $mult_result (f64.mul (f64.const 2.0) (f64.const 4.0))) ;; Ніт! mult_result має тип f64! + + ;; У WebAssembly є вбудовані функції накшталт математики та побітових операцій. + ;; Варто зазначити, що тут відсутні вбудовані тригонометричні функції. + ;; Тож нам потрібно: + ;; - написати їх самостійно (не найкраща ідея) + ;; - звідкись їх імпортувати (як саме - побачимо згодом) + ) + + ;; Функції + ;; Параметри вказуються ключовим словом `param`, значення, що повертається - `result` + ;; Поточне значення стеку і є значенням функції, що повертається + + ;; Ми можемо викликати інші функції за допомогою `call` + + (func $get_16 (result i32) + (i32.const 16) + ) + + (func $add (param $param0 i32) (param $param1 i32) (result i32) + (i32.add + (local.get $param0) + (local.get $param1) + ) + ) + + (func $double_16 (result i32) + (i32.mul + (i32.const 2) + (call $get_16)) + ) + + ;; Досі ми не могли що-небудь вивести на консоль і не мали доступу + ;; до високорівневої математики (степеневі функції, обрахунок експоненти або тригонометрія). + ;; Більше того, ми навіть не могли викликати WASM функції у Javascript! + ;; Виклик цих функцій у WebAssembly залежить від того, + ;; де ми знаходимось - чи це Node.js, чи середовище браузера. + + ;; Якщо ми у Node.js, то потрібно виконати два кроки. По-перше, ми маємо сконвертувати + ;; текстове представлення WASM у справжній код webassembly. + ;; Наприклад, ось так (Binaryen): + + ;; wasm-as learn-wasm.wast -o learn-wasm.wasm + + ;; Давай також застосуємо оптимізації: + + ;; wasm-opt learn-wasm.wasm -o learn-wasm.opt.wasm -O3 --rse + + ;; Тепер наш скомпільований WebAssembly можна завантажити у Node.js: + ;; const fs = require('fs') + ;; const instantiate = async function (inFilePath, _importObject) { + ;; var importObject = { + ;; console: { + ;; log: (x) => console.log(x), + ;; }, + ;; math: { + ;; cos: (x) => Math.cos(x), + ;; } + ;; } + ;; importObject = Object.assign(importObject, _importObject) + ;; + ;; var buffer = fs.readFileSync(inFilePath) + ;; var module = await WebAssembly.compile(buffer) + ;; var instance = await WebAssembly.instantiate(module, importObject) + ;; return instance.exports + ;; } + ;; + ;; const main = function () { + ;; var wasmExports = await instantiate('learn-wasm.wasm') + ;; wasmExports.print_args(1, 0) + ;; } + + ;; Цей код зчитує функції з importObject + ;; (вказано у асинхронній JavaScript функції instantiate), а потім експортує функцію + ;; "print_args", яку ми викликаємо у Node.js + + (import "console" "log" (func $print_i32 (param i32))) + (import "math" "cos" (func $cos (param f64) (result f64))) + + (func $print_args (param $arg0 i32) (param $arg1 i32) + (call $print_i32 (local.get $arg0)) + (call $print_i32 (local.get $arg1)) + ) + (export "print_args" (func $print_args)) + + ;; Завантаження даних з пам'яті WebAssembly. + ;; Наприклад, ми хочемо порахувати cos для елементів Javascript масиву. + ;; Нам потрібно отримати доступ до масиву і можливість ітерувати по ньому. + ;; У прикладі нижче ми змінимо існуючий масив. + ;; f64.load і f64.store приймають адресу числа у пам'яті *у байтах*. + ;; Для того, щоб отримати доступ до 3-го елементу масиву, ми маємо передати щось + ;; накшталт (i32.mul (i32.const 8) (i32.const 2)) у функцію f64.store. + + ;; У JavaScript ми викличемо `apply_cos64` таким чином + ;; (використаємо функцію instantiate з попереднього прикладу): + ;; + ;; const main = function () { + ;; var wasm = await instantiate('learn-wasm.wasm') + ;; var n = 100 + ;; const memory = new Float64Array(wasm.memory.buffer, 0, n) + ;; for (var i=0; i local.set - ;; local_get -> local.get - - ;; Код розміщується у функціях - - ;; Типи даних - (func $data_types - ;; WebAssembly має чотири типи даних: - ;; i32 - ціле число, 32 біти - ;; i64 - ціле число, 64 біти (не підтримується у JavaScript) - ;; f32 - число з плаваючою комою, 32 біти - ;; f64 - число з плаваючою комою, 64 біти - - ;; Створити локальну змінну можна за допомогою ключового слова "local". - ;; Змінні потрібно оголошувати на початку функції. - - (local $int_32 i32) - (local $int_64 i64) - (local $float_32 f32) - (local $float_64 f64) - - ;; Змінні, оголошені вище, ще не ініціалізовані, себто, не мають значення. - ;; Давайте присвоїмо їм значення за допомогою <тип даних>.const: - - (local.set $int_32 (i32.const 16)) - (local.set $int_32 (i64.const 128)) - (local.set $float_32 (f32.const 3.14)) - (local.set $float_64 (f64.const 1.28)) - ) - - ;; Базові операції - (func $basic_operations - - ;; Нагадаємо, у WebAssembly будь-що є s-виразом, включно - ;; з математичними виразами або зчитуванням значень змінних - - (local $add_result i32) - (local $mult_result f64) - - (local.set $add_result (i32.add (i32.const 2) (i32.const 4))) - ;; тепер add_result дорівнює 6! - - ;; Для кожної операції потрібно використовувати правильний тип: - ;; (local.set $mult_result (f32.mul (f32.const 2.0) (f32.const 4.0))) ;; Ніт! mult_result має тип f64! - (local.set $mult_result (f64.mul (f64.const 2.0) (f64.const 4.0))) ;; Ніт! mult_result має тип f64! - - ;; У WebAssembly є вбудовані функції накшталт математики та побітових операцій. - ;; Варто зазначити, що тут відсутні вбудовані тригонометричні функції. - ;; Тож нам потрібно: - ;; - написати їх самостійно (не найкраща ідея) - ;; - звідкись їх імпортувати (як саме - побачимо згодом) - ) - - ;; Функції - ;; Параметри вказуються ключовим словом `param`, значення, що повертається - `result` - ;; Поточне значення стеку і є значенням функції, що повертається - - ;; Ми можемо викликати інші функції за допомогою `call` - - (func $get_16 (result i32) - (i32.const 16) - ) - - (func $add (param $param0 i32) (param $param1 i32) (result i32) - (i32.add - (local.get $param0) - (local.get $param1) - ) - ) - - (func $double_16 (result i32) - (i32.mul - (i32.const 2) - (call $get_16)) - ) - - ;; Досі ми не могли що-небудь вивести на консоль і не мали доступу - ;; до високорівневої математики (степеневі функції, обрахунок експоненти або тригонометрія). - ;; Більше того, ми навіть не могли викликати WASM функції у Javascript! - ;; Виклик цих функцій у WebAssembly залежить від того, - ;; де ми знаходимось - чи це Node.js, чи середовище браузера. - - ;; Якщо ми у Node.js, то потрібно виконати два кроки. По-перше, ми маємо сконвертувати - ;; текстове представлення WASM у справжній код webassembly. - ;; Наприклад, ось так (Binaryen): - - ;; wasm-as learn-wasm.wast -o learn-wasm.wasm - - ;; Давай також застосуємо оптимізації: - - ;; wasm-opt learn-wasm.wasm -o learn-wasm.opt.wasm -O3 --rse - - ;; Тепер наш скомпільований WebAssembly можна завантажити у Node.js: - ;; const fs = require('fs') - ;; const instantiate = async function (inFilePath, _importObject) { - ;; var importObject = { - ;; console: { - ;; log: (x) => console.log(x), - ;; }, - ;; math: { - ;; cos: (x) => Math.cos(x), - ;; } - ;; } - ;; importObject = Object.assign(importObject, _importObject) - ;; - ;; var buffer = fs.readFileSync(inFilePath) - ;; var module = await WebAssembly.compile(buffer) - ;; var instance = await WebAssembly.instantiate(module, importObject) - ;; return instance.exports - ;; } - ;; - ;; const main = function () { - ;; var wasmExports = await instantiate('learn-wasm.wasm') - ;; wasmExports.print_args(1, 0) - ;; } - - ;; Цей код зчитує функції з importObject - ;; (вказано у асинхронній JavaScript функції instantiate), а потім експортує функцію - ;; "print_args", яку ми викликаємо у Node.js - - (import "console" "log" (func $print_i32 (param i32))) - (import "math" "cos" (func $cos (param f64) (result f64))) - - (func $print_args (param $arg0 i32) (param $arg1 i32) - (call $print_i32 (local.get $arg0)) - (call $print_i32 (local.get $arg1)) - ) - (export "print_args" (func $print_args)) - - ;; Завантаження даних з пам'яті WebAssembly. - ;; Наприклад, ми хочемо порахувати cos для елементів Javascript масиву. - ;; Нам потрібно отримати доступ до масиву і можливість ітерувати по ньому. - ;; У прикладі нижче ми змінимо існуючий масив. - ;; f64.load і f64.store приймають адресу числа у пам'яті *у байтах*. - ;; Для того, щоб отримати доступ до 3-го елементу масиву, ми маємо передати щось - ;; накшталт (i32.mul (i32.const 8) (i32.const 2)) у функцію f64.store. - - ;; У JavaScript ми викличемо `apply_cos64` таким чином - ;; (використаємо функцію instantiate з попереднього прикладу): - ;; - ;; const main = function () { - ;; var wasm = await instantiate('learn-wasm.wasm') - ;; var n = 100 - ;; const memory = new Float64Array(wasm.memory.buffer, 0, n) - ;; for (var i=0; i Date: Tue, 8 Oct 2019 11:49:21 +0300 Subject: Fix [wasm/ua] lang param --- uk-ua/wasm-ua.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/uk-ua/wasm-ua.html.markdown b/uk-ua/wasm-ua.html.markdown index b5a1f4dd..34f8cef8 100644 --- a/uk-ua/wasm-ua.html.markdown +++ b/uk-ua/wasm-ua.html.markdown @@ -1,5 +1,6 @@ --- language: WebAssembly +lang: uk-ua filename: learnwasm-ua.wast contributors: - ["Dean Shaff", "http://dean-shaff.github.io"] -- cgit v1.2.3 From da2caced2209b7e60699790715ff84585864e37f Mon Sep 17 00:00:00 2001 From: Heitor Pascoal de Bittencourt Date: Tue, 8 Oct 2019 21:22:47 -0300 Subject: [c/en] Fix link for Learn C the Hard Way book --- c.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index 7975a1c2..e5ffc379 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -10,6 +10,7 @@ contributors: - ["himanshu", "https://github.com/himanshu81494"] - ["Joshua Li", "https://github.com/JoshuaRLi"] - ["Dragos B. Chirila", "https://github.com/dchirila"] + - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -820,7 +821,7 @@ Best to find yourself a copy of [K&R, aka "The C Programming Language"](https:// It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. -Another good resource is [Learn C The Hard Way](http://c.learncodethehardway.org/book/). +Another good resource is [Learn C The Hard Way](http://learncodethehardway.org/c/). If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com). -- cgit v1.2.3 From 97c80bff9e4c75d52ca7b7f4a3c3ce895863b00e Mon Sep 17 00:00:00 2001 From: Heitor Pascoal de Bittencourt Date: Tue, 8 Oct 2019 21:27:35 -0300 Subject: [c/es] Fix book link --- es-es/c-es.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 8bc1eabb..cae4349e 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adam Bard", "http://adambard.com/"] translators: - ["Francisco García", "http://flaskbreaker.tumblr.com/"] + - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"] lang: es-es --- @@ -423,7 +424,7 @@ libro de C, escrito por Dennis Ritchie, creador de C y Brian Kernighan. Aún as se cuidadoso, es antiguo, contiene algunas inexactitudes, y algunas prácticas han cambiado. -Otro buen recurso es [Learn C the hard way](http://c.learncodethehardway.org/book/). +Otro buen recurso es [Learn C the hard way](http://learncodethehardway.org/c/). Si tienes una pregunta, lee [compl.lang.c Frequently Asked Questions](http://c-faq.com). -- cgit v1.2.3 From b06385dd128cec36143853efacf7e9fac0bf9b1f Mon Sep 17 00:00:00 2001 From: Heitor Pascoal de Bittencourt Date: Tue, 8 Oct 2019 21:28:45 -0300 Subject: [c/tr] Fix book link --- tr-tr/c-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 6042a609..4ef12527 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -477,7 +477,7 @@ typedef void (*my_fnp_type)(char *); [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)'in bir kopyasını bulundurmak mükemmel olabilir -Diğer bir iyi kaynak ise [Learn C the hard way](http://c.learncodethehardway.org/book/) +Diğer bir iyi kaynak ise [Learn C the hard way](http://learncodethehardway.org/c/) It's very important to use proper spacing, indentation and to be consistent with your coding style in general. Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the -- cgit v1.2.3 From c643189c0f792402237d253dcf4110f4f69b09d6 Mon Sep 17 00:00:00 2001 From: Heitor Pascoal de Bittencourt Date: Tue, 8 Oct 2019 21:30:02 -0300 Subject: [c/pt-br] Fix book link --- pt-br/c-pt.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index e1c27958..4e55f068 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -8,6 +8,7 @@ translators: - ["João Farias", "https://github.com/JoaoGFarias"] - ["Elton Viana", "https://github.com/eltonvs"] - ["Cássio Böck", "https://github.com/cassiobsilva"] + - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"] lang: pt-br filename: c-pt.el --- @@ -641,7 +642,7 @@ typedef void (*minha_função_type)(char *); Este é *o* livro sobre C, escrito pelos criadores da linguagem. Mas cuidado - ele é antigo e contém alguns erros (bem, ideias que não são mais consideradas boas) ou práticas ultrapassadas. -Outra boa referência é [Learn C the hard way](http://c.learncodethehardway.org/book/). +Outra boa referência é [Learn C the hard way](http://learncodethehardway.org/c/). Se você tem uma pergunta, leia [compl.lang.c Frequently Asked Questions](http://c-faq.com). -- cgit v1.2.3 From 4c879a928ddc2a896aa4d1c03e450ff612843065 Mon Sep 17 00:00:00 2001 From: Heitor Pascoal de Bittencourt Date: Tue, 8 Oct 2019 21:30:56 -0300 Subject: [c/zh-ch] Fix book link --- zh-cn/c-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index 8566e811..8eecc56e 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -612,7 +612,7 @@ typedef void (*my_fnp_type)(char *); 最好找一本 [K&R, aka "The C Programming Language", “C程序设计语言”](https://en.wikipedia.org/wiki/The_C_Programming_Language)。它是关于C最重要的一本书,由C的创作者撰写。不过需要留意的是它比较古老了,因此有些不准确的地方。 -另一个比较好的资源是 [Learn C the hard way](http://c.learncodethehardway.org/book/) +另一个比较好的资源是 [Learn C the hard way](http://learncodethehardway.org/c/) 如果你有问题,请阅读[compl.lang.c Frequently Asked Questions](http://c-faq.com/)。 -- cgit v1.2.3 From ce9d59bdb2a7d263045d77e3ea40d4f6ef61c572 Mon Sep 17 00:00:00 2001 From: Heitor Pascoal de Bittencourt Date: Tue, 8 Oct 2019 21:31:20 -0300 Subject: [c/ru-ru] Fix book link --- ru-ru/c-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index 44e7ad3b..974095d8 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -471,7 +471,7 @@ void str_reverse_through_pointer(char *str_in) { Лучше всего найдите копию [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) Это **книга** написанная создателями Си. Но будьте осторожны, она содержит идеи которые больше не считаются хорошими. -Другой хороший ресурс: [Learn C the hard way](http://c.learncodethehardway.org/book/). +Другой хороший ресурс: [Learn C the hard way](http://learncodethehardway.org/c/). Если у вас появился вопрос, почитайте [compl.lang.c Frequently Asked Questions](http://c-faq.com). -- cgit v1.2.3 From f0eb830ebded612e53eef019776d6573fbc42ab0 Mon Sep 17 00:00:00 2001 From: Timothe Pardieu Date: Wed, 9 Oct 2019 11:41:14 +0200 Subject: [elixir/fr-fr] Add french translation (#3679) * Translate Elixir.html.markdown in french * Add fixes in Elixir.html.markdown #3679 --- fr-fr/elixir-fr.html.markdown | 479 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 479 insertions(+) create mode 100644 fr-fr/elixir-fr.html.markdown diff --git a/fr-fr/elixir-fr.html.markdown b/fr-fr/elixir-fr.html.markdown new file mode 100644 index 00000000..90cdad7c --- /dev/null +++ b/fr-fr/elixir-fr.html.markdown @@ -0,0 +1,479 @@ +--- +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"] +translator: + - ["Timothé Pardieu", "https://github.com/timprd"] +filename: learnelixir-fr.ex +lang: fr-fr +--- +Elixir est un langage de programmation fonctionnel moderne reposant sur la machine virtuelle BEAM, qui héberge aussi Erlang. +Il est totalement compatible avec Erlang mais dispose d'une syntaxe plus agréable et apporte de nouvelles fonctionnalités. + + +```elixir + +# Un commentaire simple sur une seule ligne commence par un dièse. + +# Il n'y a pas de commentaire multi-ligne, +# Mais il est possible de les empiler comme ici. + +# La commande `iex` permet de lancer le shell Elixir. +# La commande `elixirc` permet de compiler vos modules. + +# Les deux devraient être dans votre path si vous avez installé Elixir correctement. + +## --------------------------- +## -- Types basiques +## --------------------------- + +# Il y a les nombres +3 # Integer +0x1F # Integer +3.0 # Float + +# Les atomes, des littéraux, qui sont des constantes avec comme valeur leur nom. +# Ils commencent par `:`. + +:hello # atom + +# Il existe également des n-uplets dont les valeurs sont stockés de manière contiguë +# en mémoire. + +{1,2,3} # tuple + +# Il est possible d'accéder à un element d'un tuple avec la fonction +# `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Les listes sont implémentées sous forme de listes chainées. +[1,2,3] # list + +# La tête et le reste d'une liste peuvent être récupérés comme cela : +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# En Elixir, comme en Erlang, le `=` dénote un 'pattern matching' +# (Filtrage par motif) et non une affectation. +# Cela signifie que la partie de gauche (pattern) est comparé (match) à +# la partie de droite. + + +# Une erreur sera lancée si aucun model (match) est trouvé. +# Dans cet exemple les tuples ont des tailles différentes +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Il y a aussi les binaires +<<1,2,3>> # binary + +# Chaine de caractères et liste de caractères +"hello" # string +'hello' # char list + +# Chaine de caractères sur plusieurs lignes +""" +Je suis une chaine de caractères +sur plusieurs lignes. +""" +#=> "Je suis une chaine de caractères\nsur plusieurs lignes.\n" + +# Les chaines de caractères sont encodées en UTF-8 : +"héllò" #=> "héllò" + +# Les chaines de caractères sont des binaires tandis que +# les listes de caractères sont des listes. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` en Elixir retourne le code ASCII (Integer) de la lettre `a` +?a #=> 97 + +# Pour concaténer des listes il faut utiliser `++`, et `<>` pour les +# binaires +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" + +# Les intervalles sont représentés de cette sorte `début..fin` +# (tout deux inclusifs) +1..10 #=> 1..10 +bas..haut = 1..10 # Possibilité d'utiliser le pattern matching sur les intervalles aussi. +[bas, haut] #=> [1, 10] + +# Les Maps (Tableau associatif) sont des paires clée - valeur +genders = %{"david" => "male", "gillian" => "female"} +genders["david"] #=> "male" + +# Les maps avec des atomes peuvent être utilisés comme cela +genders = %{david: "male", gillian: "female"} +genders.gillian #=> "female" + +## --------------------------- +## -- Operateurs +## --------------------------- + +# Mathématiques +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# En Elixir l'opérateur `/` retourne toujours un Float (virgule flottante). + +# Pour faire une division avec entier il faut utiliser `div` +div(10, 2) #=> 5 + +# Pour obtenir le reste de la division il faut utiliser `rem` +rem(10, 3) #=> 1 + +# Il y a aussi les opérateurs booléen: `or`, `and` et `not`. +# Ces opérateurs attendent un booléen en premier argument. +true and true #=> true +false or true #=> true +# 1 and true +#=> ** (BadBooleanError) expected a booléens on left-side of "and", got: 1 + +# Elixir fournit aussi `||`, `&&` et `!` qui acceptent des arguments de +# tout type. +# Chaque valeur sauf `false` et `nil` seront évalués à vrai (true). +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Pour les comparaisons il y a : `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` et `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` et `!==` sont plus stricts en comparant les Integers (entiers) +# et les Floats (nombres à virgules) : +1 == 1.0 #=> true +1 === 1.0 #=> false + +# On peut aussi comparer deux types de données différents : +1 < :hello #=> true + +# L'ordre est défini de la sorte : +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# Pour citer Joe Armstrong : "The actual order is not important, +# but that a total ordering is well defined is important." + +## --------------------------- +## -- Structure de contrôle +## --------------------------- + +# Condition avec `if` (si) +if false do + "Cela ne sera pas vu" +else + "Cela le sera" +end + +# Condition avec `unless` (sauf). +# Il correspond à la négation d'un `if` (si) +unless true do + "Cela ne sera pas vu" +else + "Cela le sera" +end + +# Beaucoup de structures en Elixir se basent sur le pattern matching. +# `case` permet de comparer une valeur à plusieurs modèles: +case {:one, :two} do + {:four, :five} -> + "Ne match pas" + {:one, x} -> + "Match et lie `x` à `:two` dans ce cas" + _ -> + "Match toutes les valeurs" +end + +# Il est commun de lier la valeur à `_` si on ne l'utilise pas. +# Par exemple, si seulement la tête d'une liste nous intéresse: +[head | _] = [1,2,3] +head #=> 1 + +# Pour plus de lisibilité, ce procédé est utilisé: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` permet de vérifier plusieurs conditions à la fois. +# Il est conseillé d'utiliser `cond` plutôt que des `if` imbriqués. +cond do + 1 + 1 == 3 -> + "Je ne serai pas vu" + 2 * 5 == 12 -> + "Moi non plus" + 1 + 2 == 3 -> + "Mais moi oui" +end + +# Il est commun d'attribuer la dernière condition à true (vrai), qui +# matchera toujours. +cond do + 1 + 1 == 3 -> + "Je ne serai pas vu" + 2 * 5 == 12 -> + "Moi non plus" + true -> + "Mais moi oui (représente un else)" +end + +# `try/catch` est utilisé pour attraper les valeurs rejetées. +# Il supporte aussi un +# `after` qui est appelé autant si une valeur est jetée ou non. +try do + throw(:hello) +catch + message -> "Message : #{message}." +after + IO.puts("Je suis la clause after (après).") +end +#=> Je suis la clause after (après). +# "Message : :hello" + +## --------------------------- +## -- Modules et Fonctions +## --------------------------- + +# Fonctions anonymes (notez le point). +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Les fonctions anonymes acceptent aussi de nombreuses clauses et guards (gardes). +# Les guards permettent d'affiner le pattern matching, +# ils sont indiqués par le mot-clef `when` : +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir propose aussi de nombreuses fonctions internes. +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + +# Il est possible de grouper plusieurs fonctions dans un module. +# Dans un module, les fonctions sont définies par `def` +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 + +# Pour compiler notre module `Math`, +# il faut le sauvegarder en tant que `math.ex` et utiliser `elixirc`. +# Executez ainsi `elixirc math.ex` dans le terminal. + +# Au sein d'un module, nous pouvons définir les fonctions avec `def` +# et `defp` pour les fonctions privées. +# Une fonction définie par `def` est disponible dans les autres +# modules. Une fonction privée est disponible localement seulement. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# La déclaration de fonction supporte également les guards (gardes) +# et les clauses. +# Quand une fonction avec plusieurs clauses est appelée, +# la première fonction dont la clause est satisfaite par les arguments sera appelée. +# Exemple: le code `area({:circle, 3})` appelle la deuxième fonction definie plus bas, +# et non la première car ses arguments correspondent à la signature de cette dernière: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +# Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 + +# En raison de l'immutabilité, la récursivité est une grande partie +# d'Elixir +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Les modules Elixir supportent des attributs internes, +# ceux-ci peuvent aussi être personnalisés. +defmodule MyMod do + @moduledoc """ + This is a built-in attribute on a example module. + """ + + @my_data 100 # Attribut personnel. + IO.inspect(@my_data) #=> 100 +end + +# L'opérateur pipe (|>) permet de passer la sortie d'une expression +# en premier paramètre d'une fonction. + +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] + +## --------------------------- +## -- Structs et Exceptions +## --------------------------- + +# Les Structs sont des extensions des Maps. +# Apportant en plus les valeurs par defaut, le polymorphisme et +# la vérification à la compilation dans Elixir. +defmodule Person do + defstruct name: nil, age: 0, height: 0 +end + +jean_info = %Person{ name: "Jean", age: 30, height: 180 } +#=> %Person{age: 30, height: 180, name: "Jean"} + +# Access the value of name +jean_info.name #=> "Jean" + +# Update the value of age +older_jean_info = %{ jean_info | age: 31 } +#=> %Person{age: 31, height: 180, name: "Jean"} + +# Le bloc `try` avec le mot-clef `rescue` est utilisé pour gérer les exceptions +try do + raise "some error" +rescue + RuntimeError -> "rescued a runtime error" + _error -> "this will rescue any error" +end +#=> "rescued a runtime error" + +# Chaque exception possède un message +try do + raise "some error" +rescue + x in [RuntimeError] -> + x.message +end +#=> "some error" + +## --------------------------- +## -- Concurrence +## --------------------------- + +# Elixir se repose sur le modèle d'acteur pour gérer la concurrence. +# Pour écrire un programme concurrent en Elixir il faut trois +# primitives: spawning processes (création), sending messages (envoi) +# et receiving messages (réception). + +# Pour débuter un nouveau processus, il faut utiliser +# la fonction `spawn` qui prend en argument une fonction. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` retourn un pid (identifiant de processus), il est possible +# d'utiliser ce pid pour envoyer un message au processus. +# Pour faire parvenir le message il faut utiliser l'opérateur `send`. +# Pour que cela soit utile il faut être capable de recevoir les +# messages. +# Cela est possible grâce au mechanisme de `receive`: + +# Le bloc `receive do` est utilisé pour écouter les messages et les traiter +# au moment de la réception. Un bloc `receive do` pourra traiter un seul +# message reçu. +# Pour traiter plusieurs messages, une fonction avec un bloc `receive do` +# doit s'appeler elle-même récursivement. + +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Ceci compile le module et créer un processus qui évalue dans le terminal `area_loop` +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# Alternativement +pid = spawn(Geometry, :area_loop, []) + +# On envoi un message au `pid` qui correspond à la régle de réception. +send pid, {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# Le shell est aussi un processus, il est possible d'utiliser `self` +# pour obtenir le pid du processus courant. +self() #=> #PID<0.27.0> + +## --------------------------- +## -- Agents +## --------------------------- + +# Un agent est un processus qui garde les traces des valeurs modifiées. + +# Pour créer un agent on utilise `Agent.start_link` avec une fonction. +# L'état initial de l'agent sera ce que la fonction retourne +{ok, my_agent} = Agent.start_link(fn -> ["red", "green"] end) + +# `Agent.get` prend un nom d'agent et une fonction (`fn`). +# Qu'importe ce que cette `fn` retourne, l'état sera ce qui est retourné. +Agent.get(my_agent, fn colors -> colors end) #=> ["red", "green"] + +# Modification de l'état de l'agent +Agent.update(my_agent, fn colors -> ["blue" | colors] end) +``` + +## Références + +* [Guide de debut](http://elixir-lang.org/getting-started/introduction.html) depuis le site [Elixir](http://elixir-lang.org) +* [Documentation Elixir ](https://elixir-lang.org/docs.html) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) de Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) de Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) de Joe Armstrong -- cgit v1.2.3 From ccde50813f72e9c2bd6b8e2a9025985a8646619f Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Fri, 11 Oct 2019 10:10:44 -0300 Subject: =?UTF-8?q?[elisp/pt]=20Corre=C3=A7=C3=A3o=20ortogr=C3=A1fica?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/elisp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/elisp-pt.html.markdown b/pt-br/elisp-pt.html.markdown index fc2d1e40..aa611097 100644 --- a/pt-br/elisp-pt.html.markdown +++ b/pt-br/elisp-pt.html.markdown @@ -111,7 +111,7 @@ filename: learn-emacs-lisp-pt.el (hello) ;; `C-xC-e' => Hello, I am Bastien -;; Os parêntesis vazios na definição da função significam que ela +;; Os parênteses vazios na definição da função significam que ela ;; não aceita argumentos. Mas sempre utilizar `my-name' é um tédio! ;; Vamos dizer à função para aceitar um argumento (o argumento é ;; chamado "name"): -- cgit v1.2.3 From 2c13b562f8d5c3a81027ee3abd46410452fbf3af Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Fri, 11 Oct 2019 10:19:39 -0300 Subject: Update pascal-pt.html.markdown --- pt-br/pascal-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/pascal-pt.html.markdown b/pt-br/pascal-pt.html.markdown index 3a37271a..82cce843 100644 --- a/pt-br/pascal-pt.html.markdown +++ b/pt-br/pascal-pt.html.markdown @@ -157,7 +157,7 @@ BEGIN r := int; // um real pode receber um valor inteiro (mas não o contrário) c := str[1]; //acessando elementos de um vetor: vetor[índice do elemento] - str := 'hello' + 'world'; //concatenção de strings + str := 'hello' + 'world'; //concatenação de strings my_str[0] := 'a'; { só se pode atribuir valores a vetores elemento por elemento (não o vetor inteiro de uma vez) } -- cgit v1.2.3 From 3496f8228f7d53131ed6496dab45e4038a808e65 Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Fri, 11 Oct 2019 10:41:24 -0300 Subject: =?UTF-8?q?[whip/pt]=20Corre=C3=A7=C3=A3o=20ortogr=C3=A1fica?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/whip-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/whip-pt.html.markdown b/pt-br/whip-pt.html.markdown index 7bdeec25..b11faf28 100644 --- a/pt-br/whip-pt.html.markdown +++ b/pt-br/whip-pt.html.markdown @@ -71,7 +71,7 @@ false (= 1 1) ; => true (equal 2 1) ; => false -; Por exemplo, inigualdade pode ser verificada combinando as funções +; Por exemplo, desigualdade pode ser verificada combinando as funções ;`not` e `equal`. (! (= 2 1)) ; => true -- cgit v1.2.3 From 9fb99aa5bd2bcd742d972fa269de76c1994aff97 Mon Sep 17 00:00:00 2001 From: lbertolazzi <33129418+lbertolazzi@users.noreply.github.com> Date: Fri, 11 Oct 2019 10:51:55 -0300 Subject: =?UTF-8?q?[haskell/pt]=20Corre=C3=A7=C3=A3o=20ortogr=C3=A1fica?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/haskell-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown index 181aa471..c55a4c03 100644 --- a/pt-br/haskell-pt.html.markdown +++ b/pt-br/haskell-pt.html.markdown @@ -41,7 +41,7 @@ o desenvolvimento deste paradigma de programação. 7 * 7 -- 7 vezes 7 7 / 7 -- 7 dividido por 7 --- Divisões não são inteiras, são fracionádas por padrão da linguagem +-- Divisões não são inteiras, são fracionadas por padrão da linguagem 28736 / 82374 -- 0.3488479374559934 @@ -67,7 +67,7 @@ not False -- Nega uma falácia 7 > 7 -- 7 é maior que 7 ? -{- Haskell é uma linguagem que tem uma sintáxe bastante familiar na +{- Haskell é uma linguagem que tem uma sintaxe bastante familiar na matemática, por exemplo em chamadas de funções você tem: NomeFunção ArgumentoA ArgumentoB ArgumentoC ... -- cgit v1.2.3 From cbf8a43ca14fe063b42f2d7a209a6f7139e7cd5e Mon Sep 17 00:00:00 2001 From: Sridhar Easwaran Date: Fri, 11 Oct 2019 20:29:26 +0530 Subject: Add example for Optional Positional Parameter --- dart.html.markdown | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/dart.html.markdown b/dart.html.markdown index 07f755f7..fb1856fd 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -503,6 +503,17 @@ example30() { } } +// Optional Positional Parameter +// parameter will be disclosed with square bracket [ ] & square bracketed parameter are optional. +example31() { + findVolume(int length, int breath, [int height]) { + print('length = $length, breath = $breath, height = $height'); + } + + findVolume(10,20,30); //valid + findVolume(10,20); //also valid +} + // Programs have only one entry point in the main function. // Nothing is expected to be executed on the outer scope before a program // starts running with what's in its main function. @@ -514,7 +525,7 @@ main() { example8, example9, example10, example11, example12, example13, example14, example15, example16, example17, example18, example19, example20, example21, example22, example23, example24, example25, example26, - example27, example28, example29, example30 + example27, example28, example29, example30, example31 ].forEach((ef) => ef()); } -- cgit v1.2.3 From 170f9c7f496866b83fa5f73f19e9a4bfc074e2f1 Mon Sep 17 00:00:00 2001 From: Sridhar Easwaran Date: Fri, 11 Oct 2019 21:19:31 +0530 Subject: Update css-ta.html.markdown --- ta_in/css-ta.html.markdown | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown index cbe88f1e..4ea7f959 100644 --- a/ta_in/css-ta.html.markdown +++ b/ta_in/css-ta.html.markdown @@ -233,6 +233,48 @@ css முன்னுரிமை பின்வருமாறு * `B` இது அடுத்தது. * `D` இதுவே கடைசி . +## Media Queries [மீடியா குரிஸ்] + +CSS மீடியா குரிஸ் CSS 3 அம்சங்கள். பயன்படுத்தும் கணினி, கைபேசி அல்லது சாதனத்தின் பிஸேல் டென்சிட்டிக்கு ஏற்றவாறு மீடியா குரிஸ் விதிகளை பயன்படுத்தலாம். + +```css +/* அனைத்து டேவிஸ்களுக்கும் பொதுவான விதி */ +h1 { + font-size: 2em; + color: white; + background-color: black; +} + +/* பிரிண்ட் செய்யும்போது h1 கலர் மாற்ற */ +@media print { + h1 { + color: black; + background-color: white; + } +} + +/* 480 பிஸேல்ளுக்கு மேல் சிகிரீன் அளவு உள்ள சாதனத்தில் எழுத்து அளவு மிகை படுத்த */ +@media screen and (min-width: 480px) { + h1 { + font-size: 3em; + font-weight: normal; + } +} +``` + +மீடியா குரிஸ் வழங்கும் அம்சங்கள் : +`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. இவையுள் பெரும்பான்மை `min-` அல்லது `max-` வுடன் பயன்படுத்தலாம் . + +`resolution` பழைய சாதனங்களில் பயன்படாது, எனவே `device-pixel-ratio` பயன்படுத்தவும். + +பல கைபேசி மற்றும் கணினிகள், வீடு கணினி திரை அளவு காட்ட முற்படும். எனவே `viewport` மெட்டா டேக் பயன்படுத்தவும். + +```html + + + +``` + ## css அம்சங்களின் பொருந்தகூடிய தன்மை பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது. -- cgit v1.2.3 From 08b2589618fdc0bf61bdafd49aa19458d32af820 Mon Sep 17 00:00:00 2001 From: Sridhar Easwaran Date: Fri, 11 Oct 2019 22:17:39 +0530 Subject: Update xml-ta.html.markdown --- ta_in/xml-ta.html.markdown | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown index d782399d..13aa9255 100644 --- a/ta_in/xml-ta.html.markdown +++ b/ta_in/xml-ta.html.markdown @@ -5,6 +5,7 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] + - ["Sridhar Easwaran", "https://github.com/sridhareaswaran"] lang: in-ta --- @@ -14,6 +15,57 @@ XML ஆனது ஒரு கட்டமைப்பு மொழி ஆகு HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது + +## சில வரையறை மற்றும் முன்னுரை + +பல கூறுகளால் அமைக்கப்பட்டது. ஒவொரு கூறுகளிலும் அட்ட்ரிபூட்க்கள் இருக்கும், அவை அந்தந்த கூறுகளை வரையறுக்க பயன்படும். மேலும் அந்த கூறுகளை தகவல் அல்லது கிளை கூறுகள் இருக்கலாம். அணைத்து கோப்புகளிலும் ரூட்/ஆரம்ப கூறு இருக்கும், அது தனக்குள் கிளை கூறுகளை கொண்டுருக்கும். + +XML பாகுபடுத்தி மிகவும் கண்டிப்பான வீதிகளைக்கொண்டது. [XML தொடரியல் விதிகளை அறிய] (http://www.w3schools.com/xml/xml_syntax.asp). + + +```xml + + + + + + + +Content + + + + + + + + + + + + + + + + + + + + + + Text + + + + + + Text + + +Text +``` + * XML வாக்கிய அமைப்பு -- cgit v1.2.3 From 092b9155bede1cfe3dcec9b130823348b2d04e7f Mon Sep 17 00:00:00 2001 From: Sridhar Easwaran Date: Fri, 11 Oct 2019 22:28:57 +0530 Subject: Update dart.html.markdown --- dart.html.markdown | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/dart.html.markdown b/dart.html.markdown index fb1856fd..ce6f681b 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -503,15 +503,42 @@ example30() { } } -// Optional Positional Parameter +// Optional Positional Parameter: // parameter will be disclosed with square bracket [ ] & square bracketed parameter are optional. example31() { - findVolume(int length, int breath, [int height]) { + findVolume31(int length, int breath, [int height]) { print('length = $length, breath = $breath, height = $height'); } - findVolume(10,20,30); //valid - findVolume(10,20); //also valid + findVolume31(10,20,30); //valid + findVolume31(10,20); //also valid +} + +// Optional Named Parameter: +// parameter will be disclosed with curly bracket { } +// curly bracketed parameter are optional. +// have to use parameter name to assign a value which separated with colan : +// in curly bracketed parameter order does not matter +// these type parameter help us to avoid confusion while passing value for a function which has many parameter. +example32() { + findVolume32(int length, int breath, {int height}) { + print('length = $length, breath = $breath, height = $height'); + } + + findVolume32(10,20,height:30);//valid & we can see the parameter name is mentioned here. + findVolume32(10,20);//also valid +} + +// Optional Default Parameter: +// same like optional named parameter in addition we can assign default value for this parameter. +// which means no value is passed this default value will be taken. +example33() { + findVolume33(int length, int breath, {int height=10}) { + print('length = $length, breath = $breath, height = $height'); + } + + findVolume33(10,20,height:30);//valid + findVolume33(10,20);//valid } // Programs have only one entry point in the main function. @@ -525,7 +552,7 @@ main() { example8, example9, example10, example11, example12, example13, example14, example15, example16, example17, example18, example19, example20, example21, example22, example23, example24, example25, example26, - example27, example28, example29, example30, example31 + example27, example28, example29, example30, example31, example32, example33 ].forEach((ef) => ef()); } -- cgit v1.2.3 From 3b4ca43798a2fc0483c1a3a195ddde934cd2983f Mon Sep 17 00:00:00 2001 From: davidgtu Date: Fri, 11 Oct 2019 15:22:12 -0400 Subject: fix spacing --- css.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 64dc097c..5a9d1376 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -164,14 +164,14 @@ selector { max-width: 5in; /* inches */ /* Colors */ - color: #F6E; /* short hex format */ - color: #FF66EE; /* long hex format */ - color: tomato; /* a named color */ - color: rgb(255, 255, 255); /* as rgb values */ - color: rgb(10%, 20%, 50%); /* as rgb percentages */ - color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */ - color: transparent; /* equivalent to setting the alpha to 0 */ - color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ + color: #F6E; /* short hex format */ + color: #FF66EE; /* long hex format */ + color: tomato; /* a named color */ + color: rgb(255, 255, 255); /* as rgb values */ + color: rgb(10%, 20%, 50%); /* as rgb percentages */ + color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */ + color: transparent; /* equivalent to setting the alpha to 0 */ + color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */ /* Borders */ -- cgit v1.2.3 From 0e437a75db091eb5cb057f1a49bf07db562d1d8f Mon Sep 17 00:00:00 2001 From: davidgtu Date: Fri, 11 Oct 2019 15:53:07 -0400 Subject: add type assertion --- typescript.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index cf2111d5..6c6da2c4 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -257,8 +257,24 @@ for (const i in list) { console.log(i); // 0, 1, 2 } +// Type Assertion +let foo = {} // Creating foo as an empty object +foo.bar = 123 // Error: property 'bar' does not exist on `{}` +foo.baz = 'hello world' // Error: property 'baz' does not exist on `{}` +// Because the inferred type of foo is `{}` (an object with 0 properties), you +// are not allowed to add bar and baz to it. However with type assertion, +// the following will pass: + +interface Foo { + bar: number; + baz: string; +} + +let foo = {} as Foo; // Type assertion here +foo.bar = 123; +foo.baz = 'hello world' ``` -- cgit v1.2.3 From ceaa8824b1a7ab141e317013a8a1643dd9b02684 Mon Sep 17 00:00:00 2001 From: Alexander Meinhold <35108195+alexmeinhold@users.noreply.github.com> Date: Fri, 11 Oct 2019 22:07:05 +0200 Subject: Update common-lisp.html.markdown Real -> Read --- common-lisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index b12e50ca..1f2bb366 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -69,7 +69,7 @@ t ; another atom, denoting true ;;; is a good starting point. Third party libraries can be easily installed with ;;; Quicklisp -;;; CL is usually developed with a text editor and a Real Eval Print +;;; CL is usually developed with a text editor and a Read Eval Print ;;; Loop (REPL) running at the same time. The REPL allows for interactive ;;; exploration of the program while it is running "live". -- cgit v1.2.3 From abcfb458343c1cd0e1559dfb1d54c03f2a3c17ad Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 12 Oct 2019 19:50:10 +0530 Subject: add CSS resource --- css.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/css.html.markdown b/css.html.markdown index 64dc097c..5ecfe5e3 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -179,7 +179,7 @@ selector { border-style:solid; border-color:red; /* similar to how background-color is set */ border: 5px solid red; /* this is a short hand approach for the same */ - border-radius:20px; /* this is a CSS3 property */ + border-radius:20px; /* this is a CSS3 property */ /* Images as backgrounds of elements */ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ @@ -317,6 +317,7 @@ a new feature. * [Dabblet](http://dabblet.com/) (CSS playground) * [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference) * [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference) +* [DevTips' CSS Basics](https://www.youtube.com/playlist?list=PLqGj3iMvMa4IOmy04kDxh_hqODMqoeeCy) (Tutorials) ## Further Reading -- cgit v1.2.3 From cd08fd0018be2fc66257f5b01b9d1006b31bd1db Mon Sep 17 00:00:00 2001 From: Ilya Vorontsov Date: Sat, 12 Oct 2019 17:30:15 +0300 Subject: [kotlin, ru] fix typo --- ru-ru/kotlin-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/kotlin-ru.html.markdown b/ru-ru/kotlin-ru.html.markdown index 58dab4cd..85f44c96 100644 --- a/ru-ru/kotlin-ru.html.markdown +++ b/ru-ru/kotlin-ru.html.markdown @@ -8,7 +8,7 @@ translators: - ["Vadim Toptunov", "https://github.com/VadimToptunov"] --- -Kotlin - статистически типизированный язык для JVM, Android и браузера. Язык полностью совместим c Java. +Kotlin - статически типизированный язык для JVM, Android и браузера. Язык полностью совместим c Java. [Более детальная информация здесь.](https://kotlinlang.org/) ```kotlin -- cgit v1.2.3 From 5fe22c9c770b6a391a18c3e7f44c1e5b4620ae40 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 12 Oct 2019 20:25:05 +0530 Subject: add SQL resource --- sql.html.markdown | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/sql.html.markdown b/sql.html.markdown index 2bece208..5edf0f7c 100644 --- a/sql.html.markdown +++ b/sql.html.markdown @@ -9,14 +9,14 @@ Structured Query Language (SQL) is an ISO standard language for creating and wor Implementations typically provide a command line prompt where you can enter the commands shown here interactively, and they also offer a way to execute a series of these commands stored in a script file. (Showing that you’re done with the interactive prompt is a good example of something that isn’t standardized--most SQL implementations support the keywords QUIT, EXIT, or both.) -Several of these sample commands assume that the [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/) available on [github](https://github.com/datacharmer/test_db) has already been loaded. The github files are scripts of commands, similar to the relevant commands below, that create and populate tables of data about a fictional company’s employees. The syntax for running these scripts will depend on the SQL implementation you are using. A utility that you run from the operating system prompt is typical. +Several of these sample commands assume that the [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/) available on [github](https://github.com/datacharmer/test_db) has already been loaded. The github files are scripts of commands, similar to the relevant commands below, that create and populate tables of data about a fictional company’s employees. The syntax for running these scripts will depend on the SQL implementation you are using. A utility that you run from the operating system prompt is typical. ```sql -- Comments start with two hyphens. End each command with a semicolon. -- SQL is not case-sensitive about keywords. The sample commands here --- follow the convention of spelling them in upper-case because it makes +-- follow the convention of spelling them in upper-case because it makes -- it easier to distinguish them from database, table, and column names. -- Create and delete a database. Database and table names are case-sensitive. @@ -26,47 +26,47 @@ DROP DATABASE someDatabase; -- List available databases. SHOW DATABASES; --- Use a particular existing database. +-- Use a particular existing database. USE employees; -- Select all rows and columns from the current database's departments table. --- Default activity is for the interpreter to scroll the results on your screen. +-- Default activity is for the interpreter to scroll the results on your screen. SELECT * FROM departments; --- Retrieve all rows from the departments table, --- but only the dept_no and dept_name columns. +-- Retrieve all rows from the departments table, +-- but only the dept_no and dept_name columns. -- Splitting up commands across lines is OK. SELECT dept_no, dept_name FROM departments; --- Retrieve all departments columns, but just 5 rows. +-- Retrieve all departments columns, but just 5 rows. SELECT * FROM departments LIMIT 5; -- Retrieve dept_name column values from the departments --- table where the dept_name value has the substring 'en'. +-- table where the dept_name value has the substring 'en'. SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; -- Retrieve all columns from the departments table where the dept_name --- column starts with an 'S' and has exactly 4 characters after it. +-- column starts with an 'S' and has exactly 4 characters after it. SELECT * FROM departments WHERE dept_name LIKE 'S____'; -- Select title values from the titles table but don't show duplicates. SELECT DISTINCT title FROM titles; --- Same as above, but sorted (case-sensitive) by the title values. +-- Same as above, but sorted (case-sensitive) by the title values. SELECT DISTINCT title FROM titles ORDER BY title; -- Show the number of rows in the departments table. SELECT COUNT(*) FROM departments; -- Show the number of rows in the departments table that --- have 'en' as a substring of the dept_name value. +-- have 'en' as a substring of the dept_name value. SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; --- A JOIN of information from multiple tables: the titles table shows --- who had what job titles, by their employee numbers, from what +-- A JOIN of information from multiple tables: the titles table shows +-- who had what job titles, by their employee numbers, from what -- date to what date. Retrieve this information, but instead of the --- employee number, use the employee number as a cross-reference to +-- employee number, use the employee number as a cross-reference to -- the employees table to get each employee's first and last name -- instead. (And only get 10 rows.) @@ -85,12 +85,12 @@ WHERE TABLE_TYPE='BASE TABLE'; -- for how you specify the columns, such as their datatypes. CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); --- Insert a row of data into the table tablename1. This assumes that the --- table has been defined to accept these values as appropriate for it. +-- Insert a row of data into the table tablename1. This assumes that the +-- table has been defined to accept these values as appropriate for it. INSERT INTO tablename1 VALUES('Richard','Mutt'); -- In tablename1, change the fname value to 'John' --- for all rows that have an lname value of 'Mutt'. +-- for all rows that have an lname value of 'Mutt'. UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; -- Delete rows from the tablename1 table @@ -100,6 +100,11 @@ DELETE FROM tablename1 WHERE lname like 'M%'; -- Delete all rows from the tablename1 table, leaving the empty table. DELETE FROM tablename1; --- Remove the entire tablename1 table. +-- Remove the entire tablename1 table. DROP TABLE tablename1; ``` + +## Further Reading + +* [Codecademy - SQL](https://www.codecademy.com/learn/learn-sql) A good introduction to SQL in a "learn by doing it" format. +* [Database System Concepts](https://www.db-book.com) book's Chapter 3 - Introduction to SQL has an in depth explanation of SQL concepts. -- cgit v1.2.3 From 8a8dd005bf68b5565bba0f5e4da573bcb9c92951 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 12 Oct 2019 20:47:18 +0530 Subject: add Java resource --- java.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index ca0b04c2..4f45a268 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -289,7 +289,7 @@ public class LearnJava { // interface. This allows the execution time of basic // operations, such as get and insert element, to remain // constant-amortized even for large sets. - // TreeMap - A Map that is sorted by its keys. Each modification + // 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. @@ -470,11 +470,11 @@ public class LearnJava { // " int foo = 5; String bar = (foo < 10) ? "A" : "B"; - System.out.println("bar : " + bar); // Prints "bar : A", because the + System.out.println("bar : " + bar); // Prints "bar : A", because the // statement is true. // Or simply System.out.println("bar : " + (foo < 10 ? "A" : "B")); - + //////////////////////////////////////// // Converting Data Types @@ -918,7 +918,7 @@ public class Lambdas { planets.keySet().forEach(p -> System.out.format("%s\n", p)); // Tracing the above, we see that planets is a HashMap, keySet() returns - // a Set of its keys, forEach applies each element as the lambda + // a Set of its keys, forEach applies each element as the lambda // expression of: (parameter p) -> System.out.format("%s\n", p). Each // time, the element is said to be "consumed" and the statement(s) // referred to in the lambda body is applied. Remember the lambda body @@ -998,6 +998,8 @@ The links provided here below are just to get an understanding of the topic, fee * [Codewars - Java Katas](https://www.codewars.com/?language=java) +* [University of Helsinki - Object-Oriented programming with Java](http://moocfi.github.io/courses/2013/programming-part-1/) + **Books**: * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -- cgit v1.2.3 From b2e762307e064843059a5e649f3e7016032e8d74 Mon Sep 17 00:00:00 2001 From: Apoorv Choubey Date: Sat, 12 Oct 2019 21:08:56 +0530 Subject: add CSharp resource --- csharp.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index df6544d3..139010c7 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -725,10 +725,10 @@ on a new line! ""Wow!"", the masses cried"; int _speed; // Everything is private by default: Only accessible from within this class. // can also use keyword private public string Name { get; set; } - + // Properties also have a special syntax for when you want a readonly property // that simply returns the result of an expression - public string LongName => Name + " " + _speed + " speed"; + public string LongName => Name + " " + _speed + " speed"; // Enum is a value type that consists of a set of named constants // It is really just mapping a name to a value (an int, unless specified otherwise). @@ -1089,7 +1089,7 @@ on a new line! ""Wow!"", the masses cried"; // Spell failed return false; } - // Other exceptions, or MagicServiceException where Code is not 42 + // Other exceptions, or MagicServiceException where Code is not 42 catch(Exception ex) when (LogException(ex)) { // Execution never reaches this block @@ -1213,7 +1213,7 @@ namespace Csharp7 Console.WriteLine(tt.GetLastName()); } } - + // PATTERN MATCHING class PatternMatchingTest { @@ -1320,3 +1320,4 @@ namespace Csharp7 * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) + * [freeCodeCamp - C# Tutorial for Beginners](https://www.youtube.com/watch?v=GhQdlIFylQ8) -- cgit v1.2.3 From 17360e644f81f702d436e7d2230a1114abe16dcb Mon Sep 17 00:00:00 2001 From: Ygor Sad Date: Sun, 13 Oct 2019 19:36:14 -0300 Subject: [clojure/pt-br] Rewrite text to be more natural --- pt-br/clojure-pt.html.markdown | 599 +++++++++++++++++++++++++++-------------- 1 file changed, 391 insertions(+), 208 deletions(-) diff --git a/pt-br/clojure-pt.html.markdown b/pt-br/clojure-pt.html.markdown index b88d4eec..862d73ea 100644 --- a/pt-br/clojure-pt.html.markdown +++ b/pt-br/clojure-pt.html.markdown @@ -5,12 +5,13 @@ contributors: - ["Adam Bard", "http://adambard.com/"] translators: - ["Mariane Siqueira Machado", "https://twitter.com/mariane_sm"] + - ["Ygor Sad", "https://github.com/ysads"] lang: pt-br --- -Clojure é uma linguagem da família do Lisp desenvolvida para a JVM (máquina virtual Java). Possui uma ênfase muito mais forte em [programação funcional] (https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional) pura do que Common Lisp, mas inclui diversas utilidades [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) para lidar com estado a medida que isso se torna necessário. +Clojure é uma linguagem da família do Lisp desenvolvida para a JVM (máquina virtual Java). Possui uma ênfase muito mais forte em [programação funcional] (https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional) pura do que Common Lisp, mas inclui diversos recursos [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) para lidar com estado e mutabilidade, caso isso seja necessário. -Essa combinação permite gerenciar processamento concorrente de maneira muito simples, e frequentemente de maneira automática. +Essa combinação permite gerenciar processamento concorrente de maneira muito simples - frequentemente, de modo automático. (Sua versão de clojure precisa ser pelo menos 1.2) @@ -18,367 +19,549 @@ Essa combinação permite gerenciar processamento concorrente de maneira muito s ```clojure ; Comentários começam por ponto e vírgula -; Clojure é escrito em "forms", os quais são simplesmente -; listas de coisas dentro de parênteses, separados por espaços em branco. +; Código Clojure é escrito em formas - 'forms', em inglês. Tais estruturas são +; simplesmente listas de valores encapsuladas dentro de parênteses, separados por +; espaços em branco. -; O "reader" (leitor) de Clojure presume que o primeiro elemento de -; uma par de parênteses é uma função ou macro, e que os resto são argumentos. +; Ao interpretar um código em Clojure, o interpretador ou leitor - do inglês 'reader' - assume +; que o primeiro valor dentro de uma forma é uma função ou macro, de modo que os demais valores +; são seus argumentos. Isso se deve ao fato de que Clojure, por ser uma derivação de Lisp, +; usa notação prefixa (ou polonesa). -: A primeira chamada de um arquivo deve ser ns, para configurar o namespace (espaço de nomes) +; Num arquivo, a primeira chamada deve ser sempre para a função ns, +; que é responsável por definir em qual namespace o código em questão +; deve ser alocado (ns learnclojure) ; Alguns exemplos básicos: -; str cria uma string concatenando seus argumentos -(str "Hello" " " "World") ; => "Hello World" +; Aqui, str é uma função e "Olá" " " e "Mundo" são seus argumentos. O que ela faz é criar +; uma string concatenando seus argumentos. +(str "Olá" " " "Mundo") ; => "Olá Mundo" -; Cálculos são feitos de forma direta e intuitiva +; Note que espaços em branco separam os argumentos de uma função. Opcionalmente vírgulas +; podem ser usadas, se você quiser. +(str, "Olá", " ", "Mundo") ; => "Olá Mundo" + +; As operações matemáticas básicas usam os operadores de sempre (+ 1 1) ; => 2 (- 2 1) ; => 1 (* 1 2) ; => 2 (/ 2 1) ; => 2 -; Você pode comparar igualdade utilizando = +; Esses operadores aceitam um número arbitrário de argumentos +(+ 2 2 2) ; = 2 + 2 + 2 => 6 +(- 5 1 1) ; = 5 - 1 - 1 => 3 +(* 3 3 3 3) ; = 3 * 3 * 3 * 3 => 81 + +; Para verificar se dois valores são iguais, o operador = pode ser usado (= 1 1) ; => true (= 2 1) ; => false -; Negação para operações lógicas -(not true) ; => false +; Para saber se dois valores são diferentes +(not= 1 2) ; => true +(not (= 1 2)) ; => true -; Aninhar "forms" funciona como esperado +; Conforme vimos acima, é possível aninhar duas formas (+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 +(* (- 3 2) (+ 1 2)) ; = (3 - 2) * (1 + 2) => 3 + +; Se a leitura ficar comprometida, as fórmulas também podem ser escritas em múltiplas linhas +(* (- 3 2) + (+ 1 2)) ; => 3 +(* + (- 3 2) + (+ 1 2)) ; => 3 + ; Tipos ;;;;;;;;;;;;; -; Clojure usa os tipos de objetos de Java para booleanos, strings e números. -; Use `class` para inspecioná-los -(class 1) ; Literais Integer são java.lang.Long por padrão -(class 1.); Literais Float são java.lang.Double -(class ""); Strings são sempre com aspas duplas, e são java.lang.String +; Por ter interoperabilidade com Java, Clojure usa os tipos de objetos de Java para booleanos, +; strings e números. Para descobrir qual o tipo de um valor, você pode usar a função `class`: +(class 1234) ; Literais Integer são java.lang.Long por padrão +(class 1.50) ; Literais Float são java.lang.Double +(class "oi") ; Strings sempre usam aspas duplas e são java.lang.String (class false) ; Booleanos são java.lang.Boolean -(class nil); O valor "null" é chamado nil -; Se você quiser criar um lista de literais, use aspa simples para -; ela não ser avaliada -'(+ 1 2) ; => (+ 1 2) -; (que é uma abreviação de (quote (+ 1 2))) +; Tenha cuidado, ao dividir valores inteiros: +(= (/ 1 2) + (/ 1.0 2.0)) ; => false + +(class (/ 1 2)) ; => clojure.lang.Ratio +(class (/ 1.0 2.0)) ; => java.lang.Double + +; Aqui temos uma diferença em relação a Java, pois valores nulos são representados por `nil` +(class nil) ; nil -; É possível avaliar uma lista com aspa simples -(eval '(+ 1 2)) ; => 3 ; Coleções e sequências ;;;;;;;;;;;;;;;;;;; -; Listas são estruturas encadeadas, enquanto vetores são implementados como arrays. -; Listas e Vetores são classes Java também! -(class [1 2 3]); => clojure.lang.PersistentVector -(class '(1 2 3)); => clojure.lang.PersistentList +; Os dois tipos básicos de coleção são listas - "list" em inglês - e vetores - "vectors" +; no original. A principal diferença entre eles se +; dá pela implementação: +; - Vetores são implementados como arrays +; - Listas são listas ligadas +(class [1 2 3]) ; => clojure.lang.PersistentVector +(class '(1 2 3)) ; => clojure.lang.PersistentList -; Uma lista é escrita como (1 2 3), mas temos que colocar a aspa -; simples para impedir o leitor (reader) de pensar que é uma função. -; Também, (list 1 2 3) é o mesmo que '(1 2 3) +; Outra forma de declarar listas é usando a função list +(list 1 2 3) ; => '(1 2 3) -; "Coleções" são apenas grupos de dados -; Listas e vetores são ambos coleções: +; Clojure classifica conjuntos de dados de duas maneiras + +; "Coleções" são grupos simples de dados +; Tanto listas quanto vetores são coleções: (coll? '(1 2 3)) ; => true (coll? [1 2 3]) ; => true ; "Sequências" (seqs) são descrições abstratas de listas de dados. -; Apenas listas são seqs. +; Sequências - ou seqs - são conjuntos de dados com avaliação "lazy" +; Apenas listas são seqs: (seq? '(1 2 3)) ; => true (seq? [1 2 3]) ; => false -; Um seq precisa apenas prover uma entrada quando é acessada. -; Portanto, já que seqs podem ser avaliadas sob demanda (lazy) -- elas podem definir séries infinitas: -(range 4) ; => (0 1 2 3) -(range) ; => (0 1 2 3 4 ...) (uma série infinita) -(take 4 (range)) ; (0 1 2 3) +; Ter avaliação lazy significa que uma seq somente precisa prover uma informação quando +; ela for requisitada. Isso permite às seqs representar listas infinitas. +(range) ; => (0 1 2 3 4 ...) +(cycle [1 2]) ; => (1 2 1 2 1 2 ...) +(take 4 (range)) ; => (0 1 2 3) -; Use cons para adicionar um item no início de uma lista ou vetor +; A função cons é usada para adicionar um item ao início de uma lista ou vetor: (cons 4 [1 2 3]) ; => (4 1 2 3) (cons 4 '(1 2 3)) ; => (4 1 2 3) -; Conj adiciona um item em uma coleção sempre do jeito mais eficiente. -; Para listas, elas inserem no início. Para vetores, é inserido no final. +; Já conj adiciona um item em uma coleção sempre do jeito mais eficiente. +; Em listas, isso significa inserir no início. Já em vetores, ao final. (conj [1 2 3] 4) ; => [1 2 3 4] (conj '(1 2 3) 4) ; => (4 1 2 3) -; Use concat para concatenar listas e vetores +; Concatenação de coleções pode ser feita usando concat. Note que ela sempre gera uma +; seq como resultado e está sujeita a problemas de perfomance em coleções grandes, por +; conta da natureza lazy das seqs. +(concat '(1 2) [3 4]) ; => (1 2 3 4) (concat [1 2] '(3 4)) ; => (1 2 3 4) -; Use filter, map para interagir com coleções +; Outra forma de concatenar coleções é usando into. Ela não está sujeita a problemas +; com a avaliação lazy, mas o resultado final da ordem e do tipo dos argumentos passados +(into [1 2] '(3 4)) ; => [1 2 3 4] +(into '(1 2) [3 4]) ; => (4 3 1 2) + +; Note que em into a ordem dos parâmetros influencia a coleção final. +(into [1 2] '(3 4)) ; => (1 2 3 4) +(into '(1 2) [3 4]) ; => (4 3 1 2) + +; As funções filter e map podem ser usadas para interagir com as coleções. Repare que +; elas sempre retornam seqs, independentemente do tipo do seu argumento. (map inc [1 2 3]) ; => (2 3 4) -(filter even? [1 2 3]) ; => (2) +(filter even? [1 2 3 4]) ; => (2 4) + +; Use reduce reduzir coleções a um único valor. Também é possível passar um argumento +; para o valor inicial das operações +(reduce + [1 2 3]) ; = (+ (+ (+ 1 2) 3) 4) => 10 +(reduce + 10 [1 2 3 4]) ; = (+ (+ (+ (+ 10 1) 2) 3) 4) => 20 +(reduce conj [] '(3 2 1)) ; = (conj (conj (conj [] 3) 2) 1) => [3 2 1] + +; Reparou na semelhança entre listas e as chamadas de código Clojure? Isso se deve ao +; fato de que todo código clojure é escrito usando listas. É por isso que elas sempre +; são declaradas com o caracter ' na frente. Dessa forma o interpretador não tenta +; avaliá-las. +'(+ 2 3) ; cria uma lista com os elementos +, 2 e 3 +(+ 2 3) ; o interpretador chama a função + passando como argumentos 2 e 3 -; Use reduce para reduzi-los -(reduce + [1 2 3 4]) -; = (+ (+ (+ 1 2) 3) 4) -; => 10 +; Note que ' é apenas uma abreviação para a função quote. +(quote (1 2 3)) ; => '(1 2 3) + +; É possível passar uma lista para que o interpretador a avalie. Note que isso está +; sujeito ao primeiro elemento da lista ser um literal com um nome de uma função válida. +(eval '(+ 2 3)) ; => 5 +(eval '(1 2 3)) ; dá erro pois o interpretador tenta chamar a função 1, que não existe -; Reduce pode receber um argumento para o valor inicial -(reduce conj [] '(3 2 1)) -; = (conj (conj (conj [] 3) 2) 1) -; => [3 2 1] ; Funções ;;;;;;;;;;;;;;;;;;;;; -; Use fn para criar novas funções. Uma função sempre retorna -; sua última expressão. -(fn [] "Hello World") ; => fn +; Use fn para criar novas funções. Uma função sempre retorna sua última expressão. +(fn [] "Olá Mundo") ; => fn + +; Para executar suas funções, é preciso chamá-las, envolvendo-as em parênteses. +((fn [] "Olá Mundo")) ; => "Olá Mundo" + +; Como isso não é muito prático, você pode nomear funções atribuindo elas a literais. +; Isso torna muito mais fácil chamá-las: +(def ola-mundo (fn [] "Olá Mundo")) ; => fn +(ola-mundo) ; => "Olá Mundo" -; (É necessário colocar parênteses para chamá-los) -((fn [] "Hello World")) ; => "Hello World" +; Você pode abreviar esse processo usando defn: +(defn ola-mundo [] "Olá Mundo") -; Você pode atribuir valores a variáveis utilizando def -(def x 1) -x ; => 1 +; Uma função pode receber uma lista de argumentos: +(defn ola + [nome] + (str "Olá " nome)) +(ola "Jonas") ; => "Olá Jonas" -; Atribua uma função para uma var -(def hello-world (fn [] "Hello World")) -(hello-world) ; => "Hello World" +; É possível criar funções que recebam multivariadas, isto é, que aceitam números +; diferentes de argumentos: +(defn soma + ([] 0) + ([a] a) + ([a b] (+ a b))) -; Você pode abreviar esse processo usando defn -(defn hello-world [] "Hello World") +(soma) ; => 0 +(soma 1) ; => 1 +(soma 1 2) ; => 3 -; O [] é uma lista de argumentos para um função. -(defn hello [name] - (str "Hello " name)) -(hello "Steve") ; => "Hello Steve" +; Funções podem agrupar argumentos extras em uma seq: +(defn conta-args + [& args] + (str "Você passou " (count args) " argumentos: " args)) +(conta-args 1 2 3 4) ; => "Você passou 4 argumentos: (1 2 3 4)" -; Você pode ainda usar essa abreviação para criar funcões: -(def hello2 #(str "Hello " %1)) -(hello2 "Fanny") ; => "Hello Fanny" +; Você pode misturar argumentos regulares e argumentos em seq: +(defn ola-e-conta + [nome & args] + (str "Olá " nome ", você passou " (count args) " argumentos extras")) +(ola-e-conta "Maria" 1 2 3 4) ; => "Olá Maria, você passou 4 argumentos extras" -; Vocé pode ter funções multi-variadic, isto é, com um número variável de argumentos -(defn hello3 - ([] "Hello World") - ([name] (str "Hello " name))) -(hello3 "Jake") ; => "Hello Jake" -(hello3) ; => "Hello World" -; Funções podem agrupar argumentos extras em uma seq -(defn count-args [& args] - (str "You passed " (count args) " args: " args)) -(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +; Nos exemplos acima usamos def para associar nomes a funções, mas poderíamos usá-lo +; para associar nomes a quaisquer valores: +(def xis :x) +xis ; => :x -; Você pode misturar argumentos regulares e argumentos em seq -(defn hello-count [name & args] - (str "Hello " name ", you passed " (count args) " extra args")) -(hello-count "Finn" 1 2 3) -; => "Hello Finn, you passed 3 extra args" +; Inclusive, tais literais podem possuir alguns caracteres não usuais em outras linguagens: +(def *num-resposta* 42) +(def conexao-ativa? true) +(def grito-de-medo! "AAAAAAA") +(def ->vector-vazio []) + +; É possível, inclusive, criar apelidos a nomes que já existem: +(def somar! soma) +(somar! 41 1) ; => 42 + +; Uma forma rápida de criar funções é por meio de funções anônimas. Elas são ótimas +; para manipulação de coleções e seqs, já que podem ser passadas para map, filter +; e reduce. Nessas funções, % é substituído por cada um dos items na seq ou na coleção: +(filter #(not= % nil) ["Joaquim" nil "Maria" nil "Antônio"]) ; => ("Joaquim" "Maria" "Antônio") +(map #(* % (+ % 2)) [1 2]) ; => (3 8) ; Mapas ;;;;;;;;;; -; Hash maps e array maps compartilham uma mesma interface. Hash maps são mais -; rápidos para pesquisa mas não mantém a ordem da chave. +; Existem dois tipos de mapas: hash maps e array maps. Ambos compartilham uma mesma +; interface e funções. Hash maps são mais rápidos para retornar dados, mas não mantém +; as chaves ordenadas. (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap -; Arraymaps pode automaticamente se tornar hashmaps através da maioria das -; operações se eles ficarem grandes o suficiente, portanto não há necessida de -; se preocupar com isso. - -;Mapas podem usar qualquer valor que se pode derivar um hash como chave +; Clojure converte automaticamente array maps em hash maps, por meio da maioria das +; funções de manipulação de mapas, caso eles fiquem grandes o suficiente. Não é +; preciso se preocupar com isso. - -; Mapas podem usar qualquer valor em que se pode derivar um hash como chave, -; mas normalmente palavras-chave (keywords) são melhores. -; Keywords são como strings mas com algumas vantagens. +; Chaves podem ser qualquer valor do qual possa ser obtido um hash, mas normalmente +; usam-se keywords como chave, por possuírem algumas vantagens. (class :a) ; => clojure.lang.Keyword -(def stringmap {"a" 1, "b" 2, "c" 3}) -stringmap ; => {"a" 1, "b" 2, "c" 3} +; Keywords são como strings, porém, duas keywords de mesmo valor são sempre armazenadas +; na mesma posição de memória, o que as torna mais eficientes. +(identical? :a :a) ; => true +(identical? (String. "a") (String. "a")) ; => false -(def keymap {:a 1, :b 2, :c 3}) -keymap ; => {:a 1, :c 3, :b 2} +(def mapa-strings {"a" 1 "b" 2 "c" 3}) +mapa-strings ; => {"a" 1, "b" 2, "c" 3} -; A propósito, vírgulas são sempre tratadas como espaçoes em branco e não fazem nada. +(def mapa-keywords {:a 1 :b 2 :c 3}) +mapa-keywords ; => {:a 1, :c 3, :b 2} -; Recupere o valor de um mapa chamando ele como uma função -(stringmap "a") ; => 1 -(keymap :a) ; => 1 +; Você pode usar um mapa como função para recuperar um valor dele: +(mapa-strings "a") ; => 1 +(mapa-keywords :a) ; => 1 -; Uma palavra-chave pode ser usada pra recuperar os valores de um mapa -(:b keymap) ; => 2 +; Se a chave buscada for uma keyword, ela também pode ser usada como função para recuperar +; valores. Note que isso não funciona com strings. +(:b mapa-keywords) ; => 2 +("b" mapa-strings) ; => java.lang.String cannot be cast to clojure.lang.IFn -; Não tente isso com strings -;("a" stringmap) -; => Exception: java.lang.String cannot be cast to clojure.lang.IFn +; Se você buscar uma chave que não existe, Clojure retorna nil: +(mapa-strings "d") ; => nil -; Buscar uma chave não presente retorna nil -(stringmap "d") ; => nil +; Use assoc para adicionar novas chaves em um mapa. +(def mapa-keywords-estendido (assoc mapa-keywords :d 4)) +mapa-keywords-estendido ; => {:a 1, :b 2, :c 3, :d 4} -; Use assoc para adicionar novas chaves para hash-maps -(def newkeymap (assoc keymap :d 4)) -newkeymap ; => {:a 1, :b 2, :c 3, :d 4} +; Mas lembre-se que tipos em Clojure são sempre imutáveis! Isso significa que o mapa +; inicial continua com as mesmas informações e um novo mapa, com mais dados, é criado +; a partir dele +mapa-keywords ; => {:a 1, :b 2, :c 3} -; Mas lembre-se, tipos em Clojure são sempre imutáveis! -keymap ; => {:a 1, :b 2, :c 3} +; assoc também pode ser usado para atualizar chaves: +(def outro-mapa-keywords (assoc mapa-keywords :a 0)) +outro-mapa-keywords ; => {:a 0, :b 2, :c 3} ; Use dissoc para remover chaves -(dissoc keymap :a :b) ; => {:c 3} +(dissoc mapa-keywords :a :b) ; => {:c 3} + +; Mapas também são coleções - mas não seqs! +(coll? mapa-keywords) ; => true +(seq? mapa-keywords) ; => false + +; É possível usar filter, map e qualquer outra função de coleções em mapas. +; Porém a cada iteração um vetor no formato [chave valor] vai ser passado como +; argumento. Por isso é conveniente usar funções anônimas. +(filter #(odd? (second %)) mapa-keywords) ; => ([:a 1] [:c 3]) +(map #(inc (second %)) mapa-keywords) ; => (2 3 4) ; Conjuntos ;;;;;; -(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +; Conjuntos são um tipo especial de coleções que não permitem elementos repetidos. +; Eles podem ser criados com #{} ou com a função set. (set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet -; Adicione um membro com conj -(conj #{1 2 3} 4) ; => #{1 2 3 4} +; Note que nem sempre um set vai armazenar seus elementos na ordem esperada. +(def meu-conjunto #{1 2 3}) +meu-conjunto ; => #{1 3 2} -; Remova um membro com disj -(disj #{1 2 3} 1) ; => #{2 3} +; Adição funciona normalmente com conj. +(conj meu-conjunto 4) ; => #{1 4 3 2} -; Test por existência usando set como função: -(#{1 2 3} 1) ; => 1 -(#{1 2 3} 4) ; => nil +; Remoção, no entanto, precisa ser feita com disj: +(disj meu-conjunto 1) ; => #{3 2} -; Existem muitas outras funções no namespace clojure.sets +; Para saber se um elemento está em um conjunto, use-o como função. Nesse aspecto +; conjuntos funcionam de maneira semelhante a mapas. +(meu-conjunto 1) ; => 1 +(meu-conjunto 4) ; => nil -; Forms úteis -;;;;;;;;;;;;;;;;; -; Construções lógicas em Clojure são como macros, e -; se parecem com as demais -(if false "a" "b") ; => "b" -(if false "a") ; => nil +; Condicionais e blocos +;;;;;;;;;;;;;;;;; -; Use let para criar um novo escopo associando sîmbolos a valores (bindings) +; Você pode usar um bloco let para criar um escopo local, no qual estarão disponíveis +; os nomes que você definir: (let [a 1 b 2] - (> a b)) ; => false + (+ a b)) ; => 3 -; Agrupe comandos juntos com "do" -(do - (print "Hello") - "World") ; => "World" (prints "Hello") +(let [cores {:yellow "Amarelo" :blue "Azul"} + nova-cor :red + nome-cor "Vermelho"] + (assoc cores nova-cor nome-cor)) ; => {:yellow "Amarelo", :blue "Azul", :red "Vermelho"} -; Funções tem um do implícito -(defn print-and-say-hello [name] - (print "Saying hello to " name) - (str "Hello " name)) -(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") +; Formas do tipo if aceitam três argumentos: a condição de teste, o comando a ser +; executado caso a condição seja positiva; e o comando para o caso de ela ser falsa. +(if true "a" "b") ; => "a" +(if false "a" "b") ; => "b" + +; Opcionalmente você pode não passar o último argumento, mas se a condição for falsa +; o if vai retornar nil. +(if false "a") ; => nil + +; A forma if somente aceita um comando para ser executado em cada caso. Se você +; precisar executar mais comandos, você pode usar a função do: +(if true + (do + (print "Olá ") + (print "Mundo"))) ; => escreve "Olá Mundo" na saída + +; Se você só deseja tratar o caso de sua condição ser verdadeira, o comando when é +; uma alternativa melhor. Seu comportamento é idêntico a um if sem condição negativa. +; Uma de suas vantagens é permitir a execução de vários comandos sem exigir do: +(when true "a") ; => "a" +(when true + (print "Olá ") + (print "Mundo")) ; => também escreve "Olá Mundo" na saída + +; Isso ocorre porque when possui um bloco do implícito. O mesmo se aplica a funções e +; comandos let: +(defn escreve-e-diz-xis + [nome] + (print "Diga xis, " nome) + (str "Olá " nome)) +(escreve-e-diz-xis "João") ;=> "Olá João", além de escrever "Diga xis, João" na saída. + +(let [nome "Nara"] + (print "Diga xis, " nome) + (str "Olá " nome)) ;=> "Olá João", além de escrever "Diga xis, João" na saída. -; Assim como let -(let [name "Urkel"] - (print "Saying hello to " name) - (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") ; Módulos ;;;;;;;;;;;;;;; -; Use "use" para poder usar todas as funções de um modulo +; Você pode usar a função use para carregar todas as funções de um módulo. (use 'clojure.set) -; Agora nós podemos usar operações com conjuntos +; Agora nós podemos usar operações de conjuntos definidas nesse módulo: (intersection #{1 2 3} #{2 3 4}) ; => #{2 3} (difference #{1 2 3} #{2 3 4}) ; => #{1} -; Você pode escolher um subconjunto de funções para importar -(use '[clojure.set :only [intersection]]) - -; Use require para importar um módulo +; Isso porém não é uma boa prática pois dificulta saber de qual módulo cada função +; veio, além de expor o código a conflitos de nomes, caso dois módulos diferentes +; definam funções com o mesmo nome. A melhor forma de referenciar módulos é por meio +; de require: (require 'clojure.string) -; Use / para chamar funções de um módulo +; Com isso podemos chamar as funções de clojure.string usando o operador / ; Aqui, o módulo é clojure.string e a função é blank? (clojure.string/blank? "") ; => true -; Você pode dar para um módulo um nome mais curto no import +; Porém isso não é muito prático, por isso é possível dar para um nome mais curto para +; o módulo ao carregá-lo: (require '[clojure.string :as str]) -(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst." -; (#"" denota uma expressão regular literal) +(str/replace "alguém quer teste?" #"[aeiou]" str/upper-case) ; => "AlgUém qUEr tEstE?" -; Você pode usar require (e até "use", mas escolha require) de um namespace utilizando :require. -; Não é necessário usar aspa simples nos seus módulos se você usar desse jeito. +; Nesse exemplo usamos também a construção #"", que delimita uma expressão regular. + +; É possível carregar outros módulos direto na definição do namespace. Note que nesse +; contexto não é preciso usar ' antes do vetor que define a importação do módulo. (ns test (:require [clojure.string :as str] [clojure.set :as set])) + +; Operadores thread +;;;;;;;;;;;;;;;;; + +; Uma das funções mais interessantes de clojure são os operadores -> e ->> - respectivamente +; thread-first e thread-last macros. Elas permitem o encadeamento de chamadas de funções, +; sendo perfeitas para melhorar a legibilidade em transformações de dados. + +; -> usa o resultado de uma chamada como o primeiro argumento da chamada à função seguinte: +(-> " uMa StRIng com! aLG_uNs ##problemas. " + (str/replace #"[!#_]" "") + (str/replace #"\s+" " ") + str/trim ; se a função só aceitar um argumento, não é preciso usar parênteses + (str/lower-case)) ; => "uma string com alguns problemas." + +; Na thread uma string com vários problemas foi passada como primeiro argumento à função +; str/replace, que criou uma nova string, a partir da original, porém somente com caracteres +; alfabéticos. Essa nova string foi passada como primeiro argumento para a chamada str/replace +; seguinte, que criou uma nova string sem espaços duplos. Essa nova string foi então passada +; como primeiro argumento para str/trim, que removeu espaços de seu início e fim, passando essa +; última string para str/lower-case, que a converteu para caracteres em caixa baixa. + +; ->> é equivalente a ->, porém o retorno de cada função é passado como último argumento da +; função seguinte. Isso é particularmente útil para lidar com seqs, já que as funções que +; as manipulam sempre as tomam como último argumento. +(->> '(1 2 3 4) + (filter even?) ; => '(2 4) + (map inc) ; => '(3 5) + (reduce *)) ; => 15 + + ; Java ;;;;;;;;;;;;;;;;; -; Java tem uma biblioteca padrão enorme e muito útil, -; portanto é importante aprender como utiliza-la. +; A biblioteca padrão de Java é enorme e possui inúmeros algoritmos e estruturas de +; dados já implementados. Por isso é bastante conveniente saber como usá-la dentro +; de Clojure. -; Use import para carregar um modulo java +; Use import para carregar um módulo Java. (import java.util.Date) -; Você pode importar usando ns também. +; Você pode importar classes Java dentro de ns também: (ns test (:import java.util.Date - java.util.Calendar)) + java.util.Calendar + java.util.ArrayList)) ; Use o nome da clase com um "." no final para criar uma nova instância -(Date.) ; +(def instante (Date.)) +(class instante) => ; java.util.Date + +; Para chamar um método, use o operador . com o nome do método. Outra forma é +; usar simplesmente . +(. instante getTime) ; => retorna um inteiro representando o instante +(.getTime instante) ; => exatamente o mesmo que acima -; Use . para chamar métodos. Ou, use o atalho ".method" -(. (Date.) getTime) ; -(.getTime (Date.)) ; exatamente a mesma coisa. +; Para chamar métodos estáticos dentro de classes Java, use / +(System/currentTimeMillis) ; => retorna um timestamp -; Use / para chamar métodos estáticos -(System/currentTimeMillis) ; (o módulo System está sempre presente) +; Note que não é preciso importar o módulo System, pois ele está sempre presente + +; Caso queira submeter uma instância de uma classe mutável a uma sequência de operações, +; você pode usar a função doto. Ela é funciona de maneira semelhante à função -> - ou +; thread-first -, exceto pelo fato de que ele opera com valores mutáveis. +(doto (java.util.ArrayList.) + (.add 11) + (.add 3) + (.add 7) + (java.util.Collections/sort)) ; => # -; Use doto para pode lidar com classe (mutáveis) de forma mais tolerável -(import java.util.Calendar) -(doto (Calendar/getInstance) - (.set 2000 1 1 0 0 0) - .getTime) ; => A Date. set to 2000-01-01 00:00:00 ; STM ;;;;;;;;;;;;;;;;; -; Software Transactional Memory é o mecanismo que Clojure usa para gerenciar -; estado persistente. Tem algumas construções em Clojure que o utilizam. +; Até aqui usamos def para associar nomes a valores. Isso, no entanto, possui algumas +; limitações, já que, uma vez definido essa associação, não podemos alterar o valor +; para o qual um nome aponta. Isso significa que nomes definidos com def não se +; comportam como as variáveis de outras linguagens. + +; Para lidar com estado persistente e mutação de valores, Clojure usa o mecanismo Software +; Transactional Memory. O atom é o mais simples de todos. Passe pra ele um valor inicial e +; e ele criará um objeto que é seguro de atualizar: +(def atom-mapa (atom {})) + +; Para acessar o valor de um atom, você pode usar a função deref ou o operador @: +@atom-mapa ; => {} +(deref atom-mapa) ; => {} -; O atom é o mais simples. Passe pra ele um valor inicial -(def my-atom (atom {})) +; Para mudar o valor de um atom, você deve usar a função swap! +; O que ela faz é chamar a função passada usando o atom como seu primeiro argumento. Com +; isso, ela altera o valor do atom de maneira segura. +(swap! atom-mapa assoc :a 1) ; Atribui a atom-mapa o resultado de (assoc {} :a 1) +(swap! atom-mapa assoc :b 2) ; Atribui a atom-mapa o resultado de (assoc {:a 1} :b 2) -; Atualize o atom com um swap!. -; swap! pega uma função e chama ela com o valor atual do atom -; como primeiro argumento, e qualquer argumento restante como o segundo -(swap! my-atom assoc :a 1) ; Coloca o valor do átomo my-atom como o resultado de (assoc {} :a 1) -(swap! my-atom assoc :b 2) ; Coloca o valor do átomo my-atom como o resultado de (assoc {:a 1} :b 2) +; Observe que essas chamadas alteraram de fato o valor de atom-mapa. Seu novo valor é: +@atom-mapa ; => {:a 1 :b 2} -; Use '@' para desreferenciar um atom e acessar seu valor -my-atom ;=> Atom<#...> (Retorna o objeto do Atom) -@my-atom ; => {:a 1 :b 2} +; Isso é diferente de fazer: +(def atom-mapa-2 (atom {})) +(def atom-mapa-3 (assoc @atom-mapa-2 :a 1)) -; Abaixo um contador simples usando um atom -(def counter (atom 0)) -(defn inc-counter [] - (swap! counter inc)) +; Nesse exemplo, atom-mapa-2 permanece com o seu valor original e é gerado um novo mapa, +; atom-mapa-3, que contém o valor de atom-mapa-2 atualizado. Note que atom-mapa-3 é um +; simples mapa, e não uma instância de um atom +@atom-mapa-2 ; => {} +atom-mapa-3 ; => {:a 1} -(inc-counter) -(inc-counter) -(inc-counter) -(inc-counter) -(inc-counter) +(class atom-mapa-2) ; => clojure.lang.Atom +(class atom-mapa-3) ; => clojure.lang.PersistentArrayMap -@counter ; => 5 +; A ideia é que o valor do atom só será atualizado se, após ser executada a função passada +; para swap!, o atom ainda estiver com o mesmo valor de antes. Isto é, se durante a execução +; da função alguém alterar o valor do atom, swap! reexecutará a função recebida usando o valor +; atual do átoma como argumento. -; Outras construção STM são refs e agents. +; Isso é ótimo em situações nas quais é preciso garantir a consistência de algum valor - tais +; como sistemas bancários e sites de compra. Para mais exemplos e informações sobre outras +; construções STM: + +; Exemplos e aplicações: https://www.braveclojure.com/zombie-metaphysics/ ; Refs: http://clojure.org/refs ; Agents: http://clojure.org/agents ``` ### Leitura adicional -Esse tutorial está longe de ser exaustivo, mas deve ser suficiente para que você possa começar. +Esse tutorial está longe de ser completo, mas deve ser suficiente para que você possa dar seus primeiros passos em Clojure. +Caso queira aprender mais: -Clojure.org tem vários artigos: +* clojure.org tem vários artigos: [http://clojure.org/](http://clojure.org/) -Clojuredocs.org tem documentação com exemplos para quase todas as funções principais (pertecentes ao core): +* Brave Clojure possui um e-book que explora em profundidade diversos recursos de clojure, incluindo ótimos exemplos: +[https://www.braveclojure.com/](https://www.braveclojure.com/) + +* clojuredocs.org tem documentação com exemplos para quase todas as funções principais (pertecentes ao core): [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) -4Clojure é um grande jeito de aperfeiçoar suas habilidades em Clojure/Programação Funcional: +* 4clojure possui alguns problemas e desafios interessantes para quem quiser treinar clojure ou programação funcional: [http://www.4clojure.com/](http://www.4clojure.com/) -Clojure-doc.org tem um bom número de artigos para iniciantes: +* clojure-doc.org tem um bom número de artigos para iniciantes: [http://clojure-doc.org/](http://clojure-doc.org/) -- cgit v1.2.3 From d03ff9338abb42ffc09a52af9b55f7addc1f88ba Mon Sep 17 00:00:00 2001 From: Miltiadis Stouras Date: Mon, 14 Oct 2019 13:49:03 +0300 Subject: Add some resources for Dynamic Programming --- dynamic-programming.html.markdown | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown index c73b1845..5d260206 100644 --- a/dynamic-programming.html.markdown +++ b/dynamic-programming.html.markdown @@ -3,6 +3,7 @@ category: Algorithms & Data Structures name: Dynamic Programming contributors: - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] + - ["Miltiadis Stouras", "https://github.com/mstou"] --- # Dynamic Programming @@ -48,6 +49,15 @@ for i=0 to n-1 ## Online Resources -* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) +* MIT 6.006: [Lessons 19,20,21,22](https://www.youtube.com/playlist?list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb) +* TopCoder: [Dynamic Programming from Novice to Advanced](https://www.topcoder.com/community/data-science/data-science-tutorials/dynamic-programming-from-novice-to-advanced/) +* [CodeChef](https://www.codechef.com/wiki/tutorial-dynamic-programming) * [InterviewBit](https://www.interviewbit.com/courses/programming/topics/dynamic-programming/) - +* GeeksForGeeks: + * [Overlapping Subproblems](https://www.geeksforgeeks.org/dynamic-programming-set-1/) + * [Tabulation vs Memoization](https://www.geeksforgeeks.org/tabulation-vs-memoizatation/) + * [Optimal Substructure Property](https://www.geeksforgeeks.org/dynamic-programming-set-2-optimal-substructure-property/) + * [How to solve a DP problem](https://www.geeksforgeeks.org/solve-dynamic-programming-problem/) +* [How to write DP solutions](https://www.quora.com/Are-there-any-good-resources-or-tutorials-for-dynamic-programming-DP-besides-the-TopCoder-tutorial/answer/Michal-Danilák) + +And a [quiz](https://www.commonlounge.com/discussion/cdbbfe83bcd64281964b788969247253) to test your knowledge. -- cgit v1.2.3 From 33211b82f73a3f04a6adb8aa691f82ae767b5ae7 Mon Sep 17 00:00:00 2001 From: Amey Bhavsar Date: Mon, 14 Oct 2019 20:04:48 +0530 Subject: Minor spelling mistake corrected On line 144, it was _per_, instead of _pre_ --- latex.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/latex.html.markdown b/latex.html.markdown index c980f5e5..e8bc6064 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -141,7 +141,7 @@ Operators are essential parts of a mathematical document: trigonometric functions ($\sin$, $\cos$, $\tan$), logarithms and exponentials ($\log$, $\exp$), limits ($\lim$), etc.\ -have per-defined LaTeX commands. +have pre-defined LaTeX commands. Let's write an equation to see how it's done: $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ -- cgit v1.2.3 From 3996c22a891bb49018e2d80fa7b75fbd6e67e223 Mon Sep 17 00:00:00 2001 From: Chariton Charitonidis Date: Sat, 19 Oct 2019 16:01:29 +0300 Subject: add greek translation for python3 --- el-gr/python3-gr.html.markdown | 1030 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1030 insertions(+) create mode 100644 el-gr/python3-gr.html.markdown diff --git a/el-gr/python3-gr.html.markdown b/el-gr/python3-gr.html.markdown new file mode 100644 index 00000000..08c3d4aa --- /dev/null +++ b/el-gr/python3-gr.html.markdown @@ -0,0 +1,1030 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] +filename: learnpython3.py +--- + +Η Python δημιουργήθηκε από τον Guido van Rossum στις αρχές των 90s. Πλέον είναι μία από τις πιο +δημοφιλείς γλώσσες. Ερωτευεται κανείς την python για τη συντακτική της απλότητα. +Βασικά είναι εκτελέσιμος ψευδοκώδικας. + +Το Feedback είναι πάντα δεκτό! Μπορείτε να με βρείτε στο [@haritonaras](http://twitter.com/haritonaras) +ή τον αρχικό συγγραφέα στο [@louiedinh](http://twitter.com/louiedinh) ή στο +louiedinh [at] [google's email service] + +Σημείωση: Το παρόν άρθρο ασχολείται μόνο με την Python 3. Δείτε [εδώ](http://learnxinyminutes.com/docs/python/) αν θέλετε να μάθετε την παλιά Python 2.7 + +```python + +# Τα σχόλια μίας γραμμής ξεκινούν με # + +""" Τα σχόλια πολλαπλών γραμμών μπορούν + να γραφούν με τρία ", και συχνά χρησιμοποιούνται + ως documentation. +""" + +#################################################### +## 1. Primitive (πρωταρχικοί) Τύποι Δεδομένων και Τελεστές +#################################################### + +# Αφού έχει αριθμούς +3 # => 3 + +# Λογικά θα έχει και Μαθηματικά... +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Η διαίρεση ακεραίων κάνει στρογγυλοποίηση προς τα κάτω για θετικούς και αρνητικούς αριθμούς +5 // 3 # => 1 +-5 // 3 # => -2 +5.0 // 3.0 # => 1.0 # works on floats too +-5.0 // 3.0 # => -2.0 + +# Το αποτέλεσμα της διαίρεσης είναι πάντα float +10.0 / 3 # => 3.3333333333333335 + +# Modulo τελεστής +7 % 3 # => 1 + +# Ύψωση σε δύναμη (x**y, x στην y-οστή δύναμη) +2**3 # => 8 + +# Ελέγχουμε την προτεραιότητα πράξεων με παρενθέσεις +(1 + 3) * 2 # => 8 + +# Οι Boolean τιμές είναι primitives (Σημ.: τα κεφαλαία) +True +False + +# άρνηση με το not +not True # => False +not False # => True + +# Boolean τελεστές +# Σημ. ότι τα "and" και "or" είναι case-sensitive +True and False # => False +False or True # => True + +# Τα True και False είναι 1 και 0 αλλά με διαφορετικά keywords +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# Μπορούμε να δούμε τις αριθμητικές τιμές των True και False μέσω των τελεστών σύγκρισης +0 == False # => True +1 == True # => True +2 == True # => False +-5 != False # => True + +# Χρησιμοποιώντας τελεστές boolean σε ακεραίους, οι ακέραιοι γίνονται cast σε +# boolean ώστε να γίνει η αποτίμηση της έκφρασης. +# Το αποτέλεσμα όμως είναι non-cast, δηλαδή ίδιου τύπου με τα αρχικά ορίσματα +# Μην μπερδεύετε τις bool(ints) και bitwise and/or (&,|) +bool(0) # => False +bool(4) # => True +bool(-6) # => True +0 and 2 # => 0 +-5 or 0 # => -5 + +# Ισότητα == +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 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False +# Το Chaining (αλυσίδωση? :P) κάνει το παραπάνω πιο όμορφα +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) το is ελέγχει αν δύο μεταβλητές αναφέρονται στο ίδιο αντικείμενο, +# αλλά το == ελέγχει αν τα αντικείμενα στα οποία αναφέρονται οι μεταβλητές έχουν τις ίδιες τιμές +a = [1, 2, 3, 4] # το a δείχνει σε μία νέα λίστα, [1,2,3,4] +b = a # το b δείχνει στο αντικείμενο που δείχνει το a +b is a # => True, a και b αναφέρονται στο ίδιο αντικείμενο +b == a # => True, τα αντικείμενα των a κι b είναι ίσα +b = [1, 2, 3, 4] # Το b δείχνει σε μία νέα λίστα, [1, 2, 3, 4] +b is a # => False, a και b δεν αναφέρονται στο ίδιο αντικείμενο +b == a # => True, τα αντικείμενα των a και b είναι ίσα + +# Τα Strings (συμβολοσειρές) δημιουργούνται με " ή ' +"This is a string." +'This is also a string.' + +# Μπορούμε και να προσθέτουμε Strings, αλλά προσπαθήστε να μην το κάνετε +"Hello " + "world!" # => "Hello world!" +# Τα String literals (αλλά όχι οι μεταβλητές) μπορούν να συντμιθούν και χωρίς το '+' +"Hello " "world!" # => "Hello world!" + +# Μπορούμε να φερθούμε σε string σαν να είναι λίστα από χαρακτήρες +"This is a string"[0] # => 'T' + +# Μπορούμε να βρούμε το μήκος ενός string +len("This is a string") # => 16 + +# Το .format μπορεί να χρησιμοποιηθεί για να μορφοποιήσουμε strings, όπως εδώ: +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" + +# Μπορείς να επαναλάβεις τα ορίσματα του formatting για να γλιτώσεις λίγο χρονο +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# Μπορείς να χρησιμοποιήσεις keywords αν βαριέσαι το μέτρημα. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" + +# Αν ο κώδικας Python 3 που γράφεις πρόκειται να τρέξει και με python 2.5 ή παλιότερη +# μπορείς επίσης να χρησιμοποιήσεις το παλιό τρόπο για formatting: +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" + +# Μπορείς επίσης να μορφοποιήσεις χρησιμοποιώντας τα f-strings / formatted string literals (σε Python 3.6+) +name = "Reiko" +f"She said her name is {name}." # => "She said her name is Reiko" +# Μπορείς βασικά να βάλεις οποιαδήποτε έκφραση Python στα άγκιστρα και θα εμφανιστεί στο string. +f"{name} is {len(name)} characters long." + + +# το None είναι ένα αντικείμενο (object) +None # => None + +# Μη χρησιμοποιείτε το σύμβολο ισότητας "==" για να συγκρίνετε αντικείμενα με το None +# Χρησιμοποιείτε το "is". Αυτό ελέγχει για ισότητα της ταυτότητας του αντικειμένου. +"etc" is None # => False +None is None # => True + +# Τα None, 0, και τα κενά strings/lists/dicts/tuples αποτιμούνται στην τιμή False +# All other values are True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False + +#################################################### +## 2. Μεταβλητές (variables) και Συλλογές (collections) +#################################################### + +# Η Python έχει μία συνάρτηση print() +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# By default, η συνάρτηση print() τυπώνει και ένα χαρακτήρα αλλαγής γραμμμής στο τέλος +# Χρησιμοποιείτε το προαιρετικό όρισμο end για να τυπώνει οτιδήποτε άλλο +print("Hello, World", end="!") # => Hello, World! + +# Απλός τρόπος για να πάρουμε δεδομένα εισόδου από το console +input_string_var = input("Enter some data: ") # επιστρέφει τα δεδομένα ως string +# Σημ.: Στις προηγούμενες εκδόσεις της Python, η μέθοδος input() ονομαζόταν raw_input() + +# Δεν υπάρχουν δηλώσεις, μόνο αναθέσεις τιμών. +# Η σύμβαση είναι να χρησιμοποιούμε μικρά γράμματα με κάτω παύλες +some_var = 5 +some_var # => 5 + +# Η πρόσβαση σε μεταβλητή που δεν έχει λάβει τιμή είναι εξαίρεση +# Δες τον Έλεγχο Ροής για να μάθεις περισσότερα για το χειρισμό εξαιρέσεων +some_unknown_var # Προκαλέι ένα NameError + +# Η παρακάτω έκφραση μπορεί να χρησιμποιηθεί ισοδύναμα με τον τελεστή '?' της C +"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] +# Ας βάλουμε το 3 πίσω στη θέση του +li.append(3) # η li γίνεται πάλι [1, 2, 4, 3]. + +# Προσπελαύνουμε τις λίστες όπως τους πίνακες σε άλλες γλώσσες +li[0] # => 1 +# Το τελευταίο στοιχείο... +li[-1] # => 3 + +# Όταν βγαίνουμε εκτός ορίων της λίστας προκαλείται IndexError +li[4] # προκαλεί IndexError + +# Μπορείς να δεις ranges μιας λίστας με το slice syntax ':' +# Ο δείκτης εκίνησης περιλαμβάνεται στο διάστημα, ο δείκτης τερματισμού όχι +# (είναι ανοικτό/κλειστό διάστημα για τους φίλους των μαθηματικών) +li[1:3] # => [2, 4] +# Αγνόησε την αρχή και επίστρεψε τη λίστα +li[2:] # => [4, 3] +# Αγνόησε το τέλος και επίστρεψε τη λίστα +li[:3] # => [1, 2, 4] +# Διάλεξε κάθε δεύτερο στοιχείο +li[::2] # =>[1, 4] +# Επίστρεψε ένα reversed αντίγραφο της λίστας +li[::-1] # => [3, 4, 2, 1] +# Χρησιμοποιείστε οποιαδήποτε συνδυασμό αυτών για να φτιάξετε πιο προχωρημένα slices +# li[start:end:step] + +# Φτιάξε ένα αντίγραφο της λίστας χρησιμοποιώντας slices +li2 = li[:] # => li2 = [1, 2, 4, 3] αλλά το (li2 is li) επιστρέφει False + +# Αφαίρεσε οποιοδήποτε στοιχείο από λίστα με την εντολή "del" +del li[2] # η li γίνεται [1, 2, 3] + +# Αφαιρούμε το πρώτο στιγμυότυπο μιας τιμής +li.remove(2) # η li γίνεται [1, 3] +li.remove(2) # Προκαλεί ένα ValueError καθώς το 2 δεν βρίσκεται στη λίστα. + +# Εισαγωγή ενός στοιχείου σε συγκεκριμένη θέση +li.insert(1, 2) # η li γίνεται πάλι [1, 2, 3] + +# Βρες το index (δείκτη) του πρώτου στοιχείου με τιμή ίση με το όρισμα +li.index(2) # => 1 +li.index(4) # Προκαλεί ValueError καθώς το 4 δεν βρίσκεται στη λίστα + +# Μπορείς να προσθέτεις λίστες +# Σημ.: οι τιμές των li, other_li δεν αλλάζουν. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Σύντμιση λιστών με τη μέθοδο "extend()" +li.extend(other_li) # Τώρα η li είναι [1, 2, 3, 4, 5, 6] + +# Ελεγχος της ύπαρξης στοιχείου σε λίστα με το "in" +1 in li # => True + +# Εξατάζουμε το μήκος με "len()" +len(li) # => 6 + + +# Τα Tuples είναι σαν τις λίστες αλλά είναι αμετάβλητα (immutable). +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Προκαλεί TypeError + +# Σημειώστε ότι ένα tuple μήκους 1 πρέπει να έχει ένα κόμμα μετά το τελευταίο στοιχείο +# αλλά τα tuples άλλων μηκών, ακόμα και μηδενικού μήκους, δεν χρειάζονται κόμμα. +type((1)) # => +type((1,)) # => +type(()) # => + +# Μπορείς να εφαρμόσεις τις περισσότερες μεθόδους των λιστών και στα tuples +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Μπορείς να κάνεις unpack/"ξεπακετάρεις" tuples σε μεταβλητές +a, b, c = (1, 2, 3) # a == 1, b == 2 και c == 3 +# Μπορείς επίσης να επεκτείνεις το unpacking +a, *b, c = (1, 2, 3, 4) # a == 1, b == [2, 3] και c == 4 +# Τα Tuples δημιουργούνται by deafult αν δεν βάλεις παρενθέσεις +d, e, f = 4, 5, 6 # το tuple 4, 5, 6 "ξεπακετάρεται" στις μεταβλητές d, e και f +# αντίστοιχα έτσι ώστε να γίνεται d = 4, e = 5 and f = 6 +# Δείτε πόσο εύκολα μπορούμε να εναλλάσουμε δύο τιμές +e, d = d, e # το d παίρνει την τιμή 5 και το e παίρνει την τιμή 4 + + +# Τα λεξικά (Dictionaries) αποθηκεύουν απεικονίσεις από κλειδιά σε τιμές +empty_dict = {} +# Εδώ έχουμε ένα προ-γεμισμένο dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Σημ. ότι τα κλειδιά για τα dictionaries πρέπει να είναι αμετάβλητοι τύποι +# (immutable) αυτό γίνετια για να διασφαλίσουμε ότι τα κλειδιά μπορούν να +# μετατρέπονται σε σταθερές τιμές κατακερματισμού (hash values) για γρήγορη εύρεση. +# Μερικοί αμετάβλητοι τύποι είναι τα ints, floats, strings, tuples. +invalid_dict = {[1,2,3]: "123"} # => Προκαλεί TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Οι τιμές όμως μπορούν να έχουν οποιοδήποτε τύπο. + +# Βρίσκουμε τιμές με [] +filled_dict["one"] # => 1 + +# Μπορείς να πάρεις όλα τα κλειδιά με τη μέθοδο "keys()". +# Πρέπει να "τυλίξουμε" την κλήση με list() για να το μετατρέψουμε σε λίστα +# Θα μιλήσουμε για αυτά αργότερα. Σημ. - σε εκδόσεις Python < 3.7, η σειρά που +# εμφανίζονται τα κλειδιά δεν είναι εγγυημένη. Τα αποτελέσματά σας ίσως να μην +# είναι ακριβώς ίδια με τα παρακάτω. Στην έκδοση 3.7 πάντως, τα αντικείμενα του +# λεξικού διατηρούν τη σειρά με την οποία εισήχθησαν στο dictionary +list(filled_dict.keys()) # => ["three", "two", "one"] σε Python <3.7 +list(filled_dict.keys()) # => ["one", "two", "three"] σε Python 3.7+ + +# Παίρνουμε όλες τις τιμές ενός iterable με τη μέθοδο "values()". Και πάλι +# χρειάζεται να το περιτυλίξουμε σε list() +# Σημ. - όπως παραπάνω σχετικά με τη σειρά των keys +list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ + +# Έλεγχος της ύπαρξης κλειδιών σε ένα dictionary με το "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Αν ψάξεις την τιμή ανύπαρκτου κλειδιού προκαλείται KeyError +filled_dict["four"] # KeyError + +# Χρησιμοποιούμε τη μέθοδο "get()" για να αποφύγουμε το KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# στο δεύτερο argument της get() μπορούμε να βάλουμε μία τιμή που πρέπει να +# επιστρέψει αν δεν υπάρχει το key που ψάχνουμε +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# το "setdefault()" εισάγει στο dictionary μόνο αν δεν υπάρχει το κλειδί +filled_dict.setdefault("five", 5) # filled_dict["five"] γίνεται 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] μένει 5 (υπαρκτό κλειδί) + +# Προσθήκη σε dictionary +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +filled_dict["four"] = 4 # β' τρόπος + +# Αφαίρεση κλειδιών από dictionary με del +del filled_dict["one"] # Αφαιρεί το κλειδί "one" από το filled_dict + +# Από την Python 3.5 μπορείς να χρησιμοποιήσεις και πρόσθετες επιλογές για unpacking +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# τα Sets -όπως όλοι περιμένουμε- αποθηκεύουν σύνολα +empty_set = set() +# Αρχικοποιούμε ένα set με μερικές τιμές. Ναι, μοιάζει λίγο με dictionary, Sorry. +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} + +# Παρομοίως με τα κλειδιά του dictionary, τα στοιχεία ενός συνόλου πρέπει να είναι +# αμετάβλητα (immutable) +invalid_set = {[1], 1} # => Προκαλεί TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Προσθέτουμε άλλο ένα στοιχείο στο σύνολο +filled_set = some_set +filled_set.add(5) # το filled_set είναι τώρα {1, 2, 3, 4, 5} +# Τα σύνολα δεν έχουν διπλοτυπα αντικείμενα +filled_set.add(5) # το σύνολο παραμένει ίδιο {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. Έλεγχος Ροής και Iterables +#################################################### + +# Φτιάχνουμε μία μεταβλητή +some_var = 5 + +# Εδώ έχουμε ένα if statement. Η στοίχιση είναι σημαντική στην Python! +# Η σύμβαση είναι να χρησιμοποιούμε 4 κενά, όχι tabs. +# Το παρακάτω τυπώνει "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # το (else if) -> elif μέρος είναι προαιρετικό. + print("some_var is smaller than 10.") +else: # και το else είναι προαιρετικό. + print("some_var is indeed 10.") + + +""" +τα for loops τρέχουν πάνω σε lists +το παρακάτω τυπώνει: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use format() to interpolate formatted strings + print("{} is a mammal".format(animal)) + +""" +το "range(number)" επιστρέφει ένα iterable με αριθμούς +από το μηδέν μέχρι τον δωσμένο αριθμό number (κλειστό/ανοικτό διάστημα) +Το παρακάτω τυπώνει: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +το "range(lower, upper)" επιστρέφει ένα iterable με αριθμούς +από το lower εώς το upper (κλειστό/ανοικτό διάστημα) +το παρακάτω τυπώνει: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +το "range(lower, upper, step)" επιστρέφει ένα iterable με αριθμούς +από το lower μέχρι το upper, με βήμα step +αν δεν δώσουμε τιμή βήματος, το default βήμα είναι 1. +το παρακάτω τυπώνει: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +τα While loops τρέχουν μέχρι μία συνθήκη να γίνει ψευδής. +το παρακάτω τυπώνει: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Shorthand for x = x + 1 + +# Χειριζόμαστε εξαιρέσεις με ένα try/except block +try: + # Χρησιμοποιούμε το "raise" για να πετάξουμε ένα error + raise IndexError("This is an index error") +except IndexError as e: + pass # το Pass δεν κάνει τίποτα. Συνήθως κάνουμε ανάκτηση. +except (TypeError, NameError): + pass # Μπορούμε να χειριζόμαστε πολλές εξαιρέσεις μαζί, αν χρειαστεί +else: # Προαιρετικό στο try/except block. Πρέπει να ακολουθεί όλα τα except blocks + print("All good!") # τρέχει μόνο αν ο κώδικας στο try δεν προκαλεί εξαιρέσεις +finally: # Εκτελείται ό,τι και να γίνει + print("We can clean up resources here") + +# Αντί για try/finally για να καθαρίσουμε τους πόρους, μπορούμε να χρησιμοποιούμε το +# with expression as target: + pass to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print(line) + +# Η Python προσφέρει μία θεμελιώδη αφαίρεση (abstraction) που λέγεται Iterable. +# iterable είναι ένα αντικείμενο που μπορεί να χρησιμοποιηθεί ως ακολουθία. +# Το αντικείμενο που επιστρέφει η συνάρτηση range, είναι ένα iterable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['one', 'two', 'three']). +# Αυτό είναι ένα αντικείμενο που υλοποιεί την iterable διεπαφή μας. + +# μπορούμε να τρέχουμε loops πάνω του. +for i in our_iterable: + print(i) # Prints one, two, three + +# Ωστόσο δεν μπορούμε να προσπελάσουμε τα στοιχεία του με index. +our_iterable[1] # προκαλεί a TypeError + +# Ένα iterable είναι ένα αντικείμενο που ξέρει πώς να δημιουργήσει έναν iterator. +our_iterator = iter(our_iterable) + +# Ο iterator μας είναι ένα αντικείμενο που μπορεί να θυμάται την κατάσταση όπως το διατρέχουμε. +# Παίρνουμε το επόμενο αντικείμενο με το "next()" +next(our_iterator) # => "one" + +# Διατηρεί την κατάσταση καθώς επαναλαμβάνουμε. +next(our_iterator) # => "two" +next(our_iterator) # => "three" + +# Όταν ο iterator έχει επιστρέψει όλα τα δεδομένα του, προκαλεί ένα μια εξαίρεση StopIteration. +next(our_iterator) # προκαλεί StopIteration + +# Μπορείς να πάρεις όλα τα αντικείμενα ενός iteratior καλώντας list() πάνω του. +list(filled_dict.keys()) # => Επιστρέφει ["one", "two", "three"] + + +#################################################### +## 4. Συναρτήσεις +#################################################### + +# Χρησιμποιούμε το "def" για να ορίσουμε νέες συναρτήσεις +def add(x, y): + print("x is {} and y is {}".format(x, y)) + return x + y # επιστρέφει τιμές με την εντολή return + +# Καλούμε συναρτήσεις με παραμέτρους +add(5, 6) # => τυπώνει "x is 5 and y is 6" και επιστρέφει 11 + +# Ένας άλλος τρόπος να καλέσεις συνάρτησει είναι με keyword arguments (ορίσματα λέξεις-κλειδιά) +add(y=6, x=5) # τα Keyword arguments μπορούν να δωθούν με οποιαδήποτε σειρά. + +# Μπορείς να ορίσεις συναρτήσεις που δέχονται μεταβλητό πλήθος ορισμάτων +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Μπορούμε να ορίσουμε και συναρτήσεις που δέχονται μεταβλητό πλήθος keyword arguments +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/kwargs! +# Χρησιμοποίησε το * για να επεκτείνεις tuples και χρησιμοποίησε το ** για να επεκτείλεις kwargs +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # ισοδύναμο με all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # ισοδύναμο με all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # ισοδύναμο με all_the_args(1, 2, 3, 4, a=3, b=4) + +# Επιστρέφουμε πλειάδα τιμών (με tuple assignments) +def swap(x, y): + return y, x # Επιστρέφει πολλές τιμές ως tuple χωρίς την παρένθεση + # (Σημ.: οι παρενθέσεις έχουν παραλειφθεί αλλά μπορούν να γραφούν) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Ξανά, οι παρενθέσεις έχουν παραληφθεί αλλά μπορούν να γραφούν + +# Εμβέλεια συναρτήσεων +x = 5 + +def set_x(num): + # Η τοπική μεταβλητή x δεν είναι η ίδια με την global μεταβλητή x + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + global x + print(x) # => 5 + x = num # η global μεταβλητή 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 + +# Αλλά έχει και anonymous συναρτήσεις. +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Υπάρχουν ενσωματωμένες συναρτήσεις μεγαλύτερης τάξης +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# Μπορούμε να χρησιμοποιήσουμε list comprehensions για ωραία maps και filters +# το List comprehension αποθηκεύει την έξοδο ως μία λίστα που μπορεί και η ίδια +# να είναι μια εμφωλευμένη λίστα +[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] + +# Μπορείς επίσης να κατασκευάσεις set και dict comprehensions. +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Modules +#################################################### + +# Μπορείς να κάνεις import modules +import math +print(math.sqrt(16)) # => 4.0 + +# Μπορείς να πάρεις συγκεκριμένες συναρτήσεις από ένα module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Μπορείς να κάνεις import όλες τις συναρτήσεις από ένα module. +# Προσοχή: δεν προτείνεται +from math import * + +# Μπορείς να δημιουργείς συντομογραφίες για τα ονόματα των modules +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Τα Python modules είναι απλά αρχεία Python. Μπορείς να δημιουργήσεις τα δικά σου +# και να τα κάνεις import το όνομα του module είναι ίδιο με το όνομα του αρχείου + +# μπορείς να βρεις ποιες συναρτήσεις και γνωρίσματα ορίζονται στο module +import math +dir(math) + +# Αν έχεις ένα Python script με όνομα math.py στον ίδιο φάκελο με το τρέχον script +# το αρχείο math.py θα φορτωθεί και όχι το built-in Python module +# Αυτό συμβαίνει επειδή τα τοπικά αρχεία έχουν προτεραιότητα έναντι των built-in +# βιβλιοθηκών της Python + + +#################################################### +## 6. Κλάσεις - Classes +#################################################### + +# χρησιμοποιούμε το "class" statement για να δημιουργήσουμε μια κλάση +class Human: + + # Ένα γνώρισμα της κλάσης. Είναι κοινό για όλα τα στιγμιότυπα αυτής. + species = "H. sapiens" + + # Βασικός initializer, καλείται όταν δημιουργείται στιγμιότυπο της κλάσης. + # Σημ. οι διπλές κάτω παύλες πριν και μετά υποδηλώνουν αντικείμενα + # ή γνωρίσματα που χρησιμοποιούνται από την Python αλλά ζουν σε ελεγχόμενα από + # το χρήση namespaces. + # Μέθοδοι (ή αντικείμενα ή γνωρίσματα) σαν τα __init__, __str__, __repr__ κλπ + # είναι ειδικές μέθοδοι (λέγονται και dunder (double underscore) μέθοδοι) + # Δεν πρέπει να δηλώνεις δικές σου τέτοιες συναρτήσεις + def __init__(self, name): + # Εκχώρησε στο attribute name του object το όρισμα + self.name = name + + # Αρχικοποίησε την ιδιότητα + self._age = 0 + + # Μία μέθοδος στιγμιότυπου (instance method). Όλες οι μέθοδοι παίρνουν το + # "self" ως πρώτο όρισμα + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Ακόμα μία instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' + + # Μία μέθοδος κλάσεις είναι κοινή ανάμεσα σε όλα τα instances. + # Καλούνται με calling class ώς πρώτο όρισμα + @classmethod + def get_species(cls): + return cls.species + + # Μία στατική μέθοδος καλείται χωρίς αναφορά σε κλάση ή στιγμιότυπο + @staticmethod + def grunt(): + return "*grunt*" + + # Ένα property είναι ακριβώς σαν ένα getter. + # Μετατρέπει τη μέθοδο age σε ένα γνώρισμα (attribute) μόνο-για-ανάγνωση + # με το ίδιο όνομα. + # Δεν χρειάζεται να γράφουμε τετριμένους getters και setters στην Python όμως. + @property + def age(self): + return self._age + + # Αυτό επιτρέπει στο property να γίνει set + @age.setter + def age(self, age): + self._age = age + + # Αυτό επιτρέπει σε ένα property να διαγραφεί + @age.deleter + def age(self): + del self._age + + +# Όταν ο διερμηνέας της Python διαβάζει αρχείο πηγαίου κώδικα τον εκτελεί όλο. +# Αυτός ο έλεγχος του __name__ σιγουρεύει ότι αυτό το block κώδικα τρέχει μόνο +# αυτό το module είναι το κύριο πρόγραμμα (και όχι imported) +if __name__ == '__main__': + # Δημιουργούμε στιγμιότυπο κλάσης + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # τα i και j είναι στιγμιότυπα του τύπου Human + + # Καλούμε τη μέθοδο της κλάσης + i.say(i.get_species()) # "Ian: H. sapiens" + # Αλλάζουμε το κοινό attribute των αντικειμένων της κλάσης + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Καλούμε τη static μέθοδο + print(Human.grunt()) # => "*grunt*" + + # Δεν μπορούμε να καλέσουμε τη στατική μέθοδο με ένα στιγμιότυπο + # επειδή το i.grunt() θα βάλει αυτόματα το self (δηλαδή το αντικείμενο i) ως όρισμα + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + + # Ενημερώνουμε το property για αυτό το στγμιότυπο + i.age = 42 + # Παίρνουμε το property + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" + # Διαγράφουμε το property + del i.age + # i.age # => αυτό θα προκαλούσε AttributeError + + +#################################################### +## 6.1 Κληρονομικότητα - Inheritance +#################################################### + +# Η κληρονομικότητα επιτρέπει σε νέες κλάσεις-παιδιά να οριστούν και να υιοθετήσουν +# μεθόδους και μεταβλητές από την κλάση-γονέα. + +# Χρησιμοποιώντας την κλάση Human που ορίστηκε πριν ως τη βασική κλάση (ή κλάση-γονέα) +# μπορούμε να ορίσουμε τις κλάσεις-παιδιά Superhero, που κληρονομεί μεταβλητές όπως +# "species", "name", και "age", καθώς και μεθόδους όπως "sing" και "grunt" +# από την κλάση Human, αλλά επίσης έχει τις δικές του ξεχωριστές ιδιότητες + +# Για να εκμεταλλευτείς το modularization κατά αρχείο, μπορείς να βάλεις την παραπάνω κλάση +# σε δικό της αρχείο, ας πούμε human.py + +# Για να κάνουμε import συναρτήσεις από άλλα αρχεία χρησιμοποιούμε το παρακάτω format +# from "filename-without-extension" import "function-or-class" + +from human import Human + + +# Προσδιόρισε την/τις parent class(es) ως παραμέτρους της κλάσης που ορίζεται +class Superhero(Human): + + # Αν η κλάση-παιδί πρέπει να κληρονομήσει όλους τους οεισμούς της κλάσης-γονέα + # χωρίς καμία αλλαγή, μπορείς απλά να γράψεις pass (και τίποτα άλλο) + # αλλά σε αυτή την περίπτωση είναι σχολιασμένο για να επιτρέψει τη δημιουργία + # ξεχωριστής κλάσης-παιδιού: + # pass + + # Η κλάση παιδί μπορεί να υπερφορτώσει (override) τα attributes της κλάσης από την οποία κληρονομεί + species = 'Superhuman' + + # Τα παιδιά αυτόματα, κληρονομούν τον constructo της κλάσης-γονέα + # συμπεριλαμβανομένων των ορισμάτων, αλλά μπορείς και να ορίσεις πρόσθετα ορίσματα + # ή ορισμούς και να κάνεις override τις μεθόδους, όπως τον constructor. + # Αυτός ο constructor κληρονομεί το όρισμα "name" από την κλάση Human και + # προσθέτει τα ορίσματα "superpower" και "movie": + def __init__(self, name, movie=False, + superpowers=["super strength", "bulletproofing"]): + + # πρόσθήκη επιπλέον attributes της κλάσης: + self.fictional = True + self.movie = movie + # έχετε το νου σας τις μεταβλητές (mutable) default τιμές, καθώς είναι κοινές + self.superpowers = superpowers + + # Η συνάρτηση "super" επιτρέπει την πρόσβαση στις μεθόδους της κλάσης-γονέα + # που είναι υπερφορτωμένες από το παιδί. Σε αυτή την περίπτωση τη μέθοδο __init__ + # Το παρακάτω καλεί τον constructor της κλάσης-γονέα: + super().__init__(name) + + # υπερφόρτωση της μεθόδου sing + def sing(self): + return 'Dun, dun, DUN!' + + # προσθήκη νέας μεθόδου που εφαρμόζεται σε στιγμιότυπα + def boast(self): + for power in self.superpowers: + print("I wield the power of {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Tick") + + # Έλεγχος για το αν το στιγμιότυπο sup ανήκει στην κλάση Human + if isinstance(sup, Human): + print('I am human') + if type(sup) is Superhero: + print('I am a superhero') +# TODO: + # Παίρνουμε το Method Resolution search Order που χρησιμοποιούν οι getattr() και super() + # Αυτό το attribute είναι δυναμικό και μπορεί να ανανεωθεί + print(Superhero.__mro__) # => (, + # => , ) + + # Καλούμε μέθοδο της κλάσης-γονέα, αλλά χρησιμοποιεί το δικό της attribute + print(sup.get_species()) # => Superhuman + + # Καλεί την υπερφορτωμένη μέθοδο + print(sup.sing()) # => Dun, dun, DUN! + + # Καλεί μέθοδο από την κλάση Human + sup.say('Spoon') # => Tick: Spoon + + # Καλεί μέθοδο που υπάρχει μόνο στην κλάση Superhero + sup.boast() # => I wield the power of super strength! + # => I wield the power of bulletproofing! + + # Κληρονομημένο class attribute + sup.age = 31 + print(sup.age) # => 31 + + # Attribute που υπάρχει μόνο στην μέσα στην κλάση Superhero + print('Am I Oscar eligible? ' + str(sup.movie)) + +#################################################### +## 6.2 Πολλαπλή Κληρονομικότητα - Multiple Inheritance +#################################################### + +# Ένας ακόμη ορισμός κλάσης +# bat.py +class Bat: + + species = 'Baty' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # Αυτή η κλάση έχει επίσης μία μέθοδο say + def say(self, msg): + msg = '... ... ...' + return msg + + # Και τη δική της μέθοδο sonar + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) + + +# Και ορίζουμε μία ακόμα κλάση που κληρονομεί από τις κλάσεις Superhero και Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Ας πούμε αυτή την κλάση Batman +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # Τυπικά γα να κληρονομήουμε attributes πρέπει να καλέσουμε τη super: + # super(Batman, self).__init__(*args, **kwargs) + # Ωστόσο έχουμε να κάνουμε με πολλαπλή κληρονομικότητα εδώ, και το super() + # δουλεύει μόνο με την αμέσως ανώτερη κλάση στην ιεραρχία. + # Οπότε, καλούμε ρητά την __init__ για όλους τους πρόγονους + # Η χρήση των *args και **kwargs επιτρέπει έναν καθαρό τρόπο για να περνάμε ορίσματα + # με κάθε κλάση-γονέα να "βγάζει μία φλούδα από το κρεμμύδι". + Superhero.__init__(self, 'anonymous', movie=True, + superpowers=['Wealthy'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # υπερφορτώνουμε την τιμή του γνωρίσματος name + self.name = 'Sad Affleck' + + def sing(self): + return 'nan nan nan nan nan batman!' + + +if __name__ == '__main__': + sup = Batman() + + # + # Λάβε το Method Resolution search Order που χρησιμοποιείται από το getattr() και το super(). + # Αυτό το attribute είναι δυναμικό και μπορεί να ενημερωθεί + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Καλεί την μέθοδο της κλάσης-πατέρα αλλά χρησιμοποιεί το attribute της δικής του κλάσης + print(sup.get_species()) # => Superhuman + + # Καλεί την υπερφορτωμένη μέθοδο + print(sup.sing()) # => nan nan nan nan nan batman! + + # Καλεί μέθοδο από την κλάση Human, επειδή μετράει η σειρά της κληρονομιάς + sup.say('I agree') # => Sad Affleck: I agree + + # Καλεί μέθοδο που ανήκει μόνο στον δεύτερο πρόγονο + print(sup.sonar()) # => ))) ... ((( + + # Attribute της κληρονομημένης κλάσης + sup.age = 100 + print(sup.age) # => 100 + + # Κληρονομούμενο attribute από τον δεύτερο πρόγονο του οποίου η default τιμή + # έχει υπερφορτωθεί. + print('Can I fly? ' + str(sup.fly)) # => Can I fly? False + + + +#################################################### +## 7. Προχωρημένα +#################################################### + +# Με τους Generators μπορείς να γράψεις τεμπέλικο κώδικα. +def double_numbers(iterable): + for i in iterable: + yield i + i +# Οι Generators είναι αποδοτικοί από άποψη μνήμης επειδή φορτώνουν μόνο τα δεδομένα +# που είναι αναγκαία για να επεξεργαστούμε την επόμενη τιμή του iterable. +# Αυτό μας επιτρέπει να κάνουμε πράξεις σε τιμές που υπό άλλες συνθήκες θα ήταν +# απαγορευτικά μεγάλες. +for i in double_numbers(range(1, 900000000)): # το `range` είναι ένας generator. + print(i) + if i >= 30: + break + +# Όπως μπορείς να δημιουργήσεις list comprehension, έτσι μπορείς να δημιουργήσεις και +# generator comprehensions +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # τυπώνει -1 -2 -3 -4 -5 στο console/terminal + +# Μπορείς επίσης να μετατρέψεις ένα generator comprehension απευθείας σε λίστα. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Decorators +# σε αυτό το παράδειγμα το `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, "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 :( +``` + +## Έτοιμοι για περισσότερα? + +### Δωρεάν Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) -- cgit v1.2.3 From bd52393b70ae63c532b9321707d190d202bae28b Mon Sep 17 00:00:00 2001 From: Chariton Charitonidis Date: Sat, 19 Oct 2019 17:40:32 +0300 Subject: add greek translation for vim --- el-gr/vim-gr.html.markdown | 266 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 el-gr/vim-gr.html.markdown diff --git a/el-gr/vim-gr.html.markdown b/el-gr/vim-gr.html.markdown new file mode 100644 index 00000000..42ba3739 --- /dev/null +++ b/el-gr/vim-gr.html.markdown @@ -0,0 +1,266 @@ +--- +category: tool +tool: vim +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +filename: LearnVim.txt +--- + + +[Vim](http://www.vim.org) +To (Vi IMproved) είναι ένας κλώνος του δημοφιλούς vi editor για Unix. +Είναι ένας text editor σχεδιασμένος για ταχύτητα και αυξημένη παραγωγικότητα, +και υπάρχει σχεδόν σε όλα τα Unix-based συστήματα. Έχει διάφορα keybindings +(συντομεύσεις πλήκτρων) για να πλοηγούμαστε γρήγορα σε συγκεκριμένα σημεία ενός αρχείου, +καθώς και για γρήγορη επεξεργασία. + +## Τα βασικά της πλοήγησης στον Vim + +``` + vim # Άνοιξε το στον vim + :help # Άνοιξε το built-in βοήθημα για το αν υπάρχει + :q # Βγες από τον vim + :w # Αποθήκευσε το τρέχον αρχείο + :wq # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim + ZZ # Αποθήκευσε το τρέχον αρχείο και βγες από τον vim + :q! # Βγες χωρίς αποθήκευση + # ! *αναγκάζει* το :q να εκτελεστεί, γι αυτό βγαίνει χωρίς saving + :x # Ίδιο με το wq αλλά πιο σύντομο + + u # Undo + CTRL+R # Redo + + h # Μετακινήσου κατά ένα χαρακτήρα αριστερά + j # Μετακινήσου μια γραμμή κάτω + k # Μετακινήσου μια γραμμή πάνω + l # Μετακινήσου μια γραμμή δεξιά + + Ctrl+B # Πήγαινε μία οθόνη πίσω + Ctrl+F # Πήγαινε μία οθόνη μπροστά + Ctrl+U # Πήγαινε μισή οθόνη πίσω + Ctrl+D # Πήγαινε μισή οθόνη μπροστά + + # Μετακινήσεις στην ίδια γραμμή + + 0 # Πήγαινε στην αρχή της γραμμής + $ # Πήγαινε στο τέλος της γραμμής + ^ # Πήγαινε στον πρώτο μη κενό χαρακτήρα της γραμμής + + # Αναζήτηση στο κείμενο + + /word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης μετά τον cursor + ?word # Υπογραμμίζει όλες τις εμφανίσεις της λέξης πριν τον cursor + n # Μετακινεί τον cursor στην επόμενη εμφάνιση της λέξης + N # Μετακινεί τον cursor στην προηγούμενη εμφάνιση της λέξης + + :%s/foo/bar/g # άλλαξε το 'foo' σε 'bar' σε κάθε γραμμή του αρχείου + :s/foo/bar/g # άλλαξε το 'foo' σε 'bar' στην τρέχουσα γραμμή + + # Άλματα σε χαρακτήρες + + f # Άλμα μπροστά και προσγείωση στο επόμενο + t # Άλμα μπροστά και προσγείωση αμέσως πριν το προηγούμενο + + # Για παράδειγμα, + f< # Άλμα μπροστά και προσγείωση σε < + t< # Άλμα μπροστά και προσγείωση αμέσως πριν < + + # Μετακινήσεις κατά λέξεις + + w # Πήγαινε μια λέξη μπροστά + b # Πήγαινε μια λέξη πίσω + e # Πήγαινε στο τέλος της λέξης στην οποία είσαι + + # Άλλοι χαρακτήρες για να τριγυρνάμε + + gg # Πήγαινε στην αρχή του αρχείου + G # Πήγαινε στο τέλος του αρχείου + :NUM # Πήγαινε στη γραμμή με αριθμό NUM (οποιοσδήποτε αριθμός) + H # Πήγαινε στην κορυφή της σελίδας + M # Πήγαινε στην μέση της σελίδας + L # Πήγαινε στο κάτω άκρο της σελίδας +``` + +## Help docs: +Το Vim έχει built-in help documentation που μπορείς να δεις με `:help `. +Για παράδειγμα το `:help navigation` θα σου εμφανίσει documentation σχετικό με +το πως να πλοηγείσαι στο αρχείο! + +To `:help` μπορεί να χρησιμοποιηθεί και χωρίς option. Αυτό θα εμφανίσει το default +help dialog που σκοπεύει να κάνει το vim πιο προσιτό σε αρχάριους! + +## Modes: + +O Vim στηρίζεται στο concept των **modes**. + +- Command Mode - ο vim εκκινεί σε αυτό mode, χρησιμοποιείται για πλοήγηση και εντολές +- Insert Mode - χρησιμοποιείται για να κάνουμε αλλαγές στα αρχεία +- Visual Mode - χρησιμοποιείται για να υπογραμμίζουμε κείμενα και να κάνουμε διάφορα σε αυτά +- Ex Mode - χρησιμοποιείται για να πάμε στο κάτω μέρος με το ':' που δίνουμε εντολές + +``` + i # Βάζει το vim σε insert mode, πριν τη θέση cursor + a # Βάζει το vim σε insert mode, μετά τη θέση cursor + v # βάζει τον vim σε visual mode + : # Βάζει τον vim σε ex mode + # φεύγει από όποιο mode είμαστε και πάει σε command mode + + # Αντιγραφή-Επικόληση κειμένου + + y # Yank (κάνε copy) ό,τι είναι επιλεγμένο + yy # Yank την γραμμή στην οποία είσαι + d # διάγραψε ό,τι είναι επιλεγμένο + dd # Διάγραψε τη γραμμή στην οποία είσαι + p # Κάνε Paste το αντεγραμένο κείμενο μετά την θέση του cursor + P # Κάνε Paste το αντεγραμένο κείμενο πριν την θέση του cursor + x # Διάγραψε τον χαρακτήρα που είναι κάτω από τον cursor +``` + +## Η 'γραμματική' του Vim + +Μπορείς να σκεφτείς τον Vim ως ένα σύνολο εντολών +σε μορφή 'Verb-Modifier-Noun', όπου + +- Verb - η ενέργεια που θες να κάνεις +- Modifier - πώς κάνεις την ενέργεια +- Noun - το αντικείμενο που δέχεται την ενέργεια + +Μερικά παραδείγματα ''Ρημάτων', 'Modifiers' και 'Ουσιαστικών': + +``` + # 'Ρήματα' + + d # Διάγραψε + c # Άλλαξε + y # Yank (αντίγραψε) + v # Επίλεξε οπτικά + + # 'Modifiers' + + i # Μέσα + a # Γύρω + NUM # Αριθμός (NUM = οποιοσδήποτε αριθμός) + f # Ψάξε κάτι και πήγαινε εκεί που βρίσκεται + t # Ψάξε κάτι και πήγαινε πριν από εκεί που βρίσκεται + / # Βρες κάποιο string μετά από τον cursor + ? # Βρες κάποιο string πριν τον cursor + + # 'Ουσιαστικά' + + w # Λέξη + s # Πρόταση + p # Παράγραφος + b # Block + + # Δείγματα 'προτάσεων' ή εντολών + + d2w # Διάγραψε 2 λέξεις + cis # Άλλαξε μέσα στην πρώταση + yip # Αντίγραψε την παράγραφο στην οποία βρίσκεσαι + ct< # Άλλαξε σε < + # Άλλαξε το κείμενο από το οποίο είσαι πριν το επόμενο bracketChange the text from where you are to the next open bracket + d$ # Διάγραψε μέχρι το τέλος της γραμμής +``` + +## Μερικά shortcuts και κόλπα + + +``` + > # Στοίχισε προς τα δεξιά την επιλογή σου κατά ένα block + < # Στοίχισε προς τα αριστερά την επιλογή σου κατά ένα block + :earlier 15m # Κάνε το αρχείο όπως ήταν πριν 15 λεπτά + :later 15m # Ακύρωση για την παραπάνω εντολή + ddp # Αντάλλαξε τις θέσεις διαδοχικών γραμμών + . # Επανάλαβε την προηγούμενη ενέργεια + :w !sudo tee % # Σώσε το τρέχον αρχείο ως root + :set syntax=c # Κάνε syntax highlighting για τη γλώσσα c + :sort # Ταξινόμησε όλες τις γραμμές + :sort! # Ταξινόμησε ανάποδα όλες τις γραμμές (αύξουσα σειρά) + :sort u # Ταξινόμησε όλες τις γραμμές και διάγραψε τις διπλές γραμμές + ~ # Άλλαξε τα κεφαλαία σε μικρά στο επιλεγμένο κείμενο + u # Το επιλεγμένο κείμενο να γίνει πεζά γράμματα + U # Το επιλεγμένο κείμενο να γίνει κεφαλαία γράμματα + + # Fold text + zf # Διπλώνει (συμπιέζει τις γραμμές σε μία) το επιλεγμένο κείμενο + zo # Ξεδιπλώνει το επιλεγμένο fold + zc # Κλείνει το επιλεγμένο fold + zR # Ανοίγει όλα τα folds + zM # Κλείνει όλα τα folds +``` + +## Macros + +Τα macros βασικά είναι καταγραφή ενεργειών. +Όταν ξεικάς να καταγράφεις ένα macro καταγράφονται **όλες** οι ενέργεις και οι +εντολές που χρησιμοποιείς, μέχρι να σταματήσεις την καταγραφή. Όταν καλείς ένα macro, +εκτελείται πάλι η ίδια σειρά από ενέργειες και εντολές στο επιλεγμένο κείμενο. + +``` + qa # Ξεκίνα να καταγράφεις ένα macro που θα ονομαστεί 'a' + q # Σταμάτα την καταγραφή + @a # Τρέξε το macro +``` + +### Configuring ~/.vimrc + +Το αρχείο .vimrc μπορεί να χρησιμοποιηθεί για να κάνεις configure το Vim στο startup. + +Εδώ βλέπουμε δείγμα ενός ~/.vimrc file: + +``` +" Example ~/.vimrc +" 2015.10 + +" Required for vim to be iMproved +set nocompatible + +" Determines filetype from name to allow intelligent auto-indenting, etc. +filetype indent plugin on + +" Enable syntax highlighting +syntax on + +" Better command-line completion +set wildmenu + +" Use case insensitive search except when using capital letters +set ignorecase +set smartcase + +" When opening a new line and no file-specific indenting is enabled, +" keep same indent as the line you're currently on +set autoindent + +" Display line numbers on the left +set number + +" Indentation options, change according to personal preference + +" Number of visual spaces per TAB +set tabstop=4 + +" Number of spaces in TAB when editing +set softtabstop=4 + +" Number of spaces indented when reindent operations (>> and <<) are used +set shiftwidth=4 + +" Convert TABs to spaces +set expandtab + +" Enable intelligent tabbing and spacing for indentation and alignment +set smarttab +``` + +### Αναφορές + +[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 1ba3aa9d91c1774901ecbfc9f157d37ac9934de0 Mon Sep 17 00:00:00 2001 From: Christian Grasso Date: Sun, 20 Oct 2019 12:23:38 +0200 Subject: [zfs/it] Add zfs-it.html.markdown --- it-it/zfs-it.html.markdown | 361 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 361 insertions(+) create mode 100644 it-it/zfs-it.html.markdown diff --git a/it-it/zfs-it.html.markdown b/it-it/zfs-it.html.markdown new file mode 100644 index 00000000..c1307e67 --- /dev/null +++ b/it-it/zfs-it.html.markdown @@ -0,0 +1,361 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] +translators: + - ["Christian Grasso","https://grasso.io"] +filename: LearnZfs-it.txt +lang: it-it +--- + + +[ZFS](http://open-zfs.org/wiki/Main_Page) è un sistema di storage che combina file system +tradizionali e volume manager in un unico strumento. ZFS utilizza della terminologia +specifica, diversa da quella usata da altri sistemi di storage, ma le sue funzioni lo +rendono un ottimo tool per gli amministratori di sistema. + + +## Concetti base di ZFS + +### Virtual Device + +Un VDEV è simile a un dispositivo gestito da una scheda RAID. Esistono diversi tipi di +VDEV che offrono diversi vantaggi, tra cui ridondanza e velocità. In generale, +i VDEV offrono una maggiore affidabilità rispetto alle schede RAID. Si sconsiglia di +utilizzare ZFS insieme a RAID, poichè ZFS è fatto per gestire direttamente i dischi fisici. + +Tipi di VDEV: + +* stripe (disco singolo, senza ridondanza) +* mirror (mirror su più dischi) +* raidz + * raidz1 (parity a 1 disco, simile a RAID 5) + * raidz2 (parity a 2 dischi, simile a RAID 6) + * raidz3 (parity a 3 dischi) +* disk +* file (non consigliato in production poichè aggiunge un ulteriore filesystem) + +I dati vengono distribuiti tra tutti i VDEV presenti nella Storage Pool, per cui un maggior +numero di VDEV aumenta le operazioni al secondo (IOPS). + +### Storage Pool + +Le Storage Pool di ZFS sono un'astrazione del livello inferiore (VDEV) e consentono di +separare il filesystem visibile agli utenti dal layout reale dei dischi. + +### Dataset + +I dataset sono simili ai filesystem tradizionali, ma con molte più funzioni che rendono +vantaggioso l'utilizzo di ZFS. I dataset supportano il [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +gli snapshot, la gestione delle quota, compressione e deduplicazione. + + +### Limiti + +Una directory può contenere fino a 2^48 file, ognuno dei quali di 16 exabyte. +Una storage pool può contenere fino a 256 zettabyte (2^78), e può essere distribuita +tra 2^64 dispositivi. Un singolo host può avere fino a 2^64 storage pool. + + +## Comandi + +### Storage Pool + +Azioni: + +* List (lista delle pool) +* Status (stato) +* Destroy (rimozione) +* Get/Set (lettura/modifica proprietà) + +Lista delle zpool + +```bash +# Crea una zpool raidz +$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# Lista delle zpool +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# Informazioni dettagliate su una zpool +$ zpool list -v zroot +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75% +``` + +Stato delle zpool + +```bash +# Informazioni sullo stato delle zpool +$ zpool status + pool: zroot + state: ONLINE + scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015 +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors + +# "Scrubbing" (correzione degli errori) +$ zpool scrub zroot +$ zpool status -v zroot + pool: zroot + state: ONLINE + scan: scrub in progress since Thu Oct 15 16:59:14 2015 + 39.1M scanned out of 106G at 1.45M/s, 20h47m to go + 0 repaired, 0.04% done +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors +``` + +Proprietà delle zpool + +```bash + +# Proprietà di una zpool (gestite dal sistema o dall'utente) +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# Modifica di una proprietà +$ zpool set comment="Dati" zroot +$ zpool get comment +NAME PROPERTY VALUE SOURCE +tank comment - default +zroot comment Dati local +``` + +Rimozione di una zpool + +```bash +$ zpool destroy test +``` + + +### Dataset + +Azioni: + +* Create +* List +* Rename +* Delete +* Get/Set (proprietà) + +Creazione dataset + +```bash +# Crea un dataset +$ zfs create tank/root/data +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) + +# Crea un sottodataset +$ zfs create tank/root/data/stuff +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) +tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) + + +# Crea un volume +$ zfs create -V zroot/win_vm +$ zfs list zroot/win_vm +NAME USED AVAIL REFER MOUNTPOINT +tank/win_vm 4.13G 17.9G 64K - +``` + +Lista dei dataset + +```bash +# Lista dei dataset +$ zfs list +NAME USED AVAIL REFER MOUNTPOINT +zroot 106G 30.8G 144K none +zroot/ROOT 18.5G 30.8G 144K none +zroot/ROOT/10.1 8K 30.8G 9.63G / +zroot/ROOT/default 18.5G 30.8G 11.2G / +zroot/backup 5.23G 30.8G 144K none +zroot/home 288K 30.8G 144K none +... + +# Informazioni su un dataset +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# Lista degli snapshot +$ zfs list -t snapshot +zroot@daily-2015-10-15 0 - 144K - +zroot/ROOT@daily-2015-10-15 0 - 144K - +zroot/ROOT/default@daily-2015-10-15 0 - 24.2G - +zroot/tmp@daily-2015-10-15 124K - 708M - +zroot/usr@daily-2015-10-15 0 - 144K - +zroot/home@daily-2015-10-15 0 - 11.9G - +zroot/var@daily-2015-10-15 704K - 1.42G - +zroot/var/log@daily-2015-10-15 192K - 828K - +zroot/var/tmp@daily-2015-10-15 0 - 152K - +``` + +Rinominare un dataset + +```bash +$ zfs rename tank/root/home tank/root/old_home +$ zfs rename tank/root/new_home tank/root/home +``` + +Eliminare un dataset + +```bash +# I dataset non possono essere eliminati se hanno degli snapshot +$ zfs destroy tank/root/home +``` + +Lettura/modifica proprietà + +```bash +# Tutte le proprietà di un dataset +$ zfs get all zroot/usr/home │157 # Create Volume +NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm +zroot/home type filesystem - │159 $ zfs list zroot/win_vm +zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT +zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K - +zroot/home available 94.1G - │162 ``` +zroot/home referenced 11.9G - │163 +zroot/home mounted yes - +... + +# Proprietà specifica +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# Modifica di una proprietà +$ zfs set compression=gzip-9 mypool/lamb + +# Specifiche proprietà per tutti i dataset +$ zfs list -o name,quota,reservation +NAME QUOTA RESERV +zroot none none +zroot/ROOT none none +zroot/ROOT/default none none +zroot/tmp none none +zroot/usr none none +zroot/home none none +zroot/var none none +... +``` + + +### Snapshot + +Gli snapshot sono una delle funzioni più importanti di ZFS: + +* Lo spazio occupato è la differenza tra il filesystem e l'ultimo snapshot +* Il tempo di creazione è di pochi secondi +* Possono essere ripristinati alla velocità di scrittura del disco +* Possono essere automatizzati molto semplicemente + +Azioni: + +* Create +* Delete +* Rename +* Access +* Send / Receive +* Clone + + +Creazione di uno snapshot + +```bash +# Crea uno snapshot di un singolo dataset +zfs snapshot tank/home/sarlalian@now + +# Crea uno snapshot di un dataset e dei suoi sottodataset +$ zfs snapshot -r tank/home@now +$ zfs list -t snapshot +NAME USED AVAIL REFER MOUNTPOINT +tank/home@now 0 - 26K - +tank/home/sarlalian@now 0 - 259M - +tank/home/alice@now 0 - 156M - +tank/home/bob@now 0 - 156M - +... +``` + +Eliminazione di uno snapshot + +```bash +# Elimina uno snapshot +$ zfs destroy tank/home/sarlalian@now + +# Elimina uno snapshot ricorsivamente +$ zfs destroy -r tank/home/sarlalian@now + +``` + +Rinominare uno snapshot + +```bash +$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today +$ zfs rename tank/home/sarlalian@now today + +$ zfs rename -r tank/home@now @yesterday +``` + +Accedere ad uno snapshot + +```bash +# Utilizzare il comando cd come per una directory +$ cd /home/.zfs/snapshot/ +``` + +Invio e ricezione + +```bash +# Backup di uno snapshot su un file +$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz + +# Invia uno snapshot ad un altro dataset +$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian + +# Invia uno snapshot ad un host remoto +$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' + +# Invia l'intero dataset e i suoi snapshot ad un host remoto +$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +``` + +Clonare gli snapshot + +```bash +# Clona uno snapshot +$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new + +# Rende il clone indipendente dallo snapshot originale +$ zfs promote tank/home/sarlalian_new +``` + +### Letture aggiuntive (in inglese) + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) -- cgit v1.2.3 From ad35bbd4776ba9d23d7da431a08331a5940091b9 Mon Sep 17 00:00:00 2001 From: Christian Grasso Date: Sun, 20 Oct 2019 12:43:10 +0200 Subject: [sql/it] Add sql-it.html.markdown --- it-it/sql-it.html.markdown | 112 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 it-it/sql-it.html.markdown diff --git a/it-it/sql-it.html.markdown b/it-it/sql-it.html.markdown new file mode 100644 index 00000000..7db2eec1 --- /dev/null +++ b/it-it/sql-it.html.markdown @@ -0,0 +1,112 @@ +--- +language: SQL +filename: learnsql-it.sql +contributors: + - ["Bob DuCharme", "http://bobdc.com/"] +translators: + - ["Christian Grasso", "https://grasso.io"] +lang: it-it +--- + +Structured Query Language (SQL) è un linguaggio standard ISO per la creazione e la gestione +di database organizzati in un insieme di tabelle. Le diverse implementazioni aggiungono +spesso le proprie estensioni al linguaggio base ([confronto tra le diverse implementazioni](http://troels.arvin.dk/db/rdbms/)) + +Le diverse implementazioni forniscono inoltre un prompt per inserire in modo interattivo i comandi +o eseguire il contenuto di uno script. + +I comandi di seguito lavorano sul [database di esempio MySQL](https://dev.mysql.com/doc/employee/en/) +disponibile su [GitHub](https://github.com/datacharmer/test_db). I file .sql contengono liste di comandi +simili a quelli mostrati di seguito, che creano e riempiono delle tabelle con dati di un'azienda fittizia. +Il comando per eseguire questi script può variare in base all'implementazione in uso. + + +```sql +-- I commenti iniziano con due trattini. Ogni comando va terminato con il punto e virgola + +-- SQL è case-insensitive per quanto riguarda i comandi; in genere si +-- preferisce scriverli in maiuscolo per distinguerli dai nomi di +-- database, tabelle e colonne + +-- Crea ed elimina un database. I nomi di database e tabelle sono case-sensitive +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +-- Lista dei database disponibili +SHOW DATABASES; + +-- Attiva uno specifico database +USE employees; + +-- Seleziona tutte le righe e le colonne dalla tabella departments +SELECT * FROM departments; + +-- Seleziona tutte le righe della tabella departments, +-- ma solo le colonne dept_no e dept_name. +-- È possibile suddividere i comandi su più righe. +SELECT dept_no, + dept_name FROM departments; + +-- Seleziona solo le prime 5 righe della tabella departments. +SELECT * FROM departments LIMIT 5; + +-- Ottiene la colonna dept_name della tabella departments +-- solo per le righe il cui valore di dept_name contiene 'en'. +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; + +-- Ottiene tutte le colonne della tabella departments +-- solo per le righe che hanno un dept_name formato da una 'S' +-- seguita esattamente da altri 4 caratteri +SELECT * FROM departments WHERE dept_name LIKE 'S____'; + +-- Seleziona i valori di title dalla tabella titles eliminando i duplicati +SELECT DISTINCT title FROM titles; + +-- Come sopra, ma i valori sono ordinati alfabeticamente +SELECT DISTINCT title FROM titles ORDER BY title; + +-- Mostra il numero di righe della tabella departments +SELECT COUNT(*) FROM departments; + +-- Mostra il numero di righe della tabella departments +-- il cui valore di dept_name contiene 'en'. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; + +-- Un JOIN tra più tabelle: la tabella titles contiene gli +-- incarichi lavorativi associati ad un certo numero di impiegato. +-- Con il JOIN utilizziamo il numero di impiegato per ottenere +-- le informazioni ad esso associate nella tabella employees. +-- (Inoltre selezioniamo solo le prime 10 righe) + +SELECT employees.first_name, employees.last_name, + titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON + employees.emp_no = titles.emp_no LIMIT 10; + +-- Mostra tutte le tabelle di tutti i database. +-- Spesso le implementazioni forniscono degli shortcut per questo comando +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +-- Crea una tabella tablename1, con due colonne, per il database in uso. +-- Per le colonne specifichiamo il tipo di dato (stringa di max 20 caratteri) +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); + +-- Inserisce una riga nella tabella tablename1. I valori devono essere +-- appropriati per la definizione della tabella +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +-- In tablename1, modifica il valore di fname a 'John' +-- in tutte le righe che hanno come lname 'Mutt'. +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; + +-- Elimina tutte le righe di tablename1 +-- il cui lname inizia per 'M'. +DELETE FROM tablename1 WHERE lname like 'M%'; + +-- Elimina tutte le righe della tabella tablename1 +DELETE FROM tablename1; + +-- Elimina la tabella tablename1 +DROP TABLE tablename1; +``` -- cgit v1.2.3 From 850999a145fb4ecafe386ebbe5920311e0dfb700 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Mon, 21 Oct 2019 08:54:16 +0200 Subject: [clojure-macros/de] Translate clojure-macros to german --- de-de/clojure-macros-de.html.markdown | 161 ++++++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 de-de/clojure-macros-de.html.markdown diff --git a/de-de/clojure-macros-de.html.markdown b/de-de/clojure-macros-de.html.markdown new file mode 100644 index 00000000..088a29a8 --- /dev/null +++ b/de-de/clojure-macros-de.html.markdown @@ -0,0 +1,161 @@ +--- +language: "clojure macros" +filename: learnclojuremacros-de.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +Wie mit allen Lisps besitzt auch Clojure die inhärente [Homoikonizität](https://en.wikipedia.org/wiki/Homoiconic), +die dir den vollen Zugang der Sprache gibt, um + Code-Generierungsroutinen zu schreiben. Diese werden "Macros" genannt. +Macros geben dir eine leistungsarke Möglichkeit, die Sprache +an deine Bedürfnisse anzupassen. + +Sei aber vorsichtig, es wird als schlechter Stil angesehen, wenn du +ein Macro schreibst, obwohl eine Funktion genausogut funktionieren würde. +Verwende nur dann ein Macro, wenn du Kontrolle darüber brauchst, wann oder ob Argumente in einer Form evaluiert werden. + +Wenn du mit Clojure vertraut sein möchtest, stelle sicher, dass du alles in [Clojure in Y Minutes](/docs/clojure/) verstehst. + +```clojure +;; Definiere ein Macro mit defmacro. Dein Macro sollte eine Liste zurückgeben, +;; die als Clojure Code evaluiert werden kann. +;; +;; Dieses Macro ist das Gleiche, als ob du (reverse "Hallo Welt") geschrieben +;; hättest +(defmacro my-first-macro [] + (list reverse "Hallo Welt")) + +;; Inspiziere das Ergebnis eines Macros mit macroexpand oder macroexpand-1. +;; +;; Beachte, dass der Aufruf zitiert sein muss. +(macroexpand '(my-first-macro)) +;; -> (# "Hallo Welt") + +;; Du kannst das Ergebnis von macroexpand direkt auswerten. +(eval (macroexpand '(my-first-macro))) +; -> (\t \l \e \W \space \o \l \l \a \H) + +;; Aber du solltest diese prägnante und funktionsähnliche Syntax verwenden: +(my-first-macro) ; -> (\t \l \e \W \space \o \l \l \a \H) + +;; Du kannst es dir leichter machen, indem du die Zitiersyntax verwendest +;; um Listen in ihren Makros zu erstellen: +(defmacro my-first-quoted-macro [] + '(reverse "Hallo Welt")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hallo Welt") +;; Beachte, dass reverse nicht mehr ein Funktionsobjekt ist, sondern ein Symbol + +;; Macros können Argumente haben. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; Aber wenn du versuchst das mit einer zitierten Liste zu machen wirst du +;; einen Fehler bekommen, weil das Argument auch zitiert sein wird. +;; Um dies zu umgehen, bietet Clojure einee Art und Weise Macros zu zitieren: ` +;; In ` kannst du ~ verwenden um in den äußeren Bereich zu kommen. +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; Du kannst die normalen destruktuierungs Argumente verwenden. Expandiere +;; Listenvariablen mit ~@. +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; Erinnere dich an das do! + +(macroexpand '(unless true (reverse "Hallo Welt"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hallo Welt"))) + +;; (unless) evaluiert und gibt body zurück, wenn das erste Argument falsch ist. +;; Andernfalls gibt es nil zurück + +(unless true "Hallo") ; -> nil +(unless false "Hallo") ; -> "Hallo" + +;; Die Verwendung Macros ohne Sorgfalt kann viel Böses auslösen, indem es +;; deine Variablen überschreibt +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;; Um das zu verhindern kannst du gensym verwenden um einen eindeutigen +;; Identifikator zu bekommen +(gensym 'x) ; -> x1281 (oder etwas Ähnliches) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; Du kannst # innerhalb von ` verwenden um für jedes Symbol automatisch +;; ein gensym zu erstellen +(defmacro define-x-hygienically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygienically) ; -> (2) +(list x) ; -> (4) + +;; Es ist üblich, Hilfsfunktionen mit Macros zu verwenden. Lass uns einige +;; erstellen, die uns helfen , eine (dumme) arithmetische Syntax +;; zu unterstützen +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Bekomme die Argumente [x (+ y)], gebe (+ x y) zurück" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; Wir können es sofort testen, ohne ein Macro zu erstellen +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; Allerdings, brauchen wir ein Macro, wenn wir es zur Kompilierungszeit +; ausführen wollen +(defmacro inline-2 [form] + (inline-2-helper form)) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (eigentlich, 3N, da die Zahl zu einem rationalen Bruch mit / umgewandelt wird) +``` + +### Weiterführende Literatur + +[Macros schreiben](http://www.braveclojure.com/writing-macros/) + +[Offiziele Docs](http://clojure.org/macros) + +[Wann verwendet man Macros?](https://lispcast.com/when-to-use-a-macro/) -- cgit v1.2.3 From 60e962ee0d902ba3468b8323d50276a81124144f Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Mon, 21 Oct 2019 08:51:59 +0200 Subject: [pug/de] Translate pug to german --- de-de/pug-de.html.markdown | 208 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 208 insertions(+) create mode 100644 de-de/pug-de.html.markdown diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown new file mode 100644 index 00000000..c86494ce --- /dev/null +++ b/de-de/pug-de.html.markdown @@ -0,0 +1,208 @@ +--- +language: Pug +contributors: + - ["Michael Warner", "https://github.com/MichaelJGW"] +filename: lernepug-de.pug +translators: + - ["denniskeller", "https://github.com/denniskeller"] +lang: de-de +--- + +## Erste Schritte mit Pug + +Pug ist eine kleine Sprache, die zu HTML kompiliert. Sie hat eine +saubere Syntax mit zusätzlichen Funktionen wie if Anweisungen und Schleifen. +Sie kann auch als serverseitige Templatingsprache für Serversprachen +wie NodeJS verwendet werden. + +### Die Sprache +```pug + +//- Einzeilenkommentar + +//- Mehrzeiliger + Kommentar + +//- ---TAGS--- +//- Grundlagen +div +//-
+h1 +//-

+mein-benutzerdefiniertesTag +//- + +//- Geschwister +div +div +//-
+
+ +//- Kind +div + div +//-
+
+
+ +//- Text +h1 Hallo Welt +//-

Hallo Welt

+ +//- Multizeilentext +div. + Hallo + Welt +//-
+ Hallo + Welt +
+ +//- ---ATTRIBUTE--- +div(class="meine-klasse" id="meine-id" mein-benutzerdefiniertes-attr="data" enabled) +//-
+ +//- Kurzhand +span.meine-klasse +//- +.meine-klasse +//-
+div#meine-id +//-
+div#meine-id.meine-klasse +//-
+ + +//- ---JS--- +- const sprache = "pug"; + +//- Multizeilen JS +- + const srache = "pug"; + const cool = true; + +//- JS Klassen +- const meineKlasse = ['class1', 'class2', 'class3'] +div(class=meineKlasse) +//-
+ +//- JS Stil +- const meineStile = {'color':'white', 'background-color':'blue'} +div(styles=meineStile) +//-
+ +//- JS Attributte +- const meineAttribute = {"src": "foto.png", "alt": "meine Bilder"} +img&attributes(meineAttribute) +//- meine Bilder +- let deaktiviert = false +input(type="text" disabled=deaktiviert) +//- +- deaktiviert = true +input(type="text" disabled=deaktiviert) +//- + +//- JS Templating +- const name = "Bob"; +h1 Hi #{name} +h1= name +//-

Hi Bob

+//-

Bob

+ +//- ---Schleifen--- + +//- 'each' und 'for' machen das Selbe. Wir werden nur 'each' verwenden. + +each value, i in [1,2,3] + p=value +//- +

1

+

2

+

3

+ +each value, index in [1,2,3] + p=value + '-' + index +//- +

1-0

+

2-1

+

3-2

+ +each value in [] + p=value +//- + +each value in [] + p=value +else + p Keine Werte sind hier + +//-

Keine Werte sind hier

+ +//- ---BEDINGUNGEN--- + +- const zahl = 5 +if zahl < 5 + p zahl ist kleiner als 5 +else if zahl > 5 + p zahl ist größer als 5 +else + p zahl ist 5 +//-

zahl ist 5

+ +- const bestellungsStatus = "Ausstehend"; +case bestellungsStatus + when "Ausstehend" + p.warn Deine Bestellung steht noch aus + when "Abgeschlossen" + p.success Bestellung ist abgeschlossen. + when -1 + p.error Ein Fehler ist aufgetreten + default + p kein Bestellprotokoll gefunden +//-

Deine Bestellung steht noch aus

+ +//- --INCLUDE-- +//- File path -> "includes/nav.png" +h1 Firmenname +nav + a(href="index.html") Home + a(href="about.html") Über uns + +//- Dateipfad -> "index.png" +html + body + include includes/nav.pug +//- + + +

Firmenname

+
+ + + +//- Importiere JS und CSS +script + include scripts/index.js +style + include styles/theme.css + +//- ---MIXIN--- +mixin basic() + div Hallo ++basic("Bob") +//-
Hallo
+ +mixin comment(name, kommentar) + div + span.comment-name= name + div.comment-text= kommentar ++comment("Bob", "Das ist super") +//-
Hallo
+ +``` + + +### Zusätzliche Ressourcen +- [The Site](https://pugjs.org/) +- [The Docs](https://pugjs.org/api/getting-started.html) +- [Github Repo](https://github.com/pugjs/pug) -- cgit v1.2.3 From 653f2ee43eb0eebfcbd7f3e06c4cbf47e0191796 Mon Sep 17 00:00:00 2001 From: waynee95 Date: Mon, 21 Oct 2019 23:10:48 +0200 Subject: [elm/de] Translate elm to german --- de-de/elm-de.html.markdown | 376 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 de-de/elm-de.html.markdown diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown new file mode 100644 index 00000000..b74a975f --- /dev/null +++ b/de-de/elm-de.html.markdown @@ -0,0 +1,376 @@ +--- +language: Elm +filename: learnelm.elm +contributors: + - ["Max Goldstein", "http://maxgoldste.in/"] +translators: + - ["waynee95", "https://waynee95.me"] +lang: de-de +--- + +Elm ist eine pure funktionale Programmiersprache. Mit Elm werden GUIs +(grafische Benutzeroberfläche) für Webanwendungen erstellt. Durch die statische +Typisierung kann Elm viele Fehler schon bei der Kompilierung abfangen. Ein +Hauptmerkmal von Elm sind die ausführlichen und gut erklärten Fehlermeldungen. + +```haskell +-- Einzeilige Kommentare beginnen mit 2 Bindestrichen. +{- So wird ein mehrzeiliger Kommentar angelegt. +{- Diese können auch verschachtelt werden. -} +-} + +{-- Die Grundlagen --} + +-- Arithmetik +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 + +-- Zahlen ohne Punkt sind entweder vom Typ Int oder Float. +33 / 2 -- 16.5 mit Division von Gleitkommazahlen +33 // 2 -- 16 mit ganzzahliger Division + +-- Exponenten +5 ^ 2 -- 25 + +-- Boolsche Werte +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Strings (Zeichenketten) und Zeichen +"Das hier ist ein String." +'a' -- Zeichen + +-- Strings können konkateniert werden. +"Hello " ++ "world!" -- "Hello world!" + +{-- Listen und Tupel --} + +-- Jedes Element einer Liste muss vom gleichen Typ sein. Listen sind homogen. +["the", "quick", "brown", "fox"] +[1, 2, 3, 4, 5] +-- Das zweite Beispiel kann man auch mit Hilfe der "range" Funktion schreiben. +List.range 1 5 + +-- Listen werden genauso wie Strings konkateniert. +List.range 1 5 ++ List.range 6 10 == List.range 1 10 -- True + +-- Mit dem "cons" Operator lässt sich ein Element an den Anfang einer Liste anfügen. +0 :: List.range 1 5 -- [0, 1, 2, 3, 4, 5] + +-- Die Funktionen "head" und "tail" haben als Rückgabewert den "Maybe" Typ. +-- Dadurch wird die Fehlerbehandlung von fehlenden Elemenent explizit, weil +-- man immer mit jedem möglichen Fall umgehen muss. +List.head (List.range 1 5) -- Just 1 +List.tail (List.range 1 5) -- Just [2, 3, 4, 5] +List.head [] -- Nothing +-- List.funktionsName bedeutet, dass diese Funktion aus dem "List"-Modul stammt. + +-- Tupel sind heterogen, jedes Element kann von einem anderen Typ sein. +-- Jedoch haben Tupel eine feste Länge. +("elm", 42) + +-- Das Zugreifen auf Elemente eines Tupels geschieht mittels den Funktionen +-- "first" und "second". +Tuple.first ("elm", 42) -- "elm" +Tuple.second ("elm", 42) -- 42 + +-- Das leere Tupel, genannt "Unit", wird manchmal als Platzhalter verwendet. +-- Es ist das einzige Element vom Typ "Unit". +() + +{-- Kontrollfluss --} + +-- Eine If-Bedingung hat immer einen Else-Zweig und beide Zweige müssen den +-- gleichen Typ haben. +if powerLevel > 9000 then + "WHOA!" +else + "meh" + +-- If-Bedingungen können verkettet werden. +if n < 0 then + "n is negative" +else if n > 0 then + "n is positive" +else + "n is zero" + +-- Mit dem Mustervergleich (pattern matching) kann man bestimmte Fälle direkt +-- behandeln. +case aList of + [] -> "matches the empty list" + [x]-> "matches a list of exactly one item, " ++ toString x + x::xs -> "matches a list of at least one item whose head is " ++ toString x +-- Mustervergleich geht immer von oben nach unten. Würde man [x] als letztes +-- platzieren, dann würde dieser Fall niemals getroffen werden, weil x:xs diesen +-- Fall schon mit einschließt (xs ist in dem Fall die leere Liste). + +-- Mustervergleich an einem Maybe Typ. +case List.head aList of + Just x -> "The head is " ++ toString x + Nothing -> "The list was empty." + +{-- Funktionen --} + +-- Die Syntax für Funktionen in Elm ist minimal. Hier werden Leerzeichen anstelle +-- von runden oder geschweiften Klammern verwendet. Außerdem gibt es kein "return" +-- Keyword. + +-- Eine Funktion wird durch ihren Namen, einer Liste von Parametern gefolgt von +-- einem Gleichheitszeichen und dem Funktionskörper angegeben. +multiply a b = + a * b + +-- Beim Aufruf der Funktion (auch Applikation genannt) werden die Argumente ohne +-- Komma übergeben. +multiply 7 6 -- 42 + +-- Partielle Applikation einer Funktion (Aufrufen einer Funktion mit fehlenden +-- Argumenten). Hierbei entsteht eine neue Funktion, der wir einen Namen geben. +double = + multiply 2 + +-- Konstanten sind Funktionen ohne Parameter. +answer = + 42 + +-- Funktionen, die Funktionen als Parameter haben, nennt man Funktionen höherer +-- Ordnung. In funktionalen Programmiersprachen werden Funktionen als "first-class" +-- behandelt. Man kann sie als Argument übergeben, als Rückgabewert einer Funktion +-- zurückgeben oder einer Variable zuweisen. +List.map double (List.range 1 4) -- [2, 4, 6, 8] + +-- Funktionen können auch als anonyme Funktion (Lambda-Funktionen) übergeben werden. +-- Diese werden mit einem Blackslash eingeleitet, gefolgt von allen Argumenten. +-- Die Funktion "\a -> a * 2" beschreibt die Funktion f(x) = x * 2. +List.map (\a -> a * 2) (List.range 1 4) -- [2, 4, 6, 8] + +-- Mustervergleich kann auch in der Funktionsdefinition verwendet werden. +-- In diesem Fall hat die Funktion ein Tupel als Parameter. (Beachte: Hier +-- werden die Werte des Tupels direkt ausgepackt. Dadurch kann man auf die +-- Verwendung von "first" und "second" verzichten.) +area (width, height) = + width * height + +area (6, 7) -- 42 + +-- Mustervergleich auf Records macht man mit geschweiften Klammern. +-- Bezeichner (lokale Variablen) werden mittels dem "let" Keyword angelegt. +-- (Mehr zu Records weiter unten!) +volume {width, height, depth} = + let + area = width * height + in + area * depth + +volume { width = 3, height = 2, depth = 7 } -- 42 + +-- Rekursive Funktion +fib n = + if n < 2 then + 1 + else + fib (n - 1) + fib (n - 2) + +List.map fib (List.range 0 8) -- [1, 1, 2, 3, 5, 8, 13, 21, 34] + +-- Noch eine rekursive Funktion (Nur ein Beispiel, verwende stattdessen immer +-- List.length!) +listLength aList = + case aList of + [] -> 0 + x::xs -> 1 + listLength xs + +-- Funktionsapplikation hat die höchste Präzedenz, sie binden stärker als Operatoren. +-- Klammern bietet die Möglichkeit der Bevorrangung. +cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 +-- Als erstes wird die Funktion "degrees" mit dem Wert 30 aufgerufen. +-- Danach wird das Ergenis davon den Funktionen "cos", bzw. "sin" übergeben. +-- Dann wird das Ergebnis davon mit 2 quadriert und als letztes werden diese +-- beiden Werte dann addiert. + +{-- Typen und Typ Annotationen --} + +-- Durch Typinferenz kann der Compiler jeden Typ genau bestimmen. Man kann diese +-- aber auch manuell selber angeben (guter Stil!). +-- Typen beginnen immer mit eine Großbuchstaben. Dabei liest man "x : Typ" als +-- "x" ist vom Typ "Typ". +-- Hier ein paar übliche Typen: +5 : Int +6.7 : Float +"hello" : String +True : Bool + +-- Funktionen haben ebenfalls einen Typ. Dabei ist der ganz rechte Typ der +-- Rückgabetyp der Funktion und alle anderen sind die Typen der Parameter. +not : Bool -> Bool +round : Float -> Int + +-- Es ist guter Stil immer den Typ anzugeben, da diese eine Form von Dokumentation +-- sind. Außerdem kann so der Compiler genauere Fehlermeldungen geben. +double : Int -> Int +double x = x * 2 + +-- Funktionen als Parameter werden durch Klammern angegeben. Die folgende Funktion +-- ist nicht auf einen Typ festgelegt, sondern enthält Typvariablen (beginnend +-- mit Kleinbuchstaben). Die konkreten Typen werden erst bei Anwendung der +-- Funktion festgelegt. "List a" bedeutet, dass es sich um eine Liste mit +-- Elementen vom Typ "a" handelt. +List.map : (a -> b) -> List a -> List b + +-- Es gibt drei spezielle kleingeschriebene Typen: "number", "comparable" und +-- "appendable". +add : number -> number -> number +add x y = x + y -- funktioniert mit Ints und Floats. + +max :: comparable -> comparable -> comparable +max a b = if a > b then a else b -- funktioniert mit Typen, die vergleichbar sind. + +append :: appendable -> appendable -> appendable +append xs ys = xs ++ ys -- funktioniert mit Typen, die konkatenierbar sind. + +append "hello" "world" -- "helloworld" +append [1,1,2] [3,5,8] -- [1,1,2,3,5,8] + +{-- Eigene Datentypen erstellen --} + +-- Ein "Record" ist ähnlich wie ein Tupel, nur das jedes Feld einen Namne hat. +-- Dabei spielt die Reihenfolge keine Rolle. +{ x = 3, y = 7 } + +-- Um auf Werte eines Records zuzugreifen, benutzt man einen Punkt gefolgt +-- von dem Namen des Feldes. +{ x = 3, y = 7 }.x -- 3 + +-- Oder mit einer Zugriffsfunktion, welche aus einem Punkt und dem Feldnamen besteht. +.y { x = 3, y = 7 } -- 7 + +-- Wert eines Feldes ändern. (Achtung: Das Feld muss aber vorher schon vorhanden sein!) +{ person | + name = "George" } + +-- Mehrere Felder aufeinmal ändern unter Verwendung des alten Wertes. +{ particle | + position = particle.position + particle.velocity, + velocity = particle.velocity + particle.acceleration } + +-- Du kannst ein Record auch als Typ Annotation verwenden. +-- (Beachte: Ein Record Typ benutzt einen Doppelpunkt und ein Record Wert benutzt +-- ein Gleichheitszeichen!) +origin : { x : Float, y : Float, z : Float } +origin = + { x = 0, y = 0, z = 0 } + +-- Durch das "type" Keyword kann man einem existierenden Typen einen Namen geben. +type alias Point3D = + { x : Float, y : Float, z : Float } + +-- Der Name kann dann als Konstruktor verwendet werden. +otherOrigin : Point3D +otherOrigin = + Point3D 0 0 0 + +-- Aber es ist immernoch der selbe Typ, da es nur ein Alias ist! +origin == otherOrigin -- True + +-- Neben den Records gibt es auch noch so genannte Summentypen. +-- Ein Summentyp hat mehrere Konstruktoren. +type Direction = + North | South | East | West + +-- Ein Konstruktor kann außerdem noch andere Typen enthalten. Rekursion ist +-- auch möglich. +type IntTree = + Leaf | Node Int IntTree IntTree + +-- Diese können auch als Typ Annotation verwendet werden. +root : IntTree +root = + Node 7 Leaf Leaf + +-- Außerdem können auch Typvariablen verwendet werden in einem Konstruktor. +type Tree a = + Leaf | Node a (Tree a) (Tree a) + +-- Beim Mustervergleich kann man auf die verschiedenen Konstruktoren matchen. +leftmostElement : Tree a -> Maybe a +leftmostElement tree = + case tree of + Leaf -> Nothing + Node x Leaf _ -> Just x + Node _ subtree _ -> leftmostElement subtree + +{-- Module und Imports --} + +-- Die Kernbibliotheken und andere Bibliotheken sind in Module aufgeteilt. +-- Für große Projekte können auch eigene Module erstellt werden. + +-- Eine Modul beginnt mit ganz oben. Ohne diese Angabe befindet man sich +-- automatisch im Modul "Main". +module Name where + +-- Ohne genaue Angabe von Exports wird alles exportiert. Es können aber alle +-- Exporte explizit angegeben werden. +module Name (MyType, myValue) where + +-- Importiert das Modul "Dict". Jetzt kann man Funktionen mittels "Dict.insert" +-- aufrufen. +import Dict + +-- Importiert das "Dict" Modul und den "Dict" Typ. Dadurch muss man nicht "Dict.Dict" +-- verwenden. Man kann trotzdem noch Funktionen des Moduls aufrufen, wie "Dict.insert". +import Dict exposing (Dict) + +-- Abkürzung für den Modulnamen. Aufrufen der Funktionen mittels "C.funktionsName". +import Graphics.Collage as C + +{-- Kommandozeilen Programme --} + +-- Eine Elm-Datei kompilieren. +$ elm make MyFile.elm + +-- Beim ersten Aufruf wird Elm die "core" Bibliotheken installieren und eine +-- "elm-package.json"-Datei anlegen, die alle Informationen des Projektes +-- speichert. + +-- Der Reactor ist ein Server, welche alle Dateinen kompiliert und ausführt. +$ elm reactor + +-- Starte das REPL (read-eval-print-loop). +$ elm repl + +-- Bibliotheken werden durch den Github-Nutzernamen und ein Repository identifiziert. +-- Installieren einer neuen Bibliothek. +$ elm package install elm-lang/html +-- Diese wird der elm-package.json Datei hinzugefügt. + +-- Zeigt alle Veränderungen zwischen zwei bestimmten Versionen an. +$ elm package diff elm-lang/html 1.1.0 2.0.0 +-- Der Paketmanager von Elm erzwingt "semantic versioning"! +``` + +Elm ist eine besonders kleine Programmiersprache. Jetzt hast du genug Wissen an +deiner Seite, um dich in fast jedem Elm Code zurecht zu finden. + +Noch ein paar weitere hilfreiche Ressourcen (in Englisch): + +- Die [Elm Homepage](http://elm-lang.org/). Dort findest du: + + - [Anleitung zur Installierung von Elm](http://elm-lang.org/install) + - [Dokumentation](http://elm-lang.org/docs), sowie eine [Referenz zur Syntax](http://elm-lang.org/docs/syntax) + - Viele hilfreiche [Beispiele](http://elm-lang.org/examples) + +- Dokumentation der [Elm Kernbibliotheken](http://package.elm-lang.org/packages/elm-lang/core/latest/). Insbesondere: + + - [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics) (standardmäßig importiert) + - [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) sowie [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result) (benutzt für Fehlerbehandlung) + - Datenstrukturen, wie [List](http://package.elm-lang.org/packages/elm-lang/core/latest/List), [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), und [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) + - JSON [encoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Encode) und [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) + +- [Die Elm Architektur](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). + +- Die [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). -- cgit v1.2.3 From 2486fa8c1e51e975c603fa7972542deae287817b Mon Sep 17 00:00:00 2001 From: Mariusz Skoneczko Date: Tue, 22 Oct 2019 12:08:08 +1100 Subject: [python3/en] Clarify difference between iterators and iterables in the last example (closes #3586) --- python3.html.markdown | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 430927a9..61c53408 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -550,8 +550,14 @@ next(our_iterator) # => "three" # After the iterator has returned all of its data, it raises a StopIteration exception next(our_iterator) # Raises StopIteration -# You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) # => Returns ["one", "two", "three"] +# We can also loop over it, in fact, "for" does this implicitly! +our_iterator = iter(our_iterable) +for i in our_iterator: + print(i) # Prints one, two, three + +# You can grab all the elements of an iterable or iterator by calling list() on it. +list(our_iterable) # => Returns ["one", "two", "three"] +list(our_iterator) # => Returns [] because state is saved #################################################### -- cgit v1.2.3 From db010c8a72a3390461fea62db0890e9f986993bd Mon Sep 17 00:00:00 2001 From: Hugo Locurcio Date: Tue, 22 Oct 2019 09:10:07 +0200 Subject: [swift/en] Fix typos --- swift.html.markdown | 56 ++++++++++++++++++++++++++--------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index c2fb3471..1f9fe897 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -91,7 +91,7 @@ let multiLineString = """ This is a multi-line string. It's called that because it takes up multiple lines (wow!) Any indentation beyond the closing quotation marks is kept, the rest is discarded. - You can include " or "" in multi-line strings because the delimeter is three "s. + You can include " or "" in multi-line strings because the delimiter is three "s. """ // Arrays @@ -159,12 +159,12 @@ let `class` = "keyword" or contains nil (no value) to indicate that a value is missing. Nil is roughly equivalent to `null` in other languages. A question mark (?) after the type marks the value as optional of that type. - + If a type is not optional, it is guaranteed to have a value. - + Because Swift requires every property to have a type, even nil must be explicitly stored as an Optional value. - + Optional is an enum, with the cases .none (nil) and .some(T) (the value) */ @@ -178,7 +178,7 @@ let someOptionalString4 = String?.none //nil To access the value of an optional that has a value, use the postfix operator !, which force-unwraps it. Force-unwrapping is like saying, "I know that this optional definitely has a value, please give it to me." - + Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value. @@ -194,7 +194,7 @@ if someOptionalString != nil { // Swift supports "optional chaining," which means that you can call functions // or get properties of optional values and they are optionals of the appropriate type. // You can even do this multiple times, hence the name "chaining." - + let empty = someOptionalString?.isEmpty // Bool? // if-let structure - @@ -370,7 +370,7 @@ func say(_ message: String) { } say("Hello") -// Default parameters can be ommitted when calling the function. +// Default parameters can be omitted when calling the function. func printParameters(requiredParameter r: Int, optionalParameter o: Int = 10) { print("The required parameter was \(r) and the optional parameter was \(o)") } @@ -443,7 +443,7 @@ func testGuard() { return // guard statements MUST exit the scope that they are in. // They generally use `return` or `throw`. } - + print("number is \(aNumber)") } testGuard() @@ -564,7 +564,7 @@ enum Furniture { case desk(height: Int) // Associate with String and Int case chair(String, Int) - + func description() -> String { //either placement of let is acceptable switch self { @@ -591,15 +591,15 @@ print(chair.description()) // "Chair of Foo with 40 cm" - Define initializers to set up their initial state - Be extended to expand their functionality beyond a default implementation - Conform to protocols to provide standard functionality of a certain kind - + Classes have additional capabilities that structures don't have: - Inheritance enables one class to inherit the characteristics of another. - Type casting enables you to check and interpret the type of a class instance at runtime. - Deinitializers enable an instance of a class to free up any resources it has assigned. - Reference counting allows more than one reference to a class instance. - + Unless you need to use a class for one of these reasons, use a struct. - + Structures are value types, while classes are reference types. */ @@ -607,7 +607,7 @@ print(chair.description()) // "Chair of Foo with 40 cm" struct NamesTable { let names: [String] - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -629,7 +629,7 @@ class Shape { class Rect: Shape { var sideLength: Int = 1 - + // Custom getter and setter property var perimeter: Int { get { @@ -640,16 +640,16 @@ class Rect: Shape { sideLength = newValue / 4 } } - + // Computed properties must be declared as `var`, you know, cause' they can change var smallestSideLength: Int { return self.sideLength - 1 } - + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) - + // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` @@ -659,19 +659,19 @@ class Rect: Shape { print(someIdentifier) } } - + init(sideLength: Int) { self.sideLength = sideLength // always super.init last when init custom properties super.init() } - + func shrink() { if sideLength > 0 { sideLength -= 1 } } - + override func getArea() -> Int { return sideLength * sideLength } @@ -703,13 +703,13 @@ class Circle: Shape { override func getArea() -> Int { return 3 * radius * radius } - + // Place a question mark postfix after `init` is an optional init // which can return nil init?(radius: Int) { self.radius = radius super.init() - + if radius <= 0 { return nil } @@ -813,7 +813,7 @@ for _ in 0..<10 { - Internal: Accessible and subclassible in the module it is declared in. - Fileprivate: Accessible and subclassible in the file it is declared in. - Private: Accessible and subclassible in the enclosing declaration (think inner classes/structs/enums) - + See more here: https://docs.swift.org/swift-book/LanguageGuide/AccessControl.html */ @@ -878,11 +878,11 @@ extension Int { var doubled: Int { return self * 2 } - + func multipliedBy(num: Int) -> Int { return num * self } - + mutating func multiplyBy(num: Int) { self *= num } @@ -965,18 +965,18 @@ func fakeFetch(value: Int) throws -> String { guard 7 == value else { throw MyError.reallyBadValue(msg: "Some really bad value") } - + return "test" } func testTryStuff() { // assumes there will be no error thrown, otherwise a runtime exception is raised let _ = try! fakeFetch(value: 7) - + // if an error is thrown, then it proceeds, but if the value is nil // it also wraps every return value in an optional, even if its already optional let _ = try? fakeFetch(value: 7) - + do { // normal try operation that provides error handling via `catch` block try fakeFetch(value: 1) -- cgit v1.2.3 From fb48be47d6cac609cf9d29caae5d4e73df3e214a Mon Sep 17 00:00:00 2001 From: Ross Mackay Date: Tue, 22 Oct 2019 13:16:52 +0100 Subject: Fix outdated comment in en/th-th typescript docs --- th-th/typescript.th.html.markdown | 2 +- typescript.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/th-th/typescript.th.html.markdown b/th-th/typescript.th.html.markdown index fc2a823b..5395c2a7 100644 --- a/th-th/typescript.th.html.markdown +++ b/th-th/typescript.th.html.markdown @@ -190,7 +190,7 @@ interface Person { } var p1: Person = { name: "Tyrone", age: 42 }; -p1.age = 25; // Error แน่นอน เพราะ p1.x ถูกกำหนดเป็น read-only +p1.age = 25; // Error แน่นอน เพราะ p1.age ถูกกำหนดเป็น read-only var p2 = { name: "John", age: 60 }; // สังเกตว่า p2 ไม่ได้กำหนดเป็น Person var p3: Person = p2; // ทำได้ เป็น read-only alias ของ p2 และกำหนดเป็น Person diff --git a/typescript.html.markdown b/typescript.html.markdown index cf2111d5..6f238d5b 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -199,7 +199,7 @@ interface Person { } var p1: Person = { name: "Tyrone", age: 42 }; -p1.age = 25; // Error, p1.x is read-only +p1.age = 25; // Error, p1.age is read-only var p2 = { name: "John", age: 60 }; var p3: Person = p2; // Ok, read-only alias for p2 -- cgit v1.2.3 From 05872fc6316d7c6d8cc821a7bb4a74b306d9ce5f Mon Sep 17 00:00:00 2001 From: Vy Hong Date: Tue, 22 Oct 2019 08:35:34 -0700 Subject: Update comment in Java doWhile loop --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index ca0b04c2..aa8923ab 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -381,7 +381,7 @@ public class LearnJava { do { System.out.println(fooDoWhile); // Increment the counter - // Iterated 99 times, fooDoWhile 0->99 + // Iterated 100 times, fooDoWhile 0->99 fooDoWhile++; } while(fooDoWhile < 100); System.out.println("fooDoWhile Value: " + fooDoWhile); -- cgit v1.2.3 From 18b796972639303e472c8f5d1575061d8c8da2ac Mon Sep 17 00:00:00 2001 From: Flo Date: Tue, 22 Oct 2019 23:11:23 +0100 Subject: add go build tags --- go.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index ae99535b..4fc155b5 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -30,6 +30,12 @@ Go comes with a good standard library and a sizeable community. /* Multi- line comment */ + /* A build tag is a line comment starting with // +build + and can be execute by go build -tags="foo bar" command. + Build tags are placed before the package clause near or at the top of the file + followed by a blank line or other line comments. */ +// +build prod, dev, test + // A package clause starts every source file. // Main is a special name declaring an executable rather than a library. package main -- cgit v1.2.3 From 11413f734b6792ece40a80833bee24608e316731 Mon Sep 17 00:00:00 2001 From: Jack Smith Date: Tue, 22 Oct 2019 21:31:02 -0500 Subject: [hdl/en] Add Hardware Description Language Documentation --- hdl.html.markdown | 230 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 230 insertions(+) create mode 100644 hdl.html.markdown diff --git a/hdl.html.markdown b/hdl.html.markdown new file mode 100644 index 00000000..02ab1c41 --- /dev/null +++ b/hdl.html.markdown @@ -0,0 +1,230 @@ +--- +language: hdl +filename: learnhdl.hdl +contributors: + - ["Jack Smith", "https://github.com/JSmithTech2019"] +--- + +HDL (hardware description language) is a specialized language used to describe the structure/behavior of real world circuits. + +It is used by circuit designers to simulate circuits and logic prior to wiring and fabricating a hardware circuit. + +HDL allows circuit designers to simulate circuits at a high level without being connected to specific components. + +## Basic building blocks & introduction to the language--- +This programming language is built by simulating hardware chips and wiring. Normal programming functions are replaced with specialized chips that are added to the current wiring desing. Every base chip must be written as it's own file and imported to be used in the current chip, though they may be reused as often as desired. + +```verilog +// Single line comments start with two forward slashes. + +/* + * Multiline comments can be written using '/*' and 'star/'. + * These are often used as comments. + * + * Note that they cannot be nested and will end at the first 'star/'. + */ + +//////////////////////////////////////////////////// +// 1. Chips & Components +//////////////////////////////////////////////////// +/* + * Unlike other languages HDL creates an individual chip (function) per file + * These are defined with a name, input arguments, output arguments + * and finally the parts/logic of that specific chip. + */ + +// Note CHIP is capitalized, the chip name does not need to be. +CHIP Ex { + IN a, // Single bit (0 or 1) variable. + c[16]; // 16 bit variable bus of single bit values. + + OUT out[16], // 16 bit variable bus output. + carry; // Single bit output variable + + PARTS: + // The functional components of the chip. +} + +// Lines are ended with semicolons but can be continued using commas. The +// whitespace is ignored. + + + +//////////////////////////////////////////////////// +// 2. Inputs, Outputs, & Variables +//////////////////////////////////////////////////// +/* + * Variables and IO are treated as pins/wires and can carry a single bit + * of data (0 or 1). + */ + +// Hardware works on low level 0's and 1's, in order to use a constant +// high or low we use the terms true and false. +a=false; // This is a 0 value. +b=true; // This is a 1 value. + +// Inputs and outputs can be defined as single bits +IN a, b; // Creates two single bit inputs + +// They can also be defined as busses act as arrays where each +// index can contain a single bit value. +OUT c[16]; // Creates a 16 bit output array. + +// Bussed values can be accessed using brackets +a[0] // The first indexed value in the bus a. +a[0..3] // The first 4 values in the a bus. +// Values can also be passed in entirety. For example if the function +// foo() takes an 8 bit input bus and outputs a 2 bit bus: +foo(in=a[0..7], out=c); // C is now a 2 bit internal bus + + +// Note that internally defined busses cannot be subbussed! +// To access these elements, output or input them seperately: +foo(in[0]=false, in[1..7]=a[0..6], out[0]=out1, out[1]=out2); +// out1 and out2 can then be passed into other circuits within the design. + + + +//////////////////////////////////////////////////// +// Combining Subsystems +//////////////////////////////////////////////////// +/* + * HDL relies heavily on using smaller "building block" chips to then be + * added into larger and more complex designs. Creating the smaller components + * and then adding them to the larger circuit allows for fewer lines of code + * as well as reduction in total rewriting of code. + */ + +// We are writing the function AND that checks if inputs I and K are both one. +// To implement this chip we will use the built in NAND gate as well as design +// a custom NOT gate to invert a single input. + +// First we construct the Negation (not) chip. We will use the logically +// complete gate NAND that is built in for this task. +CHIP Not { + IN i; // Not gates only take one single bit input. + OUT o; // The negated value of a. + + PARTS: + // Add the input to the built in chip, which then sends output to the NOT + // output. This effectively negates the given value. + Nand(a=i, b=i, out=o); +} + +// By using the built in NAND gate we were able to construct a NOT gate +// that works like a real world hardware logic chip. Now we must construct +// the AND gate using these two gate primitives. + +// We define a two input, single output AND gate: +CHIP And { + IN i, k; // Two single bit inputs. + OUT o; // One single bit output. + + PARTS: + // Insert I and K into the nand gate and store the output in an internal + // wire called notOut. + Nand(a=i,b=b,out=notOut); + + // Use the not gate we constructed to invert notOut and send to the AND + // output. + Not(in=notOut,out=o); +} + +// Easy! Now we can use Nand, And, and Not gates in higher level circuits. +// Many of these low level components are built in to HDL but any chip can +// be written as a submodule and used in larger designs. +``` + +## Test Files +When working with the nand2tetris hardware simulator chips written using HDL will +then be processed against test and comparison files to test functionality of the +simulated chip versus the expected output. To do this a test file will be loaded +into the hardware simulator and run against the simulated hardware. + +```verilog +// First the chip the test file is written for is loaded +load .hdl + +// We set the output file for the simulated chip output as well as the comparison +// file that it will be tested against. We also specify what the output is expected +// to look like. In this case there will be two output columns, each will be buffered +// by a single space on either side and 4 binary values in the center of each column. +output-file .out, +compare-to .cmp, +output-list in%B1.4.1 out%B1.4.1; + +// Then we set initial values for inputs to the chip. For example +set enable1 1, // set input enable1 to 1 +set enable2 0, // set input enable2 to 0 + +// The clock is also controlled in the test file using tick and tock. Tick is a positive +// pulse and tock takes the clock back to 0. Clock cycles can be run multiple times in +// a row with no other changes to inputs or outputs. +tick, +tock, + +// Finally we output the first expected value (from the test file) which is then compared +// with the first line of real output from our HDL circuit. This output +// can be viewed in the .out file. +output; + +// An example of , a chip that takes in a 4 bit value as input and adds 1 to +// that value could have the following as test code: + +// Set the input value to 0000, clock pulse, compare output from cmp file to actual out. +set in %B0000, +tick, +tock, +output; + +// Set the input value to 0110, clock pulse, compare output from cmp file to actual out. +set in %B0110, +tick, +tock, +output; + +// The expected output for case 1 should be 0001 and case 2 expects 0111, lets learn +// a little more about comparison files before finalizing our lesson. +``` + +## Comparison Files +Now lets take a look at comparison files, the files that hold what the test file compares +with the actual output of an HDL chip in the hardware simulator! + +```verilog +// Like the example above, the structure of the comparison file would look +// something like this +| in | out | +| 0000 | 0001 | +| 0110 | 0111 | + +// Notice how the input values specified in the test case are equivalent to the +// `in` column of the comparison file, and that the space buffer is 1 on either side. + +// If the output from the HDL code we not this, such as the output below, then the +// test will fail and the user will know that the simulated chip is not correctly designed. +| in | out | +| 0000 | 0001 | +| 0110 | 0110 | // Error! The chip did not add 1 here, something went wrong. + + +``` + +This is incredibly useful as it allows designers to simulate chip logic prior to +fabricating real life hardware and identify problems in their designs. Be warned that +errors in the test or comparison files can lead to both false positives and also +the more damaging false negatives so ensure that the logic is sound behind the test +creation. + + +Good luck and happy coding! + +## Resources + +* [From Nand To Tetris](https://www.nand2tetris.org) + +## Further Reading + +* [Hardware Description Language](https://en.wikipedia.org/wiki/Hardware_description_language) + +* [HDL Programming Fundamentals](https://www.electronicdesign.com/products/hdl-programming-fundamentals) \ No newline at end of file -- cgit v1.2.3 From 0650f7b0183d4a5aa1ec905fd47de8c96adecdc0 Mon Sep 17 00:00:00 2001 From: Jack Smith Date: Tue, 22 Oct 2019 21:39:03 -0500 Subject: [hdl/en] Add Hardware Description Language Documentation --- hdl.html.markdown | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/hdl.html.markdown b/hdl.html.markdown index 02ab1c41..cad07817 100644 --- a/hdl.html.markdown +++ b/hdl.html.markdown @@ -146,9 +146,10 @@ into the hardware simulator and run against the simulated hardware. load .hdl // We set the output file for the simulated chip output as well as the comparison -// file that it will be tested against. We also specify what the output is expected -// to look like. In this case there will be two output columns, each will be buffered -// by a single space on either side and 4 binary values in the center of each column. +// file that it will be tested against. We also specify what the output is +// expected to look like. In this case there will be two output columns, each +// will be buffered by a single space on either side and 4 binary values in +// the center of each column. output-file .out, compare-to .cmp, output-list in%B1.4.1 out%B1.4.1; @@ -157,19 +158,19 @@ output-list in%B1.4.1 out%B1.4.1; set enable1 1, // set input enable1 to 1 set enable2 0, // set input enable2 to 0 -// The clock is also controlled in the test file using tick and tock. Tick is a positive -// pulse and tock takes the clock back to 0. Clock cycles can be run multiple times in -// a row with no other changes to inputs or outputs. +// The clock is also controlled in the test file using tick and tock. Tick is a +// positive pulse and tock takes the clock back to 0. Clock cycles can be run +// multiple times in a row with no other changes to inputs or outputs. tick, tock, -// Finally we output the first expected value (from the test file) which is then compared -// with the first line of real output from our HDL circuit. This output +// Finally we output the first expected value (from the test file) which is then +// compared with the first line of real output from our HDL circuit. This output // can be viewed in the .out file. output; -// An example of , a chip that takes in a 4 bit value as input and adds 1 to -// that value could have the following as test code: +// An example of , a chip that takes in a 4 bit value as input and +// adds 1 to that value could have the following as test code: // Set the input value to 0000, clock pulse, compare output from cmp file to actual out. set in %B0000, @@ -183,17 +184,17 @@ tick, tock, output; -// The expected output for case 1 should be 0001 and case 2 expects 0111, lets learn -// a little more about comparison files before finalizing our lesson. +// The expected output for case 1 should be 0001 and case 2 expects 0111, lets +// learn a little more about comparison files before finalizing our lesson. ``` ## Comparison Files -Now lets take a look at comparison files, the files that hold what the test file compares -with the actual output of an HDL chip in the hardware simulator! +Now lets take a look at comparison files, the files that hold what the test file +compares with the actual output of an HDL chip in the hardware simulator! ```verilog -// Like the example above, the structure of the comparison file would look -// something like this +// Like the example above, the structure of the comparison file +// would look something like this | in | out | | 0000 | 0001 | | 0110 | 0111 | -- cgit v1.2.3 From 5657bd4fa2a038a56d22b02060e217fff0049f94 Mon Sep 17 00:00:00 2001 From: waynee95 Date: Wed, 23 Oct 2019 15:34:13 +0200 Subject: [nix/de] Fix broken link --- de-de/nix-de.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown index 79b60d20..ea02e81d 100644 --- a/de-de/nix-de.html.markdown +++ b/de-de/nix-de.html.markdown @@ -8,11 +8,11 @@ translators: lang: de-de --- -Nix ist eine simple funktionale Programmiersprache, die für den +Nix ist eine simple funktionale Programmiersprache, die für den [Nix package manager](https://nixos.org/nix/) und [NixOS](https://nixos.org/) entwickelt wurde. -Du kannst Nix Ausdrücke evaluieren mithilfe von +Du kannst Nix Ausdrücke evaluieren mithilfe von [nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate) oder [`nix-repl`](https://github.com/edolstra/nix-repl). @@ -24,7 +24,7 @@ with builtins; [ # Inline Kommentare sehen so aus. - /* Multizeilen Kommentare + /* Multizeilen Kommentare sehen so aus. */ @@ -61,7 +61,7 @@ with builtins; [ "String Literale sind in Anführungszeichen." " - String Literale können mehrere + String Literale können mehrere Zeilen umspannen. " @@ -95,7 +95,7 @@ with builtins; [ tutorials/learn.nix #=> /the-base-path/tutorials/learn.nix - # Ein Pfad muss mindestens einen Schrägstrich enthalten. Ein Pfad für eine + # Ein Pfad muss mindestens einen Schrägstrich enthalten. Ein Pfad für eine # Datei im selben Verzeichnis benötigt ein ./ Präfix. ./learn.nix #=> /the-base-path/learn.nix @@ -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 zugewiesen wurde. + # das Attribut selbst nicht zugewiesen wurde. { a = { b = 1; }; a.c = 2; @@ -261,9 +261,9 @@ with builtins; [ #=> 7 # Die erste Linie diese Tutorials startet mit "with builtins;", - # weil builtins ein Set mit allen eingebauten + # weil builtins ein Set mit allen eingebauten # Funktionen (length, head, tail, filter, etc.) umfasst. - # Das erspart uns beispielsweise "builtins.length" zu schreiben, + # Das erspart uns beispielsweise "builtins.length" zu schreiben, # anstatt nur "length". @@ -305,7 +305,7 @@ with builtins; [ (tryEval (abort "foo")) #=> error: evaluation aborted with the following error message: ‘foo’ - # `assert` evaluiert zu dem gegebenen Wert, wenn die Bedingung wahr ist, sonst + # `assert` evaluiert zu dem gegebenen Wert, wenn die Bedingung wahr ist, sonst # löst es eine abfangbare Exception aus. (assert 1 < 2; 42) #=> 42 @@ -319,7 +319,7 @@ with builtins; [ #========================================= # 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 + # werden in der Nix Sprache reine funktionale Elemente betont. Es gibt aber ein paar # unreine Elemente. # Du kannst auf Umgebungsvariablen verweisen. (getEnv "HOME") @@ -355,4 +355,4 @@ with builtins; [ (https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55) * [Susan Potter - Nix Cookbook - Nix By Example] - (http://funops.co/nix-cookbook/nix-by-example/) + (https://ops.functionalalgebra.com/nix-by-example/) -- cgit v1.2.3 From 05018243abce940afe4e221054759d588e812342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20de=20Santa?= Date: Thu, 24 Oct 2019 12:20:33 -0300 Subject: Fix language typos in clojure-macros-pt.html.markdown --- pt-br/clojure-macros-pt.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown index d56840e0..c686bb80 100644 --- a/pt-br/clojure-macros-pt.html.markdown +++ b/pt-br/clojure-macros-pt.html.markdown @@ -13,15 +13,15 @@ do Clojure lhe dá acesso a toda a extensão da linguagem para escrever rotinas de geração de código chamados "macros". Macros fornecem uma poderosa forma de adequar a linguagem às suas necessidades. -Pórem Tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas -quando você precisar do controle sobre quando ou se os argumentos para um formulário será avaliado. +Pórem, tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas +quando você precisar de controle sobre quando ou se os argumentos de um formulário serão avaliados. Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo em -[Clojure em Y Minutos](/docs/clojure/). +[Aprenda Clojure em Y Minutos](/docs/clojure/). ```clojure -;; Defina uma macro utilizando defmacro. Sua macro deve ter como saida uma lista que possa -;; ser avaliada como codigo Clojure. +;; Defina uma macro utilizando defmacro. Sua macro deve ter como saída uma lista que possa +;; ser avaliada como código Clojure. ;; ;; Essa macro é a mesma coisa que se você escrever (reverse "Hello World") (defmacro my-first-macro [] @@ -33,14 +33,14 @@ Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo (macroexpand '(my-first-macro)) ;; -> (# "Hello World") -;; Você pode avaliar o resultad de macroexpand diretamente: +;; Você pode avaliar o resultado de macroexpand diretamente: (eval (macroexpand '(my-first-macro))) ; -> (\d \l \o \r \W \space \o \l \l \e \H) -;; mas você deve usar esse mais suscinto, sintax como de função: +;; mas você deve usar essa sintaxe mais sucinta e familiar a funções: (my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) -;; Você pode tornar as coisas mais faceis pra você, utilizando a sintaxe de citação mais suscinta +;; Você pode tornar as coisas mais fáceis pra você, utilizando a sintaxe de citação mais suscinta ;; para criar listas nas suas macros: (defmacro my-first-quoted-macro [] '(reverse "Hello World")) -- cgit v1.2.3 From 68083173eca275cbb4f9e068ab47812786146797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20de=20Santa?= Date: Thu, 24 Oct 2019 13:22:35 -0300 Subject: Add "Clojure for the Brave and True" resource --- pt-br/clojure-pt.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pt-br/clojure-pt.html.markdown b/pt-br/clojure-pt.html.markdown index b88d4eec..409394f2 100644 --- a/pt-br/clojure-pt.html.markdown +++ b/pt-br/clojure-pt.html.markdown @@ -382,3 +382,6 @@ Clojuredocs.org tem documentação com exemplos para quase todas as funções pr Clojure-doc.org tem um bom número de artigos para iniciantes: [http://clojure-doc.org/](http://clojure-doc.org/) + +Clojure for the Brave and True é um livro de introdução ao Clojure e possui uma versão gratuita online: +[https://www.braveclojure.com/clojure-for-the-brave-and-true/](https://www.braveclojure.com/clojure-for-the-brave-and-true/) -- cgit v1.2.3 From aa353ba1a555baae1f47051f3b5713a5769be1ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20de=20Santa?= Date: Thu, 24 Oct 2019 13:29:43 -0300 Subject: Add "Clojure for the Brave and True" resource --- clojure.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/clojure.html.markdown b/clojure.html.markdown index c94625d6..16771e25 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -416,3 +416,6 @@ Clojuredocs.org has documentation with examples for most core functions: Clojure-doc.org (yes, really) has a number of getting started articles: [http://clojure-doc.org/](http://clojure-doc.org/) + +Clojure for the Brave and True has a great introduction to Clojure and a free online version: +[https://www.braveclojure.com/clojure-for-the-brave-and-true/](https://www.braveclojure.com/clojure-for-the-brave-and-true/) -- cgit v1.2.3 From 0af4996d08c550144cf368f0fd6e0693294896a0 Mon Sep 17 00:00:00 2001 From: Philippe Coval Date: Fri, 25 Oct 2019 11:35:24 +0200 Subject: [ansible/en]: Fix quotes in command line example Change-Id: I46fe48764029d243b211cef04f06fdf62ea39219 Forwarded: https://github.com/adambard/learnxinyminutes-docs/pull/3729 Signed-off-by: Philippe Coval --- ansible.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ansible.html.markdown b/ansible.html.markdown index 41a8c9b5..bfb1406b 100644 --- a/ansible.html.markdown +++ b/ansible.html.markdown @@ -513,7 +513,7 @@ $ # Now we would run the above playbook with roles 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 +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 -- cgit v1.2.3 From f47496b08327441eb3d6e553ce80efdd16fddc82 Mon Sep 17 00:00:00 2001 From: Felipe N Souza Date: Sat, 26 Oct 2019 21:39:37 -0300 Subject: [Python/pt-br] Improve translation --- pt-br/python3-pt.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown index b72c732a..c8b234f6 100644 --- a/pt-br/python3-pt.html.markdown +++ b/pt-br/python3-pt.html.markdown @@ -11,11 +11,11 @@ lang: pt-br filename: learnpython3-pt.py --- -Python foi criado por Guido Van Rossum nos anos 1990. Ele é atualmente uma -das mais populares linguagens em existência. Eu fiquei morrendo de amor -pelo Python por sua clareza sintática. É praticamente pseudocódigo executável. +Python foi criada por Guido Van Rossum nos anos 1990. Ela é atualmente uma +das linguagens mais populares existentes. Eu me apaixonei por +Python por sua clareza sintática. É praticamente pseudocódigo executável. -Suas opiniões são grandemente apreciadas. Você pode encontrar-me em +Opniões são muito bem vindas. Você pode encontrar-me em [@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] [serviço de e-mail do google]. -- cgit v1.2.3 From 7e27297ea555764a5e690f251205d9323b349bb2 Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Sun, 27 Oct 2019 12:41:50 -0500 Subject: Formatting the dart example --- dart.html.markdown | 78 +++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 57 insertions(+), 21 deletions(-) diff --git a/dart.html.markdown b/dart.html.markdown index 07f755f7..dec2c904 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -29,6 +29,7 @@ example1() { nested2() => print("Example1 nested 1 nested 2"); nested2(); } + nested1(); } @@ -37,6 +38,7 @@ example2() { nested1(fn) { fn(); } + nested1(() => print("Example2 nested 1")); } @@ -47,9 +49,12 @@ example3() { planA(fn(informSomething)) { fn("Example3 plan A"); } - planB(fn) { // Or don't declare number of parameters. + + planB(fn) { + // Or don't declare number of parameters. fn("Example3 plan B"); } + planA((s) => print(s)); planB((s) => print(s)); } @@ -60,17 +65,20 @@ example4() { nested1(fn(informSomething)) { fn(example4Something); } + nested1((s) => print(s)); } // Class declaration with a sayIt method, which also has closure access // to the outer variable as though it were a function as seen before. var example5method = "Example5 sayIt"; + class Example5Class { sayIt() { print(example5method); } } + example5() { // Create an anonymous instance of the Example5Class and call the sayIt // method on it. @@ -86,6 +94,7 @@ class Example6Class { print(instanceVariable); } } + example6() { new Example6Class().sayIt(); } @@ -96,10 +105,12 @@ class Example7Class { static sayItFromClass() { print(classVariable); } + sayItFromInstance() { print(classVariable); } } + example7() { Example7Class.sayItFromClass(); new Example7Class().sayItFromInstance(); @@ -111,7 +122,7 @@ example7() { // by default. But arrays and maps are not. They can be made constant by // declaring them "const". var example8Array = const ["Example8 const array"], - example8Map = const {"someKey": "Example8 const map"}; + example8Map = const {"someKey": "Example8 const map"}; example8() { print(example8Array[0]); print(example8Map["someKey"]); @@ -172,6 +183,7 @@ example13() { print("Example13 regexp doesn't match '${s}'"); } } + match(s1); match(s2); } @@ -190,7 +202,7 @@ example14() { } // dynamic typed null can be convert to bool - var b;// b is dynamic type + var b; // b is dynamic type b = "abc"; try { if (b) { @@ -240,9 +252,11 @@ example15() { // StringBuffer. Or you could join a string array. example16() { var sb = new StringBuffer(), a = ["a", "b", "c", "d"], e; - for (e in a) { sb.write(e); } + for (e in a) { + sb.write(e); + } print("Example16 dynamic string created with " - "StringBuffer '${sb.toString()}'"); + "StringBuffer '${sb.toString()}'"); print("Example16 join string array '${a.join()}'"); } @@ -302,11 +316,13 @@ class Example21 { 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"); @@ -320,7 +336,9 @@ class Example22A { var _name = "Some Name!"; get name => _name; } + class Example22B extends Example22A {} + example22() { var o = new Example22B(); print("Example22 class inheritance '${o.name}'"); @@ -334,19 +352,21 @@ example22() { // single inheritance doesn't get in the way of reusable code. // Mixins follow the "with" statement during the class declaration. 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); + 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}'"); } @@ -362,12 +382,13 @@ class Example24A { } get value => _value; } + class Example24B extends Example24A { Example24B({value: "someOtherValue"}) : super(value: value); } + example24() { - var o1 = new Example24B(), - o2 = new Example24B(value: "evenMore"); + 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}'"); } @@ -379,10 +400,11 @@ 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}'"); + "'${o.anotherValue}'"); } // Named parameters are available when declared between {}. @@ -394,17 +416,19 @@ example26() { _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}'"); + "email '${_email}'"); setConfig2("Mary", "Jane"); print("Example26 name '${_name}', surname '${_surname}', " - "email '${_email}'"); + "email '${_email}'"); } // Variables declared with final can only be set once. @@ -416,6 +440,7 @@ class Example27 { // that follows the : Example27({this.color1, color2}) : color2 = color2; } + example27() { final color = "orange", o = new Example27(color1: "lilac", color2: "white"); print("Example27 color is '${color}'"); @@ -434,6 +459,7 @@ class Example28 extends IterableBase { } get iterator => names.iterator; } + example28() { var o = new Example28(); o.forEach((name) => print("Example28 '${name}'")); @@ -459,10 +485,12 @@ example29() { callItForMe(fn()) { return fn(); } + rand() { v = new DM.Random().nextInt(50); return v; } + while (true) { print("Example29 callItForMe(rand) '${callItForMe(rand)}'"); if (v != 30) { @@ -477,8 +505,12 @@ example29() { // Parse int, convert double to int, or just keep int when dividing numbers // by using the ~/ operation. Let's play a guess game too. example30() { - var gn, tooHigh = false, - n, n2 = (2.0).toInt(), top = int.parse("123") ~/ n2, bottom = 0; + 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 because nextInt top is exclusive print("Example30 Guess a number between 0 and ${top}"); @@ -488,10 +520,11 @@ example30() { } else { tooHigh = n > gn; print("Example30 Number ${n} is too " - "${tooHigh ? 'high' : 'low'}. Try again"); + "${tooHigh ? 'high' : 'low'}. Try again"); } return n == gn; } + n = (top - bottom) ~/ 2; while (!guessNumber(n)) { if (tooHigh) { @@ -510,12 +543,15 @@ example30() { // the program needs to startup with. main() { print("Learn Dart in 15 minutes!"); - [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()); + [ + 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 // Adding this comment stops the dart formatter from putting all items on a new line + ].forEach((ef) => ef()); } ``` -- cgit v1.2.3 From 6b5938017b5105066d27484605af8dd88fab183d Mon Sep 17 00:00:00 2001 From: AstiaSun Date: Mon, 28 Oct 2019 01:20:19 +0200 Subject: [mips/uk-ua] Add ukrainian translation for MIPS Assemly --- uk-ua/mips-ua.html.markdown | 366 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 366 insertions(+) create mode 100644 uk-ua/mips-ua.html.markdown diff --git a/uk-ua/mips-ua.html.markdown b/uk-ua/mips-ua.html.markdown new file mode 100644 index 00000000..20fa7638 --- /dev/null +++ b/uk-ua/mips-ua.html.markdown @@ -0,0 +1,366 @@ +--- +language: "MIPS Assembly" +filename: MIPS.asm +contributors: + - ["Stanley Lim", "https://github.com/Spiderpig86"] +translators: + - ["AstiaSun", "https://github.com/AstiaSun"] +lang: uk-ua +--- + +Мова асемблера MIPS (англ. Microprocessor without Interlocked Pipeline Stages) була написана для роботи з мікропорцесорами MIPS, парадигма яких була описана в 1981 році [Джоном Геннессі](https://uk.wikipedia.org/wiki/Джон_Лерой_Геннессі). Ці RISC процесори використовуються у таких вбудованих системах, як маршрутизатори та мережеві шлюзи. + +[Read More](https://en.wikipedia.org/wiki/MIPS_architecture) + +```asm +# Коментарі позначені як'#' + +# Всі символи після '#' ігноруються лексичним аналізатором асемблера. + +# Зазвичай програми поділяються на .data та .text частини + +.data # У цьому розділі дані зберігаються у пам'яті, виділеній в RAM, подібно до змінних + # в мовах програмування вищого рівня + + # Змінна оголошується наступним чином: [назва]: .[тип] [значенння] + # Наприклад: + hello_world: .asciiz "Hello World\n" # Оголосити текстову змінну + num1: .word 42 # word - це чисельний тип 32-бітного розряду + + arr1: .word 1, 2, 3, 4, 5 # Масив чисел + arr2: .byte 'a', 'b' # Масив буквених символів (розмір кожного - 1 байт) + buffer: .space 60 # Виділити місце в RAM + # (не очищується, тобто не заповнюється 0) + + # Розміри типів даних + _byte: .byte 'a' # 1 байт + _halfword: .half 53 # 2 байти + _word: .word 3 # 4 байти + _float: .float 3.14 # 4 байти + _double: .double 7.0 # 8 байтів + + .align 2 # Вирівнення пам'яті даних, де число + # показує кількість байтів, вирівнених + # у степені 2. (.align 2 означає + # чисельне (word) вирівнювання оскільки + # 2^2 = 4 байти) + +.text # Розділ, що містить інструкції та + # логіку програми + +.globl _main # Оголошує назву інструкції як + # глобальну, тобто, яка є доступною для + # всіх інших файлів + + _main: # програми MIPS виконують інструкції + # послідовно, тобто першочергово код + # буде виконуватись після цієї позначки + + # Виведемо на екран "hello world" + la $a0, hello_world # Завантажує адресу тексту у пам'яті + li $v0, 4 # Завантажує значення системної + # команди (вказуючи тип функціоналу) + syscall # Виконує зазначену системну команду + # з обраним аргументом ($a0) + + # Регісти (використовуються, щоб тримати дані протягом виконання програми) + # $t0 - $t9 # Тимчасові регістри використовуються + # для проміжних обчислень всередині + # підпрограм (не зберігаються між + # викликами функцій) + + # $s0 - $s7 # Збережені регісти, у яких значення + # збегіраються між викликами підпрограм. + # Зазвичай збегрігаються у стеку. + + # $a0 - $a3 # Регістри для передачі аргументів для + # підпрограм + # $v0 - $v1 # Регістри для значень, що повертаються + # від викликаної функції + + # Типи інструкції завантаження / збереження + la $t0, label # Скопіювати адресу в пам'яті, де + # зберігається значення змінної label + # в регістр $t0 + lw $t0, label # Скопівати чисельне значення з пам'яті + lw $t1, 4($s0) # Скопівати чисельне значення з адреси + # пам'яті ресгіста зі зміщенням в + # 4 байти (адреса + 4) + lb $t2, label # Скопіювати буквений символ в частину + # нижчого порядку регістра $t2 + lb $t2, 0($s0) # Скопіювати буквений символ з адреси + # в $s0 із зсувом 0 + # Подіне використання і 'lh' для halfwords + + sw $t0, label # Збегігти чисельне значення в адресу в + # пам'яті, що відповідає змінній label + sw $t0, 8($s0) # Збегігти чисельне значення в адресу, + # зазначеній у $s0, та зі зсувом у 8 байтів + # Така ж ідея використання 'sb' та 'sh' для буквених символів та halfwords. + # 'sa' не існує + + +### Математичні операції ### + _math: + # Пам'ятаємо, що попередньо потрібно завантажити данні в пам'ять + lw $t0, num # Із розділа з данними + li $t0, 5 # Або безпосередньо з константи + 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 (Може не підтримуватись + # деякими версіями MARS) + div $t0, $t1 # Виконує $t0 / $t1. Отримати частку можна + # за допомогою команди 'mflo', остаток - 'mfhi' + + # Bitwise Shifting + sll $t0, $t0, 2 # Побітовий здвиг вліво з безпосереднім + # значенням (константою) 2 + sllv $t0, $t1, $t2 # Здвиг вліво зі змінною кількістю у + # регістрі + srl $t0, $t0, 5 # Побітовий здвиг вправо (не збегігає + # знак, знак розширюється 0) + srlv $t0, $t1, $t2 # Здвиг вправо зі змінною кількістю у + # регістрі + sra $t0, $t0, 7 # Побітовий арифметичний збвиг вправо + # (зберігає знак) + srav $t0, $t1, $t2 # Здвиг вправо зі змінною кількістю у + # регістрі + + # Bitwise operators + and $t0, $t1, $t2 # Побітове І (AND) + andi $t0, $t1, 0xFFF # Побітове І з беспосереднім значенням + or $t0, $t1, $t2 # Побітове АЛЕ (OR) + ori $t0, $t1, 0xFFF # Побітове АЛЕ з беспосереднім значенням + xor $t0, $t1, $t2 # Побітова виключна диз'юнкція (XOR) + xori $t0, $t1, 0xFFF # Побітове XOR з беспосереднім значенням + nor $t0, $t1, $t2 # Побітова стрілка Пірса (NOR) + +## Розгалуження ## + _branching: + # В овсновному інструкції розгалуження мають наступну форму: + #