From ff3b464026313e6ca2a11a9671c27c43b340da8f Mon Sep 17 00:00:00 2001 From: Elena Bolshakova Date: Fri, 28 Nov 2014 11:36:41 +0300 Subject: [perl/ru] Russian translation for Perl 5 --- ru-ru/perl-ru.html.markdown | 169 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 169 insertions(+) create mode 100644 ru-ru/perl-ru.html.markdown diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown new file mode 100644 index 00000000..9e9c7748 --- /dev/null +++ b/ru-ru/perl-ru.html.markdown @@ -0,0 +1,169 @@ +--- +category: language +language: perl +filename: learnperl-ru.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] +translators: + - ["Elena Bolshakova", "http://github.com/liruoko"] +lang: ru-ru +--- + +Perl 5 -- высокоуровневый мощный язык с 25-летней историей. +Особенно хорош для обработки разнообразных текстовых данных. + +Perl 5 работает более чем на 100 платформах, от портативных устройств +до мейнфреймов, и подходит как для быстрого прототипирования, +так и для крупных проектов. + +```perl +# Комментарии начинаются с символа решетки. + + +#### Типы переменных в Perl + +# Скалярные переменные начинаются с знака доллара $. +# Имя переменной состоит из букв, цифр и знаков подчеркивания, +# начиная с буквы или подчеркивания. + +### В Perl три основных типа переменных: скаляры, массивы, хеши. + +## Скаляры +# Скаляр хранит отдельное значение: +my $animal = "camel"; +my $answer = 42; + +# Скаляры могут быть строками, целыми и вещественными числами. +# Когда требуется, Perl автоматически выполняет преобразования к нужному типу. + +## Массивы +# Массив хранит список значений: +my @animals = ("camel", "llama", "owl"); +my @numbers = (23, 42, 69); +my @mixed = ("camel", 42, 1.23); + + +## Хеши +# Хеш хранит набор пар ключ/значение: + +my %fruit_color = ("apple", "red", "banana", "yellow"); + +# Можно использовать оператор "=>" для большей наглядности: + +my %fruit_color = ( + apple => "red", + banana => "yellow", + ); + +# Важно: вставка и поиск в хеше выполняются за константное время, +# независимо от его размера. + +# Скаляры, массивы и хеши подробно описаны в разделе perldata +# (perldoc perldata). + +# Более сложные структуры данных можно получить, если использовать ссылки. +# С помощью ссылок можно получить массив массивов хешей, в которых хранятся другие хеши. + +#### Условные операторы и циклы + +# В Perl есть большинсво привычных условных и циклических конструкций. + +if ( $var ) { + ... +} elsif ( $var eq 'bar' ) { + ... +} else { + ... +} + +unless ( condition ) { + ... + } +# Это более читаемый вариант для "if (!condition)" + +# Специфические Perl-овые пост-условия: +print "Yow!" if $zippy; +print "We have no bananas" unless $bananas; + +# while + while ( condition ) { + ... + } + + +# for, foreach +for ($i = 0; $i <= $max; $i++) { + ... + } + +foreach (@array) { + print "This element is $_\n"; + } + +for my $el (@array) { + print "This element is $el\n"; + } + +#### Регулярные выражения + +# Регулярные выражения занимают важное место вPerl-е, +# и подробно описаны в разделах документации perlrequick, perlretut и других. +# Вкратце: + +# Сопоставление с образцом +if (/foo/) { ... } # выполняется, если $_ содержит "foo" +if ($a =~ /foo/) { ... } # выполняется, если $a содержит "foo" + +# Простые замены + +$a =~ s/foo/bar/; # заменяет foo на bar в строке $a +$a =~ s/foo/bar/g; # заменяет ВСЕ ВХОЖДЕНИЯ foo на bar в строке $a + + +#### Файлы и ввод-вывод + +# Открыть файл на чтение или запись можно с помощью функции "open()". + +open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; +open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; +open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; + +# Читать из файлового дескриптора можно с помощью оператора "<>". +# В скалярном контексте он читает одру строку из файла, в списковом -- +# читает сразу весь файл, сохраняя по одной строке в элементе массива: + +my $line = <$in>; +my @lines = <$in>; + +#### Подпрограммы (функции) + +# Объявить функцию просто: + +sub logger { + my $logmessage = shift; + open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; + print $logfile $logmessage; +} + +# Теперь можно использовать эту функцию так же, как и встроенные: + +logger("We have a logger subroutine!"); +``` + +#### Perl-модули + +Perl-овые модули предоставляют широкий набор функциональности, +так что вы можете не изобретать заново велосипеды, а просто скачать +нужный модуль с CPAN (http://www.cpan.org/). +Некоторое количество самых полезных модулей включено в стандартную +поставку Perl. + +Раздел документации perlfaq содержит вопросы и ответы о многих частых +задачах, и часто предлагает подходящие CPAN-модули. + +#### Смотрите также + + - [perl-tutorial](http://perl-tutorial.org/) + - [обучающий раздел на www.perl.com](http://www.perl.org/learn.html) + - [perldoc в вебе](http://perldoc.perl.org/) + - встроенная справка : `perldoc perlintro` -- cgit v1.2.3 From 9f765b9c7b0b207b51b914161313fdb7ecadaa5c Mon Sep 17 00:00:00 2001 From: Suzane Sant Ana Date: Sat, 17 Jan 2015 09:17:39 -0200 Subject: removing a piece in english in pt-br translation --- pt-br/c++-pt.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 243627cb..61625ebe 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -9,8 +9,7 @@ translators: lang: pt-br --- -C++ é uma linguagem de programação de sistemas que, -C++ is a systems programming language that, +C++ é uma linguagem de programação de sistemas que, [de acordo com seu inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), foi concebida para @@ -588,4 +587,4 @@ Leitura Adicional: Uma referência atualizada da linguagem pode ser encontrada em -Uma fonte adicional pode ser encontrada em \ No newline at end of file +Uma fonte adicional pode ser encontrada em -- cgit v1.2.3 From 3fa59915d0e30b5b0f08bea5e1a62b73f4250ebb Mon Sep 17 00:00:00 2001 From: yelite Date: Sun, 18 Jan 2015 16:06:48 +0800 Subject: Update swift.html.markdown --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 0d1d2df4..2fbbe544 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -481,7 +481,7 @@ extension Int { } println(7.customProperty) // "This is 7" -println(14.multiplyBy(2)) // 42 +println(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. -- cgit v1.2.3 From 40c38c125b94430b518d7e402d595694149b7c53 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 18 Jan 2015 13:07:31 -0700 Subject: [Java/cn] Fix inc/dec operator explanation --- zh-cn/java-cn.html.markdown | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index f7d319e6..f08d3507 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -124,7 +124,7 @@ public class LearnJava { // HashMaps /////////////////////////////////////// - // 操作符 + // 操作符 /////////////////////////////////////// System.out.println("\n->Operators"); @@ -161,10 +161,13 @@ public class LearnJava { // 自增 int i = 0; System.out.println("\n->Inc/Dec-rementation"); - System.out.println(i++); //i = 1 后自增 - System.out.println(++i); //i = 2 前自增 - System.out.println(i--); //i = 1 后自减 - System.out.println(--i); //i = 0 前自减 + // ++ 和 -- 操作符使变量加或减1。放在变量前面或者后面的区别是整个表达 + // 式的返回值。操作符在前面时,先加减,后取值。操作符在后面时,先取值 + // 后加减。 + System.out.println(i++); // 后自增 i = 1, 输出0 + System.out.println(++i); // 前自增 i = 2, 输出2 + System.out.println(i--); // 后自减 i = 1, 输出2 + System.out.println(--i); // 前自减 i = 0, 输出0 /////////////////////////////////////// // 控制结构 @@ -192,7 +195,7 @@ public class LearnJava { } System.out.println("fooWhile Value: " + fooWhile); - // Do While循环 + // Do While循环 int fooDoWhile = 0; do { -- cgit v1.2.3 From 8d43943b678846f1fb81c925e8232f92f46baa02 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Mon, 19 Jan 2015 17:40:07 +0300 Subject: [swift/ru] Translating Swift guide into Russian --- ru-ru/swift-ru.html.markdown | 535 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 535 insertions(+) create mode 100644 ru-ru/swift-ru.html.markdown diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown new file mode 100644 index 00000000..d78365a5 --- /dev/null +++ b/ru-ru/swift-ru.html.markdown @@ -0,0 +1,535 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] +filename: learnswift.swift +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +Swift - это язык программирования, созданный компанией Apple, для разработки +приложений iOS и OS X. Разработанный, чтобы сосуществовать с Objective-C и +быть более устойчивым к ошибочному коду, Swift был представлен в 2014 году на +конференции разработчиков Apple, WWDC. Приложения на Swift собираются +с помощью LLVM компилятора, включенного в Xcode 6+. + +Официальная книга по [языку программирования Swift](https://itunes.apple.com/us/book/swift-programming-language/id881256329) от Apple доступна в iBooks. + +Смотрите еще [начальное руководство](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) Apple, которое содержит полное учебное пособие по Swift. + +```swift +// импорт модуля +import UIKit + +// +// MARK: Основы +// + +// Xcode поддерживает заметные маркеры, чтобы давать примечания свою коду +// и вносить их в список обозревателя (Jump Bar) +// MARK: Метка раздела +// TODO: Сделайте что-нибудь вскоре +// FIXME: Исправьте этот код + +println("Привет, мир") + +// переменные (var), значение которых можно изменить после инициализации +// константы (let), значение которых нельзя изменить после инициализации + +var myVariable = 42 +let øπΩ = "значение" // именование переменной символами unicode +let π = 3.1415926 +let convenience = "Ключевое слово" // контекстное имя переменной +let weak = "Ключевое слово"; let override = "еще ключевое слово" // операторы + // могут быть отделены точкой с запятой +let `class` = "Ключевое слово" // одинарные кавычки позволяют использовать + // ключевые слова в именовании переменных +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "некоторый текст " + String(myVariable) // Приведение типа +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Вставка переменных в строку + +// Сборка особых значений +// используя ключ -D сборки конфигурации +#if false + println("Не печатается") + let buildValue = 3 +#else + let buildValue = 7 +#endif +println("Значение сборки: \(buildValue)") // Значение сборки: 7 + +/* + Optional - это особенность языка Swift, которая допускает вам сохранять + `некоторое` или `никакое` значения. + + Язык Swift требует, чтобы каждое свойство имело значение, поэтому даже nil + должен явно сохранен как Optional значение. + + Optional является перечислением. +*/ +var someOptionalString: String? = "optional" // Может быть nil +// как и выше, только ? это постфиксный оператор (синтаксический сахар) +var someOptionalString2: Optional = "optional" + +if someOptionalString != nil { + // я не nil + if someOptionalString!.hasPrefix("opt") { + println("содержит префикс") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +// неявная развертка переменной Optional +var unwrappedString: String! = "Ожидаемое значение." +// как и выше, только ! постфиксный оператор (с еще одним синтаксическим сахаром) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Ожидаемое значение." + +if let someOptionalStringConstant = someOptionalString { + // имеется некоторое значение, не nil + if !someOptionalStringConstant.hasPrefix("ok") { + // нет такого префикса + } +} + +// Swift поддерживает сохранение значение любого типа +// AnyObject == id +// В отличие от `id` в Objective-C, AnyObject работает с любым значением (Class, +// Int, struct и т.д.) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Изменять значение на строку не является хорошей практикой, но возможно." + +/* + Комментируйте здесь + + /* + Вложенные комментарии тоже поддерживаются + */ +*/ + +// +// MARK: Коллекции +// + +/* + Массив (Array) и словарь (Dictionary) являются структурами (struct). Так + `let` и `var` также означают, что они изменяются (var) или не изменяются (let) + при объявлении типов. +*/ + +// Массив +var shoppingList = ["сом", "вода", "лимоны"] +shoppingList[1] = "бутылка воды" +let emptyArray = [String]() // let == неизменный +let emptyArray2 = Array() // как и выше +var emptyMutableArray = [String]() // var == изменяемый + + +// Словарь +var occupations = [ + "Malcolm": "Капитан", + "kaylee": "Техник" +] +occupations["Jayne"] = "Связи с общественностью" +let emptyDictionary = [String: Float]() // let == неизменный +let emptyDictionary2 = Dictionary() // как и выше +var emptyMutableDictionary = [String: Float]() // var == изменяемый + + +// +// MARK: Поток управления +// + +// цикл for для массива +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("Один!") + } else { + println("Не один!") + } +} + +// цикл for для словаря +var dict = ["один": 1, "два": 2] +for (key, value) in dict { + println("\(key): \(value)") +} + +// цикл for для диапазона чисел +for i in -1...shoppingList.count { + println(i) +} +shoppingList[1...2] = ["бифштекс", "орехи пекан"] +// используйте ..< для исключения последнего числа + +// цикл while +var i = 1 +while i < 1000 { + i *= 2 +} + +// цикл do-while +do { + println("привет") +} while 1 == 2 + +// Переключатель +// Очень мощный оператор, представляйте себе операторы `if` с синтаксическим +// сахаром +// Они поддерживают строки, объекты и примитивы (Int, Double, etc) +let vegetable = "красный перец" +switch vegetable { +case "сельдерей": + let vegetableComment = "Добавьте немного изюма и make ants on a log." +case "огурец", "жеруха": + let vegetableComment = "Было бы неплохо сделать бутерброд с чаем." +case let localScopeValue where localScopeValue.hasSuffix("перец"): + let vegetableComment = "Это острый \(localScopeValue)?" +default: // обязательный (чтобы преодолеть все возможные вхождения) + let vegetableComment = "Все вкусы хороши для супа." +} + + +// +// MARK: Функции +// + +// Функции являются типом первого класса, т.е. они могут быть вложены в функциях +// и могут передаваться между собой + +// Функция с документированным заголовком Swift (формат reStructedText) + +/** + Операция приветствия + + - Жирная метка в документировании + - Еще одна жирная метка в документации + + :param: name - это имя + :param: day - это день + :returns: Строка, содержащая значения name и day. +*/ +func greet(name: String, day: String) -> String { + return "Привет \(name), сегодня \(day)." +} +greet("Боб", "вторник") + +// как и выше, кроме обращения параметров функции +func greet2(#requiredName: String, externalParamName localParamName: String) -> String { + return "Привет \(requiredName), сегодня \(localParamName)" +} +greet2(requiredName:"Иван", externalParamName: "воскресенье") + +// Функция, которая возвращает множество элементов в кортеже +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Пропускайте значения кортежей с помощью подчеркивания _ +let (_, price1, _) = pricesTuple // price1 == 3.69 +println(price1 == pricesTuple.1) // вывод: true +println("Цена газа: \(price)") + +// Переменное число аргументов +func setup(numbers: Int...) { + // это массив + let number = numbers[0] + let argCount = numbers.count +} + +// Передача и возврат функций +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// передача по ссылке +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +println(someIntB) // 7 + + +// +// MARK: Замыкания +// +var numbers = [1, 2, 6] + +// Функции - это частный случай замыканий ({}) + +// Пример замыкания. +// `->` отделяет аргументы и возвращаемый тип +// `in` отделяет заголовок замыкания от тела замыкания +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Когда тип известен, как и выше, мы можем сделать так +numbers = numbers.map({ number in 3 * number }) +// Или даже так +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Упрощение замыкания +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Суперсокращение, поскольку оператор < выполняет логический вывод типов + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Структуры +// + +// Структуры и классы имеют очень похожие характеристики +struct NamesTable { + let names = [String]() + + // Пользовательский индекс + subscript(index: Int) -> String { + return names[index] + } +} + +// У структур автогенерируемый (неявно) инициализатор +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +println("Name is \(name)") // Name is Them + +// +// MARK: Классы +// + +// Классы, структуры и их члены имеют трехуровневый контроль доступа +// Уровни: internal (по умолчанию), public, private + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Все методы и свойства класса являются открытыми (public). +// Если вам необходимо содержать только данные +// в структурированном объекте, вы должны использовать `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Пользовательский сеттер и геттер + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` - неявная переменная, доступная в сеттере + sideLength = newValue / 4 + } + } + + // Ленивая загрузка свойства + // свойство subShape остается равным nil (неинициализированным), + // пока не вызовется геттер + lazy var subShape = Rect(sideLength: 4) + + // Если вам не нужны пользовательские геттеры и сеттеры, + // но все же хотите запустить код перед и после вызовов геттера или сеттера + // свойств, вы можете использовать `willSet` и `didSet` + var identifier: String = "defaultID" { + // аргумент у `willSet` будет именем переменной для нового значения + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // всегда вызывается super.init последним, когда init с параметрами + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// Простой класс `Square` наследует `Rect` +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// преобразование объектов +let aShape = mySquare as Shape + +// сравнение объектов, но не как операция ==, которая проверяет эквивалентность +if mySquare === mySquare { + println("Ага, это mySquare") +} + + +// +// MARK: Перечисления +// + +// Перечисления могут быть определенного или своего типа. +// Они могут содержать методы подобно классам. + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// Значения перечислений допускают жесткий синтаксис, нет необходимости +// указывать тип перечисления, когда переменная объявляется явно +var suitValue: Suit = .Hearts + +// Нецелочисленные перечисления требуют прямого указания значений +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +println("Имя: \(BookName.John.rawValue)") + + +// +// MARK: Протоколы +// + +// `protocol` может потребовать, чтобы у соответствующих типов +// были определенные свойства экземпляра, методы экземпляра, тип методов, +// операторы и индексы. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Протоколы, объявленные с @objc, допускают необязательные функции, +// которые позволяют вам проверять на соответствие +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // проверка делегата на выполнение метода + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Прочее +// + +// `extension`s: Добавляет расширенный функционал к существующему типу + +// Класс Square теперь "соответствует" протоколу `Printable` +extension Square: Printable { + var description: String { + return "Площадь: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Объект Square: \(mySquare)") + +// Вы также можете расширить встроенные типы +extension Int { + var customProperty: String { + return "Это \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "Это 7" +println(14.multiplyBy(3)) // 42 + +// Обобщения: Подобно языкам Java и C#. Используйте ключевое слово `where`, +// чтобы определить условия обобщений. + +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // вывод: true + +// Операторы: +// Пользовательские операторы могут начинаться с символов: +// / = - + * % < > ! & | ^ . ~ +// или +// Unicode- знаков математики, символов, стрелок, декорации и линий/кубов, +// нарисованных символов. +prefix operator !!! {} + +// Префиксный оператор, который утраивает длину стороны, когда используется +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// текущее значение +println(mySquare.sideLength) // 4 + +// Используя пользовательский оператор !!!, изменится длина стороны +// путем увеличения размера в 3 раза +!!!mySquare +println(mySquare.sideLength) // 12 +``` -- cgit v1.2.3 From 4e130fce1c202c31cd0c7b94706da2cab7747aa1 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Mon, 19 Jan 2015 17:54:12 +0300 Subject: Update filename in the doc header. --- ru-ru/swift-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown index d78365a5..f788ad4c 100644 --- a/ru-ru/swift-ru.html.markdown +++ b/ru-ru/swift-ru.html.markdown @@ -3,7 +3,7 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] -filename: learnswift.swift +filename: learnswift-ru.swift translators: - ["Dmitry Bessonov", "https://github.com/TheDmitry"] lang: ru-ru -- cgit v1.2.3 From ea9acc1b346fffcc820a79b585a5251cc74e857f Mon Sep 17 00:00:00 2001 From: Johnathan Maudlin Date: Mon, 19 Jan 2015 22:10:37 -0500 Subject: Update contributors --- tmux.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 9eb96303..2ccb067a 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -2,7 +2,7 @@ category: tool tool: tmux contributors: - - ["wzsk", "https://github.com/wzsk"] + - ["mdln", "https://github.com/mdln"] filename: LearnTmux.txt --- -- cgit v1.2.3 From 209dc039ecc5ee280e5239afe5e2a77a851f795f Mon Sep 17 00:00:00 2001 From: searoso Date: Tue, 20 Jan 2015 21:34:18 +0300 Subject: Update r.html.markdown Added logical operators that were missing. --- r.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/r.html.markdown b/r.html.markdown index c555d748..13fa2654 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -229,6 +229,13 @@ FALSE != FALSE # FALSE FALSE != TRUE # TRUE # Missing data (NA) is logical, too class(NA) # "logical" +# Use for | and & for logic operations. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# You can test if x is TRUE +isTRUE(TRUE) # TRUE # Here we get a logical vector with many elements: c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE -- cgit v1.2.3 From 7a55b4a9b1badebd4b9342304c902fde049dd172 Mon Sep 17 00:00:00 2001 From: Keito Uchiyama Date: Tue, 20 Jan 2015 14:52:31 -0800 Subject: Explain Optional Chaining Without going into too much detail, mention optional chaining so it's not confusing that there is a question mark suffix (it's not currently mentioned anywhere on the page). --- swift.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 2fbbe544..c6d2a8af 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -445,7 +445,10 @@ class MyShape: Rect { func grow() { sideLength += 2 - + + // Place a question mark after an optional property, method, or + // subscript to gracefully ignore a nil value and return nil + // instead of throwing a runtime error ("optional chaining"). if let allow = self.delegate?.canReshape?() { // test for delegate then for method self.delegate?.reshaped?() -- cgit v1.2.3 From 0d01004725423b29e196acf74a626bd3585934cc Mon Sep 17 00:00:00 2001 From: hirohope Date: Tue, 20 Jan 2015 23:16:35 -0300 Subject: haml-es --- es-es/haml-es.html.markdown | 159 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 es-es/haml-es.html.markdown diff --git a/es-es/haml-es.html.markdown b/es-es/haml-es.html.markdown new file mode 100644 index 00000000..be90b8f3 --- /dev/null +++ b/es-es/haml-es.html.markdown @@ -0,0 +1,159 @@ +--- +language: haml +filename: learnhaml-es.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] +lang: es-es +--- + +Haml es un lenguage de marcas principalmente usado con Ruby, que de forma simple y limpia describe el HTML de cualquier documento web sin el uso de código en linea. Es una alternativa popular respecto a usar el lenguage de plantilla de Rails (.erb) y te permite embeber código Ruby en tus anotaciones. + +Apunta a reducir la repetición en tus anotaciones cerrando los tags por ti, basándose en la estructura de identación de tu código. El resultado es una anotación bien estructurada, que no se repite, lógica y fácil de leer. + +También puedes usar Haml en un proyecto independiente de Ruby, instalando la gema Haml en tu máquina y usando la línea de comandos para convertirlo en html. + +$ haml archivo_entrada.haml archivo_salida.html + + +```haml +/ ------------------------------------------- +/ Identación +/ ------------------------------------------- + +/ + Por la importancia que la identación tiene en cómo tu código es traducido, + la identación debe ser consistente a través de todo el documento. Cualquier + diferencia en la identación lanzará un error. Es una práctica común usar dos + espacios, pero realmente depende de tí, mientras sea consistente. + + +/ ------------------------------------------- +/ Comentarios +/ ------------------------------------------- + +/ Así es como un comentario se ve en Haml. + +/ + Para escribir un comentario multilínea, identa tu código a comentar de tal forma + que sea envuelto por por una barra. + + +-# Este es un comentario silencioso, significa que no será traducido al código en absoluto + + +/ ------------------------------------------- +/ Elementos Html +/ ------------------------------------------- + +/ Para escribir tus tags, usa el signo de porcentaje seguido por el nombre del tag +%body + %header + %nav + +/ Nota que no hay tags de cierre. El código anterior se traduciría como + +
+ +
+ + +/ El tag div es un elemento por defecto, por lo que pueden ser escritos simplemente así +.foo + +/ Para añadir contenido a un tag, añade el texto directamente después de la declaración +%h1 Headline copy + +/ Para escribir contenido multilínea, anídalo. +%p + Esto es mucho contenido que podríamos dividirlo en dos + líneas separadas. + +/ + Puedes escapar html usando el signo ampersand y el signo igual ( &= ). + Esto convierte carácteres sensibles en html a su equivalente codificado en html. + Por ejemplo + +%p + &= "Sí & si" + +/ se traduciría en 'Sí & si' + +/ Puedes desescapar html usando un signo de exclamación e igual ( != ) +%p + != "Así es como se escribe un tag párrafo

" + +/ se traduciría como 'Así es como se escribe un tag párrafo

' + +/ Clases CSS puedes ser añadidas a tus tags, ya sea encadenando .nombres-de-clases al tag +%div.foo.bar + +/ o como parte de un hash Ruby +%div{:class => 'foo bar'} + +/ Atributos para cualquier tag pueden ser añadidos en el hash +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ Para atributos booleanos asigna el valor verdadero 'true' +%input{:selected => true} + +/ Para escribir atributos de datos, usa la llave :dato con su valor como otro hash +%div{:data => {:attribute => 'foo'}} + + +/ ------------------------------------------- +/ Insertando Ruby +/ ------------------------------------------- + +/ + Para producir un valor Ruby como contenido de un tag, usa un signo igual + seguido por código Ruby + +%h1= libro.nombre + +%p + = libro.autor + = libro.editor + + +/ Para correr un poco de código Ruby sin traducirlo en html, usa un guión +- libros = ['libro 1', 'libro 2', 'libro 3'] + +/ Esto te permite hacer todo tipo de cosas asombrosas, como bloques de Ruby +- libros.shuffle.each_with_index do |libro, indice| + %h1= libro + + if libro do + %p Esto es un libro + +/ + Nuevamente, no hay necesidad de añadir los tags de cerrado en el código, ni siquiera para Ruby + La identación se encargará de ello por tí. + + +/ ------------------------------------------- +/ Ruby en linea / Interpolación de Ruby +/ ------------------------------------------- + +/ Incluye una variable Ruby en una línea de texto plano usando #{} +%p Tu juego con puntaje más alto es #{mejor_juego} + + +/ ------------------------------------------- +/ Filtros +/ ------------------------------------------- + +/ + Usa un signo dos puntos para definir filtros Haml, un ejemplo de filtro que + puedes usar es :javascript, el cual puede ser usado para escribir javascript en línea. + +:javascript + console.log('Este es un + + + + + +``` + + + +### Optimizar todo un proyecto usando r.js + + + +Muchas personas prefiere usar AMD para la sana organización del código durante el desarrollo, pero todavía prefiere enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. + + + +`require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. + + + +Instálalo usando `npm`: + +```shell + +$ npm install requirejs -g + +``` + + + +Ahora puedes alimentarlo con un fichero de configuración: + +```shell + +$ r.js -o app.build.js + +``` + + + +Para nuestro ejemplo anterior el archivo de configuración luciría así: + +```javascript + +/* file : app.build.js */ + +({ + + name : 'main', // name of the entry point + + out : 'main-built.js', // name of the file to write the output to + + baseUrl : 'app', + + paths : { + + // `empty:` tells r.js that this should still be loaded from the CDN, using + + // the location specified in `main.js` + + jquery : 'empty:', + + coolLibFromBower : '../bower_components/cool-lib/coollib' + + } + +}) + +``` + + + +Para usar el fichero creado en producción, simplemente intercambia `data-main`: + +```html + + + +``` + + + +Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. + + + +### Tópicos no cubiertos en este tutorial + +* [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) + +* [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) + +* [Configuración avanzada](http://requirejs.org/docs/api.html#config) + +* [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim) + +* [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss) + +* [Usando almond.js para construcciones](https://github.com/jrburke/almond) + + + +### Otras lecturas: + + + +* [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD) + +* [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html) + +* [Definición Universal de Módulos](https://github.com/umdjs/umd) + + + +### Implementaciones: + + + +* [require.js](http://requirejs.org) + +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) + +* [cujo.js](http://cujojs.com/) + +* [curl.js](https://github.com/cujojs/curl) + +* [lsjs](https://github.com/zazl/lsjs) + +* [mmd](https://github.com/alexlawrence/mmd) -- cgit v1.2.3 From 8dd11eee84a36ac2d81f266574b07bf603327e0e Mon Sep 17 00:00:00 2001 From: Moritz Kammerer Date: Sat, 17 Oct 2015 15:56:00 +0200 Subject: Adds german translation for LateX --- de-de/latex-de.html.markdown | 235 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 de-de/latex-de.html.markdown diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown new file mode 100644 index 00000000..2c18b8fd --- /dev/null +++ b/de-de/latex-de.html.markdown @@ -0,0 +1,235 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Moritz Kammerer", "https://github.com/phxql"] +lang: de-de +filename: latex-de.tex +--- +``` +% Alle Kommentare starten fangen mit % an +% Es gibt keine Kommentare über mehrere Zeilen + +% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% MS Word oder OpenOffice Writer + +% Jedes LateX-Kommando startet mit einem Backslash (\) + +% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% Weitere Dokumententypen sind z.B. book, report, presentations, etc. +% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall +% wollen wir einen 12 Punkte-Font verwenden. +\documentclass[12pt]{article} + +% Als nächstes definieren wir die Pakete, die wir verwenden wollen. +% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, +% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% Wir verwenden die Pakete float und caption für Bilder. +\usepackage{caption} +\usepackage{float} + +% Mit diesem Paket können leichter Umlaute getippt werden +\usepackage[utf8]{inputenc} + +% Es können durchaus noch weitere Optione für das Dokument gesetzt werden! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Nun kann's losgehen mit unserem Dokument. +% Alles vor dieser Zeile wird die Preamble genannt. +\begin{document} +% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann +% LateX für uns eine Titelseite generieren +\maketitle + +% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem +% Inhalt erscheinen. +% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. +\begin{abstract} + LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! +\end{abstract} + +% Section Befehle sind intuitiv. +% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. +\section{Einleitung} +Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! + +\section{Noch eine section} +Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. + +\subsection{Das ist eine subsection} % Subsections sind auch ziemlich intuitiv. +Ich glaube, wir brauchen noch eine. + +\subsubsection{Pythagoras} +So ist's schon viel besser. +\label{subsec:pythagoras} + +% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. +% Das funktioniert auch bei anderen Befehlen. +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle sections nummeriert sein! + +\section{Ein paar Notizen} +LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge +\textbackslash\textbackslash in den Code ein.\\ + +\section{Listen} +Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +also lass uns eine Einkaufsliste schreiben: +\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. + % \item bringt enumerate dazu, eins weiterzuzählen. + \item Salat. + \item 27 Wassermelonen. + \item einen Hasen. + % Wir können die Nummer des Eintrags durch [] überschreiben + \item[Wie viele?] Mittelgroße Wasserpistolen. + + Kein Listeneintrag, aber immer noch Teil von enumerate. + +\end{enumerate} % Alle Umgebungen müssen ein end haben. + +\section{Mathe} + +Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder +anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle +Symbole zu unserem Paper hinzuzufügen! \\ + +Mathe kennt sehr viele Symbole, viel mehr als auf einer Tastatur zu finden sind; +Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstaben, +um nur ein paar zu nennen.\\ + +Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen +Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ + +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings +% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und +% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. + +Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! + +Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Logarithmus und Exponenten ($\log$, $\exp$), +Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. +Lass uns eine Gleichung schreiben: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ + +Brüche (Zähler / Nenner) können so geschrieben werden: + +% 10 / 7 +$^{10}/_{7}$ + +% Komplexere Brüche können so geschrieben werden: +% \frac{Zähler}{Nenner} +$\frac{n!}{k!(n - k)!}$ \\ + +Wir können Gleichungen auch in einer equation Umgebung verwenden. + +% Dies zeigt Mathe in einer equation Umgebung an +\begin{equation} % Aktiviert automatisch den Mathe-Modus. + c^2 = a^2 + b^2. + \label{eq:pythagoras} % Pythagoras referenzieren +\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen + +Wir können nun unsere Gleichung referenzieren! +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: +Grafiken, Gleichungen, Sections, etc. + +Summen und Integrale können mit den sum und int Befehlen dargestellt werden: + +% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Grafiken} + +Lass uns eine Grafik einfügen. Das Platzieren von Grafiken kann etwas trickreich sein. +Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. + +\begin{figure}[H] % H ist die Platzierungsoption + \centering % Zentriert die Grafik auf der Seite + % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Auskommentiert, damit es nicht im Dokument auftaucht. + \caption{Dreieck mit den Seiten $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabellen} +Wir können Tabellen genauso wie Grafiken einfügen. + +\begin{table}[H] + \caption{Überschrift der Tabelle.} + % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. + % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. + \begin{tabular}{c|cc} + Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt + \hline % Eine horizontale Linie + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Links} % Kommen bald! + +\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll +in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden +wir eine verbatim Umgebung. + +% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) +% aber verbatim ist das simpelste. +\begin{verbatim} + print("Hello World!") + a%b; % Schau dir das an! Wir können % im verbatim verwenden! + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Kompilieren} + +Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF +verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ + +Dafür musst du folgende Schritte durchführen: + \begin{enumerate} + \item Schreibe das Dokument. (den LateX-Quelltext). + \item Kompiliere den Quelltext in ein PDF. + Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +2 wird unsichtbar im Hintergrund ausgeführt. + +Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet +dann diese Informationen und kümmert sich drum, dass das Dokument korrekt erstellt wird. + +\section{Ende} + +Das war's erst mal! + +% Dokument beenden +\end{document} +``` +## Mehr Informationen über LateX + +* Das tolle LaTeX wikibook: [https://de.wikibooks.org/wiki/LaTeX-Kompendium](https://de.wikibooks.org/wiki/LaTeX-Kompendium) +* Ein Tutorial (englisch): [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) -- cgit v1.2.3 From 0768364a4d69e8b3a81fa0dcfea9d996ad2fea7f Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sat, 17 Oct 2015 15:57:07 +0200 Subject: Add myself as a translator --- it-it/java-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 0e782dd1..54602cff 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] translators: - ["Ivan Sala","http://github.com/slavni96"] + - ["Tommaso Pifferi","http://github.com/neslinesli93"] lang: it-it --- -- cgit v1.2.3 From 600483a4582713b515e1e72fd842927bbb30a613 Mon Sep 17 00:00:00 2001 From: Santhosh Kumar Srinivasan Date: Sat, 17 Oct 2015 19:38:39 +0530 Subject: Fix typo on readme Just a typo. Changed `tag your issues pull requests with` to `tag your issues and pull requests with` --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 28fa5093..46408a04 100644 --- a/README.markdown +++ b/README.markdown @@ -18,7 +18,7 @@ All contributions are welcome, from the tiniest typo to a brand new article. Tra in all languages are welcome (or, for that matter, original articles in any language). Send a pull request or open an issue any time of day or night. -**Please tag your issues pull requests with [language/lang-code] at the beginning** +**Please tag your issues and pull requests with [language/lang-code] at the beginning** **(e.g. [python/en] for English Python).** This will help everyone pick out things they care about. -- cgit v1.2.3 From df1f9fdb9ea25953820209d3a4ef547f8afa8dce Mon Sep 17 00:00:00 2001 From: Gloria Dwomoh Date: Sat, 17 Oct 2015 18:22:55 +0300 Subject: Update racket-gr.html.markdown --- el-gr/racket-gr.html.markdown | 72 +++++++++++++++++++++---------------------- 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 4c4576bb..589adfeb 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -31,12 +31,12 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την ;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να -;; κάνουμε σχόλια κάποιες εκφράσεις κατα τη διάρκεια του debugging +;; κάνουμε σχόλια κάποιες εκφράσεις κατά τη διάρκεια του debugging #; (αυτή η έκφραση δεν θα εκτελεστεί) ;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε -;; πολύ συντομα!) +;; πολύ σύντομα!) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -57,8 +57,8 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;; όπου το f είναι η συνάρτηση και τα x y z ;; είναι οι όροι που η συνάρτηση δέχεται ;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε -;; μια λίστα στην κυριολεξία απο δίαφορα δεδομένα, -;; χρησιμοποιούμε το ' για να το εμποδίσουμε απο το να +;; μια λίστα στην κυριολεξία από δίαφορα δεδομένα, +;; χρησιμοποιούμε το ' για να το εμποδίσουμε από το να ;; αξιολογηθεί σαν έκφραση. Για παράδειγμα: '(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη ;; Τώρα , ας κάνουμε μερικές πράξεις @@ -88,15 +88,15 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής -"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, +"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήρες διαφυγής της C, ; σε Unicode "λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες -;; Μπορούμε να εννώσουμε αλφαριθμητικά! +;; Μπορούμε να ενώσουμε αλφαριθμητικά! (string-append "Hello " "world!") ; => "Hello world!" -;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοπιησουμε -;; όπως και μια λίστα απο χαρακτήρες +;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοποιήσουμε +;; όπως και μια λίστα από χαρακτήρες (string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο ;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για @@ -117,18 +117,18 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ some-var ; => 5 ;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες. -(define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? +(define ⊆ subset?) ;; Εδώ ουσιαστικά δίνουμε στη ήδη υπάρχουσα συνάρτηση subset? ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. (⊆ (set 3 2) (set 1 2 3)) ; => #t -;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ +;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πριν π.χ. (printf name) ;; θα πάρουμε το παρακάτω μήνυμα ;name: undefined; ; cannot reference undefined identifier ; context...: -;; Η τοπική δέσμευση : `me' δευσμεύεται με το "Bob" μόνο μέσα στο (let ...) +;; Η τοπική δέσμευση : `me' δεσμεύεται με το "Bob" μόνο μέσα στο (let ...) (let ([me "Bob"]) "Alice" me) ; => "Bob" @@ -156,7 +156,7 @@ my-pet ; => # ;;; Λίστες ;; Οι λίστες είναι linked-list δομές δεδομένων, -;; που έχουν δημιουργηθεί απο ζευγάρια 'cons' +;; που έχουν δημιουργηθεί από ζευγάρια 'cons' ;; και τελειώνουν με 'null' (ή αλλιώς '()) για να ;; δηλώσουν ότι αυτό είναι το τέλος της λίστας (cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) @@ -191,12 +191,12 @@ my-pet ; => # ;; Τα διανύσματα είναι πίνακες σταθερού μήκους #(1 2 3) ; => '#(1 2 3) -;; Χρησιμοποιύμε το `vector-append' για να προσθέσουμε διανύσματα +;; Χρησιμοποιούμε το `vector-append' για να προσθέσουμε διανύσματα (vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) ;;; Σύνολα -;; Δημιουργούμε ένα σύνολο απο μία λίστα +;; Δημιουργούμε ένα σύνολο από μία λίστα (list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) ;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add' @@ -214,10 +214,10 @@ my-pet ; => # ;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού (define m (hash 'a 1 'b 2 'c 3)) -;; Παίρνουμε μια τιμή απο τον πίνακα +;; Παίρνουμε μια τιμή από τον πίνακα (hash-ref m 'a) ; => 1 -;; Άν ζητήσουμε μια τιμή που δέν υπάρχει παίρνουμε μία εξαίρεση +;; Αν ζητήσουμε μια τιμή που δεν υπάρχει παίρνουμε μία εξαίρεση ; (hash-ref m 'd) => no value found for key ;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν @@ -234,7 +234,7 @@ m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε -;; κλειδία +;; κλειδιά (hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -247,12 +247,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ' (λ () "Hello World") ; => Ίδια συνάρτηση -;; Χρησιμοποιύμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις +;; Χρησιμοποιούμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις ;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα' ((lambda () "Hello World")) ; => "Hello World" ((λ () "Hello World")) ; => "Hello World" -;; Εκχωρούμε σε μια μετάβλητη την συνάρτηση +;; Εκχωρούμε σε μια μεταβλητή την συνάρτηση (define hello-world (lambda () "Hello World")) (hello-world) ; => "Hello World" @@ -302,7 +302,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (lambda (name . args) (format "Hello ~a, you passed ~a extra args" name (length args)))) -;; Και με λέξεις κλειδία +;; Και με λέξεις κλειδιά (define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) (format "~a ~a, ~a extra args" g name (length args))) (hello-k) ; => "Hello World, 0 extra args" @@ -347,7 +347,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f -;; Το `eqv?' υποστηρίζει την σύκριση αριθμών αλλα και χαρακτήρων +;; Το `eqv?' υποστηρίζει την σύγκριση αριθμών αλλά και χαρακτήρων ;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο. (eqv? 3 3.0) ; => #f (eqv? (expt 2 100) (expt 2 100)) ; => #t @@ -365,12 +365,12 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (equal? (list 3) (list 3)) ; => #t ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 5. Έλεχγος Ροής +;; 5. Έλεγχος Ροής ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Συνθήκες (conditionals) -(if #t ; έκφραση ελέχγου +(if #t ; έκφραση ελέγχου "this is true" ; έκφραση then "this is false") ; έκφραση else ; => "this is true" @@ -483,7 +483,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (values i (number->string i))) ; => '#hash((1 . "1") (2 . "2") (3 . "3")) -;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε +;; Υπάρχουν πολλά είδη από προϋπάρχοντες τρόπους για να συλλέγουμε ;; τιμές από τους βρόχους (for/sum ([i 10]) (* i i)) ; => 285 @@ -491,7 +491,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t (for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t -;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιούμε +;; Και για να χρησιμοποιήσουμε ένα αυθαίρετο συνδυασμό χρησιμοποιούμε ;; το 'for/fold' (for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 @@ -524,17 +524,17 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (set! n (add1 n)) n ; => 6 -;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβητή -;; θα είναι mutable (θα μπορεί να αλλάξη η τιμή της) +;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβλητή +;; θα είναι mutable (θα μπορεί να αλλάξει η τιμή της) ;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες (define n* (box 5)) (set-box! n* (add1 (unbox n*))) (unbox n*) ; => 6 -;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι πχ τα ζεύγη, οι +;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι π.χ. τα ζεύγη, οι ;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή -;; πχ αλφαριθμητικά, διανύσματα κτλ +;; π.χ. αλφαριθμητικά, διανύσματα κτλ. (define vec (vector 2 2 3 4)) (define wall (make-vector 100 'bottle-of-beer)) ;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια @@ -579,7 +579,7 @@ vec ; => #(1 2 3 4) (printf fmt (make-string n ch)) (newline))) -;; Χρησιμοποιομε το 'require' για να πάρουμε όλα τα +;; Χρησιμοποιουμε το 'require' για να πάρουμε όλα τα ;; παρεχόμενα ονόματα από μία ενότητα (require 'cake) ; το ' είναι για τοπική υποενότητα (print-cake 3) @@ -634,7 +634,7 @@ vec ; => #(1 2 3 4) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε -;; το συντακτικό μιάς γλώσσας. +;; το συντακτικό μιας γλώσσας. ;; Ας προσθέσουμε έναν βρόχο while (define-syntax-rule (while condition body ...) @@ -664,20 +664,20 @@ vec ; => #(1 2 3 4) ;; (set! tmp other) ;; (set! other tmp_1)) -;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ: +;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ.: (define-syntax-rule (bad-while condition body ...) (when condition body ... (bad-while condition body ...))) -;; αυτή η μακροεντολή είναι χαλασμένη: δημιουγεί ατέρμονα βρόχο +;; αυτή η μακροεντολή είναι χαλασμένη: δημιουργεί ατέρμονα βρόχο ;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής -;; θα μπεί στον ατέρμονα βρόχο. +;; θα μπει στον ατέρμονα βρόχο. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 10. Συμβόλαια (Contracts) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται +;; Τα συμβόλαια βάζουν περιορισμούς σε τιμές που προέρχονται ;; από ενότητες (modules) (module bank-account racket (provide (contract-out @@ -719,7 +719,7 @@ vec ; => #(1 2 3 4) (displayln "Hola mundo" out-port) (close-output-port out-port) -;; Διαβάζουμε απο αρχείο ξανά +;; Διαβάζουμε από αρχείο ξανά (define in-port (open-input-file "/tmp/tmp.txt")) (displayln (read-line in-port)) ; => "Hello World" -- cgit v1.2.3 From 1ae02fc6cf7642911125e088ec5e7ce15552b95d Mon Sep 17 00:00:00 2001 From: Persa Zula Date: Sat, 17 Oct 2015 11:25:05 -0400 Subject: Adds more string operations to ruby doc --- ruby.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 0e798706..f4de8038 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -12,7 +12,8 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - - ["Gabriel Halley", https://github.com/ghalley"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] --- ```ruby @@ -107,6 +108,12 @@ placeholder = 'use string interpolation' 'hello ' + 3 #=> TypeError: can't convert Fixnum into String 'hello ' + 3.to_s #=> "hello 3" +# Combine strings and operators +'hello ' * 3 #=> "hello hello hello" + +# Append to string +'hello' << ' world' #=> "hello world" + # print to the output with a newline at the end puts "I'm printing!" #=> I'm printing! @@ -284,7 +291,7 @@ end #=> iteration 4 #=> iteration 5 -# There are a bunch of other helpful looping functions in Ruby, +# There are a bunch of other helpful looping functions in Ruby, # for example "map", "reduce", "inject", the list goes on. Map, # for instance, takes the array it's looping over, does something # to it as defined in your block, and returns an entirely new array. -- cgit v1.2.3 From 547bc1df42ff8dfb463e2d64d1ca1f6887a91300 Mon Sep 17 00:00:00 2001 From: "G. Reiter" Date: Sat, 10 Oct 2015 19:03:49 +0200 Subject: Improve the translation several characters were wrong, additionally German spelling/grammar is now correct (German is my primary language). --- de-de/bash-de.html.markdown | 223 ++++++++++++++++++++++++++++++++++++++++---- de-de/git-de.html.markdown | 30 +++--- 2 files changed, 223 insertions(+), 30 deletions(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index fb9cd9d4..541d28bb 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -28,18 +28,50 @@ echo Hello, world! echo 'Dies ist die erste Zeile'; echo 'Dies die zweite Zeile' # Variablen deklariert man so: -VARIABLE="irgendein String" +Variable="irgendein String" # Aber nicht so: -VARIABLE = "irgendein String" -# Bash wird VARIABLE für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, +Variable = "irgendein String" +# Bash wird 'Variable' für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, # weil es den Befehl nicht findet. +# Und so auch nicht: +Variable= 'Some string' +# Bash wird 'Variable' wieder für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, +# Hier wird der Teil 'Variable=' als nur für diesen einen Befehl gültige Zuweisung an die Variable gesehen. + # Eine Variable wird so benutzt: -echo $VARIABLE -echo "$VARIABLE" -# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anders –, +echo $Variable +echo "$Variable" +echo ${Variable} +# aber +echo '$Variable' +# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anderes –, # dann über ihren Namen ohne $. Aber wenn du ihren zugewiesenen Wert willst, dann musst du $ voranstellen. +# Beachte: ' (Hochkomma) verhindert das Interpretieren der Variablen + +# Ersetzen von Zeichenketten in Variablen +echo ${Variable/irgendein/neuer} +# Ersetzt das erste Vorkommen von "irgendein" durch "neuer" + +# Teil einer Zeichenkette +Laenge=7 +echo ${Variable:0:Laenge} +# Gibt nur die ersten 7 Zeichen zurück + +# Standardwert verwenden +echo ${Foo:-"ErsatzWennLeerOderUngesetzt"} +# Das funktioniert mit nicht gesetzten Variablen (Foo=) und leeren Zeichenketten (Foo="") +# Die Zahl 0 (Foo=0) liefert 0. +# Beachte: der wert der Variablen wird nicht geändert + +# Eingebaute Variable (BUILTINS): +# Einige nützliche Beispiele +echo "Rückgabewert des letzten Befehls: $?" +echo "Die PID des skripts: $$" +echo "Anzahl der Argumente beim Aufruf: $#" +echo "Alle Argumente beim Aufruf: $@" +echo "Die Argumente in einzelnen Variablen: $1 $2..." # Einen Wert aus der Eingabe lesen: echo "Wie heisst du?" @@ -47,14 +79,30 @@ read NAME # Wir mussten nicht mal eine neue Variable deklarieren echo Hello, $NAME! # Wir haben die übliche if-Struktur: -if true +# 'man test' liefert weitere Informationen zu Bedingungen +if [ "$NAME" -ne $USER ] then - echo "Wie erwartet" + echo "Dein Name ist nicht dein Login-Name" else - echo "Und dies nicht" + echo "Dein Name ist dein Login-Name" +fi + +# Es gibt auch bedingte Ausführung +echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschlägt" +echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat" + +# Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern: +if [ $NAME == "Steve" ] && [ $Alter -eq 15 ] +then + echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'." fi -# Ausdrücke werden im folgenden Format festgehalten: +# Ausdrücke haben folgendes Format: echo $(( 10 + 5 )) # Anders als andere Programmiersprachen ist Bash eine Shell – es arbeitet also im Kontext von Verzeichnissen. @@ -69,13 +117,60 @@ ls -l # Liste alle Dateien und Unterverzeichnisse auf einer eigenen Zeile auf # txt-Dateien im aktuellen Verzeichnis auflisten: ls -l | grep "\.txt" -# Befehle können innerhalb anderer Befehle mit $( ) erstetzt werden: +# Ein- und Ausgabe können umgeleitet werden (stdin, stdout, and stderr). +# Von stdin lesen bis "EOF" allein in einer Zeile auftaucht +# und die Datei hello.py mit den Zeilen zwischen den beiden "EOF" +# überschreiben: +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 + +# Führe hello.py mit verschiedenen Umleitungen von +# stdin, stdout und stderr aus: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Die Fehlerausgabe würde die Datei "error.err" überschreiben (falls sie existiert) +# verwende ">>" um stattdessen anzuhängen: +python hello.py >> "output.out" 2>> "error.err" + +# Überschreibe output.out, hänge an error.err an und zähle die Zeilen beider Dateien: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Führe einen Befehl aus und gib dessen "file descriptor" (zB /dev/fd/123) aus +# siehe: man fd +echo <(echo "#helloworld") + +# Mehrere Arten, um output.out mit "#helloworld" zu überschreiben: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Löschen der Hilfsdateien von oberhalb, mit Anzeige der Dateinamen +# (mit '-i' für "interactive" erfolgt für jede Date eine Rückfrage) +rm -v output.out error.err output-and-error.log + +# Die Ausgabe von Befehlen kann mit Hilfe von $( ) in anderen Befehlen verwendet weden: # Der folgende Befehl zeigt die Anzahl aller Dateien und Unterverzeichnisse # im aktuellen Verzeichnis an. echo "Dieser Ordner beinhaltet $(ls | wc -l) Dateien und Verzeichnisse." +# Dasselbe kann man mit "backticks" `` erreichen, aber diese können +# nicht verschachtelt werden. $() ist die empfohlene Methode. +echo "Dieser Ordner beinhaltet `ls | wc -l` Dateien und Verzeichnisse." + # Bash nutzt einen case-Ausdruck, der sich ähnlich wie switch in Java oder C++ verhält. -case "$VARIABLE" +case "$Variable" in # Liste der Fälle, die unterschieden werden sollen 0) echo "Hier ist eine Null." @@ -83,10 +178,106 @@ in *) echo "Das ist nicht Null." esac -# loops iterieren über die angegebene Zahl von Argumenten: -# Der Inhalt von $VARIABLE wird dreimal ausgedruckt. -for $VARIABLE in x y z +# 'for' Schleifen iterieren über die angegebene Zahl von Argumenten: +# Der Inhalt von $Variable wird dreimal ausgedruckt. +for $Variable in {1..3} do - echo "$VARIABLE" + echo "$Variable" done + +# Oder verwende die "traditionelle 'for'-Schleife": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Schleifen können auch mit Dateien arbeiten: +# 'cat' zeigt zuerst file1 an und dann file2 +for Variable in file1 file2 +do + cat "$Variable" +done + +# .. oder mit der Ausgabe eines Befehls: +# Ausgabe des Inhalts jeder Datei, die von 'ls' aufgezählt wird +for Output in $(ls) +do + cat "$Output" +done + +# while Schleife: +while [ true ] +do + echo "Schleifenkörper..." + break +done + +# Funktionen definieren +# Definition: +function foo () +{ + echo "Argumente funktionieren wie bei skripts: $@" + echo Und: $1 $2..." + echo "Dies ist eine Funktion" + return 0 +} + +# oder einfacher +bar () +{ + echo "Auch so kann man Funktionen deklarieren!" + return 0 +} + +# Aufruf der Funktion: +foo "My name is" $Name + +# Was du noch lernen könntest: +# Ausgabe der letzten 10 Zeilen von file.txt +tail -n 10 file.txt +# Ausgabe der ersten 10 Zeilen von file.txt +head -n 10 file.txt +# sortierte Ausgabe von file.txt +sort file.txt +# Mehrfachzeilen in sortierten Dateien unterdrücken +# oder (mit -d) nur diese ausgeben +uniq -d file.txt +# Ausgabe nur der ersten Spalte (vor dem ersten ',') +cut -d ',' -f 1 file.txt +# ersetze in file.txt jedes vorkommende 'gut' durch 'super' (versteht regex) +sed -i 's/gut/super/g' file.txt +# Ausgabe nach stdout aller Zeilen von file.txt, die auf eine regex passen +# Im Beispiel: Zeilen, die mit "foo" beginnen und mit "bar" enden +grep "^foo.*bar$" file.txt +# Mit der Option "-c" wird stattdessen die Anzahl der gefundenen Zeilen ausgegeben +grep -c "^foo.*bar$" file.txt +# verwende 'fgrep' oder 'grep -F' wenn du buchstäblich nach den Zeichen +# suchen willst, ohne sie als regex zu interpretieren +fgrep "^foo.*bar$" file.txt + +# Dokumentation über die in bash eingebauten Befehle +# bekommst du mit dem eingebauten Befehl 'help' +help +help help +help for +help return +help source +help . + +# Das bash-Handbuch liest du mit 'man' +apropos bash +man 1 bash +man bash + +# Dann gibt es noch das 'info' System (drücke ? um Hilfe angezeigt zu bekommen) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# info Dokumentation über bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash ``` diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index 43939129..dea329d5 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -18,12 +18,12 @@ Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* ### Was ist Versionsverwaltung? -Eine Versionskontrolle erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. +Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. ### Zentrale im Vergleich mit verteilter Versionverwaltung -* Zentrale Versionskontrolle konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. -* Verteilte Versionskontrolle konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. +* Zentrale Versionsverwaltung konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. +* Verteilte Versionsverwaltung konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. * Verteilte Systeme haben keine vorbestimmte Struktur. Ein SVN-ähnliches, zentrales System wäre mit Git ebenso umsetzbar. [Weiterführende Informationen](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -61,7 +61,7 @@ Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arb ### Commit -Ein Commit ist ein Schnappschuss von Uderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositorys gepusht werden. Oder nicht! +Ein Commit ist ein Schnappschuss von Änderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositories gepusht werden. Oder nicht! ### Branch @@ -69,7 +69,9 @@ Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, ### HEAD und head (Teil des .git-Verzeichnisses) -HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. Ein head ist ein Pointer, der auf ein beliebige Zahl von heads zeigt. +HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. + +Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Repository kann eine beliebige Zahl von *heads* enthalten. ### Konzeptionelle Hintergründe @@ -127,7 +129,7 @@ Zeigt die Unterschiede zwischen Index (im Grunde dein Arbeitsverzeichnis/-reposi ```bash -# Zeigt den Branch, nicht-verfolgte Dateien, Uderungen und andere Unterschiede an +# Zeigt den Branch, nicht-verfolgte Dateien, Änderungen und andere Unterschiede an $ git status # Anderes Wissenswertes über git status anzeigen @@ -151,7 +153,7 @@ $ git add ./*.java ### branch -Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erschaffen oder löschen. +Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erzeugen oder löschen. ```bash # Liste alle bestehenden Branches und Remotes auf @@ -186,7 +188,7 @@ $ git checkout -b newBranch ### clone -Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für hedes geklonte Repo remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen. +Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für jedes geklonte Repository remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen. ```bash # Klone learnxinyminutes-docs @@ -288,16 +290,16 @@ $ git mv -f myFile existingFile ### pull -Führe einen Pull, zieht alle Daten, eines Repositorys und f?? einen Merge mit einem anderen Branch durch. +Führe einen Pull (zieht alle Daten eines Repositories) aus und führt einen Merge mit einem anderen Branch durch. ```bash -# Update deines lokalen Repos, indem ein Merge der neuen Uderungen -# von den remote-liegenden "origin"- und "master"-Branches durchgef?? wird. +# Update deines lokalen Repos, indem ein Merge der neuen Änderungen +# von den remote-liegenden "origin"- und "master"-Branches durchgeführt wird. # git pull # git pull => impliziter Verweis auf origin und master $ git pull origin master -# F?? einen Merge von Uderungen eines remote-Branch und ein Rebase +# Führt einen Merge von Änderungen eines remote-Branch und ein Rebase # des Branch-Commits im lokalen Repo durch. Wie: pull , git rebase " $ git pull origin master --rebase ``` @@ -337,8 +339,8 @@ $ git reset # Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen und überschreibe das Arbeitsverzeichnis $ git reset --hard -# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unber??) -# Alle Uderungen bleiben im Verzeichnis erhalten +# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unberührt) +# Alle Änderungen bleiben im Verzeichnis erhalten $ git reset 31f2bb1 # Bewegt die Spitze des Branches zurück zu dem angegebenen Commit -- cgit v1.2.3 From c030e8aab18e2d63a40eb1321b21a62471094bc0 Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 21:17:09 +0530 Subject: CSS Translation En to Tamil --- ta_in/css.html.markdown | 261 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 ta_in/css.html.markdown diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown new file mode 100644 index 00000000..b55ab363 --- /dev/null +++ b/ta_in/css.html.markdown @@ -0,0 +1,261 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: learncss.css +lang:in-ta +--- + + +இணையத்தின் ஆரம்ப காலத்தில் முழுமையாக உரைகளை மட்டுமே கொண்டிருந்தன. +ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன் +கூடிய இணையதளங்கள் உருவாகின. + +CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page. +CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது. + +ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது. + + +This guide has been written for CSS 2, though CSS 3 is fast becoming popular. +இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது. + +**குறிப்பு:** +CSS ஆனது முற்று முழுதாக visual(காட்சி) மாற்றங்களை தருவதால் அதை நீங்கள் முயற்சிக்க +இதை உபயோகபடுத்தலாம் [dabblet](http://dabblet.com/). +இந்த வழிகாட்டியின் பிரதான நோக்கம் CSS இன் syntax மற்றும் மேலும் சில வழிமுறைகளை +உங்களுக்கு கற்று தருவதாகும் + +```css +/* css இல் குறிப்புகளை இப்படி இடலாம் */ + +/* #################### + ## SELECTORS + #################### */ + +/* ஒரு HTML பக்கத்தில் இருக்கும் உறுப்பை நாம் selector மூலம் தெரிவு செய்யலாம் +selector { property: value; /* more properties...*/ } + +/* +கிழே ஒரு உதாரணம் காட்டப்பட்டுள்ளது: + +
+*/ + +/* நீங்கள் அந்த உறுப்பை அதன் CSS class மூலம் தெரியலாம் */ +.class1 { } + +/* அல்லது இவ்வாறு இரண்டு class மூலம் தெரியலாம்! */ +.class1.class2 { } + +/* அல்லது அதன் பெயரை பாவித்து தெரியலாம் */ +div { } + +/* அல்லது அதன் id ஐ பயன்படுத்தி தெரியலாம்*/ +#anID { } + +/* அல்லது ஒரு உறுப்பின் பண்பு ஒன்றின் மூலம்! */ +[attr] { font-size:smaller; } + +/* அல்லது அந்த பண்பு ஒரு குறிப்பிட்ட பெறுமானத்தை கொண்டு இருப்பின் */ +[attr='value'] { font-size:smaller; } + +/* ஒரு பெறுமதியுடன் ஆரம்பமாகும் போது (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* அல்லது ஒரு பெறுமதியுடன் முடிவடையும் போது (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* அல்லது காற்புள்ளியால் பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின் */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* அல்லது `-` பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின், உ.ம்:-, "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* நாம் இரண்டு selectors ஐ ஒன்றாக உபயோகித்தும் ஒரு உறுப்பை அணுக முடியும் , +அவற்றுக்கு இடயே இடைவெளி காணப்படகூடாது + */ +div.some-class[attr$='ue'] { } + +/*அல்லது ஒரு உறுப்பினுள் இருக்கும் இன்னொரு உறுப்பை (child element) அணுக */ +div.some-parent > .class-name { } + +/* ஒரு ஒரு பிரதான உறுப்பில் உள்ள உப உறுப்புகளை அணுக*/ +div.some-parent .class-name { } + +/* மேலே குறிபிட்ட அணுகுமுறையில் இடைவெளி காணப்படாது விடின் + அந்த selector வேலை செய்யாது + */ +div.some-parent.class-name { } + +/* அல்லது ஒரு உறுப்புக்கு அடுத்துள்ள */ +.i-am-just-before + .this-element { } + +/* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */ +.i-am-any-element-before ~ .this-element { } + +/* There are some selectors called pseudo classes that can be used to select an + element when it is in a particular state + சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை + குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும் + */ + +/* உதாரணமாக நாம் ஒரு உறுப்பின் மீதாக cursor ஐ நகர்த்தும் போது */ +selector:hover { } + +/* அல்லது ஒரு +பார்வையிட்ட இணைப்பு */ +selector:visited { } + +/* அல்லது ஒரு பார்வையிடபடாத இணைப்பு */ +selected:link { } + +/* அல்லது ஒரு element ஐ focus செய்யும் போது */ +selected:focus { } + +/* + எல்லா elementகளையும் ஒரே நேரத்தில் அணுக `*` +*/ +* { } /* all elements */ +.parent * { } /* all descendants */ +.parent > * { } /* all children */ + +/* #################### + ## பண்புகள் + #################### */ + +selector { + + /* நீளத்தின் அலகுகள் absolute அல்லது relative ஆக இருக்கலாம். */ + + /* Relative units */ + width: 50%; /* percentage of parent element width */ + font-size: 2em; /* multiples of element's original font-size */ + font-size: 2rem; /* or the root element's font-size */ + font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */ + font-size: 2vh; /* or its height */ + font-size: 2vmin; /* whichever of a vh or a vw is smaller */ + font-size: 2vmax; /* or greater */ + + /* Absolute units */ + width: 200px; /* pixels */ + font-size: 20pt; /* points */ + width: 5cm; /* centimeters */ + min-width: 50mm; /* millimeters */ + 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: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */ + + /* Images as backgrounds of elements */ + background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ + + /* Fonts */ + font-family: Arial; + /* if the font family name has a space, it must be quoted */ + font-family: "Courier New"; + /* if the first one is not found, the browser uses the next, and so on */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Usage + +ஒரு css file ஐ save செய்ய `.css`. + +```xml + + + + + + + +
+
+``` + +## Precedence or Cascade + +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. + +This process is called cascading, hence the name Cascading Style Sheets. + +ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் +ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன +இது Cascading Style Sheets என அழைக்கபடுகிறது. + + +கிழே தரப்பட்டுள்ள css இன் படி: + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +அத்துடன் கிழே தரப்பட்டுள்ள கட்டமைப்பின்படியும்: + +```xml +

+``` + +The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. +css முன்னுரிமை பின்வருமாறு +* `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் +* `F` இது இரண்டாவது காரணம் இது inline style. +* `A` இது மூன்றவதாக வருகிறது, காரணம் இது மூன்று காரணிகளை குறிக்கிறது : element(உறுப்பு) பெயர் `p`, அதன் class `class1`, an அதன் பண்பு(attribute) `attr='value'`. +* `C` இது அடுத்த நிலையில் உள்ளது கடைசி. +* `B` இது அடுத்தது. +* `D` இதுவே கடைசி . + +## css அம்சங்களின் பொருந்தகூடிய தன்மை + +பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது. + +## வளங்கள் + +* To run a quick compatibility check, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) + +## மேலும் வாசிக்க + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) -- cgit v1.2.3 From 19a5714600892bedda76b4b4562d961fc579a890 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sat, 17 Oct 2015 18:02:47 +0200 Subject: Added lang tag --- it-it/json-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/json-it.html.markdown b/it-it/json-it.html.markdown index 51bc9fc8..379bad73 100644 --- a/it-it/json-it.html.markdown +++ b/it-it/json-it.html.markdown @@ -7,6 +7,7 @@ contributors: translators: - ["Robert Margelli", "http://github.com/sinkswim/"] - ["Christian Grasso", "http://chris54721.net"] +lang: it-it --- JSON è un formato per l'interscambio di dati estremamente semplice, per cui questo sarà -- cgit v1.2.3 From 0f003ef3e9fc00c33741303e4979a44f285f5e05 Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Sat, 17 Oct 2015 11:35:56 -0430 Subject: Spanish translation version 1 --- es-es/amd-es.html.markdown | 241 +++------------------------------------------ 1 file changed, 16 insertions(+), 225 deletions(-) diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown index 3de23a6c..7a59ddd6 100644 --- a/es-es/amd-es.html.markdown +++ b/es-es/amd-es.html.markdown @@ -1,423 +1,214 @@ --- category: tool - tool: amd - contributors: - - ["Frederik Ring", "https://github.com/m90"] translators: - - ["Damaso Sanoja", "https://github.com/damasosanoja"] - filename: learnamd-es.js - lang: es-es - --- - - ## Iniciando con AMD - - -El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos - -JavaScript de manera que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso cruzado de dominios. - - +El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios. ### Conceptos básicos - ```javascript - -// El API básico de AMD consiste en nada más que dos métodos: `define` y `require` - +// El API básico de AMD consiste en tan solo dos métodos: `define` y `require` // y se basa en la definición y consumo de los módulos: - -// `define(id?, dependencies?, factory)` define un módulo - -// `require(dependencies, callback)` importa un conjunto de dependencias y - -// las consume en el callback invocado - - +// `define(id?, dependencias?, fábrica)` define un módulo +// `require(dependencias, callback)` importa un conjunto de dependencias y +// las consume al invocar el callback // Comencemos usando define para definir un nuevo módulo - // que no posee dependencias. Lo haremos enviando un nombre - -// y una función factoría para definirla: - +// y una función fábrica para definirla: define('awesomeAMD', function(){ - var isAMDAwesome = function(){ - return true; - }; - - // El valor que regresa de la función factoría del módulo es - - // aquello que los otros módulos o llamados require reciben cuando - - // solicitan nuestro módulo `awesomeAMD`. - + // El valor que regresa la función fábrica del módulo será + // lo que los otros módulos o llamados require recibirán cuando + // soliciten nuestro módulo `awesomeAMD`. // El valor exportado puede ser cualquier cosa, funciones (constructores), - // objetos, primitivos, incluso indefinidos (aunque eso no ayuda mucho). - return isAMDAwesome; - }); - - // Ahora definamos otro módulo que dependa de nuestro módulo `awesomeAMD`. - // Observe que ahora hay un argumento adicional que define - // las dependencias de nuestro módulo: - define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ - - // las dependencias serán enviadas a los argumentos de la factoría - + // las dependencias serán enviadas a los argumentos de la fábrica // en el orden que sean especificadas - var tellEveryone = function(){ - if (awesomeAMD()){ - alert('This is sOoOo rad!'); - } else { - alert('Pretty dull, isn\'t it?'); - } - }; - return tellEveryone; - }); - - // Como ya sabemos utilizar define usemos ahora `require` para poner en marcha - // nuestro programa. La firma de `require` es `(arrayOfDependencies, callback)`. - require(['loudmouth'], function(loudmouth){ - loudmouth(); - }); - - // Para hacer que este tutorial corra código, vamos a implementar una - // versión muy básica (no-asíncrona) de AMD justo aquí: - function define(name, deps, factory){ - // observa como son manejados los módulos sin dependencias - define[name] = require(factory ? deps : [], factory || deps); - } - - function require(deps, callback){ - var args = []; - // primero recuperemos todas las dependencias que necesita - // el llamado require - for (var i = 0; i < deps.length; i++){ - args[i] = define[deps[i]]; - } - // satisfacer todas las dependencias del callback - return callback.apply(null, args); - } - // puedes ver este código en acción aquí: http://jsfiddle.net/qap949pd/ - ``` - - ### Uso en el mundo real con require.js - - En contraste con el ejemplo introductorio, `require.js` (la librería AMD más popular) implementa la **A** de **AMD**, permitiéndote cargar los módulos y sus dependencias asincrónicamente via XHR: - - ```javascript - /* file: app/main.js */ - require(['modules/someClass'], function(SomeClass){ - // el callback es diferido hasta que la dependencia sea cargada - var thing = new SomeClass(); - }); - console.log('So here we are, waiting!'); // esto correrá primero - ``` - - -Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` es asumido que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada: - - +Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` asumimos que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada: * app/ - * main.js - * modules/ - * someClass.js - * someHelpers.js - * ... - * daos/ - * things.js - * ... - - Esto significa que podemos definir `someClass` sin especificar su id de módulo: - - ```javascript - /* file: app/modules/someClass.js */ - define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ - // definición de módulo, por supuesto, ocurrirá también asincrónicamente - function SomeClass(){ - this.method = function(){/**/}; - // ... - } - return SomeClass; - }); - ``` Para alterar el comportamiento del mapeo de ruta usa `requirejs.config(configObj)` en tu `main.js`: - - ```javascript - /* file: main.js */ - requirejs.config({ - baseUrl : 'app', - paths : { - // también puedes cargar módulos desde otras ubicaciones - jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } - }); - require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ - // un fichero `main` necesita llamar a require al menos una vez, - // de otra forma jamás correrá el código - coolLib.doFancyStuffWith(helpers.transform($('#foo'))); - }); - ``` - Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página: - - ```html - - - - Cien etiquetas de script? Nunca más! - - - - - - ``` - - ### Optimizar todo un proyecto usando r.js - - -Muchas personas prefiere usar AMD para la sana organización del código durante el desarrollo, pero todavía prefiere enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. - - +Muchas personas prefieren usar AMD para la organización del código durante el desarrollo, pero quieren enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. `require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. - - Instálalo usando `npm`: - ```shell - $ npm install requirejs -g - ``` - - Ahora puedes alimentarlo con un fichero de configuración: - ```shell - $ r.js -o app.build.js - ``` - - Para nuestro ejemplo anterior el archivo de configuración luciría así: - ```javascript - /* file : app.build.js */ - ({ - - name : 'main', // name of the entry point - - out : 'main-built.js', // name of the file to write the output to - + name : 'main', // nombre del punto de entrada + out : 'main-built.js', // nombre del fichero donde se escribirá la salida baseUrl : 'app', - paths : { - - // `empty:` tells r.js that this should still be loaded from the CDN, using - - // the location specified in `main.js` - + // `empty:` le dice a r.js que esto aún debe ser cargado desde el CDN, usando + // la ubicación especificada en `main.js` jquery : 'empty:', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } - }) - ``` - - Para usar el fichero creado en producción, simplemente intercambia `data-main`: - ```html - - ``` - - Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. - - ### Tópicos no cubiertos en este tutorial - * [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) - * [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) - * [Configuración avanzada](http://requirejs.org/docs/api.html#config) - * [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim) - * [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss) - * [Usando almond.js para construcciones](https://github.com/jrburke/almond) - - ### Otras lecturas: - - * [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD) - * [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html) - * [Definición Universal de Módulos](https://github.com/umdjs/umd) - - ### Implementaciones: - - * [require.js](http://requirejs.org) - * [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) - * [cujo.js](http://cujojs.com/) - * [curl.js](https://github.com/cujojs/curl) - * [lsjs](https://github.com/zazl/lsjs) - * [mmd](https://github.com/alexlawrence/mmd) -- cgit v1.2.3 From a1939d8e89716378d4dd76c824a6908bf21bfe88 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:13:47 +0800 Subject: Update latex.html.markdown Add opening tex tag --- latex.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/latex.html.markdown b/latex.html.markdown index e180e622..9b7b4feb 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -6,6 +6,8 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] filename: learn-latex.tex --- + +```tex % All comment lines start with % % There are no multi-line comments @@ -225,6 +227,7 @@ That's all for now! % end the document \end{document} ``` + ## More on LaTeX * The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) -- cgit v1.2.3 From a875e6d589b7e6e8a396417adc001bc0f88e82fd Mon Sep 17 00:00:00 2001 From: Persa Date: Sat, 17 Oct 2015 12:16:14 -0400 Subject: Fixes output on combining strings and operators --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index f4de8038..4e9f8aee 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -109,7 +109,7 @@ placeholder = 'use string interpolation' 'hello ' + 3.to_s #=> "hello 3" # Combine strings and operators -'hello ' * 3 #=> "hello hello hello" +'hello ' * 3 #=> "hello hello hello " # Append to string 'hello' << ' world' #=> "hello world" -- cgit v1.2.3 From 85fa357b8a3e441e5c160f18ca6d19cdea7d0160 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:26:19 +0800 Subject: Update clojure-fr.html.markdown --- fr-fr/clojure-fr.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index 25911ea8..1cedda1d 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -276,12 +276,14 @@ ressemblent à toutes les autres formes: (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") -; Utilisez les Threading Macros (-> et ->>) pour exprimer plus clairement vos transformations, en y pensant de manière multi-niveaux: -; La "flèche simple" ou "Thread-first", insère, à chaque niveau de la transformation, la forme courante en la seconde position de la forme suivante, constituant à chaque fois un nouvel étage de transformation.Par exemple: +; Utilisez les Threading Macros (-> et ->>) pour exprimer plus clairement vos transformations, en y pensant de manière multi-niveaux. + +; La "flèche simple" ou "Thread-first", insère, à chaque niveau de la transformation, la forme courante en la seconde position de la forme suivante, constituant à chaque fois un nouvel étage de transformation. Par exemple: (-> {:a 1 :b 2} (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3) (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b) + ; Cette expression est ré-écrite en: (dissoc (assoc {:a 1 :b 2} :c 3) :b) et est évaluée en : {:a 1 :c 3} ; La "flèche double" ou "Thread-last" procède de la même manière que "->", mais insère le résultat de la réécriture de chaque étage en dernière position. Par exemple: (->> -- cgit v1.2.3 From 085bc20c1afc7bb45aae9d269c12df06ba804a1e Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:27:50 +0800 Subject: Fix spacing. --- fr-fr/clojure-fr.html.markdown | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index 1cedda1d..63bc25b5 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -276,16 +276,25 @@ ressemblent à toutes les autres formes: (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") -; Utilisez les Threading Macros (-> et ->>) pour exprimer plus clairement vos transformations, en y pensant de manière multi-niveaux. +; Utilisez les Threading Macros (-> et ->>) pour exprimer plus +; clairement vos transformations, en y pensant de manière multi-niveaux. -; La "flèche simple" ou "Thread-first", insère, à chaque niveau de la transformation, la forme courante en la seconde position de la forme suivante, constituant à chaque fois un nouvel étage de transformation. Par exemple: +; La "flèche simple" ou "Thread-first", insère, à chaque niveau +; de la transformation, la forme courante en la seconde position +; de la forme suivante, constituant à chaque fois un nouvel étage +; de transformation. Par exemple: (-> {:a 1 :b 2} (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3) (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b) -; Cette expression est ré-écrite en: (dissoc (assoc {:a 1 :b 2} :c 3) :b) et est évaluée en : {:a 1 :c 3} -; La "flèche double" ou "Thread-last" procède de la même manière que "->", mais insère le résultat de la réécriture de chaque étage en dernière position. Par exemple: +; Cette expression est ré-écrite en: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; et est évaluée en : {:a 1 :c 3} + +; La "flèche double" ou "Thread-last" procède de la même manière +; que "->", mais insère le résultat de la réécriture de chaque +; étage en dernière position. Par exemple: (->> (range 10) (map inc) ;=> Génère ici (map inc (range 10) -- cgit v1.2.3 From aea4d998b446185ab66a0800e470bc36c132362a Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:31:19 +0800 Subject: Copy arrow docs from french. --- clojure.html.markdown | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/clojure.html.markdown b/clojure.html.markdown index a125d18f..58e835c9 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -264,6 +264,31 @@ keymap ; => {:a 1, :b 2, :c 3} (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Use the threading macros (-> and ->>) to express transformations of +; data more clearly. + +; The "Thread-first" macro (->) inserts into each form the result of +; the previous, as the first argument (second item) +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; This expression could be written as: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; and evaluates to {:a 1 :c 3} + +; The double arrow does the same thing, but inserts the result of +; each line at the *end* of the form. This is useful for collection +; operations in particular: +(->> + (range 10) + (map inc) ;=> (map inc (range 10) + (filter odd?) ;=> (filter odd? (map inc (range 10)) + (into [])) ;=> (into [] (filter odd? (map inc (range 10))) + ; Result: [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; -- cgit v1.2.3 From 30413639edaa382a4667cc0411aca8d2752c508c Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:33:27 +0800 Subject: Update ruby-de.html.markdown --- de-de/ruby-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown index 560d3958..bdeaa30b 100644 --- a/de-de/ruby-de.html.markdown +++ b/de-de/ruby-de.html.markdown @@ -13,7 +13,7 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] -filename: ruby-de.html.markdown +filename: ruby-de.rb lang: de-de --- -- cgit v1.2.3 From 0ddc0b743d5512494df23a27a967c2c27b9873ca Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:33:54 +0800 Subject: Update scala-de.html.markdown --- de-de/scala-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown index 42808580..7fd299b4 100644 --- a/de-de/scala-de.html.markdown +++ b/de-de/scala-de.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Ha-Duong Nguyen", "http://reference-error.org"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] -filename: scala-de.html.markdown +filename: learnscala-de.scala lang: de-de --- @@ -813,4 +813,4 @@ writer.close() * [The scala documentation](http://docs.scala-lang.org/) * [Try Scala in your browser](http://scalatutorials.com/tour/) * [Neophytes Guide to Scala](http://danielwestheide.com/scala/neophytes.html) -* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) \ No newline at end of file +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From 978c8fb15cc2ee89a4eedcb8c7955eb90bea5bfc Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sun, 18 Oct 2015 00:34:14 +0800 Subject: Update ruby-ecosystem-de.html.markdown --- de-de/ruby-ecosystem-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown index e1f3c5e7..a7e1f75f 100644 --- a/de-de/ruby-ecosystem-de.html.markdown +++ b/de-de/ruby-ecosystem-de.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Rafal Chmiel", "http://github.com/rafalchmiel"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] -filename: ruby-ecosystem-de.html.markdown +filename: ruby-ecosystem-de.txt lang: de-de --- -- cgit v1.2.3 From 9ecbf76fe4c89ae3ca577a42cbf41a4b3e3497f0 Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Sat, 17 Oct 2015 13:18:27 -0430 Subject: tmux spanish translation --- es-es/tmux-es.html.markdown | 253 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 es-es/tmux-es.html.markdown diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown new file mode 100644 index 00000000..a7354be1 --- /dev/null +++ b/es-es/tmux-es.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux-es.txt +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + + +[tmux](http://tmux.sourceforge.net) +es un terminal multiplexor: habilita la creación, acceso y control +de múltiples terminales controlados desde una sola pantalla. tmux +puede ser separado de una pantalla y continuar corriendo en el fondo +y luego ser insertado nuevamente. + + +``` + + tmux [command] # Corre un comando + # 'tmux' sin comandos creará una nueva sesión + + new # Crea una nueva sesión + -s "Session" # Crea sesión con nombre + -n "Window" # Crea ventana con nombre + -c "/dir" # Comienza en el directorio destino + + attach # Adjunta sesión última/disponible + -t "#" # Adjunta sesión destino + -d # Separa la sesión de otras instancias + + ls # Lista las sesiones abiertas + -a # Lista todas las sesiones abiertas + + lsw # Lista las ventanas + -a # Lista todas las ventanas + -s # Lista todas las ventanas en la sesión + + lsp # Lista los páneles + -a # Lista todos los páneles + -s # Lista todos los páneles de la sesión + -t # Lista los páneles de aplicación en el destino + + kill-window # Cierra la ventana actual + -t "#" # Cierra la ventana destino + -a # Cierra todas las ventanas + -a -t "#" # Cierra todas las ventanas menos el destino + + kill-session # Cierra la sesión actual + -t "#" # Cierra la sesión destino + -a # Cierra todas las sesiones + -a -t "#" # Cierra todas las sesiones menos el destino + +``` + + +### Atajos de Teclado + +El método para controlar una sesión adjunta tmux es mediante +combinaciones de teclas llamadas teclas 'Prefijo'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos + + (M-1) = Meta + 1 -o- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos los atajos de teclado + : # Entra en la línea de comandos tmux + r # Fuerza el redibujado del cliente adjuntado + c # Crea una nueva ventana + + ! # Separa el panel actual fuera de la ventana. + % # Separa el panel actual en dos, izquierdo y derecho + " # Separa el panel actual en dos, superior e inferior + + n # Cambia a la siguiente ventana + p # Cambia a la ventana previa + { # Intercambia el panel actual con el anterior + } # Intercambia el panel actual con el próximo + + s # Selecciona una nueva sesión para el cliente adjuntado + interactivamente + w # Elegir la ventana actual interactivamente + 0 al 9 # Seleccionar ventanas 0 al 9 + + d # Separa el cliente actual + D # Elige un cliente para separar + + & # Cierra la ventana actual + x # Cierra el panel actual + + Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho + Left, Right + + M-1 to M-5 # Organizar páneles: + # 1) uniformes horizontales + # 2) uniformes verticales + # 3) principal horizontal + # 4) principal vertical + # 5) mozaico + + C-Up, C-Down # Redimensiona el panel actual en pasos de una celda + C-Left, C-Right + + M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. + +``` +# Ejemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Fuera de pantalla/Historia límite +set -g history-limit 2048 + +# Comienzo de índice +set -g base-index 1 + +# Ratón +set-option -g mouse-select-pane on + +# Forza recarga de fichero de configuración +unbind r +bind r source-file ~/.tmux.conf + + +### Atajos de teclado +########################################################################### + +# Desvincula C-b como el prefijo por defecto +unbind C-b + +# Establece el nuevo prefijo +set-option -g prefix ` + +# Regresa a la ventana previa cuando el prefijo es accionado dos veces +bind C-a last-window +bind ` last-window + +# Permite intercambiar C-a y ` usando F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencias de atajos +setw -g mode-keys vi +set-option -g status-keys vi + +# Moviéndose entre paneles con movimientos de teclas vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Ciclo/Intercambio de Ventana +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# División rápida de paneles +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activar sesión mas interna (cuando se anida tmux) para enviar comandos +bind a send-prefix + + +### Temas +########################################################################### + +# Paleta de Colores de la Barra de estado +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de Colores del Borde del Panel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Paleta de Colores de Mensajes +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de Colores de la Ventana +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificación +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Establece automáticamente títulos de ventanas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes de barra de estado +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Muestra indicadores de rendimiento en barra de estado +# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referencias + +[Tmux | Inicio](http://tmux.sourceforge.net) + +[Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -- cgit v1.2.3 From 8d809eac2e621daf92c609ed2cff6edeeedc983e Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:44:41 +0530 Subject: Updated translation --- ta_in/css.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index b55ab363..3a46816c 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -197,10 +197,6 @@ selector { ## Precedence or Cascade -An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Generally, a rule in a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. - -This process is called cascading, hence the name Cascading Style Sheets. - ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன இது Cascading Style Sheets என அழைக்கபடுகிறது. -- cgit v1.2.3 From 4143b1d87ed465eb8f0dffa07d299ebe82566d45 Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:46:03 +0530 Subject: removed EN Tamil translated added removed EN from markdown --- ta_in/css.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index 3a46816c..1e3aa9b0 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -102,8 +102,7 @@ div.some-parent.class-name { } /* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */ .i-am-any-element-before ~ .this-element { } -/* There are some selectors called pseudo classes that can be used to select an - element when it is in a particular state +/* சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும் */ -- cgit v1.2.3 From 29e35f633534fe81d478694c53585718c350b632 Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:47:25 +0530 Subject: updated removed white spaces and removed old EN translation --- ta_in/css.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index 1e3aa9b0..93c29bae 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -17,13 +17,11 @@ lang:in-ta ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன் கூடிய இணையதளங்கள் உருவாகின. -CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page. + CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது. ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது. - -This guide has been written for CSS 2, though CSS 3 is fast becoming popular. இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது. **குறிப்பு:** @@ -226,7 +224,7 @@ p { property: value !important; }

``` -The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. + css முன்னுரிமை பின்வருமாறு * `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் * `F` இது இரண்டாவது காரணம் இது inline style. -- cgit v1.2.3 From 6b2fa0cd2b3f49d60e15207d288d58c4a0ba72ad Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sat, 17 Oct 2015 23:49:43 +0530 Subject: Commited translation ta --- ta_in/css.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown index 93c29bae..56f94ed0 100644 --- a/ta_in/css.html.markdown +++ b/ta_in/css.html.markdown @@ -192,7 +192,7 @@ selector {

``` -## Precedence or Cascade +## Precedence அல்லது Cascade ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன -- cgit v1.2.3 From c245b7528501003a07fe7a88c23abfed480d12a5 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sat, 17 Oct 2015 20:20:33 +0200 Subject: Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: 7bc99fcaf4329b3c25cca671f62a03b67aa4d46e 8b7a2fff9a71b8fa8754947434b8b1f184ed2de1 e4c261567533921f35ce4e65ebfe6621a128992b 8909457ae46dc8fb151ef146acb3f6b8402f3407 de676b62b83fcaaa9977cca9adb9c38383b64f35 acc9a73c018a28a9c8ead7b108dd1fdfee7a797b 960ee4a1856db8eadb96277bb2422edfa8f2a81c f4022052471d6dc0a9c2fb8794e1352253b4c5ad --- it-it/bash-it.html.markdown | 72 ++++++++++++++++++++++++++------------------- 1 file changed, 42 insertions(+), 30 deletions(-) diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown index f892845f..af8823c4 100644 --- a/it-it/bash-it.html.markdown +++ b/it-it/bash-it.html.markdown @@ -13,13 +13,14 @@ contributors: filename: LearnBash.sh translators: - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] lang: it-it --- Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X. Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell. -[Per saperne di piu'.](http://www.gnu.org/software/bash/manual/bashref.html) +[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html) ```bash #!/bin/bash @@ -34,32 +35,34 @@ echo Ciao mondo! echo 'Questa è la prima riga'; echo 'Questa è la seconda riga' # Per dichiarare una variabile: -VARIABILE="Una stringa" +Variabile="Una stringa" # Ma non così: -VARIABILE = "Una stringa" -# Bash stabilirà che VARIABILE è un comando da eseguire e darà un errore +Variabile = "Una stringa" +# Bash stabilirà che Variabile è un comando da eseguire e darà un errore # perchè non esiste. # Usare la variabile: -echo $VARIABILE -echo "$VARIABILE" -echo '$VARIABILE' +echo $Variabile +echo "$Variabile" +echo '$Variabile' # Quando usi la variabile stessa - assegnala, esportala, oppure — scrivi # il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $. # Nota che ' (singolo apice) non espande le variabili! # Sostituzione di stringhe nelle variabili -echo ${VARIABILE/Una/A} +echo ${Variabile/Una/A} # Questo sostituirà la prima occorrenza di "Una" con "La" # Sottostringa di una variabile -echo ${VARIABILE:0:7} +Lunghezza=7 +echo ${Variabile:0:Lunghezza} # Questo ritornerà solamente i primi 7 caratteri # Valore di default per la variabile -echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"} -# Questo funziona per null (FOO=), stringa vuota (FOO=""), zero (FOO=0) ritorna 0 +echo ${Foo:-"ValoreDiDefaultSeFooMancaOppureÈVuoto"} +# Questo funziona per null (Foo=), stringa vuota (Foo=""), zero (Foo=0) ritorna 0 +# Nota: viene ritornato il valore di default, il contenuto della variabile pero' non cambia. # Variabili builtin: # Ci sono delle variabili builtin molto utili, come @@ -71,31 +74,40 @@ echo "Argomenti dello script separati in variabili distinte: $1 $2..." # Leggere un valore di input: echo "Come ti chiami?" -read NOME # Nota che non abbiamo dovuto dichiarare una nuova variabile -echo Ciao, $NOME! +read Nome # Nota che non abbiamo dovuto dichiarare una nuova variabile +echo Ciao, $Nome! # Classica struttura if: # usa 'man test' per maggiori informazioni sulle condizionali -if [ $NOME -ne $USER ] +if [ $Nome -ne $USER ] then echo "Il tuo nome non è lo username" else echo "Il tuo nome è lo username" fi +# Nota: se $Name è vuoto, la condizione precedente viene interpretata come: +if [ -ne $USER ] +# che genera un errore di sintassi. Quindi il metodo sicuro per usare +# variabili che possono contenere stringhe vuote è il seguente: +if [ "$Name" -ne $USER ] ... +# che viene interpretato come: +if [ "" -ne $USER ] ... +# e dunque funziona correttamente. + # C'è anche l'esecuzione condizionale echo "Sempre eseguito" || echo "Eseguito solo se la prima condizione fallisce" echo "Sempre eseguito" && echo "Eseguito solo se la prima condizione NON fallisce" # Per usare && e || con l'if, c'è bisogno di piu' paia di parentesi quadre: -if [ $NOME == "Steve" ] && [ $ETA -eq 15 ] +if [ "$Nome" == "Steve" ] && [ "$Eta" -eq 15 ] then - echo "Questo verrà eseguito se $NOME è Steve E $ETA è 15." + echo "Questo verrà eseguito se $Nome è Steve E $Eta è 15." fi -if [ $NOME == "Daniya" ] || [ $NOME == "Zach" ] +if [ "$Nome" == "Daniya" ] || [ "$Nome" == "Zach" ] then - echo "Questo verrà eseguito se $NAME è Daniya O Zach." + echo "Questo verrà eseguito se $Nome è Daniya O Zach." fi # Le espressioni sono nel seguente formato: @@ -137,7 +149,7 @@ python hello.py > /dev/null 2>&1 # se invece vuoi appendere usa ">>": python hello.py >> "output.out" 2>> "error.err" -# Sovrascrivi output.txt, appendi a error.err, e conta le righe: +# Sovrascrivi output.out, appendi a error.err, e conta le righe: info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err @@ -145,7 +157,7 @@ wc -l output.out error.err # vedi: man fd echo <(echo "#ciaomondo") -# Sovrascrivi output.txt con "#helloworld": +# Sovrascrivi output.out con "#helloworld": cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out @@ -164,7 +176,7 @@ echo "Ci sono $(ls | wc -l) oggetti qui." echo "Ci sono `ls | wc -l` oggetti qui." # Bash utilizza uno statemente case che funziona in maniera simile allo switch in Java e C++: -case "$VARIABILE" in +case "$Variabile" in #Lista di pattern per le condizioni che vuoi soddisfare 0) echo "C'è uno zero.";; 1) echo "C'è un uno.";; @@ -172,10 +184,10 @@ case "$VARIABILE" in esac # I cicli for iterano per ogni argomento fornito: -# I contenuti di $VARIABILE sono stampati tre volte. -for VARIABILE in {1..3} +# I contenuti di $Variabile sono stampati tre volte. +for Variabile in {1..3} do - echo "$VARIABILE" + echo "$Variabile" done # O scrivilo con il "ciclo for tradizionale": @@ -186,16 +198,16 @@ done # Possono essere usati anche per agire su file.. # Questo eseguirà il comando 'cat' su file1 e file2 -for VARIABILE in file1 file2 +for Variabile in file1 file2 do - cat "$VARIABILE" + cat "$Variabile" done # ..o dall'output di un comando # Questo eseguirà cat sull'output di ls. -for OUTPUT in $(ls) +for Output in $(ls) do - cat "$OUTPUT" + cat "$Output" done # while loop: @@ -223,7 +235,7 @@ bar () } # Per chiamare la funzione -foo "Il mio nome è" $NOME +foo "Il mio nome è" $Nome # Ci sono un sacco di comandi utili che dovresti imparare: # stampa le ultime 10 righe di file.txt @@ -245,7 +257,7 @@ grep "^foo.*bar$" file.txt grep -c "^foo.*bar$" file.txt # se vuoi letteralmente cercare la stringa, # e non la regex, usa fgrep (o grep -F) -fgrep "^foo.*bar$" file.txt +fgrep "^foo.*bar$" file.txt # Leggi la documentazione dei builtin di bash con il builtin 'help' di bash: -- cgit v1.2.3 From a1217767d3dceb40dba35159abb523b233cf0005 Mon Sep 17 00:00:00 2001 From: Damaso Sanoja Date: Sat, 17 Oct 2015 14:05:01 -0430 Subject: tmux spanish translation --- es-es/tmux-es.html.markdown | 253 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 es-es/tmux-es.html.markdown diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown new file mode 100644 index 00000000..a7354be1 --- /dev/null +++ b/es-es/tmux-es.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux-es.txt +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + + +[tmux](http://tmux.sourceforge.net) +es un terminal multiplexor: habilita la creación, acceso y control +de múltiples terminales controlados desde una sola pantalla. tmux +puede ser separado de una pantalla y continuar corriendo en el fondo +y luego ser insertado nuevamente. + + +``` + + tmux [command] # Corre un comando + # 'tmux' sin comandos creará una nueva sesión + + new # Crea una nueva sesión + -s "Session" # Crea sesión con nombre + -n "Window" # Crea ventana con nombre + -c "/dir" # Comienza en el directorio destino + + attach # Adjunta sesión última/disponible + -t "#" # Adjunta sesión destino + -d # Separa la sesión de otras instancias + + ls # Lista las sesiones abiertas + -a # Lista todas las sesiones abiertas + + lsw # Lista las ventanas + -a # Lista todas las ventanas + -s # Lista todas las ventanas en la sesión + + lsp # Lista los páneles + -a # Lista todos los páneles + -s # Lista todos los páneles de la sesión + -t # Lista los páneles de aplicación en el destino + + kill-window # Cierra la ventana actual + -t "#" # Cierra la ventana destino + -a # Cierra todas las ventanas + -a -t "#" # Cierra todas las ventanas menos el destino + + kill-session # Cierra la sesión actual + -t "#" # Cierra la sesión destino + -a # Cierra todas las sesiones + -a -t "#" # Cierra todas las sesiones menos el destino + +``` + + +### Atajos de Teclado + +El método para controlar una sesión adjunta tmux es mediante +combinaciones de teclas llamadas teclas 'Prefijo'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos + + (M-1) = Meta + 1 -o- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos los atajos de teclado + : # Entra en la línea de comandos tmux + r # Fuerza el redibujado del cliente adjuntado + c # Crea una nueva ventana + + ! # Separa el panel actual fuera de la ventana. + % # Separa el panel actual en dos, izquierdo y derecho + " # Separa el panel actual en dos, superior e inferior + + n # Cambia a la siguiente ventana + p # Cambia a la ventana previa + { # Intercambia el panel actual con el anterior + } # Intercambia el panel actual con el próximo + + s # Selecciona una nueva sesión para el cliente adjuntado + interactivamente + w # Elegir la ventana actual interactivamente + 0 al 9 # Seleccionar ventanas 0 al 9 + + d # Separa el cliente actual + D # Elige un cliente para separar + + & # Cierra la ventana actual + x # Cierra el panel actual + + Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho + Left, Right + + M-1 to M-5 # Organizar páneles: + # 1) uniformes horizontales + # 2) uniformes verticales + # 3) principal horizontal + # 4) principal vertical + # 5) mozaico + + C-Up, C-Down # Redimensiona el panel actual en pasos de una celda + C-Left, C-Right + + M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. + +``` +# Ejemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Fuera de pantalla/Historia límite +set -g history-limit 2048 + +# Comienzo de índice +set -g base-index 1 + +# Ratón +set-option -g mouse-select-pane on + +# Forza recarga de fichero de configuración +unbind r +bind r source-file ~/.tmux.conf + + +### Atajos de teclado +########################################################################### + +# Desvincula C-b como el prefijo por defecto +unbind C-b + +# Establece el nuevo prefijo +set-option -g prefix ` + +# Regresa a la ventana previa cuando el prefijo es accionado dos veces +bind C-a last-window +bind ` last-window + +# Permite intercambiar C-a y ` usando F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencias de atajos +setw -g mode-keys vi +set-option -g status-keys vi + +# Moviéndose entre paneles con movimientos de teclas vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Ciclo/Intercambio de Ventana +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# División rápida de paneles +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activar sesión mas interna (cuando se anida tmux) para enviar comandos +bind a send-prefix + + +### Temas +########################################################################### + +# Paleta de Colores de la Barra de estado +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de Colores del Borde del Panel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Paleta de Colores de Mensajes +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de Colores de la Ventana +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificación +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Establece automáticamente títulos de ventanas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes de barra de estado +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Muestra indicadores de rendimiento en barra de estado +# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referencias + +[Tmux | Inicio](http://tmux.sourceforge.net) + +[Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -- cgit v1.2.3 From ba4f6d2bfb2f09ecc2892ab4dc0b8b35bb21fc1b Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran Date: Sun, 18 Oct 2015 00:11:56 +0530 Subject: XML commits --- ta_in/xml.html.markdown | 28 ++++++---------------------- 1 file changed, 6 insertions(+), 22 deletions(-) diff --git a/ta_in/xml.html.markdown b/ta_in/xml.html.markdown index 3ec0ab70..a9bfa9cd 100644 --- a/ta_in/xml.html.markdown +++ b/ta_in/xml.html.markdown @@ -42,15 +42,7 @@ HTML போல் அன்றி , XML ஆனது தகவலை மட் - - + - + -- cgit v1.2.3 From 7f2f4b1dfc5183109bc7ef3a1892b79819015bbb Mon Sep 17 00:00:00 2001 From: Zirak Date: Sat, 17 Oct 2015 20:49:34 +0000 Subject: Changed code block language to clojure ...again :( --- hy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hy.html.markdown b/hy.html.markdown index 039312db..5333410e 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -12,7 +12,7 @@ hy to call native python code or python to call native hy code as well This tutorial works for hy ≥ 0.9.12, with some corrections for hy 0.11. -```hy +```clojure ;; this gives an gentle introduction to hy for a quick trial head to ;; http://try-hy.appspot.com ;; -- cgit v1.2.3 From 989615be41c78eee9bfe5d7f3786dd5a90a40565 Mon Sep 17 00:00:00 2001 From: Gloria Dwomoh Date: Sun, 18 Oct 2015 00:02:18 +0300 Subject: Update scala-gr.html.markdown --- el-gr/scala-gr.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown index e29c7e70..415fda5c 100644 --- a/el-gr/scala-gr.html.markdown +++ b/el-gr/scala-gr.html.markdown @@ -40,7 +40,7 @@ Scala - Η επεκτάσιμη γλώσσα /* Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε - να δείτε , φαίνοται κάπως έτσι. + να δείτε , φαίνονται κάπως έτσι. */ // Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση @@ -59,12 +59,12 @@ var y = 10 y = 20 // το y είναι τώρα 20 /* - Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω + Η Scala είναι στατικού τύπου γλώσσα, εν τούτοις προσέξτε ότι στις παραπάνω δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να - μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε - αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: + μαντέψει ποιος είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε + αναλυτικά τον τύπο μιας μεταβλητής ως εξής: */ val z: Int = 10 val a: Double = 1.0 @@ -85,7 +85,7 @@ false true == false // false 10 > 5 // true -// Η αριθμιτική είναι όπως τα συνηθισμένα +// Η αριθμητική είναι όπως τα συνηθισμένα 1 + 1 // 2 2 - 1 // 1 5 * 3 // 15 @@ -117,14 +117,14 @@ true == false // false "Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά" 'a' // Ένας χαρακτήρας στην Scala // res30: Char = a -// 'Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. +// Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. // Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους. "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") -// Έχουν επίσης μερικές επιπλένον μεθόδους Scala. +// Έχουν επίσης μερικές επιπλέον μεθόδους Scala. // Δείτε επίσης : scala.collection.immutable.StringOps "hello world".take(5) "hello world".drop(5) @@ -253,7 +253,7 @@ r foreach println var i = 0 while (i < 10) { println("i " + i); i+=1 } -while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβει; Γιατί; +while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβη; Γιατί; i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος // με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή @@ -268,8 +268,8 @@ do { } while (x < 10) // Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα -// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί -// ρητά ο τύπος που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γραφτεί +// ρητά ο τύπος που θα επιστρέψουν, αλλιώς ο μεταγλωττιστής δεν μπορεί // αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. def showNumbersInRange(a:Int, b:Int):Unit = { print(a) @@ -332,7 +332,7 @@ s(1) val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα - // της ακαίρεας διαίρεσης και το υπόλοιπο. + // της ακέραιας διαίρεσης και το υπόλοιπο. // Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n // όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου. @@ -349,7 +349,7 @@ d._2 /* Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις - (τιμές , συναρτήσεις , κτλ). Αυτές οι εκφράσεις βολεύουν όταν τις + (τιμές, συναρτήσεις, κτλ.). Αυτές οι εκφράσεις βολεύουν όταν τις γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα @@ -394,7 +394,7 @@ println(mydog.bark) // => "Woof, woof!" // αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances // της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις // μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες. -// Προσέξτε οτι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. +// Προσέξτε ότι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. object Dog { def allKnownBreeds = List("pitbull", "shepherd", "retriever") def createDog(breed: String) = new Dog(breed) @@ -402,7 +402,7 @@ object Dog { // Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον // λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην -// Scala είναι πότε να χρησιμοπούνται κλάσεις και πότε case κλάσεις. +// Scala είναι πότε να χρησιμοποιούνται κλάσεις και πότε case κλάσεις. // Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον // πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις // τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες. @@ -411,7 +411,7 @@ object Dog { // έχουν παρενέργειες. case class Person(name: String, phoneNumber: String) -// Δημιουργία ενός instance. Πραρατηρήστε ότι τα case classes +// Δημιουργία ενός instance. Παρατηρήστε ότι τα case classes // δεν χρειάζονται την λέξη "new" . val george = Person("George", "1234") val kate = Person("Kate", "4567") @@ -419,7 +419,7 @@ val kate = Person("Kate", "4567") // Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως: george.phoneNumber // => "1234" -// Ελέχγεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να +// Ελέγχεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να // κάνουμε override στο .equals) Person("George", "1234") == Person("Kate", "1236") // => false @@ -509,7 +509,7 @@ List(1, 2, 3) map (x => x + 10) // ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή. List(1, 2, 3) map (_ + 10) -// Αν το μπλόκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται +// Αν το μπλοκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται // (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα // μπορείτε να παραλείψετε την κάτω παύλα. List("Dom", "Bob", "Natalia") foreach println -- cgit v1.2.3 From 3253734d4c03f93aa9b6a59d62733f0a3b683392 Mon Sep 17 00:00:00 2001 From: Lucas Moreira Date: Sat, 17 Oct 2015 19:53:33 -0300 Subject: =?UTF-8?q?Corre=C3=A7=C3=A3o=20de=20palavra.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/json-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index fc63b126..e4f10a61 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -35,7 +35,7 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. "array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5], "outro objeto": { - "ccomentário": "Estas coisas podem ser aninhadas, muito úteis." + "comentário": "Estas coisas podem ser aninhadas, muito úteis." } }, -- cgit v1.2.3 From 65f951d87c80deff6c447faa4690dcfe1bb4d36a Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Sat, 17 Oct 2015 19:37:47 -0400 Subject: Added documentation on receive do blocks in Elixir. --- elixir.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/elixir.html.markdown b/elixir.html.markdown index 9fdf37e9..60f0b01c 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -369,6 +369,13 @@ spawn(f) #=> #PID<0.40.0> # messages to the process. To do message passing we use the `send` operator. # For all of this to be useful we need to be able to receive messages. This is # achieved with the `receive` mechanism: + +# The `receive do` block is used to listen for messages and process +# them when they are received. A `receive do` block will only +# process one received message. In order to process multiple +# messages, a function with a `receive do` block must recursively +# call itself to get into the `receive do` block again. + defmodule Geometry do def area_loop do receive do -- cgit v1.2.3 From 9f510f3044138429ce616c390e42d8e0b6ceb2df Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Sat, 17 Oct 2015 19:50:09 -0400 Subject: Fixed indentation in csharp file. --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 59f3e42b..31c0417e 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -395,8 +395,8 @@ 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 - count = 15; // out param must be assigned before control leaves the method + //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 } // GENERICS -- cgit v1.2.3 From c613e3bc6a3c59214faaa6e6273cb98ab8a97c1d Mon Sep 17 00:00:00 2001 From: Romin Irani Date: Sun, 18 Oct 2015 06:19:24 +0530 Subject: Added Git and Github Tutorial Link --- git.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index 72079f6c..e9d62b69 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -499,3 +499,6 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) * [Pro Git](http://www.git-scm.com/book/en/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + -- cgit v1.2.3 From 07e04e7a2d0f2b7269e4495c338b039a30f70e64 Mon Sep 17 00:00:00 2001 From: "chris@chriszimmerman.net" Date: Sat, 17 Oct 2015 20:49:58 -0400 Subject: Fixed spacing with Elixir comment. --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 60f0b01c..eedeb227 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -391,7 +391,7 @@ end # Compile the module and create a process that evaluates `area_loop` in the shell pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> -#Alternatively +# Alternatively pid = spawn(Geometry, :area_loop, []) # Send a message to `pid` that will match a pattern in the receive statement -- cgit v1.2.3 From 24f9fd6ba53213568192f5dbb61fc7b66f457841 Mon Sep 17 00:00:00 2001 From: Romin Irani Date: Sun, 18 Oct 2015 06:27:36 +0530 Subject: Added tmuxinator in References --- tmux.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tmux.html.markdown b/tmux.html.markdown index c11da5fc..49d1bba6 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -249,3 +249,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) [Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) + + -- cgit v1.2.3 From 53366ebdbeecb502131c2768979e4b6ed9d59d9f Mon Sep 17 00:00:00 2001 From: venegu Date: Sat, 17 Oct 2015 22:21:25 -0400 Subject: Adding modulo division to JavaScript article --- javascript.html.markdown | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 34ba9b47..937354eb 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -54,6 +54,11 @@ doStuff() // Including uneven division. 5 / 2; // = 2.5 +// And modulo division. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 @@ -104,7 +109,7 @@ null == undefined; // = true // ...unless you use === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false // ...which can result in some weird behaviour... 13 + !0; // 14 @@ -220,15 +225,15 @@ for (var i = 0; i < 5; i++){ //The For/In statement loops iterates over every property across the entire prototype chain var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ description += person[x] + " "; } -//If only want to consider properties attached to the object itself, +//If only want to consider properties attached to the object itself, //and not its prototypes use hasOwnProperty() check var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ if (person.hasOwnProperty(x)){ description += person[x] + " "; -- cgit v1.2.3 From 95af711a03e89d6f95b81e5b9d9b4cb530789a35 Mon Sep 17 00:00:00 2001 From: Tomy Date: Sun, 18 Oct 2015 13:00:23 +0900 Subject: begin translate --- ja-jp/php.html.markdown | 767 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 767 insertions(+) create mode 100644 ja-jp/php.html.markdown diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown new file mode 100644 index 00000000..3831e220 --- /dev/null +++ b/ja-jp/php.html.markdown @@ -0,0 +1,767 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Kazushige Tominaga", "https://github.com/kazu9su"] +filename: learnphp.php +--- + +このドキュメントでは、 PHP 5+ について説明します。 + +```php + +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (a leading 0 denotes an octal number) +$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) + +// Floats (aka doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Delete variable +unset($int1); + +// Arithmetic +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Shorthand arithmetic +$number = 0; +$number += 1; // Increment $number by 1 +echo $number++; // Prints 1 (increments after evaluation) +echo ++$number; // Prints 3 (increments before evaluation) +$number /= $float; // Divide and assign the quotient to $number + +// Strings should be enclosed in single quotes; +$sgl_quotes = '$String'; // => '$String' + +// Avoid using double quotes except to embed other variables +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Special characters are only escaped in double quotes +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// Enclose a variable in curly braces if needed +$money = "I have $${number} in the bank."; + +// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs will do string interpolation +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 introduced a new syntax +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // prints 1 + +// List literals implicitly assign integer keys +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Add an element to the end of an array +$array[] = 'Four'; +// or +array_push($array, 'Five'); + +// Remove element from array +unset($array[3]); + +/******************************** + * Output + */ + +echo('Hello World!'); +// Prints Hello World! to stdout. +// Stdout is the web page if running in a browser. + +print('Hello World!'); // The same as echo + +// echo is actually a language construct, so you can drop the parentheses. +echo 'Hello World!'; +print 'Hello World!'; // So is print + +$paragraph = 'paragraph'; + +echo 100; // Echo scalar variables directly +echo $paragraph; // or variables + +// If short open tags are configured, or your PHP version is +// 5.4.0 or greater, you can use the short echo syntax +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Dumps type and value of variable to stdout +var_dump($z); // prints int(0) + +// Prints variable to stdout in human-readable format +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logic + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert throws a warning if its argument is not true + +// These comparisons will always be true, even if the types aren't the same. +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// The following will only be true if the values match and are the same type. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// spaceship operator since PHP 7 +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 since they are equal +echo $a <=> $b; // -1 since $a < $b +echo $b <=> $a; // 1 since $b > $a + +// Variables can be converted between types, depending on their usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (strings are coerced to integers) + +$string = 'one'; +echo $string + $string; // => 0 +// Outputs 0 because the + operator cannot cast the string 'one' to a number + +// Type casting can be used to treat a variable as another type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// There are also dedicated functions for casting most types +$integer = 5; +$string = strval($integer); + +$var = null; // Null value + + +/******************************** + * Control Structures + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// ternary operator +print (false ? 'Does not get printed' : 'Does'); + +// ternary shortcut operator since PHP 5.3 +// equivalent of "$x ? $x : 'Does'"" +$x = false; +print($x ?: 'Does'); + +// null coalesce operator since php 7 +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// This alternative syntax is useful for templates: +?> + + +This is displayed if the test is truthy. + +This is displayed otherwise. + + + 2, 'car' => 4]; + +// Foreach loops can iterate over arrays +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// You can iterate over the keys as well as the values +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * Functions + */ + +// Define a function with "function": +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// A valid function name starts with a letter or underscore, followed by any +// number of letters, numbers, or underscores. + +function add ($x, $y = 1) { // $y is optional and defaults to 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result is not accessible outside the function +// print $result; // Gives a warning. + +// Since PHP 5.3 you can declare anonymous functions; +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Functions can return functions +function bar ($x, $y) { + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// You can call named functions using strings +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Useful for programatically determining which function to run. +// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +/******************************** + * Includes + */ + +instanceProp = $instanceProp; + } + + // Methods are declared as functions inside a class + public function myMethod() + { + print 'MyClass'; + } + + //final keyword would make a function unoverridable + final function youCannotOverrideMe() + { + } + +/* + * Declaring class properties or methods as static makes them accessible without + * needing an instantiation of the class. A property declared as static can not + * be accessed with an instantiated class object (though a static method can). + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Class constants can always be accessed statically +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; + +// Instantiate classes using new +$my_class = new MyClass('An instance property'); +// The parentheses are optional if not passing in an argument. + +// Access class members using -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Sun, 18 Oct 2015 13:27:55 +0900 Subject: translate first block --- ja-jp/php.html.markdown | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 3831e220..4448a1f5 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -13,32 +13,30 @@ filename: learnphp.php ```php Hello World Again! Date: Sun, 18 Oct 2015 11:35:38 +0530 Subject: json values translated to tamil --- ta_in/json.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ta_in/json.html.markdown b/ta_in/json.html.markdown index 777dfaeb..d85e0d82 100644 --- a/ta_in/json.html.markdown +++ b/ta_in/json.html.markdown @@ -42,29 +42,29 @@ Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. ```json { - "key": "value", + "key": "ஒரு சாவிக்கு ஒரு பெறுமதி உள்ளது ", - "keys": "must always be enclosed in double quotes", + "keys": "சாவிகள் , மற்றும் பெறுமானங்கள் மேற்கோள் குறிக்குள் இடல் வேண்டும்", "numbers": 0, - "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", + "strings": "Hellø, wørld. எல்லாவகையான unicode உம் அனுமதிக்கப்படும், அத்துடன் \"escaping\".", "has bools?": true, "nothingness": null, "big number": 1.2e+100, "objects": { - "comment": "Most of your structure will come from objects.", + "comment": "பெரும்பாலான கட்டமைப்புகள் objects இல் இருந்தே வருகின்றன", - "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + "array": [0, 1, 2, 3, "array யானது எல்லாவகையான பெறுமானங்களையும் கொண்டிருக்கும்", 5], "another object": { - "comment": "These things can be nested, very useful." + "comment": "இவை ஒன்றுக்குள் இன்னொன்றை எழுத முடியும்" } }, "silliness": [ { - "sources of potassium": ["bananas"] + "sources of potassium": ["வாழைபழம்"] }, [ [1, 0, 0, 0], @@ -75,12 +75,12 @@ Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. ], "alternative style": { - "comment": "check this out!" + "comment": "இதை பார்க்கவும்" , "comma position": "doesn't matter - as long as it's before the value, then it's valid" , "another comment": "how nice" }, - "that was short": "And, you're done. You now know everything JSON has to offer." + "that was short": "நீங்கள் ஜேசன் பற்றி யாவற்றையும் கற்றுள்ளீர்கள்" } ``` -- cgit v1.2.3 From 10d0865214928a396bdb9d2ef187ed90b48a975c Mon Sep 17 00:00:00 2001 From: Saurabh Sandav Date: Sun, 18 Oct 2015 13:21:31 +0530 Subject: [whip/en] Fix typos --- whip.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/whip.html.markdown b/whip.html.markdown index 3faee98a..61c301a5 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -2,6 +2,7 @@ language: whip contributors: - ["Tenor Biel", "http://github.com/L8D"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] author: Tenor Biel author_url: http://github.com/L8D filename: whip.lisp @@ -93,13 +94,13 @@ null ; used to indicate a deliberate non-value undefined ; user to indicate a value that hasn't been set ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 2. Vairbles, Lists, and Dicts +; 2. Variables, Lists, and Dicts ; Variables are declared with the `def` or `let` functions. ; Variables that haven't been set will be `undefined`. (def some_var 5) ; `def` will keep the variable in the global context. -; `let` will only have the variable inside its context, and has a wierder syntax. +; `let` will only have the variable inside its context, and has a weirder syntax. (let ((a_var 5)) (+ a_var 5)) ; => 10 (+ a_var 5) ; = undefined + 5 => undefined @@ -163,7 +164,7 @@ undefined ; user to indicate a value that hasn't been set (my_function 10 10) ; = (+ (+ 10 10) 10) => 30 -; Obiously, all lambdas by definition are anonymous and +; Obviously, all lambdas by definition are anonymous and ; technically always used anonymously. Redundancy. ((lambda (x) x) 10) ; => 10 @@ -191,7 +192,7 @@ undefined ; user to indicate a value that hasn't been set (slice (.. 1 5) 2) ; => (3 4 5) (\ (.. 0 100) -5) ; => (96 97 98 99 100) -; `append` or `<<` is self expanatory +; `append` or `<<` is self explanatory (append 4 (1 2 3)) ; => (1 2 3 4) (<< "bar" ("foo")) ; => ("foo" "bar") -- cgit v1.2.3 From 35b921505b38ff3686c79826aadde9847e9b2f53 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 11:42:37 +0200 Subject: [c++/it] Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: 462ac892179d64437b1124263402378a6054e50b 3db1042157204ad05484d6b42140261f849040cc cea52ca43490b74316781c23779654fd46aaeab4 47d3cea47e8c5203efa857070a00dcfbff67b019 894792e1e17173823a5d50de24439427c69d63f4 06889be239622266d9c36c750f7ee755ccdae05d 97b97408eab97fbe322df4266cda9ab2ed21fceb 1d1def16a5d7925bb8f7fba7dc49182e33359e85 a230d76307ecbc0f53c4b359cdb90628720f915e fc9ae44e4887500634bf3a87343d687b4d7d4e3c 85f6ba0b57b9d894c694df66449b1e1c555c625b 8eb410208a8d9b0a42f6c52411455ace04c78101 ae86e4ebabb0c78c1bd8052e6ab5916446ef39c2 455afa3a7bf59fc272f3439825da55659765eec0 12286a4b78f82bde3907d4bf348e20c12dd6d46f 9bc553c46ce9b7154ec7c82451d71608f4beda82 87e8e77e5fd8d84a252dbb6d6697202118378774 3b246fd869564b0a7f7c847f44aecac82d318c78 9d64b532f8ccdfd95c2417dcf65257385956353a e32eb715ef41e411da0a91b40e6e35f150a9c2eb ca435fbb0dd09cdc9c70fe945a891ae3e6c19ab2 --- it-it/c++-it.html.markdown | 211 +++++++++++++++++++++++++++++++++++++++------ 1 file changed, 185 insertions(+), 26 deletions(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index e7e1d89e..92ebc165 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -4,6 +4,8 @@ filename: learncpp-it.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] translators: - ["Robert Margelli", "http://github.com/sinkswim/"] lang: it-it @@ -54,11 +56,11 @@ int main(int argc, char** argv) // Tuttavia, il C++ varia nei seguenti modi: -// In C++, i caratteri come letterali sono da un byte. -sizeof('c') == 1 +// In C++, i caratteri come letterali sono dei char. +sizeof('c') == sizeof(char) == 1 -// In C, i caratteri come letterali sono della stessa dimensione degli interi. -sizeof('c') == sizeof(10) +// In C, i caratteri come letterali sono degli interi. +sizeof('c') == sizeof(int) // C++ ha prototipizzazione rigida @@ -160,11 +162,14 @@ void foo() int main() { - // Assume che tutto venga dal namespace "Secondo" - // a meno che non venga dichiarato altrimenti. + // Include tutti i simboli del namespace Secondo nello scope attuale. + // Osserva che chiamare semplicemente foo() non va più bene perché è ambiguo: + // bisogna specificare se vogliamo chiamare foo definita nel namespace Secondo + // o foo definita nel livello principale del programma. + using namespace Secondo; - foo(); // stampa "Questa è Secondo::foo" + Secondo::foo(); // stampa "Questa è Secondo::foo" Primo::Annidato::foo(); // stampa "Questa è Primo::Annidato::foo" ::foo(); // stampa "Questa è foo globale" } @@ -244,12 +249,137 @@ cout << fooRef; // Stampa "Io sono foo. Ciao!" // Non riassegna "fooRef". Questo è come scrivere "foo = bar", e // foo == "Io sono bar" // dopo questa riga. +cout << &fooRef << endl; // Stampa l'indirizzo di foo fooRef = bar; +cout << &fooRef << endl; // Stampa lo stesso l'indirizzo di foo +cout << fooRef; // Stampa "Io sono bar" + +// L'indirizzo di fooRef rimane lo stesso, ovvero si riferisce ancora a foo. + const string& barRef = bar; // Crea un riferimento const a bar. // Come in C, i valori const (i puntatori e i riferimenti) non possono essere modificati. barRef += ". Ciao!"; // Errore, i riferimenti const non possono essere modificati. +// Facciamo un piccolo excursus: prima di approfondire ancora i riferimenti, è necessario +// introdurre il concetto di oggetto temporaneo. Supponiamo di avere il seguente codice: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// Nella seconda riga si ha che: +// - un oggetto di tipo stringa viene ritornato da tempObjectFun +// - viene costruita una nuova stringa, utilizzando l'oggetto ritornato come +// argomento per il costruttore +// - l'oggetto ritornato da tempObjectFun viene distrutto +// L'oggetto ritornato da tempObjectFun viene detto oggetto temporaneo. +// Un oggetto temporaneo viene creato quando una funzione ritorna un oggetto, e viene +// distrutto quando l'espressione che lo racchiude termina la sua esecuzione - questo +// comportamento viene definito dallo standard, ma i compilatori possono modificarlo +// a piacere. Cerca su google "return value optimization" se vuoi approfondire. +// Dunque nel seguente codice: +foo(bar(tempObjectFun())) + +// dando per scontato che foo e bar esistano, l'oggetto ritornato da tempObjectFun +// è passato a bar ed è distrutto prima dell'invocazione di foo. + +// Tornando ai riferimenti, c'è un'eccezione a quanto appena detto. +// Infatti un oggetto temporaneo "viene distrutto quando l'espressione +// che lo racchiude termina la sua esecuzione", tranne quando è legato ad un +// riferimento di tipo const. In tal caso la sua vita viene estesa per tutto +// lo scope attuale: + +void constReferenceTempObjectFun() { + // constRef riceve l'oggetto temporaneo, che non viene distrutto fino + // alla fine di questa funzione. + const string& constRef = tempObjectFun(); + ... +} + +// Un altro tipo di riferimento introdotto nel C++11 è specifico per gli +// oggetti temporanei. Non puoi dichiarare una variabile di quel tipo, ma +// ha la precedenza nella risoluzione degli overload: + +void someFun(string& s) { ... } // Riferimento normale +void someFun(string&& s) { ... } // Riferimento ad un oggetto temporaneo + +string foo; +someFun(foo); // Chiama la versione con il riferimento normale +someFun(tempObjectFun()); // Chiama la versione con il riferimento temporaneo + +// Ad esempio potrai vedere questi due costruttori per std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// L'idea è che se noi costruiamo una nuova stringa a partire da un oggetto temporaneo +// (che in ogni caso verrà distrutto), possiamo avere un costruttore più efficiente +// che in un certo senso "recupera" parti di quella stringa temporanea. +// Ci si riferisce a questo concetto come "move semantics". + +///////////////////// +// Enum +///////////////////// + +// Gli enum sono un modo per assegnare un valore ad una costante, e sono +// principalmente usati per rendere il codice più leggibile. +enum ETipiMacchine +{ + AlfaRomeo, + Ferrari, + SUV, + Panda +}; + +ETipiMacchine GetPreferredCarType() +{ + return ETipiMacchine::Ferrari; +} + +// Dal C++11 in poi c'è un modo molto semplice per assegnare un tipo ad un enum, +// che può essere utile per la serializzazione dei dati o per convertire gli enum +// tra il tipo desiderato e le rispettive costanti. +enum ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // L'enum viene implicitamente convertito ad un uint8_t poiché + // è stato dichiarato come tale + WriteByteToFile(InputCarType); +} + +// D'altro canto potresti voler evitare che un enum venga accidentalmente convertito +// in un intero o in un altro tipo, quindi è possibile create una classe enum che +// impedisce la conversione implicita. +enum class ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // Il compilatore darà errore anche se ETipiMacchine è un uint8_t: questo + // perchè abbiamo dichiarato l'enum come "enum class"! + WriteByteToFile(InputCarType); +} + ////////////////////////////////////////////////// // Classi e programmazione orientata agli oggetti ///////////////////////////////////////////////// @@ -296,13 +426,16 @@ public: // Questi sono chiamati quando un oggetto è rimosso o esce dalla visibilità. // Questo permette paradigmi potenti come il RAII // (vedi sotto) - // I distruttori devono essere virtual per permettere a classi di essere derivate da questa. + // I distruttori devono essere virtual per permettere a classi di essere + // derivate da questa; altrimenti, il distruttore della classe derivata + // non viene chiamato se l'oggetto viene distrutto tramite un riferimento alla + // classe da cui ha ereditato o tramite un puntatore. virtual ~Dog(); }; // Un punto e virgola deve seguire la definizione della funzione // Le funzioni membro di una classe sono generalmente implementate in files .cpp . -void Cane::Cane() +Cane::Cane() { std::cout << "Un cane è stato costruito\n"; } @@ -325,7 +458,7 @@ void Cane::print() const std::cout << "Il cane è " << nome << " e pesa " << peso << "kg\n"; } -void Cane::~Cane() +Cane::~Cane() { cout << "Ciao ciao " << nome << "\n"; } @@ -340,10 +473,12 @@ int main() { // Ereditarietà: -// Questa classe eredita tutto ciò che è public e protected dalla classe Cane +// Questa classe eredita tutto ciò che è public e protected dalla classe Cane, +// ma anche ciò che privato: tuttavia non potrà accedere direttamente a membri/metodi +// privati se non c'è un metodo pubblico o privato che permetta di farlo. class MioCane : public Cane { - void impostaProprietario(const std::string& proprietarioCane) + void impostaProprietario(const std::string& proprietarioCane); // Sovrascrivi il comportamento della funzione print per tutti i MioCane. Vedi // http://it.wikipedia.org/wiki/Polimorfismo_%28informatica%29 @@ -447,6 +582,7 @@ int main () { // definire una classe o una funzione che prende un parametro di un dato tipo: template class Box { +public: // In questa classe, T può essere usato come qualsiasi tipo. void inserisci(const T&) { ... } }; @@ -519,19 +655,23 @@ printMessage<10>(); // Stampa "Impara il C++ più velocemente in soli 10 minuti // (vedi http://en.cppreference.com/w/cpp/error/exception) // ma ogni tipo può essere lanciato come eccezione #include +#include // Tutte le eccezioni lanciate all'interno del blocco _try_ possono essere catturate dai successivi // handlers _catch_. try { // Non allocare eccezioni nello heap usando _new_. - throw std::exception("È avvenuto un problema"); + throw std::runtime_error("C'è stato un problema."); } + // Cattura le eccezioni come riferimenti const se sono oggetti catch (const std::exception& ex) { - std::cout << ex.what(); + std::cout << ex.what(); +} + // Cattura ogni eccezioni non catturata dal blocco _catch_ precedente -} catch (...) +catch (...) { std::cout << "Catturata un'eccezione sconosciuta"; throw; // Rilancia l'eccezione @@ -541,7 +681,7 @@ catch (const std::exception& ex) // RAII /////// -// RAII sta per Resource Allocation Is Initialization. +// RAII sta per "Resource Allocation Is Initialization". // Spesso viene considerato come il più potente paradigma in C++. // È un concetto semplice: un costruttore di un oggetto // acquisisce le risorse di tale oggetto ed il distruttore le rilascia. @@ -563,9 +703,9 @@ void faiQualcosaConUnFile(const char* nomefile) // Sfortunatamente, le cose vengono complicate dalla gestione degli errori. // Supponiamo che fopen fallisca, e che faiQualcosaConUnFile e // faiQualcosAltroConEsso ritornano codici d'errore se falliscono. -// (Le eccezioni sono la maniera preferita per gestire i fallimenti, -// ma alcuni programmatori, specialmente quelli con un passato in C, -// non sono d'accordo con l'utilità delle eccezioni). +// (Le eccezioni sono la maniera preferita per gestire i fallimenti, +// ma alcuni programmatori, specialmente quelli con un passato in C, +// non sono d'accordo con l'utilità delle eccezioni). // Adesso dobbiamo verificare che ogni chiamata per eventuali fallimenti e chiudere il gestore di file // se un problema è avvenuto. bool faiQualcosaConUnFile(const char* nomefile) @@ -615,7 +755,7 @@ void faiQualcosaConUnFile(const char* nomefile) { FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura if (fh == nullptr) - throw std::exception("Non è stato possibile aprire il file."). + throw std::runtime_error("Errore nell'apertura del file."); try { faiQualcosaConIlFile(fh); @@ -678,26 +818,29 @@ class Foo { virtual void bar(); }; class FooSub : public Foo { - virtual void bar(); // sovrascrive Foo::bar! + virtual void bar(); // Sovrascrive Foo::bar! }; // 0 == false == NULL (la maggior parte delle volte)! bool* pt = new bool; -*pt = 0; // Setta il valore puntato da 'pt' come falso. +*pt = 0; // Setta il valore puntato da 'pt' come falso. pt = 0; // Setta 'pt' al puntatore null. Entrambe le righe vengono compilate senza warnings. // nullptr dovrebbe risolvere alcune di quei problemi: int* pt2 = new int; -*pt2 = nullptr; // Non compila +*pt2 = nullptr; // Non compila pt2 = nullptr; // Setta pt2 a null. -// Ma in qualche modo il tipo 'bool' è una eccezione (questo è per rendere compilabile `if (ptr)`. -*pt = nullptr; // Questo compila, anche se '*pt' è un bool! +// C'è un'eccezione per i bool. +// Questo permette di testare un puntatore a null con if(!ptr), ma +// come conseguenza non puoi assegnare nullptr a un bool direttamente! +*pt = nullptr; // Questo compila, anche se '*pt' è un bool! // '=' != '=' != '='! -// Chiama Foo::Foo(const Foo&) o qualche variante del costruttore di copia. +// Chiama Foo::Foo(const Foo&) o qualche variante (vedi "move semantics") +// del costruttore di copia. Foo f2; Foo f1 = f2; @@ -711,6 +854,22 @@ Foo f1 = fooSub; Foo f1; f1 = f2; + +// Come deallocare realmente le risorse all'interno di un vettore: +class Foo { ... }; +vector v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// La riga seguente riduce la dimensione di v a 0, ma il distruttore non +// viene chiamato e dunque le risorse non sono deallocate! +v.empty(); +v.push_back(Foo()); // Il nuovo valore viene copiato nel primo Foo che abbiamo inserito + +// Distrugge realmente tutti i valori dentro v. Vedi la sezione riguardante gli +// oggetti temporanei per capire come mai funziona così. +v.swap(vector()); + ``` Letture consigliate: -- cgit v1.2.3 From c23bba2b6010e659d518f144d689102d0e9fb147 Mon Sep 17 00:00:00 2001 From: Cameron Wood Date: Sun, 18 Oct 2015 05:46:35 -0400 Subject: [javascript/en] Small typo fix Just a simple 1-word typo fix --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 937354eb..9c4f06fc 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -324,7 +324,7 @@ i; // = 5 - not undefined as you'd expect in a block-scoped language // scope. (function(){ var temporary = 5; - // We can access the global scope by assiging to the "global object", which + // We can access the global scope by assigning to the "global object", which // in a web browser is always `window`. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10; -- cgit v1.2.3 From b0ae4db5589ce91ca52f9aece0cf065524c027fe Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sun, 18 Oct 2015 08:23:59 -0300 Subject: =?UTF-8?q?Iniciando=20tradu=C3=A7=C3=A3o=20do=20MatLab=20para=20P?= =?UTF-8?q?T-BR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/matlab.html.markdown | 531 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 531 insertions(+) create mode 100644 pt-br/matlab.html.markdown diff --git a/pt-br/matlab.html.markdown b/pt-br/matlab.html.markdown new file mode 100644 index 00000000..7c0760d1 --- /dev/null +++ b/pt-br/matlab.html.markdown @@ -0,0 +1,531 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] +translators: + - ["Claudson Martins", "https://github.com/claudsonm"] +lang: pt-br + +--- + +MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática. + +Se você tem algum feedback, por favor fique a vontade para me contactar via +[@the_ozzinator](https://twitter.com/the_ozzinator), ou +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```matlab +% Comentários iniciam com um sinal de porcentagem + +%{ +Comentários de múltiplas linhas +parecem +com +algo assim +%} + +% comandos podem ocupar várinhas linhas, usando '...': + a = 1 + 2 + ... + + 4 + +% comandos podem ser passados para o sistema operacional +!ping google.com + +who % Exibe todas as variáveis na memória +whos % Exibe todas as variáveis na memória, com seus tipos +clear % Apaga todas as suas variáveis da memória +clear('A') % Apaga uma variável em particular +openvar('A') % Abre a variável no editor de variável + +clc % Apaga o conteúdo escrito na sua janela de comando +diary % Alterna o conteúdo escrito na janela de comando para um arquivo de texto +ctrl-c % Aborta a computação atual + +edit('minhafuncao.m') % Abre a função/script no editor +type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando + +profile on % Ativa o perfil de código +profile off % Desativa o perfil de código +profile viewer % Visualiza os resultados na janela de Profiler + +help comando % Exibe a documentação do comando na janela de comando +doc comando % Exibe a documentação do comando na janela de ajuda +lookfor comando % Procura por comando na primeira linha comentada de todas as funções +lookfor comando -all % Procura por comando em todas as funções + + +% Formatação de saída +format short % 4 casas decimais em um número flutuante +format long % 15 casas decimais +format bank % 2 dígitos após o ponto decimal - para cálculos financeiros +fprintf('texto') % Imprime na tela "texto" +disp('texto') % Imprime na tela "texto" + +% Variáveis & Expressões +minhaVariavel = 4 % O painel Workspace mostra a variável recém-criada +minhaVariavel = 4; % Ponto e vírgula suprime a saída para a janela de comando +4 + 6 % Resposta = 10 +8 * minhaVariavel % Resposta = 32 +2 ^ 3 % Resposta = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% A chamada de funções pode ser feita por uma das duas maneiras: +% Sintaxe de função padrão: +load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula +% Sintaxe de comando: +load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas +% Observe a falta de aspas no formulário de comando: entradas são sempre +% passadas como texto literal - não pode passar valores de variáveis. +% Além disso, não pode receber saída: +[V,D] = eig(A); % this has no equivalent in command form +[~,D] = eig(A); % if you only want D and not V + + + +% Logicals +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % Not equal to -> ans = 1 +3 == 3 % equal to -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Logicals can be applied to matrices: +A > 5 +% for each element, if condition is true, that element is 1 in returned matrix +A( A > 5 ) +% returns a vector containing the elements in A for which condition is true + +% Strings +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Cells +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - returns a cell +char(a(1)) % ans = one - returns a string + +% Structures +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; + +% Vectors +x = [4 32 53 7 1] +x(2) % ans = 32, indices in Matlab start 1, not 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Column vector + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrices +A = [1 2 3; 4 5 6; 7 8 9] +% Rows are separated by a semicolon; elements are separated with space or comma +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(6) % ans = 8 +% (implicitly concatenates columns into vector, then indexes into that) + + +A(2,3) = 42 % Update row 2 col 3 with 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Creates a new matrix from the old one +%ans = + +% 5 42 +% 8 9 + +A(:,1) % All rows in column 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % All columns in row 1 +%ans = + +% 1 2 3 + +[A ; A] % Concatenation of matrices (vertically) +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% this is the same as +vertcat(A,A); + + +[A , A] % Concatenation of matrices (horizontally) + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% this is the same as +horzcat(A,A); + + +A(:, [3 1 2]) % Rearrange the columns of original matrix +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % ans = 3 3 + +A(1, :) =[] % Delete the first row of the matrix +A(:, 1) =[] % Delete the first column of the matrix + +transpose(A) % Transpose the matrix, which is the same as: +A one +ctranspose(A) % Hermitian transpose the matrix +% (the transpose, followed by taking complex conjugate of each element) + + + + +% Element by Element Arithmetic vs. Matrix Arithmetic +% On their own, the arithmetic operators act on whole matrices. When preceded +% by a period, they act on each element instead. For example: +A * B % Matrix multiplication +A .* B % Multiple each element in A by its corresponding element in B + +% There are several pairs of functions, where one acts on each element, and +% the other (whose name ends in m) acts on the whole matrix. +exp(A) % exponentiate each element +expm(A) % calculate the matrix exponential +sqrt(A) % take the square root of each element +sqrtm(A) % find the matrix whose square is A + + +% Plotting +x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 +y = sin(x); +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot +legend('Line 1 label', 'Line 2 label') % Label curves with a legend + +% Alternative method to plot multiple functions in one plot. +% while 'hold' is on, commands add to existing graph rather than replacing it +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % A log-log plot +semilogx(x, y) % A plot with logarithmic x-axis +semilogy(x, y) % A plot with logarithmic y-axis + +fplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5 + +grid on % Show grid; turn off with 'grid off' +axis square % Makes the current axes region square +axis equal % Set aspect ratio so data units are the same in every direction + +scatter(x, y); % Scatter-plot +hist(x); % Histogram + +z = sin(x); +plot3(x,y,z); % 3D line plot + +pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value +contour(A) % Contour plot of matrix +mesh(A) % Plot as a mesh surface + +h = figure % Create new figure object, with handle f +figure(h) % Makes the figure corresponding to handle h the current figure +close(h) % close figure with handle h +close all % close all open figure windows +close % close current figure window + +shg % bring an existing graphics window forward, or create new one if needed +clf clear % clear current figure window, and reset most figure properties + +% Properties can be set and changed through a figure handle. +% You can save a handle to a figure when you create it. +% The function gcf returns a handle to the current figure +h = plot(x, y); % you can save a handle to a figure when you create it +set(h, 'Color', 'r') +% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +set(h, 'LineStyle', '--') + % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line +get(h, 'LineStyle') + + +% The function gca returns a handle to the axes for the current figure +set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis + +% To create a figure that contains several axes in tiled positions, use subplot +subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots +plot(x1); title('First Plot') % plot something in this position +subplot(2,3,2); % select second position in the grid +plot(x2); title('Second Plot') % plot something there + + +% To use functions or scripts, they must be on your path or current directory +path % display current path +addpath /path/to/dir % add to path +rmpath /path/to/dir % remove from path +cd /path/to/move/into % change directory + + +% Variables can be saved to .mat files +save('myFileName.mat') % Save the variables in your Workspace +load('myFileName.mat') % Load saved variables into Workspace + +% M-file Scripts +% A script file is an external file that contains a sequence of statements. +% They let you avoid repeatedly typing the same code in the Command Window +% Have .m extensions + +% M-file Functions +% Like scripts, and have the same .m extension +% But can accept input arguments and return an output +% Also, they have their own workspace (ie. different variable scope). +% Function name should match file name (so save this example as double_input.m). +% 'help double_input.m' returns the comments under line beginning function +function output = double_input(x) + %double_input(x) returns twice the value of x + output = 2*x; +end +double_input(6) % ans = 12 + + +% You can also have subfunctions and nested functions. +% Subfunctions are in the same file as the primary function, and can only be +% called by functions in the file. Nested functions are defined within another +% functions, and have access to both its workspace and their own workspace. + +% If you want to create a function without creating a new file you can use an +% anonymous function. Useful when quickly defining a function to pass to +% another function (eg. plot with fplot, evaluate an indefinite integral +% with quad, find roots with fzero, or find minimum with fminsearch). +% Example that returns the square of it's input, assigned to to the handle sqr: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % find out more + +% User input +a = input('Enter the value: ') + +% Stops execution of file and gives control to the keyboard: user can examine +% or change variables. Type 'return' to continue execution, or 'dbquit' to exit +keyboard + +% Reading in data (also xlsread/importdata/imread for excel/CSV/image files) +fopen(filename) + +% Output +disp(a) % Print out the value of variable a +disp('Hello World') % Print out a string +fprintf % Print to Command Window with more control + +% Conditional statements (the parentheses are optional, but good style) +if (a > 15) + disp('Greater than 15') +elseif (a == 23) + disp('a is 23') +else + disp('neither condition met') +end + +% Looping +% NB. looping over elements of a vector/matrix is slow! +% Where possible, use functions that act on whole vector/matrix at once +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Timing code execution: 'toc' prints the time since 'tic' was called +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Connecting to a MySQL Database +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % Example sql statement +a = fetch(conn, sql) %a will contain your data + + +% Common math functions +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % Uniformly distributed pseudorandom numbers +randi % Uniformly distributed pseudorandom integers +randn % Normally distributed pseudorandom numbers + +% Common constants +pi +NaN +inf + +% Solving matrix equations (if no solution, returns a least squares solution) +% The \ and / operators are equivalent to the functions mldivide and mrdivide +x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b. +x=b/A % Solves xA=b + +inv(A) % calculate the inverse matrix +pinv(A) % calculate the pseudo-inverse + +% Common matrix functions +zeros(m,n) % m x n matrix of 0's +ones(m,n) % m x n matrix of 1's +diag(A) % Extracts the diagonal elements of a matrix A +diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere +eye(m,n) % Identity matrix +linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 +inv(A) % Inverse of matrix A +det(A) % Determinant of A +eig(A) % Eigenvalues and eigenvectors of A +trace(A) % Trace of matrix - equivalent to sum(diag(A)) +isempty(A) % Tests if array is empty +all(A) % Tests if all elements are nonzero or true +any(A) % Tests if any elements are nonzero or true +isequal(A, B) % Tests equality of two arrays +numel(A) % Number of elements in matrix +triu(x) % Returns the upper triangular part of x +tril(x) % Returns the lower triangular part of x +cross(A,B) % Returns the cross product of the vectors A and B +dot(A,B) % Returns scalar product of two vectors (must have the same length) +transpose(A) % Returns the transpose of A +fliplr(A) % Flip matrix left to right +flipud(A) % Flip matrix up to down + +% Matrix Factorisations +[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix +[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues +[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order + +% Common vector functions +max % largest component +min % smallest component +length % length of a vector +sort % sort in ascending order +sum % sum of elements +prod % product of elements +mode % modal value +median % median value +mean % mean value +std % standard deviation +perms(x) % list all permutations of elements of x + + +% Classes +% Matlab can support object-oriented programming. +% Classes must be put in a file of the class name with a .m extension. +% To begin, we create a simple class to store GPS waypoints. +% Begin WaypointClass.m +classdef WaypointClass % The class name. + properties % The properties of the class behave like Structures + latitude + longitude + end + methods + % This method that has the same name of the class is the constructor. + function obj = WaypointClass(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Other functions that use the Waypoint object + function r = multiplyLatBy(obj, n) + r = n*[obj.latitude]; + end + + % If we want to add two Waypoint objects together without calling + % a special function we can overload Matlab's arithmetic like so: + function r = plus(o1,o2) + r = WaypointClass([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End WaypointClass.m + +% We can create an object of the class using the constructor +a = WaypointClass(45.0, 45.0) + +% Class properties behave exactly like Matlab Structures. +a.latitude = 70.0 +a.longitude = 25.0 + +% Methods can be called in the same way as functions +ans = multiplyLatBy(a,3) + +% The method can also be called using dot notation. In this case, the object +% does not need to be passed to the method. +ans = a.multiplyLatBy(a,1/3) + +% Matlab functions can be overloaded to handle objects. +% In the method above, we have overloaded how Matlab handles +% the addition of two Waypoint objects. +b = WaypointClass(15.0, 32.0) +c = a + b + +``` + +## More on Matlab + +* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* The official MATLAB Answers forum: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) + -- cgit v1.2.3 From 1aaf79b6e56b7d4947335dd60613f8096b66b0d9 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 13:26:58 +0200 Subject: [coffeescript/it] Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: 7afadb01811e1fb97a928a0e2d8b1a3b7a3a42f6 960ee4a1856db8eadb96277bb2422edfa8f2a81c a67d9d9e0ed3d351ce0139de18a4b212b47ab9cb d115a86ac8602c680a059e7a53d227cbccdf157a ef40704f9b66ae85d7a8a6853abbbf8810af3b90 --- it-it/coffeescript-it.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown index 16eb9bd4..d30ba819 100644 --- a/it-it/coffeescript-it.html.markdown +++ b/it-it/coffeescript-it.html.markdown @@ -59,34 +59,34 @@ matematica = quadrato: quadrato cubo: (x) -> x * quadrato x #=> var matematica = { -# "radice": Math.sqrt, -# "quadrato": quadrato, -# "cubo": function(x) { return x * quadrato(x); } -#} +# "radice": Math.sqrt, +# "quadrato": quadrato, +# "cubo": function(x) { return x * quadrato(x); } +# } # Splats: gara = (vincitore, partecipanti...) -> print vincitore, partecipanti #=>gara = function() { -# var partecipanti, vincitore; -# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; -# return print(vincitore, partecipanti); -#}; +# var partecipanti, vincitore; +# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vincitore, partecipanti); +# }; # Esistenza: alert "Lo sapevo!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Lo sapevo!"); } # Comprensione degli Array: -cubi = (matematica.cubo num for num in lista) +cubi = (matematica.cubo num for num in lista) #=>cubi = (function() { -# var _i, _len, _results; -# _results = []; -# for (_i = 0, _len = lista.length; _i < _len; _i++) { -# num = lista[_i]; -# _results.push(matematica.cubo(num)); -# } -# return _results; +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = lista.length; _i < _len; _i++) { +# num = lista[_i]; +# _results.push(matematica.cubo(num)); +# } +# return _results; # })(); cibi = ['broccoli', 'spinaci', 'cioccolato'] -- cgit v1.2.3 From ade3e872abaa21bb00bc0eaafdabce8bc5039399 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 13:34:40 +0200 Subject: [elixir/it] Bring this version up to date with the english one The following commits were taken into consideration and translated into italian: d8001da79909734d333de31079ca2f4d884a6b21 65f951d87c80deff6c447faa4690dcfe1bb4d36a 07e04e7a2d0f2b7269e4495c338b039a30f70e64 --- it-it/elixir-it.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown index f5d0c172..d4a7ab54 100644 --- a/it-it/elixir-it.html.markdown +++ b/it-it/elixir-it.html.markdown @@ -379,6 +379,12 @@ spawn(f) #=> #PID<0.40.0> # Per passare messaggi si usa l'operatore `send`. # 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, +# 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 def calcolo_area do receive do @@ -394,6 +400,8 @@ end # Compila il modulo e crea un processo che esegue `calcolo_area` nella shell 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 send pid, {:rettangolo, 2, 3} -- cgit v1.2.3 From 90334770b6ffe4e690aedc20f678be95a93177d4 Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 18 Oct 2015 13:36:42 +0200 Subject: Add myself as a translator --- it-it/coffeescript-it.html.markdown | 2 ++ it-it/elixir-it.html.markdown | 2 ++ 2 files changed, 4 insertions(+) diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown index d30ba819..31973369 100644 --- a/it-it/coffeescript-it.html.markdown +++ b/it-it/coffeescript-it.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Luca 'Kino' Maroni", "http://github.com/kino90"] - ["Tenor Biel", "http://github.com/L8D"] - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] filename: coffeescript-it.coffee lang: it-it --- diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown index d4a7ab54..60301b1a 100644 --- a/it-it/elixir-it.html.markdown +++ b/it-it/elixir-it.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Luca 'Kino' Maroni", "https://github.com/kino90"] - ["Joao Marques", "http://github.com/mrshankly"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] filename: learnelixir-it.ex lang: it-it --- -- cgit v1.2.3 From 670e71c4990aefe739f108e15bf707eaf795f922 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sun, 18 Oct 2015 13:47:03 +0200 Subject: [git/en] Fixed 'git pull' documentation While translating git.html.markdown to Italian, I found a mistake: `git pull` does not default to `git pull origin master`. By default, it updates the current branch by merging changes from its remote-tracking branch. --- git.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index f678f9d1..ed9aec15 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -371,9 +371,12 @@ Pulls from a repository and merges it with another branch. # Update your local repo, by merging in new changes # from the remote "origin" and "master" branch. # git pull -# git pull => implicitly defaults to => git pull origin master $ git pull origin master +# By default, git pull will update your current branch +# by merging in new changes from its remote-tracking branch +$ git pull + # Merge in changes from remote branch and rebase # branch commits onto your local repo, like: "git pull , git rebase " $ git pull origin master --rebase -- cgit v1.2.3 From 6d20f58cbd3022fb8990ace8f88f8f4c15591a88 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sun, 18 Oct 2015 13:54:06 +0200 Subject: [git/en] Fixed 'git push' documentation The 'git push' documentation had the same problem of the 'git pull' one I just fixed. --- git.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index ed9aec15..bedc9853 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -390,9 +390,12 @@ Push and merge changes from a branch to a remote & branch. # Push and merge changes from a local repo to a # remote named "origin" and "master" branch. # git push -# git push => implicitly defaults to => git push origin master $ git push origin master +# By default, git push will push and merge changes from +# the current branch to its remote-tracking branch +$ git push + # To link up current local branch with a remote branch, add -u flag: $ git push -u origin master # Now, anytime you want to push from that same local branch, use shortcut: -- cgit v1.2.3 From 13adcc49e616d81a8d89179e95619846eaf6f9b1 Mon Sep 17 00:00:00 2001 From: Chris54721 Date: Sun, 18 Oct 2015 14:14:51 +0200 Subject: Translated git.html.markdown into Italian --- it-it/git-it.html.markdown | 497 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 497 insertions(+) create mode 100644 it-it/git-it.html.markdown diff --git a/it-it/git-it.html.markdown b/it-it/git-it.html.markdown new file mode 100644 index 00000000..42510192 --- /dev/null +++ b/it-it/git-it.html.markdown @@ -0,0 +1,497 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] +translators: + - ["Christian Grasso", "http://chris54721.net"] +filename: LearnGit.txt +--- + +Git è un sistema di +[controllo versione distribuito](https://it.wikipedia.org/wiki/Controllo_versione_distribuito) +e di gestione del codice sorgente. + +Git esegue una serie di _snapshot_ per salvare lo stato di un progetto, così +facendo può fornirti la possibilità di gestire il tuo codice e di salvarne lo +stato assegnando delle versioni. + +## Basi del controllo versione + +### Cos'è il controllo versione? + +Il controllo versione (_Version Control_ o _Versioning_) è un sistema che +registra le modifiche apportate a uno o più file nel tempo. + +### Controllo versione centralizzato e distribuito + +* Il controllo versione centralizzato si concentra sulla sincronizzazione, il + monitoraggio e il backup dei file. +* Il controllo versione distribuito si concentra sulla condivisione delle + modifiche. Ogni modifica ha un identificatore univoco. +* I sistemi distribuiti non hanno una struttura definita. Si potrebbe creare + ad esempio un sistema centralizzato simile a SVN utilizzando Git. + +[Ulteriori informazioni](http://git-scm.com/book/it/v1/Per-Iniziare-Il-Controllo-di-Versione) + +### Perchè usare Git? + +* Consente di lavorare offline. +* Collaborare con altre persone è semplice! +* Utilizzare i branch (rami di sviluppo) è semplice! +* Git è veloce. +* Git è flessibile. + +## Architettura di Git + +### Repository + +Un insieme di file, cartelle, registrazioni della cronologia e versioni. +Immaginalo come una struttura dati del codice, con la caratteristica che ogni +"elemento" del codice ti fornisce accesso alla sua cronologia delle revisioni, +insieme ad altre cose. + +Un repository comprende la cartella .git e il working tree. + +### Cartella .git (componente del repository) + +La cartella .git contiene tutte le configurazioni, i log, i rami e altro. +[Lista dettagliata](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Working Tree (componente del repository) + +Si tratta semplicemente delle cartelle e dei file presenti nel repository. +Spesso viene indicato come "directory di lavoro" ("working directory"). + +### Index (componente della cartella .git) + +L'Index è l'area di staging di Git. Si tratta di un livello che separa il +working tree dal repository. Ciò fornisce agli sviluppatori più controllo su +cosa viene inviato al repository. + +### Commit + +Un commit è uno snapshot di una serie di modifiche apportate al working tree. +Ad esempio, se hai aggiunto 5 file e ne hai rimossi 2, ciò sarà registrato in +un commit. Il commit può essere pushato (inviato) o meno ad altri repository. + +### Branch (ramo) + +Un branch (ramo) è essenzialmente un puntatore all'ultimo commit che hai +effettuato. Effettuando altri commit, il puntatore verrà automaticamente +aggiornato per puntare all'ultimo commit. + +### Tag + +Un tag è un contrassegno applicato a un punto specifico nella cronologia dei +commit. Di solito i tag vengono utilizzati per contrassegnare le versioni +rilasciate (v1.0, v1.1, etc.). + +### HEAD e head (componenti della cartella .git) + +HEAD (in maiuscolo) è un puntatore che punta al branch corrente. Un repository +può avere solo 1 puntatore HEAD *attivo*. + +head (in minuscolo) è un puntatore che può puntare a qualsiasi commit. Un +repository può avere un numero qualsiasi di puntatori head. + +### Stadi di Git +* _Modified_ - Un file è stato modificato, ma non è ancora stato effettuato + un commit per registrare le modifiche nel database di Git +* _Staged_ - Un file modificato è stato contrassegnato per essere incluso nel + prossimo commit +* _Committed_ - È stato effettuato un commit e le modifiche sono state + registrate nel database di Git + +## Comandi + +### init + +Crea un repository Git vuoto. Le impostazioni e le informazioni del repository +sono salvate nella cartella ".git". + +```bash +$ git init +``` + +### config + +Utilizzato per configurare le impostazioni, sia specifiche del repository, sia +a livello globale. Le impostazioni globali sono salvate in `~/.gitconfig`. + +```bash +$ git config --global user.email "email@example.com" +$ git config --global user.name "Nome utente" +``` + +[Ulteriori informazioni su git config](http://git-scm.com/docs/git-config) + +### help + +Fornisce una documentazione molto dettagliata di ogni comando. + +```bash +# Mostra i comandi più comuni +$ git help + +# Mostra tutti i comandi disponibili +$ git help -a + +# Documentazione di un comando specifico +# git help +$ git help add +$ git help commit +$ git help init +# oppure git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### Ignorare file + +Per impedire intenzionalmente che file privati o temporanei vengano inviati +al repository Git. + +```bash +$ echo "temp/" >> .gitignore +$ echo "privato.txt" >> .gitignore +``` + + +### status + +Mostra le differenza tra lo stato attuale del working tree e l'attuale commit +HEAD. + +```bash +$ git status +``` + +### add + +Aggiunge file alla staging area, ovvero li contrassegna per essere inclusi nel +prossimo commit. Ricorda di aggiungere i nuovi file, altrimenti non saranno +inclusi nei commit! + +```bash +# Aggiunge un file nella directory attuale +$ git add HelloWorld.java + +# Aggiunge un file in una sottocartella +$ git add /path/to/file/HelloWorld.c + +# Il comando supporta le espressioni regolari +$ git add ./*.java + +# Aggiunge tutti i file non ancora contrassegnati +$ git add --all +``` + +Questo comando contrassegna soltanto i file, senza effettuare un commit. + +### branch + +Utilizzato per gestire i branch (rami). Puoi visualizzare, modificare, creare o +eliminare branch utilizzando questo comando. + +```bash +# Visualizza i branch e i remote +$ git branch -a + +# Crea un nuovo branch +$ git branch nuovoBranch + +# Elimina un branch +$ git branch -d nomeBranch + +# Rinomina un branch +$ git branch -m nomeBranch nuovoNomeBranch + +# Permette di modificare la descrizione di un branch +$ git branch nomeBranch --edit-description +``` + +### tag + +Utilizzato per gestire i tag. + +```bash +# Visualizza i tag esistenti +$ git tag +# Crea un nuovo tag +# L'opzione -m consente di specificare una descrizione per il tag. +# Se l'opzione -m non viene aggiunta, Git aprirà un editor per consentire +# l'inserimento del messaggio. +$ git tag -a v2.0 -m 'Versione 2.0' +# Mostra informazioni relative a un tag +# Include informazioni sul creatore del tag, la data di creazione, e il +# messaggio assegnato al tag oltre alle informazioni sul commit. +$ git show v2.0 +``` + +### checkout + +Consente di cambiare branch o ripristinare i file a una revisione specifica. +Tutti i file nel working tree vengono aggiornati per corrispondere alla versione +presente nel branch o nel commit specificato. + +```bash +# Effettua il checkout di un repository - il branch predefinito è 'master' +$ git checkout +# Effettua il checkout di un branch specifico +$ git checkout nomeBranch +# Crea un nuovo branch e ne effettua il checkout +# Equivalente a "git branch ; git checkout " +$ git checkout -b nuovoBranch +``` + +### clone + +Clona, o copia, un repository esistente in una nuova directory. Inoltre, +aggiunge dei branch _remote-tracking_, utilizzati per monitorare i branch +remoti corrispondenti a quelli locali, e consentendo così di inviare le +modifiche al repository remoto. + +```bash +# Clona learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +# Clona solo l'ultima revisione di un repository +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git +# Clona solo un branch specifico +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Effettua uno _snapshot_ dello stato attuale del working tree e registra le +modifiche in un nuovo commit. Il commit contiene, oltre alle modifiche apportate, +anche l'autore e una descrizione. + +```bash +# Crea un nuovo commit con un messaggio +$ git commit -m "Aggiunta la funzione multiplyNumbers() in HelloWorld.c" + +# Aggiunge (git add) automaticamente i file modificati o eliminati (ESCLUSI +# i nuovi file) e quindi effettua il commit +$ git commit -a -m "Modificato foo.php e rimosso bar.php" + +# Modifica l'ultimo commit (il comando elimina il commit precedente e lo +# sostituisce con uno nuovo) +$ git commit --amend -m "Messaggio corretto" +``` + +### diff + +Mostra la differenza tra un file nel working tree e la sua versione nell'index, +in un branch o ad un commit specifico. + +```bash +# Mostra la differenza tra il working tree e l'index +$ git diff + +# Mostra la differenza tra l'index e il commit più recente +$ git diff --cached + +# Mostra la differenza tra il working tree e un commit specifico +$ git diff + +# Mostra la differenza tra due commit +$ git diff +``` + +### grep + +Consente di effettuare una ricerca veloce nel repository. + +```bash +# Cerca "variableName" nei file Java +$ git grep 'variableName' -- '*.java' + +# Cerca una riga contenente "arrayListName" E "add" oppure "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Impostazioni relative a `git grep`: + +```bash +# Mostra il numero delle righe +$ git config --global grep.lineNumber true + +# Rende i risultati più leggibili +$ git config --global alias.g "grep --break --heading --line-number" +``` + +### log + +Mostra la cronologia dei commit inviati al repository. + +```bash +# Mostra tutti i commit +$ git log + +# Mostra ogni commit su una sola riga +$ git log --oneline + +# Mostra solo i commit legati ai merge +$ git log --merges +``` + +### merge + +Effettua un "merge", ovvero unisce le modifiche di un branch in quello attuale. + +```bash +# Unisce il branch specificato a quello attuale +$ git merge nomeBranch + +# Genera un commit in ogni caso dopo aver eseguito il merge +$ git merge --no-ff nomeBranch +``` + +### mv + +Rinomina o sposta un file. + +```bash +# Rinomina un file +$ git mv HelloWorld.c HelloNewWorld.c + +# Sposta un file +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Forza l'esecuzione del comando +# Se un file "nuovoNomeFile" esiste già nella directory, verrà sovrascritto +$ git mv -f nomeFile nuovoNomeFile +``` + +### pull + +Aggiorna il repository effettuando il merge delle nuove modifiche. + +```bash +# Aggiorna il branch attuale dal remote "origin" +$ git pull + +# Di default, git pull aggiorna il branch attuale effettuando il merge +# delle nuove modifiche presenti nel branch remote-tracking corrispondente +$ git pull + +# Aggiorna le modifiche dal branch remoto, quindi effettua il rebase dei commit +# nel branch locale +# Equivalente a: "git pull ; git rebase " +$ git pull origin master --rebase +``` + +### push + +Invia ed effettua il merge delle modifiche da un branch locale ad uno remoto. + +```bash +# Invia ed effettua il merge delle modifiche dal branch "master" +# al remote "origin". +# git push +$ git push origin master + +# Di default, git push invia ed effettua il merge delle modifiche +# dal branch attuale al branch remote-tracking corrispondente +$ git push + +# Per collegare il branch attuale ad uno remoto, basta aggiungere l'opzione -u +$ git push -u origin master +``` + +### stash + +Salva lo stato attuale del working tree in una lista di modifiche non ancora +inviate al repository con un commit che possono essere applicate nuovamente +in seguito. + +Questo comando può essere utile se, ad esempio, mentre stai effettuando delle +modifiche non ancora completate, hai bisogno di aggiornare il repository locale +con `git pull`. Poichè non hai ancora effettuato il commit di tutte le modifiche, +non sarà possibile effettuare il pull. Tuttavia, puoi utilizzare `git stash` per +salvare temporaneamente le modifiche e applicarle in seguito. + +```bash +$ git stash +``` + +Ora puoi effettuare il pull: + +```bash +$ git pull +``` + +A questo punto, come già suggerito dall'output del comando `git stash`, puoi +applicare le modifiche: + +```bash +$ git stash apply +``` + +Infine puoi controllare che tutto sia andato bene: + +```bash +$ git status +``` + +Puoi visualizzare gli accantonamenti che hai effettuato finora utilizzando: + +```bash +$ git stash list +``` + +### rebase (attenzione) + +Applica le modifiche effettuate su un branch su un altro branch. +*Non effettuare il rebase di commit che hai già inviato a un repository pubblico!* + +```bash +# Effettua il rebase di experimentBranch in master +$ git rebase master experimentBranch +``` + +[Ulteriori informazioni](https://git-scm.com/book/it/v1/Diramazioni-in-Git-Rifondazione) + +### reset (attenzione) + +Effettua il reset del commit HEAD attuale ad uno stato specifico. +Questo comando consente di annullare `merge`, `pull`, `commit`, `add` e altro. +Tuttavia, può essere pericoloso se non si sa cosa si sta facendo. + +```bash +# Effettua il reset della staging area (annullando le aggiunte e le rimozioni +# di file dal repository, senza modificare il working tree) +$ git reset + +# Effettua il reset completo della staging area, ovvero annulla qualsiasi +# modifica al repository eliminando definitivamente anche tutte le modifiche +# ai file non inviate e ripristinando il working tree +$ git reset --hard + +# Effettua il reset del branch attuale al commit specificato (lasciando il +# working tree intatto) +$ git reset 31f2bb1 + +# Effettua il reset completo del branch attuale al commit specificato, +# eliminando qualsiasi modifica non inviata +$ git reset --hard 31f2bb1 +``` + +### rm + +Consente di rimuovere un file dal working tree e dal repository. +Per eliminare un file solo dal working tree ma non dal repository, è invece +necessario utilizzare `/bin/rm`. + +```bash +# Elimina un file nella directory attuale +$ git rm HelloWorld.c + +# Elimina un file da una sottocartella +$ git rm /pather/to/the/file/HelloWorld.c +``` -- cgit v1.2.3 From 6b58f22ec9bd3809f39a6ba62bcac02161fc6214 Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Sun, 18 Oct 2015 18:07:43 +0200 Subject: First version of Make to german translation --- de-de/make-de.html.markdown | 260 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 de-de/make-de.html.markdown diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown new file mode 100644 index 00000000..bed7abf3 --- /dev/null +++ b/de-de/make-de.html.markdown @@ -0,0 +1,260 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] +translators: + - ["Martin Schimandl", "https://github.com/Git-Jiro"] +filename: Makefile +lang: de-de +--- + +Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele) +zu erzeugen. Es dient dazu die geringste Menge an Arbeit zu verrichten um +ein Ziel in einklang mit dem Quellcode zu bringen. Make wurde berühmterweise +von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer +sehr verbreitet (vorallem im Unix umfeld) obwohl es bereits sehr viel +Konkurrenz und Kritik zu Make gibt. + +Es gibt eine vielzahl an Varianten von Make, dieser Artikel beschäftig sich +mit der Version GNU Make. Diese Version ist standard auf Linux. + +```make + +# Kommentare können so geschrieben werden. + +# Dateien sollten Makefile heißen, denn dann können sie als `make ` +# aufgerufen werden. Ansonsten muss `make -f "dateiname" ` verwendet +# werden. + +# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet +# werden. Niemals Leerzeichen! + +#----------------------------------------------------------------------- +# Grundlagen +#----------------------------------------------------------------------- + +# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt +# nicht existiert. +file0.txt: + echo "foo" > file0.txt + # Selbst Kommentare in der 'Rezept' Sektion werden an die Shell + # weitergegeben. Versuche `make file0.txt` oder einfach `make` + # die erste Regel ist die Standard-Regel. + + +# Diese Regel wird nur abgearbeitet wenn file0.txt aktueller als file1.txt ist. +file1.txt: file0.txt + cat file0.txt > file1.txt + # Verwende die selben Quoting-Regeln wie die Shell + @cat file0.txt >> file1.txt + # @ unterdrückt die Ausgabe des Befehls an stdout. + -@echo 'hello' + # - bedeutet das Make die Abarbeitung fortsetzt auch wenn Fehler passieren. + # Versuche `make file1.txt` auf der Kommandozeile. + +# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben. +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make wird sich beschweren wenn es mehrere Rezepte für die gleiche Regel gibt. +# Leere Rezepte zählen nicht und können dazu verwendet werden weitere +# Voraussetzungen hinzuzufügen. + +#----------------------------------------------------------------------- +# Phony-Ziele +#----------------------------------------------------------------------- + +# Ein Phony-Ziel ist ein Ziel das keine Datei ist. +# Es wird nie aktuell sein, daher wird Make immer versuchen es abzuarbeiten +all: maker process + +# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren. +maker: + touch ex0.txt ex1.txt + +# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den +# selben namen wie ein Phony-Ziel hat: +.PHONY: all maker process +# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon. + +# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet +ex0.txt ex1.txt: maker + +# Häufige Phony-Ziele sind: all make clean install ... + +#----------------------------------------------------------------------- +# Automatische Variablen & Wildcards +#----------------------------------------------------------------------- + +process: file*.txt # Eine Wildcard um Dateinamen zu Vergleichen + @echo $^ # $^ ist eine Variable die eine Liste aller + # Voraussetzungen enthält. + @echo $@ # Namen des Ziels ausgeben. + #(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung + #der Regel.) + @echo $< # Die erste Voraussetzung aus der Liste + @echo $? # Nur die Voraussetzungen die nicht aktuell sind. + @echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich) + #@echo $| # Alle 'order only' Voraussetzungen + +# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden. +process: ex1.txt file0.txt +# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert. + +#----------------------------------------------------------------------- +# Muster +#----------------------------------------------------------------------- + +# Mit Mustern kann man make beibringen wie Dateien in andere Dateien +# umgewandelt werden. + +%.png: %.svg + inkscape --export-png $^ + +# Muster-Vergleichs-Regeln werden nur abgearbeitet wenn make entscheidet das Ziel zu +# erzeugen + +# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert. +# Aber make wird versuchen die am besten passende Regel zu verwenden. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden die es +# findet. +%.png: %.svg + @echo this rule is chosen + +# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden die das +# Ziel erzeugen kann. +%.png: %.ps + @echo this rule is not chosen if *.svg and *.ps are both present + +# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel +# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt. + +# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt +# Muster-Vergleichs-Regeln. +.png.ps: + @echo this rule is similar to a pattern rule. + +# Aktivieren der Suffix-Regel +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variablen +#----------------------------------------------------------------------- +# auch Makros genannt. + +# Variablen sind im Grunde genommen Zeichenketten-Typen. + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Das funktioniert nicht, wird als $(n)ame behandelt. + @echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt. + +# Es git 4 Stellen um Variablen zu setzen. +# In Reihenfolge der Priorität von höchster zu niedrigster: +# 1: Befehls-Zeilen Argumente +# 2: Makefile +# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch. +# 3: MAke hat einige vordefinierte Variablen. + +name4 ?= Jean +# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch +# nicht gibt. + +override name5 = David +# Verhindert das Kommando-Zeilen Argumente diese Variable ändern können. + +name4 +=grey +# Werte an eine Variable anhängen (inkludiert Leerzeichen). + +# Muster-Spezifische Variablen Werte (GNU Erweiterung). +echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb + # rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören + # kann wenn es zu kompilizert wird!) + +# Ein paar Variablen die von Make automatisch definiert werden. +echo_inbuilt: + echo $(CC) + echo ${CXX)} + echo $(FC) + echo ${CFLAGS)} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variablen 2 +#----------------------------------------------------------------------- + +# Der erste Typ von Variablen wird bei jeder verwendung ausgewertet. +# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen. +# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung) + +var := hello +var2 ::= $(var) hello +#:= und ::= sind äquivalent. + +# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie +# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache! + +# Das funktioniert nicht +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funktionen +#----------------------------------------------------------------------- + +# Make verfügt über eine vielzahl von Funktionen. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# Das Format ist $(func arg0,arg1,arg2...) + +# Ein paar Beispiele +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Direktiven +#----------------------------------------------------------------------- + +# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code +include foo.mk + +sport = tennis +# Konditionale kompiliereung +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# Es gibt auch ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + + +### Mehr Resourcen + ++ [gnu make documentation](https://www.gnu.org/software/make/manual/) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) + -- cgit v1.2.3 From 5c84b03a49553856049e4d9c677b09c9a7eb9419 Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sun, 18 Oct 2015 18:38:01 +0200 Subject: [css/fr] Corrects some French mistakes --- fr-fr/css-fr.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown index bdab9715..a3a5cf55 100644 --- a/fr-fr/css-fr.html.markdown +++ b/fr-fr/css-fr.html.markdown @@ -8,7 +8,7 @@ translators: lang: fr-fr --- -Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs, +Au début du web, il n'y avait pas d'élements visuels, simplement du texte pur. Mais avec le dévelopement des navigateurs, des pages avec du contenu visuel sont arrivées. CSS est le langage standard qui existe et permet de garder une séparation entre le contenu (HTML) et le style d'une page web. @@ -16,8 +16,8 @@ le contenu (HTML) et le style d'une page web. En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents sur une page HTML afin de leur donner des propriétés visuelles différentes. -Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0 -qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur. +Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parler de CSS2.0 +qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateurs. **NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. Cet article porte principalement sur la syntaxe et quelques astuces. @@ -33,7 +33,7 @@ Cet article porte principalement sur la syntaxe et quelques astuces. /* Généralement, la première déclaration en CSS est très simple */ selecteur { propriete: valeur; /* autres proprietés...*/ } -/* Le sélécteur sert à cibler un élément du HTML +/* Le sélecteur sert à cibler un élément du HTML Vous pouvez cibler tous les éléments d'une page! */ * { color:red; } @@ -81,7 +81,7 @@ div.une-classe[attr$='eu'] { } /* Un élément qui est en enfant direct */ div.un-parent > .enfant {} -/* Cela cible aussi les .enfants plus profonds dans la structure HTML */ +/* dans la structure HTML */ div.un-parent .enfants {} /* Attention : le même sélecteur sans espace a un autre sens. */ -- cgit v1.2.3 From fe4ed9080dc258e35a9fffd3a52d097eb457c745 Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sun, 18 Oct 2015 18:39:21 +0200 Subject: Brings text back --- fr-fr/css-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown index a3a5cf55..35673c47 100644 --- a/fr-fr/css-fr.html.markdown +++ b/fr-fr/css-fr.html.markdown @@ -81,7 +81,7 @@ div.une-classe[attr$='eu'] { } /* Un élément qui est en enfant direct */ div.un-parent > .enfant {} -/* dans la structure HTML */ +/* Cela cible aussi les .enfants plus profonds dans la structure HTML */ div.un-parent .enfants {} /* Attention : le même sélecteur sans espace a un autre sens. */ -- cgit v1.2.3 From 603d72e9eaca53aeb3610eceecb9af7d0aa84e0d Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sun, 18 Oct 2015 13:41:14 -0300 Subject: Matlab portuguese translation The markdown is completely translated --- pt-br/matlab.html.markdown | 506 +++++++++++++++++++++++---------------------- 1 file changed, 255 insertions(+), 251 deletions(-) diff --git a/pt-br/matlab.html.markdown b/pt-br/matlab.html.markdown index 7c0760d1..4e822a60 100644 --- a/pt-br/matlab.html.markdown +++ b/pt-br/matlab.html.markdown @@ -26,11 +26,11 @@ com algo assim %} -% comandos podem ocupar várinhas linhas, usando '...': +% Comandos podem ocupar várinhas linhas, usando '...': a = 1 + 2 + ... + 4 -% comandos podem ser passados para o sistema operacional +% Comandos podem ser passados para o sistema operacional !ping google.com who % Exibe todas as variáveis na memória @@ -46,7 +46,7 @@ ctrl-c % Aborta a computação atual edit('minhafuncao.m') % Abre a função/script no editor type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando -profile on % Ativa o perfil de código +profile on % Ativa o perfil de código profile off % Desativa o perfil de código profile viewer % Visualiza os resultados na janela de Profiler @@ -77,97 +77,98 @@ c = exp(a)*sin(pi/2) % c = 7.3891 load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula % Sintaxe de comando: load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas -% Observe a falta de aspas no formulário de comando: entradas são sempre -% passadas como texto literal - não pode passar valores de variáveis. +% Observe a falta de aspas na forma de comando: entradas são sempre passadas +% como texto literal - não pode passar valores de variáveis. % Além disso, não pode receber saída: -[V,D] = eig(A); % this has no equivalent in command form -[~,D] = eig(A); % if you only want D and not V +[V,D] = eig(A); % Isto não tem um equivalente na forma de comando +[~,D] = eig(A); % Se você só deseja D e não V -% Logicals -1 > 5 % ans = 0 -10 >= 10 % ans = 1 -3 ~= 4 % Not equal to -> ans = 1 -3 == 3 % equal to -> ans = 1 -3 > 1 && 4 > 1 % AND -> ans = 1 -3 > 1 || 4 > 1 % OR -> ans = 1 -~1 % NOT -> ans = 0 +% Operadores Lógicos e Relacionais +1 > 5 % Resposta = 0 +10 >= 10 % Resposta = 1 +3 ~= 4 % Diferente de -> Resposta = 1 +3 == 3 % Igual a -> Resposta = 1 +3 > 1 && 4 > 1 % E -> Resposta = 1 +3 > 1 || 4 > 1 % OU -> Resposta = 1 +~1 % NOT -> Resposta = 0 -% Logicals can be applied to matrices: +% Operadores Lógicos e Relacionais podem ser aplicados a matrizes A > 5 -% for each element, if condition is true, that element is 1 in returned matrix +% Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada A( A > 5 ) -% returns a vector containing the elements in A for which condition is true +% Retorna um vetor com os elementos de A para os quais a condição é verdadeira -% Strings -a = 'MyString' -length(a) % ans = 8 -a(2) % ans = y -[a,a] % ans = MyStringMyString +% Cadeias de caracteres (Strings) +a = 'MinhaString' +length(a) % Resposta = 11 +a(2) % Resposta = i +[a,a] % Resposta = MinhaStringMinhaString -% Cells -a = {'one', 'two', 'three'} -a(1) % ans = 'one' - returns a cell -char(a(1)) % ans = one - returns a string +% Vetores de células +a = {'um', 'dois', 'três'} +a(1) % Resposta = 'um' - retorna uma célula +char(a(1)) % Resposta = um - retorna uma string -% Structures -A.b = {'one','two'}; +% Estruturas +A.b = {'um','dois'}; A.c = [1 2]; A.d.e = false; -% Vectors +% Vetores x = [4 32 53 7 1] -x(2) % ans = 32, indices in Matlab start 1, not 0 -x(2:3) % ans = 32 53 -x(2:end) % ans = 32 53 7 1 +x(2) % Resposta = 32, índices no Matlab começam por 1, não 0 +x(2:3) % Resposta = 32 53 +x(2:end) % Resposta = 32 53 7 1 -x = [4; 32; 53; 7; 1] % Column vector +x = [4; 32; 53; 7; 1] % Vetor coluna x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 -% Matrices +% Matrizes A = [1 2 3; 4 5 6; 7 8 9] -% Rows are separated by a semicolon; elements are separated with space or comma +% Linhas são separadas por um ponto e vírgula; +% Elementos são separados com espaço ou vírgula % A = % 1 2 3 % 4 5 6 % 7 8 9 -A(2,3) % ans = 6, A(row, column) -A(6) % ans = 8 -% (implicitly concatenates columns into vector, then indexes into that) +A(2,3) % Resposta = 6, A(linha, coluna) +A(6) % Resposta = 8 +% (implicitamente encadeia as colunas do vetor, e então as indexa) -A(2,3) = 42 % Update row 2 col 3 with 42 +A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42 % A = % 1 2 3 % 4 5 42 % 7 8 9 -A(2:3,2:3) % Creates a new matrix from the old one -%ans = +A(2:3,2:3) % Cria uma nova matriz a partir da antiga +%Resposta = % 5 42 % 8 9 -A(:,1) % All rows in column 1 -%ans = +A(:,1) % Todas as linhas na coluna 1 +%Resposta = % 1 % 4 % 7 -A(1,:) % All columns in row 1 -%ans = +A(1,:) % Todas as colunas na linha 1 +%Resposta = % 1 2 3 -[A ; A] % Concatenation of matrices (vertically) -%ans = +[A ; A] % Concatenação de matrizes (verticalmente) +%Resposta = % 1 2 3 % 4 5 42 @@ -176,195 +177,197 @@ A(1,:) % All columns in row 1 % 4 5 42 % 7 8 9 -% this is the same as +% Isto é o mesmo de vertcat(A,A); -[A , A] % Concatenation of matrices (horizontally) +[A , A] % Concatenação de matrizes (horizontalmente) -%ans = +%Resposta = % 1 2 3 1 2 3 % 4 5 42 4 5 42 % 7 8 9 7 8 9 -% this is the same as +% Isto é o mesmo de horzcat(A,A); -A(:, [3 1 2]) % Rearrange the columns of original matrix -%ans = +A(:, [3 1 2]) % Reorganiza as colunas da matriz original +%Resposta = % 3 1 2 % 42 4 5 % 9 7 8 -size(A) % ans = 3 3 +size(A) % Resposta = 3 3 -A(1, :) =[] % Delete the first row of the matrix -A(:, 1) =[] % Delete the first column of the matrix +A(1, :) =[] % Remove a primeira linha da matriz +A(:, 1) =[] % Remove a primeira coluna da matriz -transpose(A) % Transpose the matrix, which is the same as: +transpose(A) % Transposta a matriz, que é o mesmo de: A one -ctranspose(A) % Hermitian transpose the matrix -% (the transpose, followed by taking complex conjugate of each element) +ctranspose(A) % Transposta a matriz +% (a transposta, seguida pelo conjugado complexo de cada elemento) -% Element by Element Arithmetic vs. Matrix Arithmetic -% On their own, the arithmetic operators act on whole matrices. When preceded -% by a period, they act on each element instead. For example: -A * B % Matrix multiplication -A .* B % Multiple each element in A by its corresponding element in B +% Aritmética Elemento por Elemento vs. Aritmética com Matriz +% Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando +% precedidos por um ponto, eles atuam em cada elemento. Por exemplo: +A * B % Multiplicação de matrizes +A .* B % Multiplica cada elemento em A por seu correspondente em B -% There are several pairs of functions, where one acts on each element, and -% the other (whose name ends in m) acts on the whole matrix. -exp(A) % exponentiate each element -expm(A) % calculate the matrix exponential -sqrt(A) % take the square root of each element -sqrtm(A) % find the matrix whose square is A +% Existem vários pares de funções nas quais uma atua sob cada elemento, e a +% outra (cujo nome termina com m) age na matriz por completo. +exp(A) % Exponencia cada elemento +expm(A) % Calcula o exponencial da matriz +sqrt(A) % Tira a raiz quadrada de cada elemento +sqrtm(A) % Procura a matriz cujo quadrado é A -% Plotting -x = 0:.10:2*pi; % Creates a vector that starts at 0 and ends at 2*pi with increments of .1 +% Gráficos +x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1 y = sin(x); plot(x,y) -xlabel('x axis') -ylabel('y axis') -title('Plot of y = sin(x)') -axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 +xlabel('eixo x') +ylabel('eixo y') +title('Gráfico de y = sin(x)') +axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1 -plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot -legend('Line 1 label', 'Line 2 label') % Label curves with a legend +plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico +legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda -% Alternative method to plot multiple functions in one plot. -% while 'hold' is on, commands add to existing graph rather than replacing it +% Método alternativo para traçar várias funções em um só gráfico: +% Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico +% existente ao invés de o substituirem. plot(x, y) hold on plot(x, z) hold off -loglog(x, y) % A log-log plot -semilogx(x, y) % A plot with logarithmic x-axis -semilogy(x, y) % A plot with logarithmic y-axis +loglog(x, y) % Plotar em escala loglog +semilogx(x, y) % Um gráfico com eixo x logarítmico +semilogy(x, y) % Um gráfico com eixo y logarítmico -fplot (@(x) x^2, [2,5]) % plot the function x^2 from x=2 to x=5 +fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5 -grid on % Show grid; turn off with 'grid off' -axis square % Makes the current axes region square -axis equal % Set aspect ratio so data units are the same in every direction +grid on % Exibe as linhas de grade; Oculta com 'grid off' +axis square % Torna quadrada a região dos eixos atuais +axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções -scatter(x, y); % Scatter-plot -hist(x); % Histogram +scatter(x, y); % Gráfico de dispersão ou bolha +hist(x); % Histograma z = sin(x); -plot3(x,y,z); % 3D line plot +plot3(x,y,z); % Plotar em espaço em 3D -pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value -contour(A) % Contour plot of matrix -mesh(A) % Plot as a mesh surface +pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor +contour(A) % Plotar de contorno da matriz +mesh(A) % Plotar malha 3D -h = figure % Create new figure object, with handle f -figure(h) % Makes the figure corresponding to handle h the current figure -close(h) % close figure with handle h -close all % close all open figure windows -close % close current figure window +h = figure % Cria uma nova figura objeto, com identificador h +figure(h) % Cria uma nova janela de figura com h +close(h) % Fecha a figura h +close all % Fecha todas as janelas de figuras abertas +close % Fecha a janela de figura atual -shg % bring an existing graphics window forward, or create new one if needed -clf clear % clear current figure window, and reset most figure properties +shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário +clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura -% Properties can be set and changed through a figure handle. -% You can save a handle to a figure when you create it. -% The function gcf returns a handle to the current figure -h = plot(x, y); % you can save a handle to a figure when you create it +% Propriedades podem ser definidas e alteradas através de um identificador. +% Você pode salvar um identificador para uma figura ao criá-la. +% A função gcf retorna o identificador da figura atual +h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la set(h, 'Color', 'r') -% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +% 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto set(h, 'LineStyle', '--') - % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line + % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha get(h, 'LineStyle') -% The function gca returns a handle to the axes for the current figure -set(gca, 'XDir', 'reverse'); % reverse the direction of the x-axis +% A função gca retorna o identificador para os eixos da figura atual +set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x -% To create a figure that contains several axes in tiled positions, use subplot -subplot(2,3,1); % select the first position in a 2-by-3 grid of subplots -plot(x1); title('First Plot') % plot something in this position -subplot(2,3,2); % select second position in the grid -plot(x2); title('Second Plot') % plot something there +% Para criar uma figura que contém vários gráficos use subplot, o qual divide +% a janela de gráficos em m linhas e n colunas. +subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3 +plot(x1); title('Primeiro Plot') % Plota algo nesta posição +subplot(2,3,2); % Seleciona a segunda posição na grade +plot(x2); title('Segundo Plot') % Plota algo ali -% To use functions or scripts, they must be on your path or current directory -path % display current path -addpath /path/to/dir % add to path -rmpath /path/to/dir % remove from path -cd /path/to/move/into % change directory +% Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual +path % Exibe o caminho atual +addpath /caminho/para/pasta % Adiciona o diretório ao caminho +rmpath /caminho/para/pasta % Remove o diretório do caminho +cd /caminho/para/mudar % Muda o diretório -% Variables can be saved to .mat files -save('myFileName.mat') % Save the variables in your Workspace -load('myFileName.mat') % Load saved variables into Workspace +% Variáveis podem ser salvas em arquivos *.mat +save('meuArquivo.mat') % Salva as variáveis do seu Workspace +load('meuArquivo.mat') % Carrega as variáveis em seu Workspace -% M-file Scripts -% A script file is an external file that contains a sequence of statements. -% They let you avoid repeatedly typing the same code in the Command Window -% Have .m extensions +% Arquivos M (M-files) +% Um arquivo de script é um arquivo externo contendo uma sequência de instruções. +% Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos. +% Possuem a extensão *.m -% M-file Functions -% Like scripts, and have the same .m extension -% But can accept input arguments and return an output -% Also, they have their own workspace (ie. different variable scope). -% Function name should match file name (so save this example as double_input.m). -% 'help double_input.m' returns the comments under line beginning function -function output = double_input(x) - %double_input(x) returns twice the value of x +% Arquivos M de Funções (M-file Functions) +% Assim como scripts e têm a mesma extensão *.m +% Mas podem aceitar argumentos de entrada e retornar uma saída. +% Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis). +% O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m) +% 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função +function output = dobra_entrada(x) + %dobra_entrada(x) retorna duas vezes o valor de x output = 2*x; end -double_input(6) % ans = 12 +dobra_entrada(6) % Resposta = 12 -% You can also have subfunctions and nested functions. -% Subfunctions are in the same file as the primary function, and can only be -% called by functions in the file. Nested functions are defined within another -% functions, and have access to both its workspace and their own workspace. +% Você também pode ter subfunções e funções aninhadas. +% Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados +% por funções dentro do arquivo. Funções aninhadas são definidas dentro de +% outras funções, e têm acesso a ambos workspaces. -% If you want to create a function without creating a new file you can use an -% anonymous function. Useful when quickly defining a function to pass to -% another function (eg. plot with fplot, evaluate an indefinite integral -% with quad, find roots with fzero, or find minimum with fminsearch). -% Example that returns the square of it's input, assigned to to the handle sqr: +% Se você quer criar uma função sem criar um novo arquivo, você pode usar uma +% função anônima. Úteis para definir rapidamente uma função para passar a outra +% função (ex. plotar com fplot, avaliar uma integral indefinida com quad, +% procurar raízes com fzero, ou procurar mínimo com fminsearch). +% Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr: sqr = @(x) x.^2; -sqr(10) % ans = 100 -doc function_handle % find out more +sqr(10) % Resposta = 100 +doc function_handle % Saiba mais -% User input -a = input('Enter the value: ') +% Entrada do usuário +a = input('Digite o valor: ') -% Stops execution of file and gives control to the keyboard: user can examine -% or change variables. Type 'return' to continue execution, or 'dbquit' to exit +% Para a execução do arquivo e passa o controle para o teclado: o usuário pode +% examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair keyboard -% Reading in data (also xlsread/importdata/imread for excel/CSV/image files) -fopen(filename) +% Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem) +fopen(nomedoarquivo) -% Output -disp(a) % Print out the value of variable a -disp('Hello World') % Print out a string -fprintf % Print to Command Window with more control +% Saída +disp(a) % Imprime o valor da variável a +disp('Olá Mundo') % Imprime a string +fprintf % Imprime na janela de comandos com mais controle -% Conditional statements (the parentheses are optional, but good style) +% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática) if (a > 15) - disp('Greater than 15') + disp('Maior que 15') elseif (a == 23) - disp('a is 23') + disp('a é 23') else - disp('neither condition met') + disp('Nenhuma condição reconheceu') end -% Looping -% NB. looping over elements of a vector/matrix is slow! -% Where possible, use functions that act on whole vector/matrix at once +% Estruturas de Repetição +% Nota: fazer o loop sobre elementos de um vetor/matriz é lento! +% Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez. for k = 1:5 disp(k) end @@ -374,25 +377,26 @@ while (k < 5) k = k + 1; end -% Timing code execution: 'toc' prints the time since 'tic' was called +% Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo +% passado desde que 'tic' foi chamado. tic A = rand(1000); A*A*A*A*A*A*A; toc -% Connecting to a MySQL Database -dbname = 'database_name'; +% Conectando a uma base de dados MySQL +dbname = 'nome_base_de_dados'; username = 'root'; password = 'root'; driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; -javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/ conn = database(dbname, username, password, driver, dburl); -sql = ['SELECT * from table_name where id = 22'] % Example sql statement +sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL a = fetch(conn, sql) %a will contain your data -% Common math functions +% Funções Matemáticas Comuns sin(x) cos(x) tan(x) @@ -410,122 +414,122 @@ ceil(x) floor(x) round(x) rem(x) -rand % Uniformly distributed pseudorandom numbers -randi % Uniformly distributed pseudorandom integers -randn % Normally distributed pseudorandom numbers +rand % Números pseudo-aleatórios uniformemente distribuídos +randi % Inteiros pseudo-aleatórios uniformemente distribuídos +randn % Números pseudo-aleatórios normalmente distribuídos -% Common constants +% Constantes Comuns pi NaN inf -% Solving matrix equations (if no solution, returns a least squares solution) -% The \ and / operators are equivalent to the functions mldivide and mrdivide -x=A\b % Solves Ax=b. Faster and more numerically accurate than using inv(A)*b. -x=b/A % Solves xA=b - -inv(A) % calculate the inverse matrix -pinv(A) % calculate the pseudo-inverse - -% Common matrix functions -zeros(m,n) % m x n matrix of 0's -ones(m,n) % m x n matrix of 1's -diag(A) % Extracts the diagonal elements of a matrix A -diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere -eye(m,n) % Identity matrix -linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 -inv(A) % Inverse of matrix A -det(A) % Determinant of A -eig(A) % Eigenvalues and eigenvectors of A -trace(A) % Trace of matrix - equivalent to sum(diag(A)) -isempty(A) % Tests if array is empty -all(A) % Tests if all elements are nonzero or true -any(A) % Tests if any elements are nonzero or true -isequal(A, B) % Tests equality of two arrays -numel(A) % Number of elements in matrix -triu(x) % Returns the upper triangular part of x -tril(x) % Returns the lower triangular part of x -cross(A,B) % Returns the cross product of the vectors A and B -dot(A,B) % Returns scalar product of two vectors (must have the same length) -transpose(A) % Returns the transpose of A -fliplr(A) % Flip matrix left to right -flipud(A) % Flip matrix up to down - -% Matrix Factorisations -[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix -[P, D] = eig(A) % eigen-decomposition: AP = PD, P's columns are eigenvectors and D's diagonals are eigenvalues -[U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order - -% Common vector functions -max % largest component -min % smallest component -length % length of a vector -sort % sort in ascending order -sum % sum of elements -prod % product of elements -mode % modal value -median % median value -mean % mean value -std % standard deviation -perms(x) % list all permutations of elements of x +% Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados) +% Os operadores \ e / são equivalentes às funções mldivide e mrdivide +x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b. +x=b/A % Resolve xA=b + +inv(A) % Calcula a matriz inversa +pinv(A) % Calcula a pseudo-inversa + +% Funções Matriciais Comuns +zeros(m,n) % Matriz de zeros m x n +ones(m,n) % Matriz de 1's m x n +diag(A) % Extrai os elementos diagonais da matriz A +diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições +eye(m,n) % Matriz identidade +linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2 +inv(A) % Inverso da matriz A +det(A) % Determinante da matriz A +eig(A) % Valores e vetores próprios de A +trace(A) % Traço da matriz - equivalente a sum(diag(A)) +isempty(A) % Testa se a matriz está vazia +all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro +any(A) % Testa se algum elemento é diferente de zero ou verdadeiro +isequal(A, B) % Testa a igualdade de duas matrizes +numel(A) % Número de elementos na matriz +triu(x) % Retorna a parte triangular superior de x +tril(x) % Retorna a parte triangular inferior de x +cross(A,B) % Retorna o produto cruzado das matrizes A e B +dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho) +transpose(A) % Retorna a matriz transposta de A +fliplr(A) % Inverte a matriz da esquerda para a direita +flipud(A) % Inverte a matriz de cima para baixo + +% Fatorações de Matrizes +[L, U, P] = lu(A) % Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação +[P, D] = eig(A) % Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores +[U,S,V] = svd(X) % SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente + +% Funções Vetoriais Comuns +max % Maior componente +min % Menor componente +length % Tamanho do vetor +sort % Ordena em orcer ascendente +sum % Soma de elementos +prod % Produto de elementos +mode % Valor modal +median % Valor mediano +mean % Valor médio +std % Desvio padrão +perms(x) % Lista todas as permutações de elementos de x % Classes -% Matlab can support object-oriented programming. -% Classes must be put in a file of the class name with a .m extension. -% To begin, we create a simple class to store GPS waypoints. -% Begin WaypointClass.m -classdef WaypointClass % The class name. - properties % The properties of the class behave like Structures +% Matlab pode suportar programação orientada a objetos. +% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m +% Para começar, criamos uma simples classe que armazena posições de GPS +% Início ClassePosicoesGPS.m +classdef ClassePosicoesGPS % O nome da classe. + properties % As propriedades da classe comportam-se como estruturas latitude longitude end methods - % This method that has the same name of the class is the constructor. - function obj = WaypointClass(lat, lon) + % Este método que tem o mesmo nome da classe é o construtor. + function obj = ClassePosicoesGPS(lat, lon) obj.latitude = lat; obj.longitude = lon; end - % Other functions that use the Waypoint object - function r = multiplyLatBy(obj, n) + % Outras funções que usam os objetos de PosicoesGPS + function r = multiplicarLatPor(obj, n) r = n*[obj.latitude]; end - % If we want to add two Waypoint objects together without calling - % a special function we can overload Matlab's arithmetic like so: + % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar + % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira: function r = plus(o1,o2) - r = WaypointClass([o1.latitude] +[o2.latitude], ... + r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ... [o1.longitude]+[o2.longitude]); end end end -% End WaypointClass.m +% End ClassePosicoesGPS.m -% We can create an object of the class using the constructor -a = WaypointClass(45.0, 45.0) +% Podemos criar um objeto da classe usando o construtor +a = ClassePosicoesGPS(45.0, 45.0) -% Class properties behave exactly like Matlab Structures. +% Propriedades da classe se comportam exatamente como estruturas Matlab a.latitude = 70.0 a.longitude = 25.0 -% Methods can be called in the same way as functions -ans = multiplyLatBy(a,3) +% Métodos podem ser chamados da mesma forma que funções +ans = multiplicarLatPor(a,3) -% The method can also be called using dot notation. In this case, the object -% does not need to be passed to the method. -ans = a.multiplyLatBy(a,1/3) +% O método também pode ser chamado usando a notação de ponto. Neste caso, +% o objeto não precisa ser passado para o método. +ans = a.multiplicarLatPor(a,1/3) -% Matlab functions can be overloaded to handle objects. -% In the method above, we have overloaded how Matlab handles -% the addition of two Waypoint objects. -b = WaypointClass(15.0, 32.0) +% Funções do Matlab podem ser sobrepostas para lidar com objetos. +% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de +% dois objetos PosicoesGPS. +b = ClassePosicoesGPS(15.0, 32.0) c = a + b ``` -## More on Matlab +## Mais sobre Matlab -* The official website [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) -* The official MATLAB Answers forum: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) +* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) -- cgit v1.2.3 From a98f1d041b5d492490d8b14c71b5a33fb4bad00e Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sun, 18 Oct 2015 13:46:27 -0300 Subject: Fixing some linebreaks Some lines were broken to be better presented --- pt-br/matlab.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/pt-br/matlab.html.markdown b/pt-br/matlab.html.markdown index 4e822a60..ea320d07 100644 --- a/pt-br/matlab.html.markdown +++ b/pt-br/matlab.html.markdown @@ -390,7 +390,8 @@ username = 'root'; password = 'root'; driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; -javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/ +%Abaixo, o xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/ +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); conn = database(dbname, username, password, driver, dburl); sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL a = fetch(conn, sql) %a will contain your data @@ -456,9 +457,12 @@ fliplr(A) % Inverte a matriz da esquerda para a direita flipud(A) % Inverte a matriz de cima para baixo % Fatorações de Matrizes -[L, U, P] = lu(A) % Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação -[P, D] = eig(A) % Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores -[U,S,V] = svd(X) % SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente +% Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação +[L, U, P] = lu(A) +% Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores +[P, D] = eig(A) +% SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente +[U,S,V] = svd(X) % Funções Vetoriais Comuns max % Maior componente -- cgit v1.2.3 From ada99b909743220fd7df2f379dbdb4859e4e5c2a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 18 Oct 2015 11:56:16 -0500 Subject: Update ColdFusion header --- coldfusion.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index e2f0737d..70804a1e 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -1,14 +1,14 @@ --- -language: ColdFusion +language: coldfusion +filename: learncoldfusion.cfm contributors: - ["Wayne Boka", "http://wboka.github.io"] -filename: LearnColdFusion.cfm --- ColdFusion is a scripting language for web development. [Read more here.](http://www.adobe.com/products/coldfusion-family.html) -```ColdFusion +```html HTML tags have been provided for output readability -- cgit v1.2.3 From 9ee5d3739fac053c2c156e071162638392149e1d Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sun, 18 Oct 2015 14:12:16 -0300 Subject: Rename matlab.html.markdown to matlab-pt.html.markdown --- pt-br/matlab-pt.html.markdown | 539 ++++++++++++++++++++++++++++++++++++++++++ pt-br/matlab.html.markdown | 539 ------------------------------------------ 2 files changed, 539 insertions(+), 539 deletions(-) create mode 100644 pt-br/matlab-pt.html.markdown delete mode 100644 pt-br/matlab.html.markdown diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown new file mode 100644 index 00000000..ea320d07 --- /dev/null +++ b/pt-br/matlab-pt.html.markdown @@ -0,0 +1,539 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] +translators: + - ["Claudson Martins", "https://github.com/claudsonm"] +lang: pt-br + +--- + +MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática. + +Se você tem algum feedback, por favor fique a vontade para me contactar via +[@the_ozzinator](https://twitter.com/the_ozzinator), ou +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```matlab +% Comentários iniciam com um sinal de porcentagem + +%{ +Comentários de múltiplas linhas +parecem +com +algo assim +%} + +% Comandos podem ocupar várinhas linhas, usando '...': + a = 1 + 2 + ... + + 4 + +% Comandos podem ser passados para o sistema operacional +!ping google.com + +who % Exibe todas as variáveis na memória +whos % Exibe todas as variáveis na memória, com seus tipos +clear % Apaga todas as suas variáveis da memória +clear('A') % Apaga uma variável em particular +openvar('A') % Abre a variável no editor de variável + +clc % Apaga o conteúdo escrito na sua janela de comando +diary % Alterna o conteúdo escrito na janela de comando para um arquivo de texto +ctrl-c % Aborta a computação atual + +edit('minhafuncao.m') % Abre a função/script no editor +type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando + +profile on % Ativa o perfil de código +profile off % Desativa o perfil de código +profile viewer % Visualiza os resultados na janela de Profiler + +help comando % Exibe a documentação do comando na janela de comando +doc comando % Exibe a documentação do comando na janela de ajuda +lookfor comando % Procura por comando na primeira linha comentada de todas as funções +lookfor comando -all % Procura por comando em todas as funções + + +% Formatação de saída +format short % 4 casas decimais em um número flutuante +format long % 15 casas decimais +format bank % 2 dígitos após o ponto decimal - para cálculos financeiros +fprintf('texto') % Imprime na tela "texto" +disp('texto') % Imprime na tela "texto" + +% Variáveis & Expressões +minhaVariavel = 4 % O painel Workspace mostra a variável recém-criada +minhaVariavel = 4; % Ponto e vírgula suprime a saída para a janela de comando +4 + 6 % Resposta = 10 +8 * minhaVariavel % Resposta = 32 +2 ^ 3 % Resposta = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% A chamada de funções pode ser feita por uma das duas maneiras: +% Sintaxe de função padrão: +load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula +% Sintaxe de comando: +load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas +% Observe a falta de aspas na forma de comando: entradas são sempre passadas +% como texto literal - não pode passar valores de variáveis. +% Além disso, não pode receber saída: +[V,D] = eig(A); % Isto não tem um equivalente na forma de comando +[~,D] = eig(A); % Se você só deseja D e não V + + + +% Operadores Lógicos e Relacionais +1 > 5 % Resposta = 0 +10 >= 10 % Resposta = 1 +3 ~= 4 % Diferente de -> Resposta = 1 +3 == 3 % Igual a -> Resposta = 1 +3 > 1 && 4 > 1 % E -> Resposta = 1 +3 > 1 || 4 > 1 % OU -> Resposta = 1 +~1 % NOT -> Resposta = 0 + +% Operadores Lógicos e Relacionais podem ser aplicados a matrizes +A > 5 +% Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada +A( A > 5 ) +% Retorna um vetor com os elementos de A para os quais a condição é verdadeira + +% Cadeias de caracteres (Strings) +a = 'MinhaString' +length(a) % Resposta = 11 +a(2) % Resposta = i +[a,a] % Resposta = MinhaStringMinhaString + + +% Vetores de células +a = {'um', 'dois', 'três'} +a(1) % Resposta = 'um' - retorna uma célula +char(a(1)) % Resposta = um - retorna uma string + +% Estruturas +A.b = {'um','dois'}; +A.c = [1 2]; +A.d.e = false; + +% Vetores +x = [4 32 53 7 1] +x(2) % Resposta = 32, índices no Matlab começam por 1, não 0 +x(2:3) % Resposta = 32 53 +x(2:end) % Resposta = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Vetor coluna + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrizes +A = [1 2 3; 4 5 6; 7 8 9] +% Linhas são separadas por um ponto e vírgula; +% Elementos são separados com espaço ou vírgula +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % Resposta = 6, A(linha, coluna) +A(6) % Resposta = 8 +% (implicitamente encadeia as colunas do vetor, e então as indexa) + + +A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Cria uma nova matriz a partir da antiga +%Resposta = + +% 5 42 +% 8 9 + +A(:,1) % Todas as linhas na coluna 1 +%Resposta = + +% 1 +% 4 +% 7 + +A(1,:) % Todas as colunas na linha 1 +%Resposta = + +% 1 2 3 + +[A ; A] % Concatenação de matrizes (verticalmente) +%Resposta = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% Isto é o mesmo de +vertcat(A,A); + + +[A , A] % Concatenação de matrizes (horizontalmente) + +%Resposta = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% Isto é o mesmo de +horzcat(A,A); + + +A(:, [3 1 2]) % Reorganiza as colunas da matriz original +%Resposta = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % Resposta = 3 3 + +A(1, :) =[] % Remove a primeira linha da matriz +A(:, 1) =[] % Remove a primeira coluna da matriz + +transpose(A) % Transposta a matriz, que é o mesmo de: +A one +ctranspose(A) % Transposta a matriz +% (a transposta, seguida pelo conjugado complexo de cada elemento) + + + + +% Aritmética Elemento por Elemento vs. Aritmética com Matriz +% Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando +% precedidos por um ponto, eles atuam em cada elemento. Por exemplo: +A * B % Multiplicação de matrizes +A .* B % Multiplica cada elemento em A por seu correspondente em B + +% Existem vários pares de funções nas quais uma atua sob cada elemento, e a +% outra (cujo nome termina com m) age na matriz por completo. +exp(A) % Exponencia cada elemento +expm(A) % Calcula o exponencial da matriz +sqrt(A) % Tira a raiz quadrada de cada elemento +sqrtm(A) % Procura a matriz cujo quadrado é A + + +% Gráficos +x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1 +y = sin(x); +plot(x,y) +xlabel('eixo x') +ylabel('eixo y') +title('Gráfico de y = sin(x)') +axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico +legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda + +% Método alternativo para traçar várias funções em um só gráfico: +% Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico +% existente ao invés de o substituirem. +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % Plotar em escala loglog +semilogx(x, y) % Um gráfico com eixo x logarítmico +semilogy(x, y) % Um gráfico com eixo y logarítmico + +fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5 + +grid on % Exibe as linhas de grade; Oculta com 'grid off' +axis square % Torna quadrada a região dos eixos atuais +axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções + +scatter(x, y); % Gráfico de dispersão ou bolha +hist(x); % Histograma + +z = sin(x); +plot3(x,y,z); % Plotar em espaço em 3D + +pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor +contour(A) % Plotar de contorno da matriz +mesh(A) % Plotar malha 3D + +h = figure % Cria uma nova figura objeto, com identificador h +figure(h) % Cria uma nova janela de figura com h +close(h) % Fecha a figura h +close all % Fecha todas as janelas de figuras abertas +close % Fecha a janela de figura atual + +shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário +clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura + +% Propriedades podem ser definidas e alteradas através de um identificador. +% Você pode salvar um identificador para uma figura ao criá-la. +% A função gcf retorna o identificador da figura atual +h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la +set(h, 'Color', 'r') +% 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto +set(h, 'LineStyle', '--') + % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha +get(h, 'LineStyle') + + +% A função gca retorna o identificador para os eixos da figura atual +set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x + +% Para criar uma figura que contém vários gráficos use subplot, o qual divide +% a janela de gráficos em m linhas e n colunas. +subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3 +plot(x1); title('Primeiro Plot') % Plota algo nesta posição +subplot(2,3,2); % Seleciona a segunda posição na grade +plot(x2); title('Segundo Plot') % Plota algo ali + + +% Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual +path % Exibe o caminho atual +addpath /caminho/para/pasta % Adiciona o diretório ao caminho +rmpath /caminho/para/pasta % Remove o diretório do caminho +cd /caminho/para/mudar % Muda o diretório + + +% Variáveis podem ser salvas em arquivos *.mat +save('meuArquivo.mat') % Salva as variáveis do seu Workspace +load('meuArquivo.mat') % Carrega as variáveis em seu Workspace + +% Arquivos M (M-files) +% Um arquivo de script é um arquivo externo contendo uma sequência de instruções. +% Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos. +% Possuem a extensão *.m + +% Arquivos M de Funções (M-file Functions) +% Assim como scripts e têm a mesma extensão *.m +% Mas podem aceitar argumentos de entrada e retornar uma saída. +% Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis). +% O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m) +% 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função +function output = dobra_entrada(x) + %dobra_entrada(x) retorna duas vezes o valor de x + output = 2*x; +end +dobra_entrada(6) % Resposta = 12 + + +% Você também pode ter subfunções e funções aninhadas. +% Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados +% por funções dentro do arquivo. Funções aninhadas são definidas dentro de +% outras funções, e têm acesso a ambos workspaces. + +% Se você quer criar uma função sem criar um novo arquivo, você pode usar uma +% função anônima. Úteis para definir rapidamente uma função para passar a outra +% função (ex. plotar com fplot, avaliar uma integral indefinida com quad, +% procurar raízes com fzero, ou procurar mínimo com fminsearch). +% Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr: +sqr = @(x) x.^2; +sqr(10) % Resposta = 100 +doc function_handle % Saiba mais + +% Entrada do usuário +a = input('Digite o valor: ') + +% Para a execução do arquivo e passa o controle para o teclado: o usuário pode +% examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair +keyboard + +% Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem) +fopen(nomedoarquivo) + +% Saída +disp(a) % Imprime o valor da variável a +disp('Olá Mundo') % Imprime a string +fprintf % Imprime na janela de comandos com mais controle + +% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática) +if (a > 15) + disp('Maior que 15') +elseif (a == 23) + disp('a é 23') +else + disp('Nenhuma condição reconheceu') +end + +% Estruturas de Repetição +% Nota: fazer o loop sobre elementos de um vetor/matriz é lento! +% Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez. +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo +% passado desde que 'tic' foi chamado. +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Conectando a uma base de dados MySQL +dbname = 'nome_base_de_dados'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +%Abaixo, o xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/ +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL +a = fetch(conn, sql) %a will contain your data + + +% Funções Matemáticas Comuns +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % Números pseudo-aleatórios uniformemente distribuídos +randi % Inteiros pseudo-aleatórios uniformemente distribuídos +randn % Números pseudo-aleatórios normalmente distribuídos + +% Constantes Comuns +pi +NaN +inf + +% Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados) +% Os operadores \ e / são equivalentes às funções mldivide e mrdivide +x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b. +x=b/A % Resolve xA=b + +inv(A) % Calcula a matriz inversa +pinv(A) % Calcula a pseudo-inversa + +% Funções Matriciais Comuns +zeros(m,n) % Matriz de zeros m x n +ones(m,n) % Matriz de 1's m x n +diag(A) % Extrai os elementos diagonais da matriz A +diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições +eye(m,n) % Matriz identidade +linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2 +inv(A) % Inverso da matriz A +det(A) % Determinante da matriz A +eig(A) % Valores e vetores próprios de A +trace(A) % Traço da matriz - equivalente a sum(diag(A)) +isempty(A) % Testa se a matriz está vazia +all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro +any(A) % Testa se algum elemento é diferente de zero ou verdadeiro +isequal(A, B) % Testa a igualdade de duas matrizes +numel(A) % Número de elementos na matriz +triu(x) % Retorna a parte triangular superior de x +tril(x) % Retorna a parte triangular inferior de x +cross(A,B) % Retorna o produto cruzado das matrizes A e B +dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho) +transpose(A) % Retorna a matriz transposta de A +fliplr(A) % Inverte a matriz da esquerda para a direita +flipud(A) % Inverte a matriz de cima para baixo + +% Fatorações de Matrizes +% Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação +[L, U, P] = lu(A) +% Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores +[P, D] = eig(A) +% SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente +[U,S,V] = svd(X) + +% Funções Vetoriais Comuns +max % Maior componente +min % Menor componente +length % Tamanho do vetor +sort % Ordena em orcer ascendente +sum % Soma de elementos +prod % Produto de elementos +mode % Valor modal +median % Valor mediano +mean % Valor médio +std % Desvio padrão +perms(x) % Lista todas as permutações de elementos de x + + +% Classes +% Matlab pode suportar programação orientada a objetos. +% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m +% Para começar, criamos uma simples classe que armazena posições de GPS +% Início ClassePosicoesGPS.m +classdef ClassePosicoesGPS % O nome da classe. + properties % As propriedades da classe comportam-se como estruturas + latitude + longitude + end + methods + % Este método que tem o mesmo nome da classe é o construtor. + function obj = ClassePosicoesGPS(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Outras funções que usam os objetos de PosicoesGPS + function r = multiplicarLatPor(obj, n) + r = n*[obj.latitude]; + end + + % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar + % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira: + function r = plus(o1,o2) + r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End ClassePosicoesGPS.m + +% Podemos criar um objeto da classe usando o construtor +a = ClassePosicoesGPS(45.0, 45.0) + +% Propriedades da classe se comportam exatamente como estruturas Matlab +a.latitude = 70.0 +a.longitude = 25.0 + +% Métodos podem ser chamados da mesma forma que funções +ans = multiplicarLatPor(a,3) + +% O método também pode ser chamado usando a notação de ponto. Neste caso, +% o objeto não precisa ser passado para o método. +ans = a.multiplicarLatPor(a,1/3) + +% Funções do Matlab podem ser sobrepostas para lidar com objetos. +% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de +% dois objetos PosicoesGPS. +b = ClassePosicoesGPS(15.0, 32.0) +c = a + b + +``` + +## Mais sobre Matlab + +* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) + diff --git a/pt-br/matlab.html.markdown b/pt-br/matlab.html.markdown deleted file mode 100644 index ea320d07..00000000 --- a/pt-br/matlab.html.markdown +++ /dev/null @@ -1,539 +0,0 @@ ---- -language: Matlab -contributors: - - ["mendozao", "http://github.com/mendozao"] - - ["jamesscottbrown", "http://jamesscottbrown.com"] - - ["Colton Kohnke", "http://github.com/voltnor"] -translators: - - ["Claudson Martins", "https://github.com/claudsonm"] -lang: pt-br - ---- - -MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática. - -Se você tem algum feedback, por favor fique a vontade para me contactar via -[@the_ozzinator](https://twitter.com/the_ozzinator), ou -[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). - -```matlab -% Comentários iniciam com um sinal de porcentagem - -%{ -Comentários de múltiplas linhas -parecem -com -algo assim -%} - -% Comandos podem ocupar várinhas linhas, usando '...': - a = 1 + 2 + ... - + 4 - -% Comandos podem ser passados para o sistema operacional -!ping google.com - -who % Exibe todas as variáveis na memória -whos % Exibe todas as variáveis na memória, com seus tipos -clear % Apaga todas as suas variáveis da memória -clear('A') % Apaga uma variável em particular -openvar('A') % Abre a variável no editor de variável - -clc % Apaga o conteúdo escrito na sua janela de comando -diary % Alterna o conteúdo escrito na janela de comando para um arquivo de texto -ctrl-c % Aborta a computação atual - -edit('minhafuncao.m') % Abre a função/script no editor -type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando - -profile on % Ativa o perfil de código -profile off % Desativa o perfil de código -profile viewer % Visualiza os resultados na janela de Profiler - -help comando % Exibe a documentação do comando na janela de comando -doc comando % Exibe a documentação do comando na janela de ajuda -lookfor comando % Procura por comando na primeira linha comentada de todas as funções -lookfor comando -all % Procura por comando em todas as funções - - -% Formatação de saída -format short % 4 casas decimais em um número flutuante -format long % 15 casas decimais -format bank % 2 dígitos após o ponto decimal - para cálculos financeiros -fprintf('texto') % Imprime na tela "texto" -disp('texto') % Imprime na tela "texto" - -% Variáveis & Expressões -minhaVariavel = 4 % O painel Workspace mostra a variável recém-criada -minhaVariavel = 4; % Ponto e vírgula suprime a saída para a janela de comando -4 + 6 % Resposta = 10 -8 * minhaVariavel % Resposta = 32 -2 ^ 3 % Resposta = 8 -a = 2; b = 3; -c = exp(a)*sin(pi/2) % c = 7.3891 - -% A chamada de funções pode ser feita por uma das duas maneiras: -% Sintaxe de função padrão: -load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula -% Sintaxe de comando: -load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas -% Observe a falta de aspas na forma de comando: entradas são sempre passadas -% como texto literal - não pode passar valores de variáveis. -% Além disso, não pode receber saída: -[V,D] = eig(A); % Isto não tem um equivalente na forma de comando -[~,D] = eig(A); % Se você só deseja D e não V - - - -% Operadores Lógicos e Relacionais -1 > 5 % Resposta = 0 -10 >= 10 % Resposta = 1 -3 ~= 4 % Diferente de -> Resposta = 1 -3 == 3 % Igual a -> Resposta = 1 -3 > 1 && 4 > 1 % E -> Resposta = 1 -3 > 1 || 4 > 1 % OU -> Resposta = 1 -~1 % NOT -> Resposta = 0 - -% Operadores Lógicos e Relacionais podem ser aplicados a matrizes -A > 5 -% Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada -A( A > 5 ) -% Retorna um vetor com os elementos de A para os quais a condição é verdadeira - -% Cadeias de caracteres (Strings) -a = 'MinhaString' -length(a) % Resposta = 11 -a(2) % Resposta = i -[a,a] % Resposta = MinhaStringMinhaString - - -% Vetores de células -a = {'um', 'dois', 'três'} -a(1) % Resposta = 'um' - retorna uma célula -char(a(1)) % Resposta = um - retorna uma string - -% Estruturas -A.b = {'um','dois'}; -A.c = [1 2]; -A.d.e = false; - -% Vetores -x = [4 32 53 7 1] -x(2) % Resposta = 32, índices no Matlab começam por 1, não 0 -x(2:3) % Resposta = 32 53 -x(2:end) % Resposta = 32 53 7 1 - -x = [4; 32; 53; 7; 1] % Vetor coluna - -x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 - -% Matrizes -A = [1 2 3; 4 5 6; 7 8 9] -% Linhas são separadas por um ponto e vírgula; -% Elementos são separados com espaço ou vírgula -% A = - -% 1 2 3 -% 4 5 6 -% 7 8 9 - -A(2,3) % Resposta = 6, A(linha, coluna) -A(6) % Resposta = 8 -% (implicitamente encadeia as colunas do vetor, e então as indexa) - - -A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42 -% A = - -% 1 2 3 -% 4 5 42 -% 7 8 9 - -A(2:3,2:3) % Cria uma nova matriz a partir da antiga -%Resposta = - -% 5 42 -% 8 9 - -A(:,1) % Todas as linhas na coluna 1 -%Resposta = - -% 1 -% 4 -% 7 - -A(1,:) % Todas as colunas na linha 1 -%Resposta = - -% 1 2 3 - -[A ; A] % Concatenação de matrizes (verticalmente) -%Resposta = - -% 1 2 3 -% 4 5 42 -% 7 8 9 -% 1 2 3 -% 4 5 42 -% 7 8 9 - -% Isto é o mesmo de -vertcat(A,A); - - -[A , A] % Concatenação de matrizes (horizontalmente) - -%Resposta = - -% 1 2 3 1 2 3 -% 4 5 42 4 5 42 -% 7 8 9 7 8 9 - -% Isto é o mesmo de -horzcat(A,A); - - -A(:, [3 1 2]) % Reorganiza as colunas da matriz original -%Resposta = - -% 3 1 2 -% 42 4 5 -% 9 7 8 - -size(A) % Resposta = 3 3 - -A(1, :) =[] % Remove a primeira linha da matriz -A(:, 1) =[] % Remove a primeira coluna da matriz - -transpose(A) % Transposta a matriz, que é o mesmo de: -A one -ctranspose(A) % Transposta a matriz -% (a transposta, seguida pelo conjugado complexo de cada elemento) - - - - -% Aritmética Elemento por Elemento vs. Aritmética com Matriz -% Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando -% precedidos por um ponto, eles atuam em cada elemento. Por exemplo: -A * B % Multiplicação de matrizes -A .* B % Multiplica cada elemento em A por seu correspondente em B - -% Existem vários pares de funções nas quais uma atua sob cada elemento, e a -% outra (cujo nome termina com m) age na matriz por completo. -exp(A) % Exponencia cada elemento -expm(A) % Calcula o exponencial da matriz -sqrt(A) % Tira a raiz quadrada de cada elemento -sqrtm(A) % Procura a matriz cujo quadrado é A - - -% Gráficos -x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1 -y = sin(x); -plot(x,y) -xlabel('eixo x') -ylabel('eixo y') -title('Gráfico de y = sin(x)') -axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1 - -plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico -legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda - -% Método alternativo para traçar várias funções em um só gráfico: -% Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico -% existente ao invés de o substituirem. -plot(x, y) -hold on -plot(x, z) -hold off - -loglog(x, y) % Plotar em escala loglog -semilogx(x, y) % Um gráfico com eixo x logarítmico -semilogy(x, y) % Um gráfico com eixo y logarítmico - -fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5 - -grid on % Exibe as linhas de grade; Oculta com 'grid off' -axis square % Torna quadrada a região dos eixos atuais -axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções - -scatter(x, y); % Gráfico de dispersão ou bolha -hist(x); % Histograma - -z = sin(x); -plot3(x,y,z); % Plotar em espaço em 3D - -pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor -contour(A) % Plotar de contorno da matriz -mesh(A) % Plotar malha 3D - -h = figure % Cria uma nova figura objeto, com identificador h -figure(h) % Cria uma nova janela de figura com h -close(h) % Fecha a figura h -close all % Fecha todas as janelas de figuras abertas -close % Fecha a janela de figura atual - -shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário -clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura - -% Propriedades podem ser definidas e alteradas através de um identificador. -% Você pode salvar um identificador para uma figura ao criá-la. -% A função gcf retorna o identificador da figura atual -h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la -set(h, 'Color', 'r') -% 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto -set(h, 'LineStyle', '--') - % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha -get(h, 'LineStyle') - - -% A função gca retorna o identificador para os eixos da figura atual -set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x - -% Para criar uma figura que contém vários gráficos use subplot, o qual divide -% a janela de gráficos em m linhas e n colunas. -subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3 -plot(x1); title('Primeiro Plot') % Plota algo nesta posição -subplot(2,3,2); % Seleciona a segunda posição na grade -plot(x2); title('Segundo Plot') % Plota algo ali - - -% Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual -path % Exibe o caminho atual -addpath /caminho/para/pasta % Adiciona o diretório ao caminho -rmpath /caminho/para/pasta % Remove o diretório do caminho -cd /caminho/para/mudar % Muda o diretório - - -% Variáveis podem ser salvas em arquivos *.mat -save('meuArquivo.mat') % Salva as variáveis do seu Workspace -load('meuArquivo.mat') % Carrega as variáveis em seu Workspace - -% Arquivos M (M-files) -% Um arquivo de script é um arquivo externo contendo uma sequência de instruções. -% Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos. -% Possuem a extensão *.m - -% Arquivos M de Funções (M-file Functions) -% Assim como scripts e têm a mesma extensão *.m -% Mas podem aceitar argumentos de entrada e retornar uma saída. -% Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis). -% O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m) -% 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função -function output = dobra_entrada(x) - %dobra_entrada(x) retorna duas vezes o valor de x - output = 2*x; -end -dobra_entrada(6) % Resposta = 12 - - -% Você também pode ter subfunções e funções aninhadas. -% Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados -% por funções dentro do arquivo. Funções aninhadas são definidas dentro de -% outras funções, e têm acesso a ambos workspaces. - -% Se você quer criar uma função sem criar um novo arquivo, você pode usar uma -% função anônima. Úteis para definir rapidamente uma função para passar a outra -% função (ex. plotar com fplot, avaliar uma integral indefinida com quad, -% procurar raízes com fzero, ou procurar mínimo com fminsearch). -% Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr: -sqr = @(x) x.^2; -sqr(10) % Resposta = 100 -doc function_handle % Saiba mais - -% Entrada do usuário -a = input('Digite o valor: ') - -% Para a execução do arquivo e passa o controle para o teclado: o usuário pode -% examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair -keyboard - -% Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem) -fopen(nomedoarquivo) - -% Saída -disp(a) % Imprime o valor da variável a -disp('Olá Mundo') % Imprime a string -fprintf % Imprime na janela de comandos com mais controle - -% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática) -if (a > 15) - disp('Maior que 15') -elseif (a == 23) - disp('a é 23') -else - disp('Nenhuma condição reconheceu') -end - -% Estruturas de Repetição -% Nota: fazer o loop sobre elementos de um vetor/matriz é lento! -% Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez. -for k = 1:5 - disp(k) -end - -k = 0; -while (k < 5) - k = k + 1; -end - -% Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo -% passado desde que 'tic' foi chamado. -tic -A = rand(1000); -A*A*A*A*A*A*A; -toc - -% Conectando a uma base de dados MySQL -dbname = 'nome_base_de_dados'; -username = 'root'; -password = 'root'; -driver = 'com.mysql.jdbc.Driver'; -dburl = ['jdbc:mysql://localhost:8889/' dbname]; -%Abaixo, o xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/ -javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); -conn = database(dbname, username, password, driver, dburl); -sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL -a = fetch(conn, sql) %a will contain your data - - -% Funções Matemáticas Comuns -sin(x) -cos(x) -tan(x) -asin(x) -acos(x) -atan(x) -exp(x) -sqrt(x) -log(x) -log10(x) -abs(x) -min(x) -max(x) -ceil(x) -floor(x) -round(x) -rem(x) -rand % Números pseudo-aleatórios uniformemente distribuídos -randi % Inteiros pseudo-aleatórios uniformemente distribuídos -randn % Números pseudo-aleatórios normalmente distribuídos - -% Constantes Comuns -pi -NaN -inf - -% Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados) -% Os operadores \ e / são equivalentes às funções mldivide e mrdivide -x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b. -x=b/A % Resolve xA=b - -inv(A) % Calcula a matriz inversa -pinv(A) % Calcula a pseudo-inversa - -% Funções Matriciais Comuns -zeros(m,n) % Matriz de zeros m x n -ones(m,n) % Matriz de 1's m x n -diag(A) % Extrai os elementos diagonais da matriz A -diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições -eye(m,n) % Matriz identidade -linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2 -inv(A) % Inverso da matriz A -det(A) % Determinante da matriz A -eig(A) % Valores e vetores próprios de A -trace(A) % Traço da matriz - equivalente a sum(diag(A)) -isempty(A) % Testa se a matriz está vazia -all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro -any(A) % Testa se algum elemento é diferente de zero ou verdadeiro -isequal(A, B) % Testa a igualdade de duas matrizes -numel(A) % Número de elementos na matriz -triu(x) % Retorna a parte triangular superior de x -tril(x) % Retorna a parte triangular inferior de x -cross(A,B) % Retorna o produto cruzado das matrizes A e B -dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho) -transpose(A) % Retorna a matriz transposta de A -fliplr(A) % Inverte a matriz da esquerda para a direita -flipud(A) % Inverte a matriz de cima para baixo - -% Fatorações de Matrizes -% Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação -[L, U, P] = lu(A) -% Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores -[P, D] = eig(A) -% SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente -[U,S,V] = svd(X) - -% Funções Vetoriais Comuns -max % Maior componente -min % Menor componente -length % Tamanho do vetor -sort % Ordena em orcer ascendente -sum % Soma de elementos -prod % Produto de elementos -mode % Valor modal -median % Valor mediano -mean % Valor médio -std % Desvio padrão -perms(x) % Lista todas as permutações de elementos de x - - -% Classes -% Matlab pode suportar programação orientada a objetos. -% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m -% Para começar, criamos uma simples classe que armazena posições de GPS -% Início ClassePosicoesGPS.m -classdef ClassePosicoesGPS % O nome da classe. - properties % As propriedades da classe comportam-se como estruturas - latitude - longitude - end - methods - % Este método que tem o mesmo nome da classe é o construtor. - function obj = ClassePosicoesGPS(lat, lon) - obj.latitude = lat; - obj.longitude = lon; - end - - % Outras funções que usam os objetos de PosicoesGPS - function r = multiplicarLatPor(obj, n) - r = n*[obj.latitude]; - end - - % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar - % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira: - function r = plus(o1,o2) - r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ... - [o1.longitude]+[o2.longitude]); - end - end -end -% End ClassePosicoesGPS.m - -% Podemos criar um objeto da classe usando o construtor -a = ClassePosicoesGPS(45.0, 45.0) - -% Propriedades da classe se comportam exatamente como estruturas Matlab -a.latitude = 70.0 -a.longitude = 25.0 - -% Métodos podem ser chamados da mesma forma que funções -ans = multiplicarLatPor(a,3) - -% O método também pode ser chamado usando a notação de ponto. Neste caso, -% o objeto não precisa ser passado para o método. -ans = a.multiplicarLatPor(a,1/3) - -% Funções do Matlab podem ser sobrepostas para lidar com objetos. -% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de -% dois objetos PosicoesGPS. -b = ClassePosicoesGPS(15.0, 32.0) -c = a + b - -``` - -## Mais sobre Matlab - -* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) -* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) - -- cgit v1.2.3 From 3a968a826b621c0e484268532d6b96a7b2865c8a Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Sun, 18 Oct 2015 12:22:33 -0500 Subject: Fix issue with calling block code. Fixes https://github.com/adambard/learnxinyminutes-docs/issues/1598 --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 30bb8843..f130ea0c 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -688,7 +688,7 @@ addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any pa mutableVar = 32; // Assigning new value to __block variable. return n + outsideVar; // Return statements are optional. } -int addUp = add(10 + 16); // Calls block code with arguments. +int addUp = addUp(10 + 16); // Calls block code with arguments. // Blocks are often used as arguments to functions to be called later, or for callbacks. @implementation BlockExample : NSObject -- cgit v1.2.3 From 05f7cd1a2420d5659ef89d1c5ab185600c6c153a Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Sun, 18 Oct 2015 16:37:24 -0300 Subject: Adding filename markdown --- pt-br/matlab-pt.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown index ea320d07..eb660d4c 100644 --- a/pt-br/matlab-pt.html.markdown +++ b/pt-br/matlab-pt.html.markdown @@ -7,6 +7,7 @@ contributors: translators: - ["Claudson Martins", "https://github.com/claudsonm"] lang: pt-br +filename: learnmatlab-pt.mat --- -- cgit v1.2.3 From 5cb7eba92135b3617b5247fddeb98a7e2585bca8 Mon Sep 17 00:00:00 2001 From: Brett Taylor Date: Mon, 19 Oct 2015 09:15:33 +1300 Subject: [asymptotic-notation/en] added link to Big-O Cheat Sheet --- asymptotic-notation.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown index a516737e..4167ba8d 100644 --- a/asymptotic-notation.html.markdown +++ b/asymptotic-notation.html.markdown @@ -137,3 +137,4 @@ code examples soon. * [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) * [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) +* [Big-O Cheatsheet](http://bigocheatsheet.com/) - common structures, operations, and algorithms, ranked by complexity. -- cgit v1.2.3 From 5c8942f7bcb02a59d1e0acefb0069e80de57e01e Mon Sep 17 00:00:00 2001 From: viv1 Date: Mon, 19 Oct 2015 02:50:55 +0530 Subject: [bash/en]...Added info on changing directories --- bash.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index 211d2944..dfbf9a89 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -130,6 +130,15 @@ ls -l # Lists every file and directory on a separate line # .txt files in the current directory: ls -l | grep "\.txt" +# 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 .. # go up one directory + # (^^say, from /home/username/Downloads to /home/username) +cd /home/username/Documents # change to specified directory +cd ~/Documents/.. # still in home directory..isn't it?? + + # You can redirect command input and output (stdin, stdout, and stderr). # Read from stdin until ^EOF$ and overwrite hello.py with the lines # between "EOF": -- cgit v1.2.3 From d9f3b13e278eebb173253c756ffe847b3188f4af Mon Sep 17 00:00:00 2001 From: Akshay Kalose Date: Sun, 18 Oct 2015 17:37:39 -0400 Subject: Fix Grammar and Syntax --- php.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 78d9d1f2..ac0a83b9 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -511,9 +511,9 @@ class MyClass } // opposite to __construct() - // called when object no longer referenced + // called when object is no longer referenced public function __destruct() { - print "Destroying" + print "Destroying"; } /* -- cgit v1.2.3 From ed4ac31d97b36866a48faf3b9328c320ba55074f Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Sun, 18 Oct 2015 17:46:23 -0500 Subject: Added variable amount of parameters as of php 5.6+ --- php.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index 5bc2ddce..e7b57b4b 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -445,6 +445,16 @@ function parameters() { parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | +// Since PHP 5.6 you can get a variable number of arguments +function variable($word, ...$list) { + echo $word . " || "; + foreach ($list as $item) { + echo $item . ' | '; + } +} + +variable("Separate", "Hello", "World") // Separate || Hello | world | + /******************************** * Includes */ -- cgit v1.2.3 From b4c8ff365ee1d633470ced72de5f540744fa921a Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Sun, 18 Oct 2015 17:47:42 -0500 Subject: capital letter --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index e7b57b4b..71f23871 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -453,7 +453,7 @@ function variable($word, ...$list) { } } -variable("Separate", "Hello", "World") // Separate || Hello | world | +variable("Separate", "Hello", "World") // Separate || Hello | World | /******************************** * Includes -- cgit v1.2.3 From 087dbecb2f25c2d372ed4e007f7641cbc87c0571 Mon Sep 17 00:00:00 2001 From: Tom Duff Date: Sun, 18 Oct 2015 20:21:42 -0400 Subject: Add more examples and explanations Added some clarifying examples to sections on echo(), constants, and cleaned up formatting on others. Added further explanation about the spaceship operator. --- php.html.markdown | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 5bc2ddce..127e601b 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -104,7 +104,8 @@ END; echo 'This string ' . 'is concatenated'; // Strings can be passed in as parameters to echo -echo 'Multiple', 'Parameters', 'Valid'; +echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' + /******************************** * Constants @@ -117,8 +118,10 @@ echo 'Multiple', 'Parameters', 'Valid'; // followed by any number of letters, numbers, or underscores. define("FOO", "something"); -// access to a constant is possible by direct using the choosen name -echo 'This outputs '.FOO; +// access to a constant is possible by calling the choosen name without a $ +echo FOO; // Returns 'something' +echo 'This outputs '.FOO; // Returns 'This ouputs something' + /******************************** @@ -159,9 +162,9 @@ echo('Hello World!'); print('Hello World!'); // The same as echo -// echo is actually a language construct, so you can drop the parentheses. +// echo and print are language constructs too, so you can drop the parentheses echo 'Hello World!'; -print 'Hello World!'; // So is print +print 'Hello World!'; $paragraph = 'paragraph'; @@ -219,7 +222,11 @@ assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); -// spaceship operator since PHP 7 +// 'Spaceship' operator (since PHP 7) +// Returns 0 if values on either side are equal +// Returns 1 if value on the left is greater +// Returns -1 if the value on the right is greater + $a = 100; $b = 1000; -- cgit v1.2.3 From c3387b8a611b6fbb00ac8d54102b772d44d3eca2 Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Sun, 18 Oct 2015 22:32:14 -0500 Subject: [typescript/en] Template Strings --- typescript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index e9135510..101bb5dc 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -159,6 +159,10 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); // Including references to a definition file: /// +// Template Strings +var name = 'Tyrone'; +var greeting = `Hi ${name}, how are you?` + ``` ## Further Reading -- cgit v1.2.3 From 525b6106a57baa570734e29b43f861cd8cc5de3a Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Sun, 18 Oct 2015 22:38:56 -0500 Subject: [typescript/en] Multiline Strings Multiline Strings via Template Strings --- typescript.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 101bb5dc..61b0fdb8 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -159,9 +159,13 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); // Including references to a definition file: /// -// Template Strings +// Template Strings (strings that use backtics) +// String Intepolation with Template Strings var name = 'Tyrone'; var greeting = `Hi ${name}, how are you?` +// Multiline Strings with Template Strings +var multiline = `This is an example +of a multiline string`; ``` -- cgit v1.2.3 From b782df007bd961f55af0d9a57c75c7bf490ec445 Mon Sep 17 00:00:00 2001 From: Erick Bernal Date: Sun, 18 Oct 2015 23:25:01 -0500 Subject: Update and fix typos on ruby translation --- es-es/ruby-es.html.markdown | 247 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 222 insertions(+), 25 deletions(-) diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown index 66a5d0fe..d8b67fe7 100644 --- a/es-es/ruby-es.html.markdown +++ b/es-es/ruby-es.html.markdown @@ -5,8 +5,18 @@ contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Erick Bernal", "http://www.twitter.com/billowkib"] lang: es-es --- @@ -33,6 +43,8 @@ Tu tampoco deberías 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 # La aritmética es sólo azúcar sintáctico # para llamar un método de un objeto @@ -55,8 +67,6 @@ false.class #=> FalseClass # Desigualdad 1 != 1 #=> false 2 != 1 #=> true -!true #=> false -!false #=> true # Además de 'false', 'nil' es otro valor falso @@ -70,14 +80,29 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true +# Operadores lógicos +true && false #=> false +true || false #=> true +!true #=> false + +# Existen versiones alternativas de los operadores lógicos con menor prioridad +# Estos son usados como constructores controladores de flujo que encadenan +# sentencias hasta que una de ellas retorne verdadero o falso + +# `has_otra_cosa` solo se llama si `has_algo` retorna verdadero. +has_algo() and has_otra_cosa() +# `registra_error` solo se llama si `has_algo` falla +has_algo() or registra_error() + + # Los strings son objetos 'Soy un string'.class #=> String "Soy un string también".class #=> String -referente = "usar interpolacion de strings" +referente = "usar interpolación de strings" "Yo puedo #{referente} usando strings de comillas dobles" -#=> "Yo puedo usar interpolacion de strings usando strings de comillas dobles" +#=> "Yo puedo usar interpolación de strings usando strings de comillas dobles" # Imprime a la salida estándar @@ -119,15 +144,16 @@ status == :aprovado #=> false # Arreglos # Esto es un arreglo -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +arreglo = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arreglos pueden contener elementos de distintos tipos -arreglo = [1, "hola", false] #=> => [1, "hola", false] +[1, "hola", false] #=> => [1, "hola", false] # Arreglos pueden ser indexados # Desde el frente arreglo[0] #=> 1 +arreglo.first #=> 1 arreglo[12] #=> nil # Tal como la aritmética, el acceso como variable[índice] @@ -138,15 +164,25 @@ arreglo.[] 12 #=> nil # Desde el final arreglo[-1] #=> 5 +arreglo.last #=> 5 + +# Con un índice de inicio y longitud +arreglo[2, 3] #=> [3, 4, 5] -# Con un índice de inicio y final -arreglo[2, 4] #=> [3, 4, 5] +# Invertir un arreglo +a = [1, 2, 3] +a.reverse! #=> [3, 2, 1] # O con rango arreglo[1..3] #=> [2, 3, 4] # Añade elementos a un arreglo así arreglo << 6 #=> [1, 2, 3, 4, 5, 6] +# O así +arreglo.push(6) #=> [1, 2, 3, 4, 5, 6] + +#Verifica si un elemento ya existe en ese arreglo +arreglo.include?(1) #=> true # Hashes son los diccionarios principales de Ruby con pares llave/valor. # Hashes se denotan con llaves: @@ -161,17 +197,16 @@ hash['numero'] #=> 5 # Preguntarle a un hash por una llave que no existe retorna 'nil': hash['nada aqui'] #=> nil -# Itera sobre un hash con el método 'each': -hash.each do |k, v| - puts "#{k} is #{v}" -end - # Desde Ruby 1.9, hay una sintaxis especial cuando se usa un símbolo como llave: nuevo_hash = { defcon: 3, accion: true} nuevo_hash.keys #=> [:defcon, :accion] +# Verifica la existencia de llaves y valores en el hash +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + # Tip: Tanto los arreglos como los hashes son Enumerable (enumerables) # Comparten muchos métodos útiles tales como 'each', 'map', 'count', y más @@ -194,9 +229,15 @@ end #=> iteracion 4 #=> iteracion 5 -# Aunque -# Nadie usa los ciclos `for` -# Usa `each`, así: +# SIN EMBARGO, nadie usa ciclos `for` +# En su lugar debes usar el método "each" y pasarle un block (bloque). +# Un bloque es un fragmento código que puedes pasar a métodos como `each`. +# Es símilar a las funciones lambda, funciones anónimas o `closures` en otros +# lenguajes de programación. +# +# El método `each` de un Range (rango) ejecuta el bloque una vez por cada elemento. +# Al bloque se le pasa un contador como parametro. +# Usar el método `each` con un bloque se ve así: (1..5).each do |contador| puts "iteracion #{contador}" @@ -207,10 +248,27 @@ end #=> iteracion 4 #=> iteracion 5 -counter = 1 -while counter <= 5 do - puts "iteracion #{counter}" - counter += 1 +# También puedes envolver el bloque entre llaves: +(1..5).each { |counter| puts "iteración #{contador}" } + +#El contenido de las estructuras de datos en ruby puede ser iterado usando `each`. +arreglo.each do |elemento| + puts "#{elemento} es parte del arreglo" +end +hash.each do |llave, valor| + puts "#{llave} es #{valor}" +end + +# Si aún necesitas un índice puedes usar "each_with_index" y definir una variable +# índice. +arreglo.each_with_index do |element, index| + puts "#{element} tiene la posición #{index} en el arreglo" +end + +contador = 1 +while contador <= 5 do + puts "iteracion #{contador}" + contador += 1 end #=> iteracion 1 #=> iteracion 2 @@ -218,6 +276,19 @@ end #=> iteracion 4 #=> iteracion 5 +# Hay una gran variedad de otras funciones iterativas útiles en Ruby, +# por ejemplo `map`, `reduce`, `inject`, entre otras. Map, por ejemplo, +# toma el arreglo sobre el cuál está iterando, le hace cambios +# definidos en el bloque, y retorna un arreglo completamente nuevo. +arreglo = [1,2,3,4,5] +duplicado = array.map do |elemento| + elemento * 2 +end +puts duplicado +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + nota = 'B' case nota @@ -234,6 +305,34 @@ when 'F' else puts "Sistema alternativo de notas, ¿eh?" end +#=> "Mejor suerte para la proxima" + +# Los casos también pueden usar rangos +nota = 82 + +case nota +when 90..100 + puts 'Excelente!' +when 80..100 + puts 'Buen trabajo' +else + puts '¡Reprobaste!' +end +#=> "Buen trabajo" + +# Manejo de excepciones +begin + # código que podría causar excepción + raise NoMemoryError, 'Se te acabó la memoria' +rescue NoMemoryError => variable_de_excepcion + puts 'El error NoMemoryError ocurrió', variable_de_excepcion +rescue RuntimeError => otra_variable_de_excepcion + puts 'El error RuntimeError ocurrió' +else + puts 'Esto se ejecuta si ningun error ocurrió' +ensure + puts 'Este código siempre se ejecuta, sin importar que' +end # Funciones @@ -244,7 +343,7 @@ end # Funciones (y todos los bloques) implícitamente retornan el valor de la última instrucción doble(2) #=> 4 -# Paréntesis son opcionales cuando el resultado es ambiguo +# Paréntesis son opcionales cuando el resultado no es ambiguo doble 3 #=> 6 doble doble 3 #=> 12 @@ -259,7 +358,7 @@ suma 3, 4 #=> 7 suma suma(3,4), 5 #=> 12 # yield -# Todos los métodos tienen un parámetro de bloqueo opcional e implícitp +# Todos los métodos tienen un parámetro bloque opcional e implícito # puede llamarse con la palabra clave 'yield' def alrededor @@ -274,6 +373,17 @@ alrededor { puts 'hola mundo' } # hola mundo # } +# Puedes pasar un bloque a una función +# '&' representa una referencia a un bloque +def visitantes(&bloque) + bloque.call +end + +# Puedes pasar una lista de argumentos, que serán convertidos en un arreglo +# Para eso sirve el operador ('*') +def visitantes(*arreglo) + arreglo.each { |visitante| puts visitante } +end # Define una clase con la palabra clave 'class' class Humano @@ -299,16 +409,26 @@ class Humano @nombre end + # La funcionalidad anterior puede ser encapsulada usando el método attr_accessor + # de la siguiente manera + + attr_accessor :name + + # Los métodos de tipo getter y setter también se pueden crear de manera individual + # de la siguiente manera + + attr_reader :name + attr_writer :name + # Un método de clase usa 'self' (sí mismo) para distinguirse de métodos de instancia. # Sólo puede ser llamado en la clase, no por una instancia. def self.decir(mensaje) - puts "#{mensaje}" + puts mensaje end def especie @@especie end - end @@ -328,6 +448,23 @@ dwight.nombre #=> "Dwight K. Schrute" # Llama el método de clase Humano.decir("Hi") #=> "Hi" +# El alcance de las variables es definido por la manera en que las nombramos. +# Las variables que inician con $ tienen un alcance global +$var = "Soy una variable global" +defined? $var #=> "global-variable" + +# Las variables que empiezan con @ tienen un alcance de instancia +@var = "Soy una variable de instancia" +defined? @var #=> "instance-variable" + +# Variables que empiezan con @@ tienen un alcance de clase +@@var = "Soy una variable de clase" +defined? @@var #=> "class variable" + +# Las variables que empiezan con letra mayuscula son constantes +Var = "Soy una constante" +defined? Var #=> "constant" + # Las clases también son un objeto en ruby. Por lo cual, las clases también pueden tener variables de instancia. # Variables de clase son compartidas a través de la clase y todos sus descendientes. @@ -371,7 +508,67 @@ end class Doctor < Humano end -Human.bar # 0 +Humano.bar # 0 Doctor.bar # nil +module ModuloEjemplo + def foo + 'foo' + end +end + +# Al incluir un módulo sus métodos se comparten con las instancias de la clase +# Al extender un módulo sus métodos se comparten con la clase misma + +class Persona + include ModuloEjemplo +end + +class Libro + extend ModuloEjemplo +end + +Persona.foo # => NoMethodError: undefined method `foo' for Persona:Class +Persona.new.foo # => 'foo' +Libro.foo # => 'foo' +Libro.new.foo # => NoMethodError: undefined method `foo' + +# Las llamadas de retorno (callbacks) son ejecutadas cuando se incluye o +# extiende un módulo +module EjemploConcern + def self.incluido(base) + base.extend(MetodosClase) + base.send(:include, MetodosInstancia) + end + + module MetodosClase + def bar + 'bar' + end + end + + module MetodosInstancia + def qux + 'qux' + end + end +end + +class Algo + include EjemploConcern +end + +Algo.bar #=> 'bar' +Algo.qux #=> NoMethodError: undefined method `qux' +Algo.new.bar # => NoMethodError: undefined method `bar' +Algo.new.qux # => 'qux' ``` + +## Recursos adicionales +- [Aprende Ruby Mediante Ejemplo con Ejercicios](http://www.learneroo.com/modules/61/nodes/338) - Una variante de +esta referencia con ejercicios en navegador. +- [Documentación Oficial](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby desde otros lenguajes](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programando Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una +[edición antigua](http://ruby-doc.com/docs/ProgrammingRuby/) gratuita disponible en línea. +- [Guía de estilo de Ruby](https://github.com/bbatsov/ruby-style-guide) - Guía de estilo creada por la comunidad. -- cgit v1.2.3 From d2d89cfa9742ef437e45885498677038563d56f5 Mon Sep 17 00:00:00 2001 From: Ankit Aggarwal Date: Mon, 19 Oct 2015 11:47:24 +0530 Subject: Adding documentation on ternary operator --- python3.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 2398e7ac..6d657395 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -174,6 +174,10 @@ some_var # => 5 # See Control Flow to learn more about exception handling. some_unknown_var # Raises a NameError +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + # Lists store sequences li = [] # You can start with a prefilled list -- cgit v1.2.3 From 8b3cc63b3e3441b8a8f73a5983f0de0fdd10cf02 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 19 Oct 2015 14:33:11 +0800 Subject: Fixed pythonstatcomp doc naming --- pythonstatcomp.html.markdown | 234 +++++++++++++++++++++++++++++++++++++++++++ pythonstatcomp.markdown.html | 234 ------------------------------------------- template-translations.yaml | 15 --- 3 files changed, 234 insertions(+), 249 deletions(-) create mode 100644 pythonstatcomp.html.markdown delete mode 100644 pythonstatcomp.markdown.html delete mode 100644 template-translations.yaml diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown new file mode 100644 index 00000000..78b62e33 --- /dev/null +++ b/pythonstatcomp.html.markdown @@ -0,0 +1,234 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: pythonstatcomp.py +--- + +This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Getting set up ==== + +""" Get set up with IPython and pip install the following: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Make sure to do this tutorial in the IPython notebook so that you get + the inline plots and easy documentation lookup. +""" + +# 1. Data acquisition ==== + +""" One reason people choose Python over R is that they intend to interact a lot + with the web, either by scraping pages directly or requesting data through + an API. You can do those things in R, but in the context of a project + already using Python, there's a benefit to sticking with one language. +""" + +import requests # for HTTP requests (web scraping, APIs) +import os + +# web scraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted +# save the page source in a file: +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# downloading a csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" for more on the requests module, including APIs, see + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Reading a CSV file ==== + +""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If + you've used R, you will be familiar with the idea of the "data.frame" already. +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# name age weight species +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" R users: note that Python, like most normal programming languages, starts + indexing from 0. R is the unusual one for starting from 1. +""" + +# two different ways to print out a column +pets.age +pets["age"] + +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# in R, you would expect to get 3 rows doing this, but here you get 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" If you are doing some serious linear algebra and number-crunching, you may + just want arrays, not DataFrames. DataFrames are ideal for combining columns + of different types. +""" + +# 3. Charts ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# To do data vizualization in Python, use matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn sits atop matplotlib and makes plots prettier + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# there are also some seaborn-specific plotting functions +# notice how seaborn automatically labels the x-axis on this barplot +sns.barplot(pets["age"]) + +# R veterans can still use ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# source: https://pypi.python.org/pypi/ggplot + +# there's even a d3.js port: https://github.com/mikedewar/d3py + +# 4. Simple data cleaning and exploratory analysis ==== + +""" Here's a more complicated example that demonstrates a basic data + cleaning workflow leading to the creation of some exploratory plots + and the running of a linear regression. + The data set was transcribed from Wikipedia by hand. It contains + all the Holy Roman Emperors and the important milestones in their lives + (birth, death, coronation, etc.). + The goal of the analysis will be to explore whether a relationship + exists between emperor birth year and emperor lifespan. + data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# load some data on Holy Roman Emperors +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# clean the Birth and Death columns + +import re # module for regular expressions + +rx = re.compile(r'\d+$') # match trailing digits + +""" This function applies the regular expression to an input column (here Birth, + Death), flattens the resulting list, converts it to a Series object, and + finally converts the type of the Series object from string to integer. For + more information into what different parts of the code do, see: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# make a column telling estimated age +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# simple scatterplot, no trend line, color represents dynasty +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# use scipy to run a linear regression +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# code source: http://wiki.scipy.org/Cookbook/LinearRegression + +# check the slope +slope # 0.0057672618839073328 + +# check the R^2 value: +rval**2 # 0.020363950027333586 + +# check the p-value +pval # 0.34971812581498452 + +# use seaborn to make a scatterplot and plot the linear regression trend line +sns.lmplot("BirthY", "EstAge", data=hre); + +""" For more information on seaborn, see + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + For more information on SciPy, see + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + To see a version of the Holy Roman Emperors analysis using R, see + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. + +You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers. + +Some more modules to research: + - text analysis and natural language processing: nltk, http://www.nltk.org + - social network analysis: igraph, http://igraph.org/python/ diff --git a/pythonstatcomp.markdown.html b/pythonstatcomp.markdown.html deleted file mode 100644 index 78b62e33..00000000 --- a/pythonstatcomp.markdown.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -language: Statistical computing with Python -contributors: - - ["e99n09", "https://github.com/e99n09"] -filename: pythonstatcomp.py ---- - -This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. - -```python - -# 0. Getting set up ==== - -""" Get set up with IPython and pip install the following: numpy, scipy, pandas, - matplotlib, seaborn, requests. - Make sure to do this tutorial in the IPython notebook so that you get - the inline plots and easy documentation lookup. -""" - -# 1. Data acquisition ==== - -""" One reason people choose Python over R is that they intend to interact a lot - with the web, either by scraping pages directly or requesting data through - an API. You can do those things in R, but in the context of a project - already using Python, there's a benefit to sticking with one language. -""" - -import requests # for HTTP requests (web scraping, APIs) -import os - -# web scraping -r = requests.get("https://github.com/adambard/learnxinyminutes-docs") -r.status_code # if 200, request was successful -r.text # raw page source -print(r.text) # prettily formatted -# save the page source in a file: -os.getcwd() # check what's the working directory -f = open("learnxinyminutes.html","wb") -f.write(r.text.encode("UTF-8")) -f.close() - -# downloading a csv -fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" -fn = "pets.csv" -r = requests.get(fp + fn) -print(r.text) -f = open(fn,"wb") -f.write(r.text.encode("UTF-8")) -f.close() - -""" for more on the requests module, including APIs, see - http://docs.python-requests.org/en/latest/user/quickstart/ -""" - -# 2. Reading a CSV file ==== - -""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If - you've used R, you will be familiar with the idea of the "data.frame" already. -""" - -import pandas as pd, numpy as np, scipy as sp -pets = pd.read_csv(fn) -pets -# name age weight species -# 0 fluffy 3 14 cat -# 1 vesuvius 6 23 fish -# 2 rex 5 34 dog - -""" R users: note that Python, like most normal programming languages, starts - indexing from 0. R is the unusual one for starting from 1. -""" - -# two different ways to print out a column -pets.age -pets["age"] - -pets.head(2) # prints first 2 rows -pets.tail(1) # prints last row - -pets.name[1] # 'vesuvius' -pets.species[0] # 'cat' -pets["weight"][2] # 34 - -# in R, you would expect to get 3 rows doing this, but here you get 2: -pets.age[0:2] -# 0 3 -# 1 6 - -sum(pets.age)*2 # 28 -max(pets.weight) - min(pets.weight) # 20 - -""" If you are doing some serious linear algebra and number-crunching, you may - just want arrays, not DataFrames. DataFrames are ideal for combining columns - of different types. -""" - -# 3. Charts ==== - -import matplotlib as mpl, matplotlib.pyplot as plt -%matplotlib inline - -# To do data vizualization in Python, use matplotlib - -plt.hist(pets.age); - -plt.boxplot(pets.weight); - -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); - -# seaborn sits atop matplotlib and makes plots prettier - -import seaborn as sns - -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); - -# there are also some seaborn-specific plotting functions -# notice how seaborn automatically labels the x-axis on this barplot -sns.barplot(pets["age"]) - -# R veterans can still use ggplot -from ggplot import * -ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") -# source: https://pypi.python.org/pypi/ggplot - -# there's even a d3.js port: https://github.com/mikedewar/d3py - -# 4. Simple data cleaning and exploratory analysis ==== - -""" Here's a more complicated example that demonstrates a basic data - cleaning workflow leading to the creation of some exploratory plots - and the running of a linear regression. - The data set was transcribed from Wikipedia by hand. It contains - all the Holy Roman Emperors and the important milestones in their lives - (birth, death, coronation, etc.). - The goal of the analysis will be to explore whether a relationship - exists between emperor birth year and emperor lifespan. - data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor -""" - -# load some data on Holy Roman Emperors -url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" -r = requests.get(url) -fp = "hre.csv" -f = open(fp,"wb") -f.write(r.text.encode("UTF-8")) -f.close() - -hre = pd.read_csv(fp) - -hre.head() -""" - Ix Dynasty Name Birth Death Election 1 -0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN -1 NaN Carolingian Louis I 778 20 June 840 NaN -2 NaN Carolingian Lothair I 795 29 September 855 NaN -3 NaN Carolingian Louis II 825 12 August 875 NaN -4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN - - Election 2 Coronation 1 Coronation 2 Ceased to be Emperor -0 NaN 25 December 800 NaN 28 January 814 -1 NaN 11 September 813 5 October 816 20 June 840 -2 NaN 5 April 823 NaN 29 September 855 -3 NaN Easter 850 18 May 872 12 August 875 -4 NaN 29 December 875 NaN 6 October 877 - - Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 -0 NaN NaN NaN NaN -1 Charles I son NaN NaN -2 Louis I son NaN NaN -3 Lothair I son NaN NaN -4 Louis I son NaN NaN -""" - -# clean the Birth and Death columns - -import re # module for regular expressions - -rx = re.compile(r'\d+$') # match trailing digits - -""" This function applies the regular expression to an input column (here Birth, - Death), flattens the resulting list, converts it to a Series object, and - finally converts the type of the Series object from string to integer. For - more information into what different parts of the code do, see: - - https://docs.python.org/2/howto/regex.html - - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list - - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html -""" -def extractYear(v): - return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) - -hre["BirthY"] = extractYear(hre.Birth) -hre["DeathY"] = extractYear(hre.Death) - -# make a column telling estimated age -hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) - -# simple scatterplot, no trend line, color represents dynasty -sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); - -# use scipy to run a linear regression -from scipy import stats -(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) -# code source: http://wiki.scipy.org/Cookbook/LinearRegression - -# check the slope -slope # 0.0057672618839073328 - -# check the R^2 value: -rval**2 # 0.020363950027333586 - -# check the p-value -pval # 0.34971812581498452 - -# use seaborn to make a scatterplot and plot the linear regression trend line -sns.lmplot("BirthY", "EstAge", data=hre); - -""" For more information on seaborn, see - - http://web.stanford.edu/~mwaskom/software/seaborn/ - - https://github.com/mwaskom/seaborn - For more information on SciPy, see - - http://wiki.scipy.org/SciPy - - http://wiki.scipy.org/Cookbook/ - To see a version of the Holy Roman Emperors analysis using R, see - - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R -""" -``` - -If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. - -You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers. - -Some more modules to research: - - text analysis and natural language processing: nltk, http://www.nltk.org - - social network analysis: igraph, http://igraph.org/python/ diff --git a/template-translations.yaml b/template-translations.yaml deleted file mode 100644 index 527de122..00000000 --- a/template-translations.yaml +++ /dev/null @@ -1,15 +0,0 @@ -default: - title: Learn X in Y minutes - where: Where X= - getCode: "Get the code:" - share: Share this page - suggestions: "Got a suggestion? A correction, perhaps? Open an Issue on the Github Repo, or make a pull request yourself!" - contributor: "Originally contributed by %s, and updated by %d contributors." - -zh_CN: - title: X分钟速成Y - where: 其中 Y= - getCode: 源代码下载: - share: 分享此页 - suggestions: "有建议?或者发现什么错误?在Github上开一个issue,或者你自己也可以写一个pull request!" - contributor: "原著%s,并由%d个好心人修改。" -- cgit v1.2.3 From ebb294c6f2704a9eccf8861f4c77c8f045391572 Mon Sep 17 00:00:00 2001 From: Urban Fuchs Date: Sun, 18 Oct 2015 13:32:01 +0200 Subject: translate brainfuck tutorial to German --- de-de/brainfuck-de.html.markdown | 84 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 de-de/brainfuck-de.html.markdown diff --git a/de-de/brainfuck-de.html.markdown b/de-de/brainfuck-de.html.markdown new file mode 100644 index 00000000..a5bceb10 --- /dev/null +++ b/de-de/brainfuck-de.html.markdown @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +--- + +Brainfuck ist eine extrem minimalistische Turing-vollständige Programmiersprache +mit lediglich 8 Befehlen. + +Mit dem [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/) kann +Brainfuck im Browser ausprobiert werden. + +``` +Alle Zeichen außer "><+-.,[]" (ohne die Klammern) werden ignoriert. + +Brainfuck besteht aus einem Array mit unendlich vielen Elementen, die alle mit Null initalisiert +sind und einem Datenzeiger auf das aktuelle Element. + +Es gibt acht Befehle: ++ : Erhöht den Wert an der aktuellen Stelle um Eins. +- : Verringert den Wert an der aktuellen Stelle um Eins. +> : Bewegt den Zeiger um eine Stelle weiter. +< : Bewegt den Zeiger um eine Stelle zurück. +. : Gibt den Wert der aktuellen Zelle als ASCII Wert aus (z.B. 65 = 'A'). +, : Liest ein einzelnes Zeichen von der Standardeingabe und speichert dessen ASCII Wert in der aktuellen Zelle. +[ : Wenn der Wert des aktuellen Elements Null ist, bewege des Zeiger hinter den + zugehörigen ]-Befehl. + Ansonsten, bewege den Zeiger ein Element weiter. +] : Wenn der Wert des aktuellen Elements Null ist, bewege des Zeiger um eine Stelle + weiter. + Ansonsten, bewege den Zeiger hinter den zugehörigen [-Befehl. + +[ und ] bilden eine while-Schleife. Offensichtlich müssen sie paarweise vorkommen. + +Schauen wir uns einige grundlegende Programme an. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Dieses Programm gibt den Buchstaben 'A' aus. Zunächst erhöht es den Wert der 1. Zelle auf 6. +Diese erste Zelle wird für die Schleife verwendet. Danach beginnt das Programm +die Schleife ([) und geht vor zu Zelle #2. Es erhöht den Zellwert inkrementell 10 Mal, geht dann zurück +zu Zelle #1, und verringert Zelle #1. Diese Schleife wird 6 Mal durchlaufen (nach 6 +Durchläufen ist der Wert der Zelle #1 auf 0 reduziert, dadurch wird die Schleife abgebrochen +und das Programm hinter dem korrespondierenden ] fortgesetzt). + +An dieser Stelle befinden wir uns an Zelle #1, die jetzt den Wert 0 hat, während Zelle #2 +den Wert 60 hat. Wir gehen vor zu Zelle #2, inkrementieren 5 Mal, bis zum Wert 65, +und geben dann den Wert der Zelle #2 aus. 65 ist ein 'A' im ASCII Zeichensatz, +daher wird 'A' am Terminal ausgegeben.. + + +, [ > + < - ] > . + +Dieses Programm liest ein Zeichen von der Benutzereingabe und schreibt dessen Wert +in Zelle #1. Danach beginnt eine Schleife. Rücke vor auf Zelle #2, erhöhe den Wert der Zelle #2, +gehe zurück auf Zelle #1, verringere den Wert der Zelle #1. Dies geht solange bis +Zelle #1 den Wert 0 und Zelle #2 den alten Wert aus #1 hat. Da wir am Ende der Schleife +bie Zelle #1 sind, gehe vor zu Zelle #2 und gibt denb Wert als ASCII Zeichen aus. + +Beachte biite, dass die Leerzeichen nur aus Gründen der Lesbarkeit geschrieben werden. +Man könnte genauso schreiben: + +,[>+<-]>. + +Versuche herauszufinden, was dieses Programm macht: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Dieses Programm nimmt zwei Zahlen als Eingabe und multipliziert sie. + +Im Wesentlichen liest es zunächst zwei Werte ein. Dann beginnt die äußere Schleife +mit Zelle #1 als Zähler. Danach geht das Programm zu Zelle #2 vor und startet die innere Schleife +mit Zelle #2 als Zähler. Diese zählt Zelle #3 hoch. Es gibt jedoch ein Problem: +Am Ende der inneren Schleife hat Zelle #2 den Wert Null. Daher würde die innere +Schleife beim nächsten Durchgang nicht mehr funktionieren. Daher wird auch Zelle #4 +erhöht und anschließend in Zelle #2 zurückkopiert. +Am Ende steht in Zelle #3 das Ergebnis. +``` + +Das ist Brainfuck. Nicht so schwierig, oder? Zum Spaß kannst du dein eigenes Brainfuchs +Programm schreiben oder du schreibst einen Brainfuck Interpreter in einer anderen +Programmiersprache. Der Interpreter lässt sich ziemlich einfach implementieren. +Falls du Masochist bist, kannst du auch versuchen, einen Brainfuck Interpreter in Brainfuck zu implementieren. -- cgit v1.2.3 From 7c342d41d141b375d287ed09c623d5c5a6cfb0e0 Mon Sep 17 00:00:00 2001 From: Felix Date: Mon, 19 Oct 2015 09:02:07 +0200 Subject: fixed link to the freebsd handbook --- zfs.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index 74487e35..f99d7134 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -393,7 +393,7 @@ echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ### Additional Reading * [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) -* [FreeBSD Handbook on ZFS](https://wiki.freebsd.org/ZF://wiki.freebsd.org/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) -- cgit v1.2.3 From a8ebd498338183f3469e37f7763aad6d644780e1 Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 13:34:59 +0200 Subject: [d/fr] adds translation --- fr-fr/d.html.markdown | 291 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 fr-fr/d.html.markdown diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown new file mode 100644 index 00000000..dfc3519d --- /dev/null +++ b/fr-fr/d.html.markdown @@ -0,0 +1,291 @@ +--- +language: D +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] + - ["Quentin Ladeveze", "aceawan.eu"] +lang: fr +--- + +```d +// Commençons par un classique +module hello; + +import std.stdio; + +// args n'est pas obligatoire +void main(string[] args) { + writeln("Bonjour le monde !"); +} +``` + +Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a +de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). +D est un langage de programmation moderne, généraliste, multi-paradigme qui contient +des fonctionnalités aussi bien de bas-niveau que haut-niveau. + +D is actively developed by a large group of super-smart people and is spearheaded by +[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and +[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu). +With all that out of the way, let's look at some examples! + +D est activement développé par de nombreuses personnes très intelligents, guidées par +[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et +[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). +Après cette petite introduction, jetons un coup d'oeil à quelques exemples. + +```d +import std.stdio; + +void main() { + + //Les conditions et les boucles sont classiques. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // On peut utiliser auto pour inférer automatiquement le + // type d'une variable. + auto n = 1; + + // On peut faciliter la lecture des valeurs numériques + // en y insérant des `_`. + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For et while sont très utiles, mais en D, on préfère foreach. + // Les deux points : '..', créent un intervalle continue de valeurs + // incluant la première mais excluant la dernière. + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // On peut également utiliser foreach_reverse pour itérer à l'envers. + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("Non !"); + } + } +} +``` + +We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions +are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, +we can use templates to parameterize all of these on both types and values! + +On peut définir de nouveaux types avec les mots-clés `struct`, `class`, +`union` et `enum`. Les structures et les unions sont passées au fonctions par +valeurs (elle sont copiées) et les classes sont passées par référence. De plus, +On peut utiliser les templates pour rendre toutes ces abstractions génériques. + +```d +// Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. +struct LinkedList(T) { + T data = null; + + // Utilisez '!' pour instancier un type paramétré. + // Encore une fois semblable à '' + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + + // Si il n'y a qu'un seul paramètre de template, + // on peut s'abstenir de parenthèses. + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Utilisez alias pour créer des abreviations pour les types. +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// On peut tout aussi bien créer des templates de function ! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé +// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur. +// Ici ils seront toujours passés par référence à 'swap()'. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// Avec les templates, on peut également passer des valeurs en paramètres. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // T est 'int' par défaut + +``` +À propos de classes, parlons des propriétés. Une propriété est, en gros, +une méthode qui peut se comporter comme une lvalue. On peut donc utiliser +la syntaxe des structures classiques (`struct.x = 7`) comme si il +s'agissait de méthodes getter ou setter. + +```d +// Considérons une classe paramétrée avec les types 'T' et 'U' +class MyClass(T, U) { + T _data; + U _other; +} + +// Et des méthodes "getter" et "setter" comme suit: +class MyClass(T, U) { + T _data; + U _other; + + // Les constructeurs s'apellent toujours 'this'. + this(T t, U u) { + // Ceci va appeller les setters ci-dessous. + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +// Et on l'utilise de cette façon: +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + // Importer le module 'stdio' de la bibliothèque standard permet + // d'écrire dans la console (les imports peuvent être locaux à une portée) + import std.stdio; + + // On appelle les getters pour obtenir les valeurs. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // On appelle les setter pour assigner de nouvelles valeurs. + mc.data = 8; + mc.other = "eight"; + + // On appelle les setter pour obtenir les nouvelles valeurs. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` + +With properties, we can add any amount of logic to +our getter and setter methods, and keep the clean syntax of +accessing members directly! + +Other object-oriented goodies at our disposal +include `interface`s, `abstract class`es, +and `override`ing methods. D does inheritance just like Java: +Extend one class, implement as many interfaces as you please. + +We've seen D's OOP facilities, but let's switch gears. D offers +functional programming with first-class functions, `pure` +functions, and immutable data. In addition, all of your favorite +functional algorithms (map, filter, reduce and friends) can be +found in the wonderful `std.algorithm` module! + +Avec les propriétés, on peut constuire nos setters et nos getters +comme on le souhaite, tout en gardant un syntaxe très propre, +comme si on accédait directement à des membres de la classe. + +Les autres fonctionnalités orientées objets à notre disposition +incluent les interfaces, les classes abstraites, et la surcharge +de méthodes. D gère l'héritage comme Java: On ne peut hériter que +d'une seule classe et implémenter autant d'interface que voulu. + +Nous venons d'explorer les fonctionnalités objet du D, mais changeons +un peu de domaine. D permet la programmation fonctionelle, avec les fonctions +de premier ordre, les fonctions `pure` et les données immuables. +De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter) +sont disponibles dans le module `std.algorithm`. + +```d +import std.algorithm : map, filter, reduce; +import std.range : iota; // construit un intervalle excluant la dernière valeur. + +void main() { + // On veut un algorithm qui affiche la somme de la listes des carrés + // des entiers paires de 1 à 100. Un jeu d'enfant ! + + // On se content de passer des expressions lambda en paramètre à des templates. + // On peut fournier au template n'importe quelle fonction, mais dans notre + // cas, les lambdas sont pratiques. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Vous voyez comme on a calculé `num` comme on le ferait en haskell par exemple ? +C'est grâce à une innvoation de D qu'on appelle "Uniform Function Call Syntax". +Avec l'UFCS, on peut choisir d'écrire un appelle à une fonction de manière +classique, ou comme un appelle à une méthode. Walter Brighter a écrit un +article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +Pour faire court, on peut appeller une fonction dont le premier paramètre +est de type A, comme si c'était une méthode de A. + +J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça +Voyons comment on le fait en D ! + +```d +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // On veut calculer la racine carré de tous les nombres + // dans notre tableau, et profiter de tous les coeurs + // à notre disposition. + auto arr = new double[1_000_000]; + + // On utilise un index et une référence à chaque élément du tableau. + // On appelle juste la fonction parallel sur notre tableau ! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` -- cgit v1.2.3 From 6313536895742385f743b05ed84c1efc274204f7 Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 13:35:38 +0200 Subject: [d/fr] adds translation --- fr-fr/d.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index dfc3519d..5d72a2d0 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -1,10 +1,10 @@ --- language: D -filename: learnd.d +filename: learnd-fr.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] - ["Quentin Ladeveze", "aceawan.eu"] -lang: fr +lang: fr-f --- ```d -- cgit v1.2.3 From 7f8b8d036302ee7e7ba2c47b11c3833b864bffab Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 13:38:10 +0200 Subject: correct translator name --- fr-fr/d.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index 5d72a2d0..f9dececb 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -3,6 +3,7 @@ language: D filename: learnd-fr.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +translators: - ["Quentin Ladeveze", "aceawan.eu"] lang: fr-f --- -- cgit v1.2.3 From 5507a389903c4b2ff66aa811f6952a78e99c3c7a Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 13:39:05 +0200 Subject: correct language --- fr-fr/d.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index f9dececb..2c90a628 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] translators: - ["Quentin Ladeveze", "aceawan.eu"] -lang: fr-f +lang: fr-fr --- ```d -- cgit v1.2.3 From c759b6ea2bc1dd1ddad8d08bcdf5741d7e7711b0 Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 13:39:44 +0200 Subject: removes english text --- fr-fr/d.html.markdown | 5 ----- 1 file changed, 5 deletions(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index 2c90a628..d75f1083 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -25,11 +25,6 @@ de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang. D est un langage de programmation moderne, généraliste, multi-paradigme qui contient des fonctionnalités aussi bien de bas-niveau que haut-niveau. -D is actively developed by a large group of super-smart people and is spearheaded by -[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and -[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu). -With all that out of the way, let's look at some examples! - D est activement développé par de nombreuses personnes très intelligents, guidées par [Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et [Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). -- cgit v1.2.3 From 00182d32f4e2eebf46d12910e885b0dde3eabdbc Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 13:40:27 +0200 Subject: removes english text --- fr-fr/d.html.markdown | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index d75f1083..702de206 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -72,11 +72,6 @@ void main() { } } ``` - -We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions -are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, -we can use templates to parameterize all of these on both types and values! - On peut définir de nouveaux types avec les mots-clés `struct`, `class`, `union` et `enum`. Les structures et les unions sont passées au fonctions par valeurs (elle sont copiées) et les classes sont passées par référence. De plus, @@ -204,22 +199,6 @@ void main() { writefln("Later: data = %d, str = %s", mc.data, mc.other); } ``` - -With properties, we can add any amount of logic to -our getter and setter methods, and keep the clean syntax of -accessing members directly! - -Other object-oriented goodies at our disposal -include `interface`s, `abstract class`es, -and `override`ing methods. D does inheritance just like Java: -Extend one class, implement as many interfaces as you please. - -We've seen D's OOP facilities, but let's switch gears. D offers -functional programming with first-class functions, `pure` -functions, and immutable data. In addition, all of your favorite -functional algorithms (map, filter, reduce and friends) can be -found in the wonderful `std.algorithm` module! - Avec les propriétés, on peut constuire nos setters et nos getters comme on le souhaite, tout en gardant un syntaxe très propre, comme si on accédait directement à des membres de la classe. -- cgit v1.2.3 From c60ddc6ef5d80cc87b051b848ccce0b7f335f5f1 Mon Sep 17 00:00:00 2001 From: MDS Date: Tue, 20 Oct 2015 01:01:14 +1300 Subject: Updated official python docs to always use the latest version of python 2 --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 675967f4..42a52bcf 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -707,7 +707,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) +* [The Official Docs](http://docs.python.org/2/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) -- cgit v1.2.3 From 998e76c310422e0946431b036eb7de03a9384e74 Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Mon, 19 Oct 2015 08:09:58 -0500 Subject: [typescript/en] Typo fixed in 'backticks' --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 61b0fdb8..17c56e7a 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -159,7 +159,7 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); // Including references to a definition file: /// -// Template Strings (strings that use backtics) +// Template Strings (strings that use backticks) // String Intepolation with Template Strings var name = 'Tyrone'; var greeting = `Hi ${name}, how are you?` -- cgit v1.2.3 From 5f7a161f44e683d15d85126db78a6de5f1e0bfab Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 10:17:14 -0300 Subject: Figure handle and some text issues fixed - File name added to the header; - Fixed figure handle letter; - Unnecessary extra word removed; --- matlab.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 0cbc6f57..4d97834c 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -1,10 +1,11 @@ --- language: Matlab +filename: learnmatlab.mat contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] - ["Colton Kohnke", "http://github.com/voltnor"] - + - ["Claudson Martins", "http://github.com/claudsonm"] --- MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. @@ -261,7 +262,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure % Create new figure object, with handle f +h = figure % Create new figure object, with handle h figure(h) % Makes the figure corresponding to handle h the current figure close(h) % close figure with handle h close all % close all open figure windows @@ -329,7 +330,7 @@ double_input(6) % ans = 12 % anonymous function. Useful when quickly defining a function to pass to % another function (eg. plot with fplot, evaluate an indefinite integral % with quad, find roots with fzero, or find minimum with fminsearch). -% Example that returns the square of it's input, assigned to to the handle sqr: +% Example that returns the square of it's input, assigned to the handle sqr: sqr = @(x) x.^2; sqr(10) % ans = 100 doc function_handle % find out more -- cgit v1.2.3 From 69263413a137d69c14c307f286e13b440ccdb139 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 10:25:57 -0300 Subject: Revert "Figure handle and some text issues fixed" This reverts commit 5f7a161f44e683d15d85126db78a6de5f1e0bfab. --- matlab.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 4d97834c..0cbc6f57 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -1,11 +1,10 @@ --- language: Matlab -filename: learnmatlab.mat contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] - ["Colton Kohnke", "http://github.com/voltnor"] - - ["Claudson Martins", "http://github.com/claudsonm"] + --- MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. @@ -262,7 +261,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure % Create new figure object, with handle h +h = figure % Create new figure object, with handle f figure(h) % Makes the figure corresponding to handle h the current figure close(h) % close figure with handle h close all % close all open figure windows @@ -330,7 +329,7 @@ double_input(6) % ans = 12 % anonymous function. Useful when quickly defining a function to pass to % another function (eg. plot with fplot, evaluate an indefinite integral % with quad, find roots with fzero, or find minimum with fminsearch). -% Example that returns the square of it's input, assigned to the handle sqr: +% Example that returns the square of it's input, assigned to to the handle sqr: sqr = @(x) x.^2; sqr(10) % ans = 100 doc function_handle % find out more -- cgit v1.2.3 From f8a2b28890d5d68a252d5bc0fd8247495b680e09 Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 15:28:43 +0200 Subject: fix indentation and typos --- fr-fr/d.html.markdown | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index 702de206..6782142d 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -4,7 +4,7 @@ filename: learnd-fr.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] translators: - - ["Quentin Ladeveze", "aceawan.eu"] + - ["Quentin Ladeveze", "aceawan.eu"] lang: fr-fr --- @@ -22,8 +22,8 @@ void main(string[] args) { Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). -D est un langage de programmation moderne, généraliste, multi-paradigme qui contient -des fonctionnalités aussi bien de bas-niveau que haut-niveau. +D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient +des fonctionnalités aussi bien de bas niveau que de haut niveau. D est activement développé par de nombreuses personnes très intelligents, guidées par [Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et @@ -34,18 +34,17 @@ Après cette petite introduction, jetons un coup d'oeil à quelques exemples. import std.stdio; void main() { - - //Les conditions et les boucles sont classiques. + //Les conditions et les boucles sont classiques. for(int i = 0; i < 10000; i++) { writeln(i); } - // On peut utiliser auto pour inférer automatiquement le - // type d'une variable. + // On peut utiliser auto pour inférer automatiquement le + // type d'une variable. auto n = 1; // On peut faciliter la lecture des valeurs numériques - // en y insérant des `_`. + // en y insérant des `_`. while(n < 10_000) { n += n; } -- cgit v1.2.3 From 79d0e7cd23635bb2fb545d897527fd199a9296d2 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 10:30:14 -0300 Subject: Figure handle and some text issues fixed - File name added to the header; - Fixed figure handle letter; - Unnecessary extra word removed. --- matlab.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 0cbc6f57..4d97834c 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -1,10 +1,11 @@ --- language: Matlab +filename: learnmatlab.mat contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] - ["Colton Kohnke", "http://github.com/voltnor"] - + - ["Claudson Martins", "http://github.com/claudsonm"] --- MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. @@ -261,7 +262,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure % Create new figure object, with handle f +h = figure % Create new figure object, with handle h figure(h) % Makes the figure corresponding to handle h the current figure close(h) % close figure with handle h close all % close all open figure windows @@ -329,7 +330,7 @@ double_input(6) % ans = 12 % anonymous function. Useful when quickly defining a function to pass to % another function (eg. plot with fplot, evaluate an indefinite integral % with quad, find roots with fzero, or find minimum with fminsearch). -% Example that returns the square of it's input, assigned to to the handle sqr: +% Example that returns the square of it's input, assigned to the handle sqr: sqr = @(x) x.^2; sqr(10) % ans = 100 doc function_handle % find out more -- cgit v1.2.3 From 13c9d9af5cc60ae747d42f73d795f360a15f3fd8 Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 15:33:48 +0200 Subject: fix indentation and typos --- fr-fr/d.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index 6782142d..ee69ca34 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -90,7 +90,7 @@ class BinTree(T) { T data = null; // Si il n'y a qu'un seul paramètre de template, - // on peut s'abstenir de parenthèses. + // on peut s'abstenir de mettre des parenthèses. BinTree!T left; BinTree!T right; } -- cgit v1.2.3 From d7e3def01ec674a7578581c1fb8b003cd164d335 Mon Sep 17 00:00:00 2001 From: aceawan Date: Mon, 19 Oct 2015 15:40:44 +0200 Subject: fix indentation and typos --- fr-fr/d.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index ee69ca34..96158683 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -72,9 +72,8 @@ void main() { } ``` On peut définir de nouveaux types avec les mots-clés `struct`, `class`, -`union` et `enum`. Les structures et les unions sont passées au fonctions par -valeurs (elle sont copiées) et les classes sont passées par référence. De plus, -On peut utiliser les templates pour rendre toutes ces abstractions génériques. +`union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés) +De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. ```d // Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. -- cgit v1.2.3 From 5ca38bf934801c9e85e25e19842a6f84ebe6efa0 Mon Sep 17 00:00:00 2001 From: Andrew Backes Date: Mon, 19 Oct 2015 10:40:57 -0500 Subject: [typescript/en] Fixing typo in 'Interpolation' --- typescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 17c56e7a..20974304 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -160,7 +160,7 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); /// // Template Strings (strings that use backticks) -// String Intepolation with Template Strings +// String Interpolation with Template Strings var name = 'Tyrone'; var greeting = `Hi ${name}, how are you?` // Multiline Strings with Template Strings -- cgit v1.2.3 From 3835cd26f5c58b05c547d2c9d51b39252e0eca15 Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Mon, 19 Oct 2015 10:54:42 -0500 Subject: [javascript/en] Added setInterval Added the setInterval function provided by most browsers --- javascript.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index d408e885..22a2959c 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -310,6 +310,12 @@ setTimeout(myFunction, 5000); // Note: setTimeout isn't part of the JS language, but is provided by browsers // and Node.js. +// Another function provided by browsers is setInterval +function myFunction(){ + // this code will be called every 5 seconds +} +setInterval(myFunction(), 5000); + // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ -- cgit v1.2.3 From adefaa5fdf1de01dc8318a69d440bfc71a7629c7 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 13:07:17 -0300 Subject: Ruby Ecosystem translation to portuguese The whole article has been translated. --- pt-br/ruby-ecosystem-pt.html.markdown | 147 ++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 pt-br/ruby-ecosystem-pt.html.markdown diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown new file mode 100644 index 00000000..0298f8a1 --- /dev/null +++ b/pt-br/ruby-ecosystem-pt.html.markdown @@ -0,0 +1,147 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Claudson Martins", "http://github.com/claudsonm"] +lang: pt-br + +--- + +Pessoas utilizando Ruby geralmente têm uma forma de instalar diferentes versões +do Ruby, gerenciar seus pacotes (ou gemas) e as dependências das gemas. + +## Gerenciadores Ruby + +Algumas plataformas possuem o Ruby pré-instalado ou disponível como um pacote. +A maioria dos "rubistas" não os usam, e se usam, é apenas para inicializar outro +instalador ou implementação do Ruby. Ao invés disso, rubistas tendêm a instalar +um gerenciador para instalar e alternar entre diversas versões do Ruby e seus +ambientes de projeto. + +Abaixo estão os gerenciadores Ruby mais populares: + +* [RVM](https://rvm.io/) - Instala e alterna entre os rubies. RVM também possui + o conceito de gemsets para isolar os ambientes dos projetos completamente. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Apenas instala os + rubies. Use este para um melhor controle sobre a instalação de seus rubies. +* [rbenv](https://github.com/sstephenson/rbenv) - Apenas alterna entre os rubies. + Usado com o ruby-build. Use este para um controle mais preciso sobre a forma + como os rubies são carregados. +* [chruby](https://github.com/postmodern/chruby) - Apenas alterna entre os rubies. + A concepção é bastante similar ao rbenv. Sem grandes opções sobre como os + rubies são instalados. + +## Versões do Ruby + +O Ruby foi criado por Yukihiro "Matz" Matsumoto, que continua a ser uma espécie +de [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), embora +isso esteja mudando recentemente. Como resultado, a implementação de referência +do Ruby é chamada de MRI (Matz' Reference Implementation), e quando você ver uma +versão do Ruby, ela está se referindo a versão de lançamento do MRI. + +As três principais versões do Ruby em uso são: + +* 2.0.0 - Lançada em Fevereiro de 2013. Maioria das principais bibliotecas e + suporte a frameworks 2.0.0. +* 1.9.3 - Lançada em Outubro de 2011. Está é a versão mais utilizada pelos rubistas + atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - O Ruby 1.8.7 foi + [aposentado](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +A diferença entre a versão 1.8.7 para 1.9.x é muito maior do que a da 1.9.3 para +a 2.0.0. Por exemplo, a série 1.9 introduziu encodes e uma VM bytecode. Ainda +existem projetos na versão 1.8.7, mas eles estão tornando-se uma pequena minoria +pois a maioria da comunidade migrou para a versão, pelo menos, 1.9.2 ou 1.9.3. + +## Implementações Ruby + +O ecossistema Ruby conta com várias diferentes implementações do Ruby, cada uma +com pontos fortes e estados de compatibilidade. Para ser claro, as diferentes +implementações são escritas em diferentes linguagens, mas *todas elas são Ruby*. +Cada implementação possui hooks especiais e recursos extra, mas todas elas +executam arquivos normais do Ruby tranquilamente. Por exemplo, JRuby é escrita +em Java, mas você não precisa saber Java para utilizá-la. + +Muito maduras/compatíveis: + +* [MRI](https://github.com/ruby/ruby) - Escrita em C, esta é a implementação de + referência do Ruby. Por definição, é 100% compatível (consigo mesma). Todos os + outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo). +* [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação + robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a + interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projets, e + linguagens existentes. +* [Rubinius](http://rubini.us/) - Escrita principalmente no próprio Ruby, com + uma VM bytecode em C++. Também madura e rápida. Por causa de sua implementação + em Ruby, ela expõe muitos recursos da VM na rubyland. + +Medianamente maduras/compatíveis: + +* [Maglev](http://maglev.github.io/) - Construída em cima da Gemstone, uma + máquina virtual Smalltalk. Smalltalk possui algumas ferramentas impressionantes, + e este projeto tenta trazer isso para o desenvolvimento Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Traz o Ruby para o desenvolvimento iOS. + +Pouco maduras/compatíveis: + +* [Topaz](http://topazruby.com/) - Escrita em RPython (usando o conjunto de + ferramentas PyPy), Topaz é bastante jovem e ainda não compatível. Parece ser + promissora como uma implementação Ruby de alta performance. +* [IronRuby](http://ironruby.net/) - Escrita em C# visando a plataforma .NET, + o trabalho no IronRuby parece ter parado desde que a Microsoft retirou seu apoio. + +Implementações Ruby podem ter seus próprios números de lançamento, mas elas +sempre focam uma versão específica da MRI para compatibilidade. Diversas +implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por +exemplo) para especificar qual versão da MRI focar. + +## RubySpec + +A maioria das implementações Ruby dependem fortemente da [RubySpec](http://rubyspec.org/). +Ruby não tem uma especificação oficial, então a comunidade tem escrito +especificações executáveis em Ruby para testar a compatibilidade de suas +implementações com a MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) é um gerenciador de pacotes para Ruby mantido +pela comunidade. RubyGems vem com o Ruby, portanto não é preciso baixar separadamente. + +Os pacotes do Ruby são chamados de "gemas", e elas podem ser hospedadas pela +comunidade em RubyGems.org. Cada gema contém seu código-fonte e alguns metadados, +incluindo coisas como versão, dependências, autor(es) e licença(s). + +## Bundler + +[Bundler](http://bundler.io/) é um gerenciador de dependências para as gemas. +Ele usa a Gemfile de um projeto para encontrar dependências, e então busca as +dependências dessas dependências de forma recursiva. Ele faz isso até que todas +as dependências sejam resolvidas e baixadas, ou para se encontrar um conflito. + +O Bundler gerará um erro se encontrar um conflito entre dependências. Por exemplo, +se a gema A requer versão 3 ou maior que a gema Z, mas a gema B requer a versão +2, o Bundler irá notificá-lo que há um conflito. Isso se torna extremamente útil +quando diversas gemas começam a referenciar outras gemas (que referem-se a outras +gemas), o que pode formar uma grande cascata de dependências a serem resolvidas. + +# Testes + +Testes são uma grande parte da cultura do Ruby. O Ruby vem com o seu próprio +framework de teste de unidade chamado minitest (ou TestUnit para Ruby versão 1.8.x). +Existem diversas bibliotecas de teste com diferentes objetivos. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) + - Framework de testes "Unit-style" para o Ruby 1.8 (built-in) +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) + - Framework de testes para o Ruby 1.9/2.0 (built-in) +* [RSpec](http://rspec.info/) - Um framework de testes que foca na expressividade +* [Cucumber](http://cukes.info/) - Um framework de testes BDD que analisa testes Gherkin formatados + +## Seja Legal + +A comunidade Ruby orgulha-se de ser uma comunidade aberta, diversa, e receptiva. +O próprio Matz é extremamente amigável, e a generosidade dos rubistas em geral +é incrível. -- cgit v1.2.3 From 09ceb868bc045d81fc4cf91b77708bb1f9671e50 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Mon, 19 Oct 2015 13:16:49 -0300 Subject: Test list fix and some other minor improvements --- pt-br/ruby-ecosystem-pt.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown index 0298f8a1..da4f6f37 100644 --- a/pt-br/ruby-ecosystem-pt.html.markdown +++ b/pt-br/ruby-ecosystem-pt.html.markdown @@ -47,7 +47,7 @@ As três principais versões do Ruby em uso são: * 2.0.0 - Lançada em Fevereiro de 2013. Maioria das principais bibliotecas e suporte a frameworks 2.0.0. * 1.9.3 - Lançada em Outubro de 2011. Está é a versão mais utilizada pelos rubistas - atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) + atualmente. Também [aposentada](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/). * 1.8.7 - O Ruby 1.8.7 foi [aposentado](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). @@ -72,7 +72,7 @@ Muito maduras/compatíveis: outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo). * [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a - interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projets, e + interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projetos, e linguagens existentes. * [Rubinius](http://rubini.us/) - Escrita principalmente no próprio Ruby, com uma VM bytecode em C++. Também madura e rápida. Por causa de sua implementação @@ -81,7 +81,7 @@ Muito maduras/compatíveis: Medianamente maduras/compatíveis: * [Maglev](http://maglev.github.io/) - Construída em cima da Gemstone, uma - máquina virtual Smalltalk. Smalltalk possui algumas ferramentas impressionantes, + máquina virtual Smalltalk. O Smalltalk possui algumas ferramentas impressionantes, e este projeto tenta trazer isso para o desenvolvimento Ruby. * [RubyMotion](http://www.rubymotion.com/) - Traz o Ruby para o desenvolvimento iOS. @@ -94,7 +94,7 @@ Pouco maduras/compatíveis: o trabalho no IronRuby parece ter parado desde que a Microsoft retirou seu apoio. Implementações Ruby podem ter seus próprios números de lançamento, mas elas -sempre focam uma versão específica da MRI para compatibilidade. Diversas +sempre focam em uma versão específica da MRI para compatibilidade. Diversas implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por exemplo) para especificar qual versão da MRI focar. @@ -133,10 +133,10 @@ Testes são uma grande parte da cultura do Ruby. O Ruby vem com o seu próprio framework de teste de unidade chamado minitest (ou TestUnit para Ruby versão 1.8.x). Existem diversas bibliotecas de teste com diferentes objetivos. -* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - - Framework de testes "Unit-style" para o Ruby 1.8 (built-in) -* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - - Framework de testes para o Ruby 1.9/2.0 (built-in) +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - + Framework de testes "Unit-style" para o Ruby 1.8 (built-in) +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - + Framework de testes para o Ruby 1.9/2.0 (built-in) * [RSpec](http://rspec.info/) - Um framework de testes que foca na expressividade * [Cucumber](http://cukes.info/) - Um framework de testes BDD que analisa testes Gherkin formatados -- cgit v1.2.3 From d78518288bd8d37714ff00355274a7527e0e5a66 Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Mon, 19 Oct 2015 12:42:23 -0500 Subject: removed () --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 22a2959c..81dc09a9 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -314,7 +314,7 @@ setTimeout(myFunction, 5000); function myFunction(){ // this code will be called every 5 seconds } -setInterval(myFunction(), 5000); +setInterval(myFunction, 5000); // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. -- cgit v1.2.3 From 406eb11b74c5ad5d0feb29523cf49582e3ebda7e Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Mon, 19 Oct 2015 20:59:53 +0200 Subject: typo fix --- de-de/go-de.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 765372e0..7e61bf81 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -3,6 +3,7 @@ language: Go filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] + - ["Dennis Keller", "https://github.com/denniskeller"] lang: de-de --- Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in @@ -306,7 +307,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## Weitere Resourcen Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). -Dort können sie der Tutorial folgen, interaktiv Quelltext ausprobieren und viel +Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel Dokumentation lesen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr -- cgit v1.2.3 From 7fdce9215acde388da6de41f524aefa8bfb05532 Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Mon, 19 Oct 2015 16:00:22 -0500 Subject: Fixed bracket placement --- javascript.html.markdown | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 81dc09a9..a119be88 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -291,12 +291,9 @@ myFunction("foo"); // = "FOO" // Note that the value to be returned must start on the same line as the // `return` keyword, otherwise you'll always return `undefined` due to // automatic semicolon insertion. Watch out for this when using Allman style. -function myFunction() -{ +function myFunction(){ return // <- semicolon automatically inserted here - { - thisIsAn: 'object literal' - } + {thisIsAn: 'object literal'} } myFunction(); // = undefined -- cgit v1.2.3 From 6c0652bc9c3615df8a62791110c2d02c867b4615 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 14:39:09 -0700 Subject: objc-spanish --- es-es/objective-c-es.html.markdown | 780 +++++++++++++++++++++++++++++++++++++ 1 file changed, 780 insertions(+) create mode 100644 es-es/objective-c-es.html.markdown diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown new file mode 100644 index 00000000..fc769188 --- /dev/null +++ b/es-es/objective-c-es.html.markdown @@ -0,0 +1,780 @@ +--- + +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] +translators: + - ["David Hsieh", "http://github.com/deivuh"] +lang: es-es +filename: LearnObjectiveC.m + +--- +Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch. +Es un lenguaje de programación para propósito general que le agrega al lenguaje de programación C una mensajería estilo "Smalltalk". + + +```objective_c +// Los comentarios de una sola línea inician con // + +/* +Los comentarios de múltiples líneas se ven así. +*/ + +// Importa los encabezados de Foundation con #import +// Utiliza <> para importar archivos globales (generalmente frameworks) +// Utiliza "" para importar archivos locales (del proyecto) +#import +#import "MyClass.h" + +// Si habilitas módulos para proyectos de iOS >= 7.0 u OS X >= 10.9 en +// Xcode 5, puedes importarlos de la siguiente manera: +@import Foundation; + +// El punto de entrada de tu programa es una función llamada +// main con un tipo de retorno entero. +int main (int argc, const char * argv[]) +{ + // Crear un autorelease pool para manejar la memoria al programa + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + // Si se utiliza el conteo automático de referencias (ARC), utiliza @autoreleasepool: + @autoreleasepool { + + // Utiliza NSLog para imprimir líneas a la consola + NSLog(@"Hello World!"); // Imprimir el string "Hello World!" + + /////////////////////////////////////// + // Tipos y variables + /////////////////////////////////////// + + // Declaraciones de primitivos + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; + + // Declaraciones de objetos + // Pon el * como prefijo de los nombre de las variables para declaraciones de + // objetos de tipos fuertes + MyClass *myObject1 = nil; // Tipo fuerte + id myObject2 = nil; // Tipo débil + // %@ es un objeto + // 'description' es una convención para mostrar el valor de los objetos + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // imprime => "(null) y (null)" + + // String + NSString *worldString = @"World"; + NSLog(@"Hello %@!", worldString); // imprime => "Hello World!" + // NSMutableString es una versión mutable del objeto NSString + NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; + [mutableString appendString:@" World!"]; + NSLog(@"%@", mutableString); // imprime => "Hello World!" + + // Literales de caracteres + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; // o 'Z' + NSLog(@"%c", theLetterZ); + + // Literales de enteros + NSNumber *fortyTwoNumber = @42; + int fortyTwo = [fortyTwoNumber intValue]; // o 42 + NSLog(@"%i", fortyTwo); + + NSNumber *fortyTwoUnsignedNumber = @42U; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // o 42 + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // o 42 + NSLog(@"%hi", fortyTwoShort); + + NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // o 41 + NSLog(@"%u", fortyOneUnsigned); + + NSNumber *fortyTwoLongNumber = @42L; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // o 42 + NSLog(@"%li", fortyTwoLong); + + NSNumber *fiftyThreeLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // o 53 + NSLog(@"%lu", fiftyThreeUnsigned); + + // Literales de punto flotante + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloatNumber floatValue]; // o 3.141592654f + NSLog(@"%f", piFloat); // imprime => 3.141592654 + NSLog(@"%5.2f", piFloat); // imprime => " 3.14" + + NSNumber *piDoubleNumber = @3.1415926535; + double piDouble = [piDoubleNumber doubleValue]; // o 3.1415926535 + NSLog(@"%f", piDouble); + NSLog(@"%4.2f", piDouble); // imprime => "3.14" + + // NSDecimalNumber es una clase de punto-fijo que es más preciso que float o double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber no tiene la capacidad de utilizar los operadores estándares + // +, -, * , /, por lo que cuenta con sus propios operadores: + [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // imprime => 10.99 como NSDecimalNumber es inmutable + + // Literales BOOL + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + // o + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // prints => 1 + + // Objecto arreglo + // Puede contener diferentes tipos de datos, pero deben de ser un objeto de + // Objective-C + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdNumber); // imprime => "Third number = 3" + // NSMutableArray es una versión mutable de NSArray, permitiendo el cambio + // de los elementos del arreglo y el agrandado o encojimiento del objeto arreglo. + // Conveniente, pero no tan eficiente como NSArray en cuanto a rendimiento. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Hello"]; + [mutableArray addObject:@"World"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // imprime => "World" + + // Objecto Diccionario + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Object = %@", valueObject); // imprime => "Object = (null)" + // NSMutableDictionary también está disponible como un objeto mutable + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"value1" forKey:@"key1"]; + [mutableDictionary setObject:@"value2" forKey:@"key2"]; + [mutableDictionary removeObjectForKey:@"key1"]; + + // Objeto de Set + NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; + NSLog(@"%@", set); // imprime => {(Hello, World)} (el orden puede variar) + // NSMutableSet también está disponible como un objeto mutable + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Hello"]; + [mutableSet addObject:@"Hello"]; + NSLog(@"%@", mutableSet); // prints => {(Hello)} + + /////////////////////////////////////// + // Operadores + /////////////////////////////////////// + + // Los operadores funcionan como en el lenguaje C + // Por ejemplo: + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f + 3 == 2; // => 0 (NO) + 3 != 2; // => 1 (YES) + 1 && 1; // => 1 (and lógico) + 0 || 1; // => 1 (or lógico) + ~0x0F; // => 0xF0 (negación bitwise) + 0x0F & 0xF0; // => 0x00 (AND bitwise) + 0x01 << 1; // => 0x02 (acarreamiento a la izquierda bitwise (por 1)) + + /////////////////////////////////////// + // Estructuras de control + /////////////////////////////////////// + + // Declaraciones If-Else + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Declaración Switch + switch (2) + { + case 0: + { + NSLog(@"I am never run"); + } break; + case 1: + { + NSLog(@"I am also never run"); + } break; + default: + { + NSLog(@"I print"); + } break; + } + + // Declaración de ciclos While + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ incrementa ii en la misma línea, luego de utilizar su valor + } // imprime => "0," + // "1," + // "2," + // "3," + + // Declaración de ciclos For + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // imprime => "0," + // "1," + // "2," + // "3," + + // Declaraciones foreach + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // imprime => "0," + // "1," + // "2," + // "3," + + // Objeto de ciclos For. Puede ser utilizado con cualquier tipo de objecto de Objective-C + for (id item in values) { + NSLog(@"%@,", item); + } // imprime => "0," + // "1," + // "2," + // "3," + + // Declaraciones Try-Catch-Finally + @try + { + // Tus declaraciones aquí + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"File Not Found on System" userInfo:nil]; + } @catch (NSException * e) // utiliza: @catch (id exceptionName) para atrapar todos los objetos + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally. Time to clean up."); + } // imprime => "Exception: File Not Found on System" + // "Finally. Time to clean up." + + // Los objetos NSError son útiles para argumentos de función para los errores de usuario. + NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; + + /////////////////////////////////////// + // Objetos + /////////////////////////////////////// + + // Crea una instancia de objeto alocando memoria e inicializándola + // Un objeto no es completamente funcional hasta que ambos pasos hayan sido + // completados + MyClass *myObject = [[MyClass alloc] init]; + + // El modelo de programación orientada a objetos de Objective-C es basada en + // el envío de mensajes a instancias de objetos + // En Objective-C no se llama a un método; se envía un mensaje + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Limpiar la memoria que se utilizó en el programa + [pool drain]; + + // Fin de @autoreleasepool + } + + // Fin del programa + return 0; +} + +/////////////////////////////////////// +// Clases y funciones +/////////////////////////////////////// + +// Declara tu clase en archivo de encabezado (MyClass.h) +// Sintaxis de declaración de clase: +// @interface NombreDeClase : NombreDeClasePadre +// { +// type nombre; <= declaraciones de variables; +// } +// @property tipo nombre; <= declaración de propiedades +// -/+ (tipo) Declaración de método; <= Declaración de método +// @end +@interface MyClass : NSObject // NSObject es la clase de objeto base de Objective-C. +{ + // Declaraciones de variables de instancia (puede existir en el archivo de interfaz o de implementación) + int count; // Acceso protegido por defecto. + @private id data; // Acceso privado (Más conveniente de declarar en el archivo de implementación) + NSString *name; +} +// Notación conveneinte para acceso público de las variables para generar un método setter +// Por defecto, el nombre del método setter 'set' seguido del nombre de variable @property +@property int propInt; // Nombre del método 'setter' = 'setPropInt' +@property (copy) id copyId; // (copy) => Copia el objeto durante la asignación +// (readonly) => No se le puede asignar un valor fuera de @interface +@property (readonly) NSString *roString; // utiliza @synthesize en @implementation para crear un accesor +// Puedes personalizar el nombre del getter y del setter en lugar de utilizar el nombre por defecto "set". +@property (getter=lengthGet, setter=lengthSet:) int length; + +// Métodos ++/- (return type)methodSignature:(Parameter Type *)parameterName; + +// + Para métodos de clase: ++ (NSString *)classMethod; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; + +// - Para métodos de instancia: +- (NSString *)instanceMethodWithParameter:(NSString *)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; + +// Métodos de constructor con argumentos +- (id)initWithDistance:(int)defaultDistance; +// Los nombres de los métodos de Objective-C son muy descriptivos. Siempre nombra los métodos +// de acuerdo con sus argumentos + +@end // Define el final de la interfaz + + +// Para acceder a las variables públicas desde el archivo de implementación, @property genera +// un método setter automáticamente. El nombre del método es 'set' seguido de un nombre de variable +// @property: +MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia del objeto MyClass +[myClass setCount:10]; +NSLog(@"%d", [myClass count]); // imprime => 10 +// O utilizando los métodos getter y setter personalizados en @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // imprime => 32 +// Por conveniencia, puedes utilizar la notación de punto para asignar y acceder a las variables +// de una instancia de objeto. +myClass.count = 45; +NSLog(@"%i", myClass.count); // imprime => 45 + +// Llama a métodos de clase: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Hello"]; + +// Llama a métodos de instancia: +MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia de objeto Myclass +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; + +// Selectors +// Una forma dinámica de representar métodos. Utilizados para llamar métodos de una clase, +// pasar métodos a través de funciones para avisar a otras clases para que lo llamen, y +// para guardar métodos como una variable. +// SEL es el tipo de dato. @selector() devuelve un selector del nombre de método proveído +// methodAparameterAsString:andAParameterAsNumber: es un nombre para un método en MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene un método + // Debe de poner todos los argumentos de método en un solo objeto para mandar una + // función performSelector. + NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Calls the method +} else { + // NSStringFromSelector() devuelve un NSString del nombre de método de un selector dado + NSLog(@"MyClass does not have method: %@", NSStringFromSelector(selectedVar)); +} + +// Implementa los métodos de un archivo de implementación (MyClass.m): +@implementation MyClass { + long distance; // Variable de instancia de acceso privado + NSNumber height; +} + +// Para acceder a una variable pública del archivo de interfaz, utiliza '_' seguido del +// nombre de la variable: +_count = 5; // Hace referencia a "int count" de la interfaz de MyClass +// Accede variables definidas en el archivo de implementación: +distance = 18; // Hace referencia a "long distance" de la implementación de MyClass +// Para utilizar una variable @property en el archivo de implementación, utiliza @synthesize +// para crear una variable de acceso: +@synthesize roString = _roString; // _roString ahora está disponible en @implementation + +// Lamado antes de llamar algún método o instanciar cualquier objeto ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} + +// Contraparte para inicializar un método. Llamado cuando el contador de referencias +// del objeto es cero +- (void)dealloc +{ + [height release]; // Si no utilizas ARC, asegúrate de liberar las variables de objeto de las clases + [super dealloc]; // y llama el método dealloc de la clase padre +} + +// Los constructores son una manera de crear instancias de una clase +// Este es el constructor por defecto que es llamado cuando el objeto es inicializado. +- (id)init +{ + if ((self = [super init])) // 'super' es utilizado para acceder a los métodos de la clase padre. + { + self.count = 1; // 'self' es utilizado para que el objeto se llame a sí mismo. + } + return self; +} +// Se pueden crear constructores que contiene argumentos +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + ++ (NSString *)classMethod +{ + return @"Some string"; +} + ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParameter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// Objective-C no tiene declaraciones de métodos privados, pero pueden ser simulados. +// Para simular un método privado, crea un método en @implementation pero no en @interface. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Calls private method + +// Métodos declarados dentro de MyProtocol +- (void)myProtocolMethod +{ + // statements +} + +@end // Declara el final de la implementación + +/////////////////////////////////////// +// Categorías +/////////////////////////////////////// +// Una categoría es un grupo de métodos diseñados para extender una clase. Te permiten agregar +// nuevos métodos a una clase existente por propósitos de organización. Éstos no deben de ser +// confundidos con subclases. +// Las subclases existen para CAMBIAR la funcionalidad de un objeto mientras que las categorías +// le AGREGAN funcionalidad de un objeto. +// Las categorías te permiten: +// -- Agregar métodos a una clase existente por propósitos de oganización. +// -- Extender clases de objetos de Objective-C (ejemplo: NSString) para agregar tus propios métodos. +// -- Agregar la habilidad de crear métodos protegidos y privados para las clases. +// NOTA: No sobreescribas los métodos de las clases base en una categoría aunque tengas la habilidad +// de poder hacerlo. Sobreescribir métodos puede causar errores en la compilación después entre +// diferentes categorías y puede arruinar el propósito de las categorías de solo AGREGAR funcionalidad. +// Utiliza subclass para sobreescribir métodos. + +// Aquí una clase base simple, Car. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + +@end + +// Y la implementación de la clase simple, Car +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Car is on."); +} +- (void)accelerate { + NSLog(@"Accelerating."); +} + +@end + +// Ahora, si quisieramos crear un objeto Truck (Camión), crearíamos una subclase de Car (Carro) como +// si le cambiaramos de funcionalidad de Car para que se comporte como un camión. Pero digamos que +// únicamente queremos agregar funcionalidad al Car (Carro) existente. Un buen ejemplo sería limpiar +// el carro. Así que crearíamos una cateog®iea para agregar los métodos de limpieza: +// Archivo @interface: Car+Clean.h (NombreBaseDeClase+NombreDeCategoria.h) +#import "Car.h" // Asegúrate de improtar la clase que deseas extener. + +@interface Car (Clean) // El nombre de la categoría está dentro de (), seguido del nombre de la + // clase base + +- (void)washWindows; // Nombres de los nuevos métodos que le agregamos a nuestro objeto Car +- (void)wax; + +@end + +// Archivo @implementation: Car+Clean.m (NombreBaseDeClase+NombreDeCategoria.m) +#import "Car+Clean.h" // Importa el archivo de @interface de la categoría Clean + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Windows washed."); +} +- (void)wax { + NSLog(@"Waxed."); +} + +@end + +// Cualquier instancia del objeto Car tiene la habilidad de utilizar una categoría. Todo lo +// que necesitan es importarlo: +#import "Car+Clean.h" // Importa todas las diferentes categorías que necesites utilizar +#import "Car.h" // También debes de importar la clase base para su funcionalidad original + +int main (int argc, const char * argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Red"; + mustang.make = @"Ford"; + + [mustang turnOn]; // Utiliza métodos de la clase base Car. + [mustang washWindows]; // Utiliza métodos de la categoría Clean de Car. + } + return 0; +} + +// Objective-C no tiene declaraciones para métodos protegidos, pero los puedes simular. +// Crea una categoría conteniendo todos los métodos protegidos, luego importa ÚNICAMENTE +// al archivo @implementation de una clase que pertenece a la clase Car. +@interface Car (Protected) // Nombrando la categoría 'Protected' para recordar que los métodos + // están protegidos + +- (void)lockCar; // Los métodos enlistados aquí solo puedens ser creados por objetos Car + +@end +// Para utilizar los métodos protegidos, importa la categoría, luego implementa sus métodos: +#import "Car+Protected.h" // Recuerda, importa únicamente el archivo de @implementation + +@implementation Car + +- (void)lockCar { + NSLog(@"Car locked."); // Las instancias de Car no puede utilizar lockCar porque no se + // encuentra en @interface +} + +@end + +/////////////////////////////////////// +// Extensiones +/////////////////////////////////////// +// Las Extensions te permiten sobreescribir atributos de propiedades de acceso público y métodos de +// un @interface +// Archivo @interface: Shape.h +@interface Shape : NSObject + +@property (readonly) NSNumber *numOfSides; + +- (int)getNumOfSides; + +@end +// Puedes sobreescribir la variable numOfSides o el métodos getNumOfSlides para modificarlos con una +// extensión: +// Archivo @implementation: Shape.m +#import "Shape.h" +// Las extensiones se encuentran en el mismo archivo que el archivo de @implementation +@interface Shape () // () después del nombre de la clase base declara una extensión + +@property (copy) NSNumber *numOfSides; // Hacer numOfSlides copy en lugar de readonly. +-(NSNumber)getNumOfSides; // Hacer que getNumOfSides devuelva un NSNumber en lugar de un int. +-(void)privateMethod; // También puedes crear una nuevos métodos privados dentro de las + // extensiones + +@end +// @implementation principal: +@implementation Shape + +@synthesize numOfSides = _numOfSides; + +-(NSNumber)getNumOfSides { // Todas las declaraciones dentro de extensions deben de ser + // dentro de @implementation + return _numOfSides; +} +-(void)privateMethod { + NSLog(@"Private method created by extension. Shape instances cannot call me."); +} + +@end + +/////////////////////////////////////// +// Protocolos +/////////////////////////////////////// +// Un protocolo declara métodos que pueden ser implementados por cualquier otra clase +// Los protocolos no son clases. Simplementen define una interfaz que otros objetos +// deben de implementar. +// Archivo @protocol: "CarUtilities.h" +@protocol CarUtilities // => Nombre de otro protocolo que se incluye en éste + @property BOOL engineOn; // La clase que lo adopta debe de utilizar @synthesize para todas las + // @properties definidas + - (void)turnOnEngine; // y todos los métodos definidos +@end +// A continuación una clase ejemplo que implementa el protcolo +#import "CarUtilities.h" // Importar el archivo @protocol. + +@interface Car : NSObject // El nombre del protocolo dentro de <> + // No necesitas los nombres de @property o métodos aquí para CarUtilities. Estos solo + // es requerido por @implementation. +- (void)turnOnEngineWithUtilities:(id )car; // También Puedes utilizar protocolos como datos. +@end +// El @implementation necesita que se implementen @properties y métodos del protocolo. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Crear una declaración @synthesize para el @property engineOn. + +- (void)turnOnEngine { // Implementa turnOnEngine como quieras. Los protocolos no definen + _engineOn = YES; // cómo implementas un método, con tal de que lo implementes. +} +// Puedes utilizar un protocolo como data mientras sepas quee métodos y variables tiene implementado. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // Tienes acceso a las variables + [objectOfSomeKind turnOnEngine]; // y los métodos del objeto + [objectOfSomeKind engineOn]; // Puede o no puede ser YES. La clase lo implementa como se quiera. +} + +@end +// Las instancias de Car ahora tienen acceso al protocolo. +Car *carInstance = [[Car alloc] init]; +[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Car engine is on."); // imprime => "Car engine is on." +} +// Asegúrate de revisar si un objeto de tipo 'id' implementa un protocolo antes de llamar a sus métodos: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"This does run as the Car class implements the CarUtilities protocol."); +} +// Las categorías también pueden implementar protcolos: @interface Car (CarCategory) +// Puedes implementar varios protocolos: @interface Car : NSObject +// NOTA: Si dos o más protocolos dependen entre sí, asegúrate de declararlos de manera adelantada: +#import "Brother.h" + +@protocol Brother; // Declaración adelantada. Sin ésto, el compilador tira un error. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; + +@end + +// Ver si el problema es que Sister depende de Brother, y Broteher dependa de Sister. +#import "Sister.h" + +@protocol Sister; // Estas líenas detienen la recursión, solucionando el problema. + +@protocol Brother + +- (void)beNiceToSister:(id )sister; + +@end + + +/////////////////////////////////////// +// Bloques +/////////////////////////////////////// +// Los bloques son declaraciones de código, tal como una función, pueden ser utilizados como data +// A continuación un bloque simple con un argumento entero que devuelve un el argumento más 4. +int (^addUp)(int n); // Declarar una variable para almacenar el bloque. +void (^noParameterBlockVar)(void); // Ejemplo de una declaración de variable de bloque sin argumentos. +// Los bloques tienen acceso a variables del mismo ámbito. Pero las variables son solo readonly +// y el valor pasado al bloque es el valor de la variable cuando el bloque es creado. +int outsideVar = 17; // Si modificamos outsideVar después de declarar addUp, outsideVar AÚN es 17. +__block long mutableVar = 3; // __block hace que las variables se puedan escribir en bloques. +addUp = ^(int n) { // Remueve (int n) para tener un bloque que no recibe ningún parámetro + NSLog(@"You may have as many lines in a block as you would like."); + NSSet *blockSet; // También puedes declarar variables locales. + mutableVar = 32; // Asignar un nuevo valor a la variable __block. + return n + outsideVar; // Declaraciones de retorno son opcionales. +} +int addUp = add(10 + 16); // Llama al bloque de código con argumentos. +// Los bloques son usualmente utilizados como argumentos a funciones que son llamados +// más adelante o para callbacks. +@implementation BlockExample : NSObject + + - (void)runBlock:(void (^)(NSString))block { + NSLog(@"Block argument returns nothing and takes in a NSString object."); + block(@"Argument given to block to execute."); // Calling block. + } + + @end + + +/////////////////////////////////////// +// Manejo de memoria +/////////////////////////////////////// +/* +Para cada objeto utilizado en una aplicación, la memoria debe de ser alocada para ese objeto. Cuando +la aplicación termina de utilizar ese objeto, la memoria debe de ser desalocada para asegurar la +eficiencia de la aplicación. +Objetive-C no utiliza garbage collection, y en lugar de eso utiliza conteos de referencias. Mientras +haya al menos una referencia del objeto (también conocido como tener un objeto de adueñado), entonces +el objeto estará disponible para su uso. + +Cuando una instancia es dueña un objeto, su contador de referencia incrementa por uno. Cuando +el objeto es liberado, el contador de referencia decrementa uno. Cuando el conteo de referencia +es cero, el objeto es removido de la memoria. + +Con todas las interacciones de los objetos, sigue el patrón de: +(1) Crear e lobjeto, (2) utiliza el objeto, (3) libera el objeto de la memoria. +*/ + +MyClass *classVar = [MyClass alloc]; // 'alloc' asigna uno al conteo de referencias de classVar. Devuelve un puntero al objeto +[classVar release]; // Decrementa el conteo de referencias de classVar's +// 'retain' +// 'retain' adueña la instancia de objeto existente e incrementa el conteo de referencia por uno. Devuelve un puntero al objeto. +MyClass *newVar = [classVar retain]; // Si classVar es liberado, el objeto aún se queda en memoria porque newVar es el dueño. +[classVar autorelease]; // Remueve el adueñamiento de un objeto al final del bloque @autoreleasepool. Devuelve un puntero al objeto. + +// @property puede utilizar 'retain' y 'assign' también para pequeñas definiciones convenientes +@property (retain) MyClass *instance; // Libera el valor viejo y retiene uno nuevo (referencia fuerte) +@property (assign) NSSet *set; // Apunta a un nuevo valor sin retener/liberar una referencia vieja (débil) + +// Conteo Automático de Referencias (ARC) +// Debido a que el manejo de memoria puede ser un dolor, en Xcode 4.2 y iOS 4 se introdujo el Conteo Automático +// de Referencias (ARC). +// ARC es una funcionalidad del compilador que agrega retain, release y autorealase automáticamente, así que al +// utilizar ARC, no se debe de utilizar retain, release o autorelease. +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... código utilizando arcMyClass +// Sin ARC, necesitarás llamar: [arcMyClass release] luego de terminar de utilizar arcMyClass. Pero con ARC, +// no hay necesidad. Insertará automáticamente la declaración de liberación. + +// Mientras que para los atributos de @property 'assign' y 'retain', con ARC utilizarás 'weak' y 'strong' +@property (weak) MyClass *weakVar; // 'weak' no adueña el objeto. El conteo de referencias de la instancia original +// es fijado a ceor, weakVar autom´åticamente recibe el valor de nil para evitar cualquier 'crashing'. +@property (strong) MyClass *strongVar; // 'strong' se adueña del objeto. Asegura que el objeto se quede en memoria. + +// Para variables regulares (no variables de @property), utiliza lo siguiente: +__strong NSString *strongString; // Por defecto. La variables de retenida en memoria hasta que se salga del ámbito. +__weak NSSet *weakSet; // Referencia débil a un objeto existente. Cuando el objeto existente es liberado, weakSet le es asginado un valor nil +__unsafe_unretained NSArray *unsafeArray; // Como __weak, pero unsafeArray no es asginado a nil cuando el objeto existente es liberado. + +``` +## Lecturas sugeridas + +[Wikipedia Objective-C](http://es.wikipedia.org/wiki/Objective-C) + +[Programming with Objective-C. Libro PDF de Apple](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) + +[iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) -- cgit v1.2.3 From 2f7c68978bd42cc863985a451d018e20f9711fb8 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:45:03 +0200 Subject: [yaml/pt-br] YAML translation to Brazilian Portuguese --- pt-br/yaml-pt.html.markdown | 139 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 pt-br/yaml-pt.html.markdown diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown new file mode 100644 index 00000000..a7414f2d --- /dev/null +++ b/pt-br/yaml-pt.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] +--- + +YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e +legível por seres humanos. + +É um estrito subconjunto de JSON, com a adição de sintaticamente +novas linhas e recuo significativos, como Python. Ao contrário de Python, no entanto, +YAML não permite caracteres de tabulação literais em tudo. + +```yaml +# Commentários em YAML são como este. + +################### +# TIPOS ESCALARES # +################### + +# Nosso objeto raiz (que continua por todo o documento) será um mapa, +# o que equivale a um dicionário, hash ou objeto em outras linguagens. +chave: valor +outra_chave: Outro valor vai aqui. +u_valor_numerico: 100 +notacao_cientifica: 1e+12 +boleano: true +valor_nulo: null +chave com espaco: valor +# Observe que strings não precisam de aspas. Porém, elas podem ter. +porem: "Uma string, entre aspas." +"Chaves podem estar entre aspas tambem.": "É útil se você quiser colocar um ':' na sua chave." + +# Seqüências de várias linhas podem ser escritos como um 'bloco literal' (utilizando |), +# ou em um 'bloco compacto' (utilizando '>'). +bloco_literal: | + Todo esse bloco de texto será o valor da chave 'bloco_literal', + preservando a quebra de com linhas. + + O literal continua até de-dented, e a primeira identação é + removida. + + Quaisquer linhas que são 'mais identadas' mantém o resto de suas identações - + estas linhas serão identadas com 4 espaços. +estilo_compacto: > + Todo esse bloco de texto será o valor de 'estilo_compacto', mas esta + vez, todas as novas linhas serão substituídas com espaço simples. + + Linhas em branco, como acima, são convertidas em um carater de nova linha. + + Linhas 'mais-indentadas' mantém suas novas linhas também - + este texto irá aparecer em duas linhas. + +#################### +# TIPOS DE COLEÇÃO # +#################### + +# Texto aninhado é conseguido através de identação. +um_mapa_aninhado: + chave: valor + outra_chave: Outro valor + outro_mapa_aninhado: + ola: ola + +# Mapas não tem que ter chaves com string. +0.25: uma chave com valor flutuante + +# As chaves podem ser também objetos multi linhas, utilizando ? para indicar o começo de uma chave. +? | + Esta é uma chave + que tem várias linhas +: e este é o seu valor + +# também permite tipos de coleção de chaves, mas muitas linguagens de programação +# vão reclamar. + +# Sequências (equivalente a listas ou arrays) semelhante à isso: +uma_sequencia: + - Item 1 + - Item 2 + - 0.5 # sequencias podem conter tipos diferentes. + - Item 4 + - chave: valor + outra_chave: outro_valor + - + - Esta é uma sequencia + - dentro de outra sequencia + +# Como YAML é um super conjunto de JSON, você também pode escrever mapas JSON de estilo e +# sequencias: +mapa_json: {"chave": "valor"} +json_seq: [3, 2, 1, "decolar"] + +########################## +# RECURSOS EXTRA DO YAML # +########################## + +# YAML também tem um recurso útil chamado "âncoras", que permitem que você facilmente duplique +# conteúdo em seu documento. Ambas estas chaves terão o mesmo valor: +conteudo_ancora: & nome_ancora Essa string irá aparecer como o valor de duas chaves. +outra_ancora: * nome_ancora + +# YAML também tem tags, que você pode usar para declarar explicitamente os tipos. +string_explicita: !! str 0,5 +# Alguns analisadores implementam tags específicas de linguagem, como este para Python de +# Tipo de número complexo. +numero_complexo_em_python: !! python / complex 1 + 2j + +#################### +# YAML TIPOS EXTRA # +#################### + +# Strings e números não são os únicos que escalares YAML pode entender. +# Data e 'data e hora' literais no formato ISO também são analisados. +datetime: 2001-12-15T02: 59: 43.1Z +datetime_com_espacos 2001/12/14: 21: 59: 43.10 -5 +Data: 2002/12/14 + +# A tag !!binary indica que a string é na verdade um base64-encoded (condificado) +# representação de um blob binário. +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= + +# YAML também tem um tipo de conjunto, o que se parece com isso: +set: + ? item1 + ? item2 + ? item3 + +# Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a: +set2: + item1: null + item2: null + item3: null +``` -- cgit v1.2.3 From 251ffdf894a697ec58a59d620956f4cca7172810 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:48:17 +0200 Subject: [yaml/pt-br] fixing contributors and add translators --- pt-br/yaml-pt.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index a7414f2d..93fca3f7 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -2,6 +2,8 @@ language: yaml filename: learnyaml.yaml contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] --- @@ -133,7 +135,7 @@ set: # Como Python, são apenas conjuntos de mapas com valors nulos; o acima é equivalente a: set2: - item1: null - item2: null - item3: null + item1: nulo + item2: nulo + item3: nulo ``` -- cgit v1.2.3 From 6616ee7156f2e631e18b13d0e19eb29041eec1bf Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 14:54:53 -0700 Subject: Reduced line lengths larger than 80 characters --- es-es/objective-c-es.html.markdown | 349 ++++++++++++++++++++++--------------- 1 file changed, 211 insertions(+), 138 deletions(-) diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown index fc769188..c5532c0f 100644 --- a/es-es/objective-c-es.html.markdown +++ b/es-es/objective-c-es.html.markdown @@ -38,7 +38,8 @@ int main (int argc, const char * argv[]) { // Crear un autorelease pool para manejar la memoria al programa NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - // Si se utiliza el conteo automático de referencias (ARC), utiliza @autoreleasepool: + // Si se utiliza el conteo automático de referencias (ARC), + // utiliza @autoreleasepool: @autoreleasepool { // Utiliza NSLog para imprimir líneas a la consola @@ -53,13 +54,14 @@ int main (int argc, const char * argv[]) long myPrimitive2 = 234554664565; // Declaraciones de objetos - // Pon el * como prefijo de los nombre de las variables para declaraciones de - // objetos de tipos fuertes + // Pon el * como prefijo de los nombre de las variables para declaraciones + // de objetos de tipos fuertes MyClass *myObject1 = nil; // Tipo fuerte id myObject2 = nil; // Tipo débil // %@ es un objeto // 'description' es una convención para mostrar el valor de los objetos - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // imprime => "(null) y (null)" + NSLog(@"%@ and %@", myObject1, [myObject2 description]); + // imprime => "(null) and (null)" // String NSString *worldString = @"World"; @@ -216,7 +218,8 @@ int main (int argc, const char * argv[]) int ii = 0; while (ii < 4) { - NSLog(@"%d,", ii++); // ii++ incrementa ii en la misma línea, luego de utilizar su valor + NSLog(@"%d,", ii++); // ii++ incrementa ii en la misma línea, luego de + // utilizar su valor } // imprime => "0," // "1," // "2," @@ -242,7 +245,8 @@ int main (int argc, const char * argv[]) // "2," // "3," - // Objeto de ciclos For. Puede ser utilizado con cualquier tipo de objecto de Objective-C + // Objeto de ciclos For. Puede ser utilizado con cualquier tipo de objecto de + // Objective-C for (id item in values) { NSLog(@"%@,", item); } // imprime => "0," @@ -256,7 +260,8 @@ int main (int argc, const char * argv[]) // Tus declaraciones aquí @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) // utiliza: @catch (id exceptionName) para atrapar todos los objetos + } @catch (NSException * e) // utiliza: @catch (id exceptionName) para atrapar + // todos los objetos { NSLog(@"Exception: %@", e); } @finally @@ -265,7 +270,8 @@ int main (int argc, const char * argv[]) } // imprime => "Exception: File Not Found on System" // "Finally. Time to clean up." - // Los objetos NSError son útiles para argumentos de función para los errores de usuario. + // Los objetos NSError son útiles para argumentos de función para los + // errores de usuario. NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; /////////////////////////////////////// @@ -305,20 +311,27 @@ int main (int argc, const char * argv[]) // @property tipo nombre; <= declaración de propiedades // -/+ (tipo) Declaración de método; <= Declaración de método // @end -@interface MyClass : NSObject // NSObject es la clase de objeto base de Objective-C. +@interface MyClass : NSObject // NSObject es la clase de objeto + // base de Objective-C. { - // Declaraciones de variables de instancia (puede existir en el archivo de interfaz o de implementación) + // Declaraciones de variables de instancia (puede existir en el archivo de + // interfaz o de implementación) int count; // Acceso protegido por defecto. - @private id data; // Acceso privado (Más conveniente de declarar en el archivo de implementación) + @private id data; // Acceso privado (Más conveniente de declarar en el + // archivo de implementación) NSString *name; } -// Notación conveneinte para acceso público de las variables para generar un método setter -// Por defecto, el nombre del método setter 'set' seguido del nombre de variable @property +// Notación conveneinte para acceso público de las variables para generar un +// método setter +// Por defecto, el nombre del método setter 'set' seguido del nombre de +// variable @property @property int propInt; // Nombre del método 'setter' = 'setPropInt' @property (copy) id copyId; // (copy) => Copia el objeto durante la asignación // (readonly) => No se le puede asignar un valor fuera de @interface -@property (readonly) NSString *roString; // utiliza @synthesize en @implementation para crear un accesor -// Puedes personalizar el nombre del getter y del setter en lugar de utilizar el nombre por defecto "set". +@property (readonly) NSString *roString; // utiliza @synthesize en + // @implementation para crear un accesor +// Puedes personalizar el nombre del getter y del setter en lugar de utilizar +// el nombre por defecto "set". @property (getter=lengthGet, setter=lengthSet:) int length; // Métodos @@ -334,23 +347,23 @@ int main (int argc, const char * argv[]) // Métodos de constructor con argumentos - (id)initWithDistance:(int)defaultDistance; -// Los nombres de los métodos de Objective-C son muy descriptivos. Siempre nombra los métodos -// de acuerdo con sus argumentos +// Los nombres de los métodos de Objective-C son muy descriptivos. +// Siempre nombra los métodos de acuerdo con sus argumentos @end // Define el final de la interfaz -// Para acceder a las variables públicas desde el archivo de implementación, @property genera -// un método setter automáticamente. El nombre del método es 'set' seguido de un nombre de variable -// @property: +// Para acceder a las variables públicas desde el archivo de implementación, +// @property genera un método setter automáticamente. El nombre del método +// es 'set' seguido de un nombre de variable @property: MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia del objeto MyClass [myClass setCount:10]; NSLog(@"%d", [myClass count]); // imprime => 10 // O utilizando los métodos getter y setter personalizados en @interface: [myClass lengthSet:32]; NSLog(@"%i", [myClass lengthGet]); // imprime => 32 -// Por conveniencia, puedes utilizar la notación de punto para asignar y acceder a las variables -// de una instancia de objeto. +// Por conveniencia, puedes utilizar la notación de punto para asignar y +// acceder a las variables de una instancia de objeto. myClass.count = 45; NSLog(@"%i", myClass.count); // imprime => 45 @@ -363,13 +376,14 @@ MyClass *myClass = [[MyClass alloc] init]; // Crea una instancia de objeto Mycla NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hello"]; // Selectors -// Una forma dinámica de representar métodos. Utilizados para llamar métodos de una clase, -// pasar métodos a través de funciones para avisar a otras clases para que lo llamen, y -// para guardar métodos como una variable. -// SEL es el tipo de dato. @selector() devuelve un selector del nombre de método proveído -// methodAparameterAsString:andAParameterAsNumber: es un nombre para un método en MyClass +// Una forma dinámica de representar métodos. Utilizados para llamar métodos +// de una clase, pasar métodos a través de funciones para avisar a otras clases +// para que lo llamen, y para guardar métodos como una variable. +// SEL es el tipo de dato. @selector() devuelve un selector del nombre de +// método proveído methodAparameterAsString:andAParameterAsNumber: es un nombre +// para un método en MyClass SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); -if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene un método +if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene el método // Debe de poner todos los argumentos de método en un solo objeto para mandar una // función performSelector. NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; @@ -390,8 +404,8 @@ if ([myClass respondsToSelector:selectorVar]) { // Revisa si la clase contiene u _count = 5; // Hace referencia a "int count" de la interfaz de MyClass // Accede variables definidas en el archivo de implementación: distance = 18; // Hace referencia a "long distance" de la implementación de MyClass -// Para utilizar una variable @property en el archivo de implementación, utiliza @synthesize -// para crear una variable de acceso: +// Para utilizar una variable @property en el archivo de implementación, utiliza +// @synthesize para crear una variable de acceso: @synthesize roString = _roString; // _roString ahora está disponible en @implementation // Lamado antes de llamar algún método o instanciar cualquier objeto @@ -406,7 +420,8 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC // del objeto es cero - (void)dealloc { - [height release]; // Si no utilizas ARC, asegúrate de liberar las variables de objeto de las clases + [height release]; // Si no utilizas ARC, asegúrate de liberar las variables de + // objeto de las clases [super dealloc]; // y llama el método dealloc de la clase padre } @@ -414,7 +429,8 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC // Este es el constructor por defecto que es llamado cuando el objeto es inicializado. - (id)init { - if ((self = [super init])) // 'super' es utilizado para acceder a los métodos de la clase padre. + if ((self = [super init])) // 'super' es utilizado para acceder a los + // métodos de la clase padre. { self.count = 1; // 'self' es utilizado para que el objeto se llame a sí mismo. } @@ -466,18 +482,20 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC /////////////////////////////////////// // Categorías /////////////////////////////////////// -// Una categoría es un grupo de métodos diseñados para extender una clase. Te permiten agregar -// nuevos métodos a una clase existente por propósitos de organización. Éstos no deben de ser -// confundidos con subclases. -// Las subclases existen para CAMBIAR la funcionalidad de un objeto mientras que las categorías -// le AGREGAN funcionalidad de un objeto. +// Una categoría es un grupo de métodos diseñados para extender una clase. +// Te permiten agregar nuevos métodos a una clase existente por propósitos +// de organización. Éstos no deben de serconfundidos con subclases. +// Las subclases existen para CAMBIAR la funcionalidad de un objeto mientras +// que las categoríasle AGREGAN funcionalidad de un objeto. // Las categorías te permiten: // -- Agregar métodos a una clase existente por propósitos de oganización. -// -- Extender clases de objetos de Objective-C (ejemplo: NSString) para agregar tus propios métodos. +// -- Extender clases de objetos de Objective-C (ejemplo: NSString) para +// agregar tus propios métodos. // -- Agregar la habilidad de crear métodos protegidos y privados para las clases. -// NOTA: No sobreescribas los métodos de las clases base en una categoría aunque tengas la habilidad -// de poder hacerlo. Sobreescribir métodos puede causar errores en la compilación después entre -// diferentes categorías y puede arruinar el propósito de las categorías de solo AGREGAR funcionalidad. +// NOTA: No sobreescribas los métodos de las clases base en una categoría +// aunque tengas la habilidad de poder hacerlo. Sobreescribir métodos puede +// causar errores en la compilación después entre diferentes categorías y +// puede arruinar el propósito de las categorías de solo AGREGAR funcionalidad. // Utiliza subclass para sobreescribir métodos. // Aquí una clase base simple, Car. @@ -508,17 +526,20 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC @end -// Ahora, si quisieramos crear un objeto Truck (Camión), crearíamos una subclase de Car (Carro) como -// si le cambiaramos de funcionalidad de Car para que se comporte como un camión. Pero digamos que -// únicamente queremos agregar funcionalidad al Car (Carro) existente. Un buen ejemplo sería limpiar -// el carro. Así que crearíamos una cateog®iea para agregar los métodos de limpieza: +// Ahora, si quisieramos crear un objeto Truck (Camión), crearíamos una +// subclase de Car (Carro) como si le cambiaramos de funcionalidad de Car +// para que se comporte como un camión. Pero digamos que únicamente queremos +// agregar funcionalidad al Car (Carro) existente. Un buen ejemplo sería +// limpiar el carro. Así que crearíamos una cateog®iea para agregar los +// métodos de limpieza: // Archivo @interface: Car+Clean.h (NombreBaseDeClase+NombreDeCategoria.h) #import "Car.h" // Asegúrate de improtar la clase que deseas extener. -@interface Car (Clean) // El nombre de la categoría está dentro de (), seguido del nombre de la - // clase base +@interface Car (Clean) // El nombre de la categoría está dentro de (), + // seguido del nombre de la clase base -- (void)washWindows; // Nombres de los nuevos métodos que le agregamos a nuestro objeto Car +- (void)washWindows; // Nombres de los nuevos métodos que le agregamos + // a nuestro objeto Car - (void)wax; @end @@ -537,10 +558,12 @@ distance = 18; // Hace referencia a "long distance" de la implementación de MyC @end -// Cualquier instancia del objeto Car tiene la habilidad de utilizar una categoría. Todo lo -// que necesitan es importarlo: -#import "Car+Clean.h" // Importa todas las diferentes categorías que necesites utilizar -#import "Car.h" // También debes de importar la clase base para su funcionalidad original +// Cualquier instancia del objeto Car tiene la habilidad de utilizar una +// categoría. Todo lo que necesitan es importarlo: +#import "Car+Clean.h" // Importa todas las diferentes categorías que + // necesites utilizar +#import "Car.h" // También debes de importar la clase base para su + // funcionalidad original int main (int argc, const char * argv[]) { @autoreleasepool { @@ -554,23 +577,27 @@ int main (int argc, const char * argv[]) { return 0; } -// Objective-C no tiene declaraciones para métodos protegidos, pero los puedes simular. -// Crea una categoría conteniendo todos los métodos protegidos, luego importa ÚNICAMENTE -// al archivo @implementation de una clase que pertenece a la clase Car. -@interface Car (Protected) // Nombrando la categoría 'Protected' para recordar que los métodos - // están protegidos +// Objective-C no tiene declaraciones para métodos protegidos, pero los puedes +// simular. Crea una categoría conteniendo todos los métodos protegidos, +// luego importa ÚNICAMENTE al archivo @implementation de una clase que +// pertenece a la clase Car. +@interface Car (Protected) // Nombrando la categoría 'Protected' para + // recordar que los métodos están protegidos -- (void)lockCar; // Los métodos enlistados aquí solo puedens ser creados por objetos Car +- (void)lockCar; // Los métodos enlistados aquí solo puedens ser creados + // por objetos Car @end -// Para utilizar los métodos protegidos, importa la categoría, luego implementa sus métodos: -#import "Car+Protected.h" // Recuerda, importa únicamente el archivo de @implementation +// Para utilizar los métodos protegidos, importa la categoría, +// luego implementa sus métodos: +#import "Car+Protected.h" // Recuerda, importa únicamente el archivo + // de @implementation @implementation Car - (void)lockCar { - NSLog(@"Car locked."); // Las instancias de Car no puede utilizar lockCar porque no se - // encuentra en @interface + NSLog(@"Car locked."); // Las instancias de Car no puede utilizar + // lockCar porque no se encuentra en @interface } @end @@ -578,8 +605,8 @@ int main (int argc, const char * argv[]) { /////////////////////////////////////// // Extensiones /////////////////////////////////////// -// Las Extensions te permiten sobreescribir atributos de propiedades de acceso público y métodos de -// un @interface +// Las Extensions te permiten sobreescribir atributos de propiedades de +// acceso público y métodos de un @interface // Archivo @interface: Shape.h @interface Shape : NSObject @@ -588,17 +615,21 @@ int main (int argc, const char * argv[]) { - (int)getNumOfSides; @end -// Puedes sobreescribir la variable numOfSides o el métodos getNumOfSlides para modificarlos con una -// extensión: +// Puedes sobreescribir la variable numOfSides o el métodos getNumOfSlides +// para modificarlos con una extensión: // Archivo @implementation: Shape.m #import "Shape.h" -// Las extensiones se encuentran en el mismo archivo que el archivo de @implementation -@interface Shape () // () después del nombre de la clase base declara una extensión - -@property (copy) NSNumber *numOfSides; // Hacer numOfSlides copy en lugar de readonly. --(NSNumber)getNumOfSides; // Hacer que getNumOfSides devuelva un NSNumber en lugar de un int. --(void)privateMethod; // También puedes crear una nuevos métodos privados dentro de las - // extensiones +// Las extensiones se encuentran en el mismo archivo que el archivo +// de @implementation +@interface Shape () // () después del nombre de la clase base declara + // una extensión + +@property (copy) NSNumber *numOfSides; // Hacer numOfSlides copy en lugar + // de readonly. +-(NSNumber)getNumOfSides; // Hacer que getNumOfSides devuelva un NSNumber + // en lugar de un int. +-(void)privateMethod; // También puedes crear una nuevos métodos privados + // dentro de las extensiones @end // @implementation principal: @@ -606,8 +637,8 @@ int main (int argc, const char * argv[]) { @synthesize numOfSides = _numOfSides; --(NSNumber)getNumOfSides { // Todas las declaraciones dentro de extensions deben de ser - // dentro de @implementation +-(NSNumber)getNumOfSides { // Todas las declaraciones dentro de extensions + // deben de ser dentro de @implementation return _numOfSides; } -(void)privateMethod { @@ -619,36 +650,44 @@ int main (int argc, const char * argv[]) { /////////////////////////////////////// // Protocolos /////////////////////////////////////// -// Un protocolo declara métodos que pueden ser implementados por cualquier otra clase -// Los protocolos no son clases. Simplementen define una interfaz que otros objetos -// deben de implementar. +// Un protocolo declara métodos que pueden ser implementados por cualquier otra +// clase. Los protocolos no son clases. Simplementen define una interfaz que +// otros objetos deben de implementar. // Archivo @protocol: "CarUtilities.h" -@protocol CarUtilities // => Nombre de otro protocolo que se incluye en éste - @property BOOL engineOn; // La clase que lo adopta debe de utilizar @synthesize para todas las - // @properties definidas +@protocol CarUtilities // => Nombre de otro protocolo + // que se incluye en éste + @property BOOL engineOn; // La clase que lo adopta debe de utilizar + // @synthesize para todas las @properties definidas - (void)turnOnEngine; // y todos los métodos definidos @end // A continuación una clase ejemplo que implementa el protcolo #import "CarUtilities.h" // Importar el archivo @protocol. @interface Car : NSObject // El nombre del protocolo dentro de <> - // No necesitas los nombres de @property o métodos aquí para CarUtilities. Estos solo - // es requerido por @implementation. -- (void)turnOnEngineWithUtilities:(id )car; // También Puedes utilizar protocolos como datos. + // No necesitas los nombres de @property o métodos aquí para CarUtilities. + // Estos solo es requerido por @implementation. +- (void)turnOnEngineWithUtilities:(id )car; // También Puedes + // utilizar protocolos + // como datos. @end -// El @implementation necesita que se implementen @properties y métodos del protocolo. +// El @implementation necesita que se implementen @properties y métodos +// del protocolo. @implementation Car : NSObject -@synthesize engineOn = _engineOn; // Crear una declaración @synthesize para el @property engineOn. +@synthesize engineOn = _engineOn; // Crear una declaración @synthesize para el + // @property engineOn. -- (void)turnOnEngine { // Implementa turnOnEngine como quieras. Los protocolos no definen - _engineOn = YES; // cómo implementas un método, con tal de que lo implementes. +- (void)turnOnEngine { // Implementa turnOnEngine como quieras. Los + // protocolos no definen + _engineOn = YES; // cómo implementas un método, con tal de que lo implementes. } -// Puedes utilizar un protocolo como data mientras sepas quee métodos y variables tiene implementado. +// Puedes utilizar un protocolo como data mientras sepas quee métodos y variables +// tiene implementado. - (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { [objectOfSomeKind engineOn]; // Tienes acceso a las variables [objectOfSomeKind turnOnEngine]; // y los métodos del objeto - [objectOfSomeKind engineOn]; // Puede o no puede ser YES. La clase lo implementa como se quiera. + [objectOfSomeKind engineOn]; // Puede o no puede ser YES. La clase lo + // implementa como se quiera. } @end @@ -659,18 +698,23 @@ Car *carInstance = [[Car alloc] init]; if ([carInstance engineOn]) { NSLog(@"Car engine is on."); // imprime => "Car engine is on." } -// Asegúrate de revisar si un objeto de tipo 'id' implementa un protocolo antes de llamar a sus métodos: +// Asegúrate de revisar si un objeto de tipo 'id' implementa un protocolo antes +// de llamar a sus métodos: if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol."); } else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { NSLog(@"This does run as the Car class implements the CarUtilities protocol."); } -// Las categorías también pueden implementar protcolos: @interface Car (CarCategory) -// Puedes implementar varios protocolos: @interface Car : NSObject -// NOTA: Si dos o más protocolos dependen entre sí, asegúrate de declararlos de manera adelantada: +// Las categorías también pueden implementar protcolos: @interface Car +// (CarCategory) +// Puedes implementar varios protocolos: +// @interface Car : NSObject +// NOTA: Si dos o más protocolos dependen entre sí, asegúrate de declararlos +// de manera adelantada: #import "Brother.h" -@protocol Brother; // Declaración adelantada. Sin ésto, el compilador tira un error. +@protocol Brother; // Declaración adelantada. Sin ésto, el compilador + // tira un error. @protocol Sister @@ -678,10 +722,11 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { @end -// Ver si el problema es que Sister depende de Brother, y Broteher dependa de Sister. +// Ver si el problema es que Sister depende de Brother, +// y Brother dependa de Sister. #import "Sister.h" -@protocol Sister; // Estas líenas detienen la recursión, solucionando el problema. +@protocol Sister; // Estas líneas detienen la recursión, resolviendo el problema. @protocol Brother @@ -693,23 +738,30 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { /////////////////////////////////////// // Bloques /////////////////////////////////////// -// Los bloques son declaraciones de código, tal como una función, pueden ser utilizados como data -// A continuación un bloque simple con un argumento entero que devuelve un el argumento más 4. +// Los bloques son declaraciones de código, tal como una función, pueden +// ser utilizados como data. +// A continuación un bloque simple con un argumento entero que devuelve +// un el argumento más 4. int (^addUp)(int n); // Declarar una variable para almacenar el bloque. -void (^noParameterBlockVar)(void); // Ejemplo de una declaración de variable de bloque sin argumentos. -// Los bloques tienen acceso a variables del mismo ámbito. Pero las variables son solo readonly -// y el valor pasado al bloque es el valor de la variable cuando el bloque es creado. -int outsideVar = 17; // Si modificamos outsideVar después de declarar addUp, outsideVar AÚN es 17. -__block long mutableVar = 3; // __block hace que las variables se puedan escribir en bloques. -addUp = ^(int n) { // Remueve (int n) para tener un bloque que no recibe ningún parámetro +void (^noParameterBlockVar)(void); // Ejemplo de una declaración de variable + // de bloque sin argumentos. +// Los bloques tienen acceso a variables del mismo ámbito. Pero las variables +// son solo readonly y el valor pasado al bloque es el valor de la variable +// cuando el bloque es creado. +int outsideVar = 17; // Si modificamos outsideVar después de declarar addUp, + // outsideVar AÚN es 17. +__block long mutableVar = 3; // __block hace que las variables se puedan + // escribir en bloques. +addUp = ^(int n) { // Remueve (int n) para tener un bloque que no recibe + // ningún parámetro NSLog(@"You may have as many lines in a block as you would like."); NSSet *blockSet; // También puedes declarar variables locales. mutableVar = 32; // Asignar un nuevo valor a la variable __block. return n + outsideVar; // Declaraciones de retorno son opcionales. } int addUp = add(10 + 16); // Llama al bloque de código con argumentos. -// Los bloques son usualmente utilizados como argumentos a funciones que son llamados -// más adelante o para callbacks. +// Los bloques son usualmente utilizados como argumentos a funciones que +// son llamados más adelante o para callbacks. @implementation BlockExample : NSObject - (void)runBlock:(void (^)(NSString))block { @@ -724,51 +776,72 @@ int addUp = add(10 + 16); // Llama al bloque de código con argumentos. // Manejo de memoria /////////////////////////////////////// /* -Para cada objeto utilizado en una aplicación, la memoria debe de ser alocada para ese objeto. Cuando -la aplicación termina de utilizar ese objeto, la memoria debe de ser desalocada para asegurar la -eficiencia de la aplicación. -Objetive-C no utiliza garbage collection, y en lugar de eso utiliza conteos de referencias. Mientras -haya al menos una referencia del objeto (también conocido como tener un objeto de adueñado), entonces -el objeto estará disponible para su uso. - -Cuando una instancia es dueña un objeto, su contador de referencia incrementa por uno. Cuando -el objeto es liberado, el contador de referencia decrementa uno. Cuando el conteo de referencia -es cero, el objeto es removido de la memoria. +Para cada objeto utilizado en una aplicación, la memoria debe de ser alocada +para ese objeto. Cuando la aplicación termina de utilizar ese objeto, la +memoria debe de ser desalocada para asegurar la eficiencia de la aplicación. +Objetive-C no utiliza garbage collection, y en lugar de eso utiliza conteos +de referencias. Mientras haya al menos una referencia del objeto (también +conocido como tener un objeto de adueñado), entonces el objeto estará +disponible para su uso. + +Cuando una instancia es dueña un objeto, su contador de referencia incrementa +por uno. Cuando el objeto es liberado, el contador de referencia decrementa uno. +Cuando el conteo de referencia es cero, el objeto es removido de la memoria. Con todas las interacciones de los objetos, sigue el patrón de: (1) Crear e lobjeto, (2) utiliza el objeto, (3) libera el objeto de la memoria. */ -MyClass *classVar = [MyClass alloc]; // 'alloc' asigna uno al conteo de referencias de classVar. Devuelve un puntero al objeto +MyClass *classVar = [MyClass alloc]; // 'alloc' asigna uno al conteo de + // referencias de classVar. Devuelve un + // puntero al objeto [classVar release]; // Decrementa el conteo de referencias de classVar's // 'retain' -// 'retain' adueña la instancia de objeto existente e incrementa el conteo de referencia por uno. Devuelve un puntero al objeto. -MyClass *newVar = [classVar retain]; // Si classVar es liberado, el objeto aún se queda en memoria porque newVar es el dueño. -[classVar autorelease]; // Remueve el adueñamiento de un objeto al final del bloque @autoreleasepool. Devuelve un puntero al objeto. - -// @property puede utilizar 'retain' y 'assign' también para pequeñas definiciones convenientes -@property (retain) MyClass *instance; // Libera el valor viejo y retiene uno nuevo (referencia fuerte) -@property (assign) NSSet *set; // Apunta a un nuevo valor sin retener/liberar una referencia vieja (débil) +// 'retain' adueña la instancia de objeto existente e incrementa el conteo de +// referencia por uno. Devuelve un puntero al objeto. +MyClass *newVar = [classVar retain]; // Si classVar es liberado, el objeto + // aún se queda en memoria porque newVar + // es el dueño. +[classVar autorelease]; // Remueve el adueñamiento de un objeto al final del + // bloque @autoreleasepool. Devuelve un puntero al objeto. + +// @property puede utilizar 'retain' y 'assign' también para pequeñas +// definiciones convenientes +@property (retain) MyClass *instance; // Libera el valor viejo y retiene + // uno nuevo (referencia fuerte) +@property (assign) NSSet *set; // Apunta a un nuevo valor sin retener/liberar + // una referencia vieja (débil) // Conteo Automático de Referencias (ARC) -// Debido a que el manejo de memoria puede ser un dolor, en Xcode 4.2 y iOS 4 se introdujo el Conteo Automático -// de Referencias (ARC). -// ARC es una funcionalidad del compilador que agrega retain, release y autorealase automáticamente, así que al +// Debido a que el manejo de memoria puede ser un dolor, en Xcode 4.2 y iOS 4 +// se introdujo el Conteo Automático de Referencias (ARC). +// ARC es una funcionalidad del compilador que agrega retain, release y +// autorealase automáticamente, así que al // utilizar ARC, no se debe de utilizar retain, release o autorelease. MyClass *arcMyClass = [[MyClass alloc] init]; // ... código utilizando arcMyClass -// Sin ARC, necesitarás llamar: [arcMyClass release] luego de terminar de utilizar arcMyClass. Pero con ARC, -// no hay necesidad. Insertará automáticamente la declaración de liberación. - -// Mientras que para los atributos de @property 'assign' y 'retain', con ARC utilizarás 'weak' y 'strong' -@property (weak) MyClass *weakVar; // 'weak' no adueña el objeto. El conteo de referencias de la instancia original -// es fijado a ceor, weakVar autom´åticamente recibe el valor de nil para evitar cualquier 'crashing'. -@property (strong) MyClass *strongVar; // 'strong' se adueña del objeto. Asegura que el objeto se quede en memoria. +// Sin ARC, necesitarás llamar: [arcMyClass release] luego de terminar de +// utilizar arcMyClass. Pero con ARC, no hay necesidad. Insertará +// automáticamente la declaración de liberación. + +// Mientras que para los atributos de @property 'assign' y 'retain', con ARC +// utilizarás 'weak' y 'strong' +@property (weak) MyClass *weakVar; // 'weak' no adueña el objeto. El conteo de + // referencias de la instancia original +// es fijado a ceor, weakVar automáticamente recibe el valor de nil para +// evitar cualquier 'crashing'. +@property (strong) MyClass *strongVar; // 'strong' se adueña del objeto. + // Asegura que el objeto se quede en memoria. // Para variables regulares (no variables de @property), utiliza lo siguiente: -__strong NSString *strongString; // Por defecto. La variables de retenida en memoria hasta que se salga del ámbito. -__weak NSSet *weakSet; // Referencia débil a un objeto existente. Cuando el objeto existente es liberado, weakSet le es asginado un valor nil -__unsafe_unretained NSArray *unsafeArray; // Como __weak, pero unsafeArray no es asginado a nil cuando el objeto existente es liberado. +__strong NSString *strongString; // Por defecto. La variables de retenida en + // memoria hasta que se salga del ámbito. +__weak NSSet *weakSet; // Referencia débil a un objeto existente. Cuando el + // objeto existente es liberado, weakSet le es asginado + // un valor nil +__unsafe_unretained NSArray *unsafeArray; // Como __weak, pero unsafeArray no + // es asginado a nil cuando el objeto + // existente es liberado. ``` ## Lecturas sugeridas -- cgit v1.2.3 From 400b1a4b830b6d2cae677d916781dc88a45af027 Mon Sep 17 00:00:00 2001 From: Rodrigo Russo Date: Mon, 19 Oct 2015 23:58:47 +0200 Subject: [yaml/pt-br] fixing header --- pt-br/yaml-pt.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pt-br/yaml-pt.html.markdown b/pt-br/yaml-pt.html.markdown index 93fca3f7..341ae675 100644 --- a/pt-br/yaml-pt.html.markdown +++ b/pt-br/yaml-pt.html.markdown @@ -1,10 +1,11 @@ --- language: yaml -filename: learnyaml.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Rodrigo Russo", "https://github.com/rodrigozrusso"] +filename: learnyaml-pt.yaml +lang: pt-br --- YAML é uma linguagem de serialização de dados projetado para ser diretamente gravável e -- cgit v1.2.3 From 766be7094483a06b4e289081550e1f28744a3b51 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 16:25:31 -0700 Subject: Added R Spanish translation --- es-es/r-es.html.markdown | 717 +++++++++++++++++++++++++++++++++++++++++++++++ r.html.markdown | 2 +- 2 files changed, 718 insertions(+), 1 deletion(-) create mode 100644 es-es/r-es.html.markdown diff --git a/es-es/r-es.html.markdown b/es-es/r-es.html.markdown new file mode 100644 index 00000000..db780c27 --- /dev/null +++ b/es-es/r-es.html.markdown @@ -0,0 +1,717 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] +translators: + - ["David Hsieh", "http://github.com/deivuh"] +lang: es-es +filename: learnr.r +--- + +R es un lenguaje de computación estadística. Tiene muchas librerías para cargar +y limpiar sets de datos, ejecutar procedimientos estadísticos y generar +gráficas. También puedes ejecutar comandos `R` dentro de un documento de +LaTeX. + +```r + +# Los comentariso inician con símbolos numéricos. + +# No puedes hacer comentarios de múltiples líneas +# pero puedes agrupar múltiples comentarios de esta manera. + +# En Windows puedes utilizar CTRL-ENTER para ejecutar una línea. +# En Mac utilizas COMMAND-ENTER + + +############################################################################# +# Cosas que puedes hacer sin entender nada acerca de programación +############################################################################# + +# En esta sección, mostramos algunas cosas chileras / cool que puedes hacer en +# R sin entender nada de programación. No te preocupes en entender nada +# de lo que hace este código. Solo disfruta! + +data() # Examinar sets de datos pre-cargados +data(rivers) # Obtiene este: Lengths of Major North American Rivers" +ls() # Fijarse que "rivers" ahora aparece en el workspace +head(rivers) # Echarle un ojo al set de datos +# 735 320 325 392 524 450 + +length(rivers) # ¿Cuántos ríos fueron medidos? +# 141 +summary(rivers) # ¿Cuáles son algunas estadísticas generales? +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + +# Generar una gráfica tallo-y-hoja (Visualización de datos tipo histograma) +stem(rivers) + +# El punto decimal son 2 dígitos a la derecha de | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + +stem(log(rivers)) # Fijarse que la data no es normal ni log-normal! +# Toma eso, fundamentalistas de la curva de campana! + +# El punto decimal está a 1 dígito a la izquierda del | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + +# Generar un histograma: +hist(rivers, col="#333333", border="white", breaks=25) # Juega con los estos parámetros +hist(log(rivers), col="#333333", border="white", breaks=25) # Generarás más gráficas después + +# Aquí hay otro set de datos pre-cargado. R tiene bastantes de éstos. +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Year", + main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", + main="Number of important discoveries per year") + +# En lugar de dejar el orden por defecto (por año), +# podemos ordenar de tal manera que muestre qué es típico: +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +# +# El punto decimal se encuentra en | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + +# Tirar los dados varias veces +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# Tus números será diferente de los míos, a menos que tengamos el mismo valor +# de random.seed(31337) + +# Dibuja de un Gaussian 9 veces +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + +################################################## +# Tipos de datos y aritmética básica +################################################## + +# Ahora para la parte de programación orientada a objetos del tutorial. +# En esta sección conocerás los tipos de datos importantes de R: +# Enteros, numéricos, caracteres, lógicos, y factores. +# Hay otros, pero esos son los que menos necesitas para empezar. + +# ENTEROS +# Enteros de almacenamiento largo son escritos con L +5L # 5 +class(5L) # "integer" +# (Try ?class para más información en la función class().) +# En R, cada valor único, como 5L, es considerado un vector de logitud 1 +length(5L) # 1 +# También puedes tener un vector de enteros con longitud > 1: +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# NUMÉRICOS +# Un "numérico" es un número de punto flotante de doble precisión. +5 # 5 +class(5) # "numeric" +# Nuevamente, todo en R es un vector; +# puedes hacer un vector numérico con más de un elemento +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# También puedes utilizar el notación científica +5e4 # 50000 +6.02e23 # Número de Avogadro +1.6e-35 # Logintud Planck +# También puedes tener números infinitamente grandes o pequeños +class(Inf) # "numeric" +class(-Inf) # "numeric" +# Puede que uses "Inf", por ejemplo, en integrate(dnorm, 3, Inf); +# esto obvia las tablas de puntos Z. + +# ARITMÉTICA BÁSICA +# Puedes hacer aritmética con números +# Haciendo aritmética en un mix de enteros y numéricos, te da otro numérico +10L + 66L # 76 # entero mas entero da entero +53.2 - 4 # 49.2 # entero menos entero da numérico +2.0 * 2L # 4 # numérico veces entero da numérico +3L / 4 # 0.75 # entero sobre numérico da numérico +3 %% 2 # 1 # el residuo de dos numéricos es otro numérico +# La aritmética ilegal rinde un "not-a-number" +0 / 0 # NaN +class(NaN) # "numeric" +# Puedes hacer aritmética con dos vectores con longitud mayor a 1, +# siempre que la longitud del vector mayor es un entero múltiplo del menor. +c(1,2,3) + c(1,2,3) # 2 4 6 + +# CARACTERES +# No hay diferencia entre strings y caracteres en R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# Ambos eran vectores de caracteres de longitud 1 +# Aquí hay uno más largo: +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# => +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# Puedes hacer operaciones regex en vectores de caracteres: +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R tiene varios vectores predefinidos de caracteres +letters +# => +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + +# LÓGICOS +# En R, un "logical" es un boolean +class(TRUE) # "logical" +class(FALSE) # "logical" +# Ese comportamiento es normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# El dato faltante (NA) es lógico también +class(NA) # "logical" +# Utiliza | y & para operaciones lógicas +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Puedes probar si x es TRUE (verdadero) +isTRUE(TRUE) # TRUE +# Aquí tenemos un vector lógico con varios elementos: +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + +# FACTORES +# La clase factor es para datos de categoría +# Los factores pueden ser ordenados (como las calificaciones de los niños) +# o sin orden (como el género) +factor(c("female", "female", "male", NA, "female")) +# female female male female +# Levels: female male +# Los "levels" son los valores que los datos categóricos pueden tener +# Tomar nota que los datos faltantes no entran a los niveles +levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" +# Si un vector de factores tiene longitud 1, sus niveles también tendrán +# una longitud de 1 también + +length(factor("male")) # 1 +length(levels(factor("male"))) # 1 +# Los factores son comúnmente vistos en marcos de dato, y una estructura de +# datos que cubriremos después +data(infert) # "Infertility after Spontaneous and Induced Abortion" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# NULL +# "NULL" es uno raro; utilízalo para "limpiar" un vector +class(NULL) # NULL +parakeet = c("beak", "feathers", "wings", "eyes") +parakeet +# => +# [1] "beak" "feathers" "wings" "eyes" +parakeet <- NULL +parakeet +# => +# NULL + +# COERCIÓN DE TIPO +# La coerción de tipos es cuando forzas un valor diferente tipo al que puede tomar. +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# Si pones elementos de diferentes tipos en un vector, coerciones raras pasan: +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" +as.numeric("Bilbo") +# => +# [1] NA +# Warning message: +# NAs introduced by coercion + +# También tomar nota: Esos solo eran datos de tipos básicos +# Hay mucho más tipos de datos, como las fechas, series de tiempo, etc. + + +################################################## +# Variables, ciclos, condiciones (if/else) +################################################## + +# A variable is like a box you store a value in for later use. +# We call this "assigning" the value to the variable. +# Having variables lets us write loops, functions, and if/else statements + +# VARIABLES +# Muchas maneras de asignar valores: +x = 5 # esto es posible +y <- "1" # esto es preferido +TRUE -> z # estos funciona pero es raro + +# CICLOS +# Tenemos ciclos 'for' +for (i in 1:4) { + print(i) +} +# Tenemos ciclos 'while' +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# Ten en mente que los ciclos 'for' y 'while' son lentos en R +# Operaciones con vectores enteros (i.e. una fila o columna completa) +# o tipos de función apply() (que discutiremos después) son preferidos + +# CONDICIONES (IF/ELSE) +# De nuevo, bastante normal +if (4 > 3) { + print("4 is greater than 3") +} else { + print("4 is not greater than 3") +} +# => +# [1] "4 is greater than 3" + +# FUNCIONES +# Definidos de la siguiente manera: +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) #agregar un poco de ruido (controlado) + return(x) +} +# Llamados como cualquier otra función de R +jiggle(5) # 5±ε. luego de set.seed(2716057), jiggle(5)==5.005043 + + + +########################################################################### +# Estructura de datos: Vectores, matrices, marcos da datos y arreglos +########################################################################### + +# UNIDIMENSIONAL + +# Empecemos desde el principio, y con algo que ya conoces: vectores. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# Preguntamos por elementos específicos poniendo un subconjunto en corchetes +# (Toma nota de que R empieza los conteos desde 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# También podes buscar por los índices de componentes específicos, +which(vec %% 2 == 0) # 1 3 +# obtener la primera o las últimas entradas de un vector, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# o averiguar si cierto valor se encuentra dentro de un vector +any(vec == 10) # TRUE +# Si un índice "se pasa", obtendrás un NA: +vec[6] # NA +# Puedes encontrar la longitud de un vector con length() +length(vec) # 4 +# Puedes realizar operaciones con vectores enteros o con subconjuntos de vectores +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 +any(vec[2:3] == 8) # FALSE +# y R tiene muchas funciones pre-definidas para resumir vectores +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Otras funciones pre-definidas: +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# => +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +# BIDIMENCIONAL (TODO EN UNA CLASE) + +# Puedes hacer una matriz de las entradas todos de un mismo tipo como: +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# A diferencia de un vector, una clase matriz es una 'matriz', +# sin importar qué contiene +class(mat) # => "matrix" +# Consulta la primera fila +mat[1,] # 1 4 +# Realiza una operación en la primera columna +3 * mat[,1] # 3 6 9 +# Consulta por una celda específica +mat[3,2] # 6 + +# Transpone una matriz entera +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# Multiplicación de matrices +mat %*% t(mat) +# => +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + +# cbind() une vectores como columnas para hacer una matriz +mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) +mat2 +# => +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" +# [4,] "4" "dog" +class(mat2) # matrix +# De nuevo, ten en cuenta lo que sucedió +# Debido a que las matrices deben de contener todas las entradas del mismo tipo, +# todo fue convertido a la clase caracter +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() une vectores como filas para hacer una matriz +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Ah, todo es de la misma clase. No hay coerciones. Mucho mejor. + +# BIDIMENSIONAL (DIFERENTES CLASES) + +# Para columnas de tipos diferentes, utiliza un data frame +# Esta estructura de datos es muy útil para programación estadística, +# una versión de ésta fue agregada a Python en el paquete "pandas". + +students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(students) <- c("name", "year", "house") # name the columns +class(students) # "data.frame" +students +# => +# name year house +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(students$year) # "numeric" +class(students[,3]) # "factor" +# encontrar las dimensiones +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# La función data.frame() convierte vectores de caracteres en vectores +# de factores por defecto; deshabilita este atributo +# stringsAsFactors = FALSE cuando vayas a crear el data.frame +?data.frame + +# Hay otras formas de hacer subconjuntos de data frames +students$year # 3 2 2 1 0 -1 +students[,2] # 3 2 2 1 0 -1 +students[,"year"] # 3 2 2 1 0 -1 + +# Una versión aumentada de la estructura data.frame es el data.table +# Si estás trabajando huge o panel data, o necesitas unificar algunos +# subconjuntos de datos, data.table puede ser una buena elección. +# Aquí un tour: +install.packages("data.table") # Descarga el paquete de CRAN +require(data.table) # Cárgalo +students <- as.data.table(students) +students # Tomar en cuenta la diferencia de la impresión +# => +# name year house +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +students[name=="Ginny"] # obtener filas con name == "Ginny" +# => +# name year house +# 1: Ginny -1 G +students[year==2] # obtener filas con year == 2 +# => +# name year house +# 1: Fred 2 G +# 2: George 2 G +# data.table hace que la unificación de dos sets de datos sea fácil +# Hagamos otro data.table para unifiar a los estudiantes +founders <- data.table(house=c("G","H","R","S"), + founder=c("Godric","Helga","Rowena","Salazar")) +founders +# => +# house founder +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(students, house) +setkey(founders, house) +students <- founders[students] # Unifica los dos sets de datos comparando "house" +setnames(students, c("house","houseFounderName","studentName","year")) +students[,order(c("name","year","house","houseFounderName")), with=F] +# => +# studentName year house houseFounderName +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar + +# data.table hace que sea fácil obtener resúmenes de las tablas +students[,sum(year),by=house] +# => +# house V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# Para eliminar una columna de un data.frame o data.table, +# asignarle el valor NULL. +students$houseFounderName <- NULL +students +# => +# studentName year house +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + +# Elimina una fila poniendo un subconjunto +# Usando data.table: +students[studentName != "Draco"] +# => +# house studentName year +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# Usando data.frame: +students <- as.data.frame(students) +students[students$house != "G",] +# => +# house houseFounderName studentName year +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + +# MULTI-DIMENSIONAL (TODOS LOS ELEMENTOS DE UN TIPO) + +# Arreglos crean una tabla de dimensión n +# Todos los elementos deben de ser del mismo tipo +# Puedes hacer una tabla bi-dimensional (como una matriz) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# Puedes utilizar un arreglo para hacer una matriz tri-dimensional también +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# => +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +# LISTAS (MULTI-DIMENSIONAL, POSIBLEMENTE DESIGUALES, DE DIFERENTES TIPOS) + +# Finalmente, R tiene listas (de vectores) +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # aleatorio +list1 +# Puedes obtener elementos de una lista de la siguiente manera +list1$time # Una manera +list1[["time"]] # Otra manera +list1[[1]] # Y otra manera +# => +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# Puedes crear una lista de subconjuntos como cualquier otro vector +list1$price[4] + +# Las listas no son la estructura de datos más eficiente para trabajar en R; +# a menos de que tengas una buena razón, deberías de quedarte con data.frames +# Las listas son usualmente devueltas por funciones que realizan regresiones +# lineales + +################################################## +# La familia de funciones apply() +################################################## + +# Te recuerdas de mat? +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Utiliza apply(X, MARGIN, FUN) paraaplicar una función FUN a la matriz X +# sobre las filas (MAR = 1) o las columnas (MAR = 2) +# Eso es, R aplica FUN sobre cada fila (o columna) de X, mucho más rápido que +# lo que haría un ciclo 'for' o 'loop' +apply(mat, MAR = 2, jiggle) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# Otras funciones: ?lapply, ?sapply + +# No te sientas muy intimidado; todos están de acuerdo que son confusas + +# El paquete plyr busca reemplazar (y mejorar) la familiar *apply() +install.packages("plyr") +require(plyr) +?plyr + + + +######################### +# Carga de datos +######################### + +# "pets.csv" es un archivo en internet +# (pero puede ser tan fácil como tener el archivo en tu computadora) +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +pets +head(pets, 2) # primeras dos filas +tail(pets, 1) # última fila + +# Para guardar un data frame o una matriz como un archivo .csv +write.csv(pets, "pets2.csv") # para hacer un nuevo archivo .csv +# definir el directorio de trabajo con setwd(), búscalo con getwd() + +# Prueba ?read.csv ?write.csv para más información + + +######################### +# Gráficas +######################### + +# FUNCIONES PREDEFINIDAS DE GRAFICACIÓN +# Gráficos de dispersión! +plot(list1$time, list1$price, main = "fake data") +# Regresiones! +linearModel <- lm(price ~ time, data = list1) +linearModel # Muestra el resultado de la regresión +# Grafica la línea de regresión +abline(linearModel, col = "red") +# Obtiene una veridad de diagnósticos +plot(linearModel) +# Histogramas! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Barras! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# GGPLOT2 +# Pero éstas no son las gráficas más bonitas de R +# Prueba el paquete ggplot2 para mayor variedad y mejores gráficas +install.packages("ggplot2") +require(ggplot2) +?ggplot2 +pp <- ggplot(students, aes(x=house)) +pp + geom_histogram() +ll <- as.data.table(list1) +pp <- ggplot(ll, aes(x=time,price)) +pp + geom_point() +# ggplot2 tiene una excelente documentación +# (disponible en http://docs.ggplot2.org/current/) + + + +``` + +## ¿Cómo obtengo R? + +* Obtén R y R GUI de [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) es otro GUI diff --git a/r.html.markdown b/r.html.markdown index 8896c5b0..fbc87b0e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -2,7 +2,7 @@ language: R contributors: - ["e99n09", "http://github.com/e99n09"] - - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] filename: learnr.r --- -- cgit v1.2.3 From 2c8e6490f3d5dabd859e40ca35c5370f116e31c7 Mon Sep 17 00:00:00 2001 From: Brett Taylor Date: Tue, 20 Oct 2015 12:46:58 +1300 Subject: [php-composer/en] Add new tool document for Composer, PHP's dependency manager. --- php-composer.html.markdown | 167 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 php-composer.html.markdown diff --git a/php-composer.html.markdown b/php-composer.html.markdown new file mode 100644 index 00000000..16fed582 --- /dev/null +++ b/php-composer.html.markdown @@ -0,0 +1,167 @@ +--- +category: tool +tool: composer +contributors: + - ["Brett Taylor", "https://github.com/glutnix"] +filename: LearnComposer.sh +--- + +[Composer](https://getcomposer.org/) is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you. + +# Installing + +```sh +# Installs the composer.phar binary into the current directory +curl -sS https://getcomposer.org/installer | php +# If you use this approach, you will need to invoke composer like this: +php composer.phar about + +# Installs the binary into ~/bin/composer +# Note: make sure ~/bin is in your shell's PATH environment variable +curl -sS https://getcomposer.org/installer | php -- --install-dir=~/bin --filename=composer +``` + +Windows users should follow the [Windows installation instructions](https://getcomposer.org/doc/00-intro.md#installation-windows) + +## Confirming installation + +```sh +# Check version and list options +composer + +# Get more help for options +composer help require + +# Check if Composer is able to do the things it needs, and if it's up to date +composer diagnose +composer diag # shorthand + +# Updates the Composer binary to the latest version +composer self-update +composer self # shorthand +``` + +# Usage + +Composer stores your project dependencies in `composer.json`. You can edit this file, but it is best to let Composer manage it for you. + +```sh +# Create a new project in the current folder +composer init +# runs an interactive questionnaire asking you for details about your project. Leaving them blank is fine unless you are making other projects dependent on this one. + +# If a composer.json file already exists, download the dependencies +composer install + +# To download the just the production dependencies, i.e. excluding development dependencies +composer install --no-dev + +# Add a production dependency to this project +composer require guzzlehttp/guzzle +# will figure out what the latest version of guzzlehttp/guzzle is, download it, and add the new dependency to composer.json's require field. + +composer require guzzlehttp/guzzle:6.0.* +# will download the latest version matching the pattern (eg. 6.0.2) and add the dependency to composer.json's require field + +composer require --dev phpunit/phpunit:~4.5.0 +# will require as a development dependency. Will use the latest version >=4.5.0 and < 4.6.0 + +composer require-dev phpunit/phpunit:^4.5.0 +# will require as a development dependency. Will use the latest version >=4.5.0 and < 5.0 + +# For more information on Composer version matching, see [Composer's documentation on Versions](https://getcomposer.org/doc/articles/versions.md) for more details + +# To see what packages are available to install and currently installed +composer show + +# To see what packages are currently installed +composer show --installed + +# To find a package with 'mailgun' in its name or description +composer search mailgun +``` + +[Packagist.org](https://packagist.org/) is the main repository for Composer packages. Search there for existing third-party packages. + +## `composer.json` vs `composer.lock` + +The `composer.json` file stores your project's floating version preferences for each dependency, along with other information. + +The `composer.lock` file stores exactly which version it has downloaded for each dependency. Never edit this file. + +If you include the `composer.lock` file in your git repository, every developer will install the currently used version of the dependency. Even when a new version of a dependency is released, Composer will continue to download the version recorded in the lock file. + +```sh +# If you want to update all the dependencies to their newest version still matching your version preferences +composer update + +# If you want the new version of a particular dependency: +composer update phpunit/phpunit + +# If you wish to migrate a package to a newer version preference, you may need to remove the older package and its dependencies first. +composer remove --dev phpunit/phpunit +composer require --dev phpunit/phpunit:^5.0 + +``` + +## Autoloader + +Composer creates an autoloader class you can require from your application. You can make instances of classes via their namespace. + +```php +require __DIR__ . '/vendor/autoload.php'; + +$mailgun = new Mailgun\Mailgun("key"); +``` + +### PSR-4 Autoloader + +You can add your own namespaces to the autoloader. + +In `composer.json`, add a 'autoload' field: + +```json +{ + "autoload": { + "psr-4": {"Acme\\": "src/"} + } +} +``` +This will tell the autoloader to look for anything in the `\Acme\` namespace within the `src` folder. + +You can also [use PSR-0, a Classmap or just a list of files to include](https://getcomposer.org/doc/04-schema.md#autoload). There is also the `autoload-dev` field for development-only namespaces. + +When adding or modifying the autoload key, you will need to rebuild the autoloader: + +```sh +composer dump-autoload +composer dump # shorthand + +# Optimizes PSR0 and PSR4 packages to be loaded with classmaps too. Slow to run, but improves performance on production. +composer dump-autoload --optimize --no-dev +``` + +# Composer's Cache + +```sh +# Composer will retain downloaded packages to use in the future. Clear it with: +composer clear-cache +``` + +# Troubleshooting + +```sh +composer diagnose +composer self-update +composer clear-cache +``` + +## Topics not (yet) covered in this tutorial + +* Creating and distributing your own packages on Packagist.org or elsewhere +* Pre- and post- script hooks: run tasks when certain composer events take place + +### References + +* [Composer - Dependency Manager for PHP](https://getcomposer.org/) +* [Packagist.org](https://packagist.org/) -- cgit v1.2.3 From f02ad99fdd90c4c522e00aca3b46a0db5dd24083 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 16:25:31 -0700 Subject: Fixed filename --- es-es/r-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/r-es.html.markdown b/es-es/r-es.html.markdown index db780c27..2b710b27 100644 --- a/es-es/r-es.html.markdown +++ b/es-es/r-es.html.markdown @@ -6,7 +6,7 @@ contributors: translators: - ["David Hsieh", "http://github.com/deivuh"] lang: es-es -filename: learnr.r +filename: learnr-es.r --- R es un lenguaje de computación estadística. Tiene muchas librerías para cargar -- cgit v1.2.3 From 9aca78c50a44a4e175798c1ebc66f843f82af80f Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 17:05:09 -0700 Subject: Fixed swift-es filename --- es-es/swift-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown index 86f0aab6..dcc3a607 100644 --- a/es-es/swift-es.html.markdown +++ b/es-es/swift-es.html.markdown @@ -8,7 +8,7 @@ contributors: translators: - ["David Hsieh", "http://github.com/deivuh"] lang: es-es -filename: learnswift.swift +filename: learnswift-es.swift --- Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado -- cgit v1.2.3 From e0645015b528fcb365da34d617ade037f89c0db9 Mon Sep 17 00:00:00 2001 From: David Hsieh Date: Mon, 19 Oct 2015 17:05:50 -0700 Subject: Fixed obj-c-es filename --- es-es/objective-c-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/objective-c-es.html.markdown b/es-es/objective-c-es.html.markdown index c5532c0f..7f8d130b 100644 --- a/es-es/objective-c-es.html.markdown +++ b/es-es/objective-c-es.html.markdown @@ -8,7 +8,7 @@ contributors: translators: - ["David Hsieh", "http://github.com/deivuh"] lang: es-es -filename: LearnObjectiveC.m +filename: LearnObjectiveC-es.m --- Objective C es el lenguaje de programación principal utilizado por Apple para los sistemas operativos OS X y iOS y sus respectivos frameworks, Cocoa y Cocoa Touch. -- cgit v1.2.3 From dca117cecfda42d38f13195da0cf3a05e4d7045a Mon Sep 17 00:00:00 2001 From: everblut Date: Mon, 19 Oct 2015 19:27:06 -0500 Subject: Fix typos and update yaml-es content --- es-es/yaml-es.html.markdown | 189 +++++++++++++++++++++++++++++++------------- 1 file changed, 132 insertions(+), 57 deletions(-) diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown index a5157b5d..cd3143fb 100644 --- a/es-es/yaml-es.html.markdown +++ b/es-es/yaml-es.html.markdown @@ -4,6 +4,7 @@ lang: es-es filename: learnyaml-es.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Everardo Medina","https://github.com/everblut"] translators: - ["Daniel Zendejas","https://github.com/DanielZendejas"] --- @@ -14,7 +15,7 @@ leído y escrito por humanos. Basa su funcionalidad en JSON, con la adición de líneas nuevas e indentación inspirada en Python. A diferencia de Python, YAML -no permite tabs literales. +no permite tabulaciones literales. ```yaml # Los comentarios en YAML se ven así. @@ -38,97 +39,177 @@ llave con espacios: valor llave: "Un string, entre comillas." "Las llaves tambien pueden estar entre comillas.": "valor entre comillas" -# Los strings de líneas múltiples pueden ser escritos +# Los strings de líneas múltiples pueden ser escritos # como un 'bloque literal' (usando pipes |) # o como un 'bloque doblado' (usando >) bloque_literal: | Este bloque completo de texto será preservado como el valor de la llave 'bloque_literal', incluyendo los saltos de línea. - - Se continúa guardando la literal hasta que se cese la indentación. + + Se continúa guardando la literal hasta que se cese la indentación. Cualquier línea que tenga más indentación, mantendrá los espacios dados (por ejemplo, estas líneas se guardarán con cuatro espacios) -nloque_doblado: > +bloque_doblado: > De la misma forma que el valor de 'bloque_literal', todas estas líneas se guardarán como una sola literal, pero en esta ocasión todos los saltos de línea serán reemplazados por espacio. - Las líneas en blanco, como la anterior, son convertidos a un salto de línea. + Las líneas en blanco, como la anterior, son convertidas a un salto de línea. Las líneas con mayor indentación guardan sus saltos de línea. Esta literal ocuparán dos líneas. -######################## -# TIPOS DE COLECCIONES # -######################## - -# La indentación se usa para anidar. +# La indentación se usa para anidar elementos un_mapa_indentado: llave: valor otra_llave: otro valor otro_mapa_indentado: llave_interna: valor_interno -# Las llaves de los mapas no deben ser strings necesariamente +# Las llaves de los mapas no requieren ser strings necesariamente 0.25: una llave numérica -# Las llaves también pueden ser objetos de multi línea, usando ? para indicar -# el inicio de una llave +# Las llaves también pueden ser objetos de multiples líneas, +# usando ? para indicar el inicio de una llave ? | Esto es una llave que tiene múltiples líneas : y este es su valor -# YAML tambien permite colecciones como llaves, pero muchos lenguajes de +######################## +# TIPOS DE COLECCIONES # +######################## + +# Las colecciones en YAML usan la indentación para delimitar el alcance +# y cada elemento de la colección inicia en su propia línea. +# YAML tambien permite colecciones como llaves, pero muchos lenguajes de # programación se quejarán. # Las secuencias (equivalentes a listas o arreglos) se ven así: -una_secuencia: - - Item 1 - - Item 2 - - 0.5 # las secuencias pueden tener distintos tipos en su contenido. - - Item 4 - - llave: valor - otra_llave: otro_valor +- Amarillo +- Verde +- Azul + +# Se puede usar una secuencia como valor para una llave. +secuencia: + - Elemento 1 + - Elemento 2 + - Elemento 3 + - Elemento 4 + +# Las secuencias pueden contener secuencias como elementos. +- [Uno, Dos, Tres] +- [Domingo, Lunes, Martes] +- [Luna, Marte, Tierra] + +# Las secuencias pueden tener distintos tipos en su contenido. +secuencia_combinada: + - texto + - 5 + - 0.6 + - llave: valor # se convierte en un json dentro de la secuencia - - Esta es una secuencia - ...dentro de otra secuencia -# Dado que todo JSON está incluído dentro de YAML, también puedes escribir -# mapas con la sintaxis de JSON y secuencias: -mapa_de_json: {"llave": "valor"} -secuencia_de_json: [3, 2, 1, "despegue"] +# Dado que todo JSON está incluído dentro de YAML, también puedes escribir +# mapas con la sintaxis de JSON y secuencias: +mapa_de_json_1: {"llave": "valor"} +mapa_de_json_2: + llave: valor + +# Las secuencias tambien se pueden escribir como un arreglo al estilo JSON +secuencia_de_json_1: [3, 2, 1, "despegue"] +secuencia_de_json_2: + - 3 + - 2 + - 1 + - "despegue" + +# YAML también soporta conjuntos usando el simbolo ? +# y se ven de la siguiente forma: +set: + ? item1 + ? item2 + ? item3 + +# Se puede usar el tag !!set +# Al igual que Python, los conjuntos sólo son mapas con valores nulos. +# El ejemplo de arriba es equivalente a: +set2: + item1: null + item2: null + item3: null ################################## # CARACTERÍSTICAS EXTRAS DE YAML # ################################## +# YAML usa tres guiones (---) para diferenciar entre directivas +# y contenido del documento. +# Por otra parte, tres puntos (...) se utilizan para indicar +# el final del documento en casos especiales. + # YAML tiene funciones útiles llamadas 'anchors' (anclas), que te permiten -# duplicar fácilmente contenido a lo largo de tu documento. En el ejemplo -# a continuación, ambas llaves tendrán el mismo valor: -contenido_anclado: &nombre_del_ancla Este string será el valor de las llaves -otra_ancla: *nombre_del_ancla - -# YAML también tiene tags, que puedes usar para declarar tipos explícitamente. -string_explícito: !!str 0.5 -# Algunos parseadores implementar tags específicas del lenguaje, como el +# duplicar fácilmente contenido a lo largo de tu documento. +# El ampersand indica la declaración del ancla, +declara_ancla: &texto texto de la llave +# el asterisco indica el uso de dicha ancla. +usa_ancla: *texto # tendrá el valor "texto de la llave" + +################ +# TAGS EN YAML # +################ + +# En YAML, los nodos que no tienen un tag obtienen su tipo +# según la aplicación que los use, al usar un tag +# se pueden declarar tipos explícitamente. +string_explicito: !!str 0.5 # !!str para declarar un string +integer_explicito: !!int 5 # !!int para declarar un integer +float_explicito: !!float 1.2 # !!float para declarar un float +conjunto_explicito: !!set # !!set para declarar un conjunto + ? Uno + ? Dos + ? Tres +mapa_ordenado_explicito: !!omap # !!omap para declarar un mapa ordenado +- Primero: 1 +- Segundo: 2 +- Tercero: 3 +- Cuarto: 4 + +# Tags para los numeros enteros +llave_canonica: 5222 +llave_decimal: +5222 +llave_octal: 010 +llave_hexadecimal: 0xC + +#Tags para los numeros flotantes +llave_canonica: 1.215e+3 +llave_exponencial: 12.3555e+02 +llave_fija: 12.15 +llave_negativa_infinita: -.inf +llave_numero_invalido: .NaN + +# Tags para las fechas y horas +llave_canonica: 2001-12-15T02:59:43.1Z +llave_iso8601: 2001-12-14t21:59:43.10-05:00 +llave_con_espacios: 2001-12-14 21:59:43.10 -5 +llave_fecha: 2002-12-14 + +# Además existen tags para +null: #valor nulo +booleans: [ true, false ] # Valores booleanos +string: '012345' # Valor en string + + +# Algunos parseadores implementan tags específicas del lenguaje, como el # que se muestra a continuación, encargado de manejar números complejos en # Python: numero_complejo_python: !!python/complex 1+2j -######################## -# TIPOS EXTRAS EN YAML # -######################## - -# Stirngs y números no son los únicos escalares que YAML puede entener. -# YAML también puede parsear fechas en formato ISO . -fechaHora: 2001-12-15T02:59:43.1Z -fechaHora_con_espacios: 2001-12-14 21:59:43.10 -5 -fecha: 2002-12-14 - -# La tag !!binary indica que un string es, en realidad, un blob +# El tag !!binary indica que un string es en realidad un blob # representado en base-64. archivo_gif: !!binary | R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 @@ -136,16 +217,10 @@ archivo_gif: !!binary | +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML también tiene un tipo set, que se ve de la siguiente forma: -set: - ? item1 - ? item2 - ? item3 - -# Al igual que Python, los sets sólo son mapas con valores nulos. -# El ejemplo de arriba es equivalente a: -set2: - item1: null - item2: null - item3: null ``` + +### Recursos adicionales + ++ [Sitio oficial de YAML](http://yaml.org/) ++ [Parser en línea de de YAML](http://yaml-online-parser.appspot.com/) ++ [Validador en línea de YAML](http://codebeautify.org/yaml-validator) -- cgit v1.2.3 From a6eb459b611b67132c76e34095afd87a5aada78c Mon Sep 17 00:00:00 2001 From: Vipul Sharma Date: Tue, 20 Oct 2015 09:57:53 +0530 Subject: Modified string format [python/en] --- python.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 42a52bcf..01e5d481 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -123,8 +123,11 @@ not False # => True # A string can be treated like a list of characters "This is a string"[0] # => 'T' -# % can be used to format strings, like this: -"%s can be %s" % ("strings", "interpolated") +#String formatting with % +#Even though the % string operator will be deprecated on Python 3.1 and removed later at some time, it may still be #good to know how it works. +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y) # A newer way to format strings is the format method. # This method is the preferred way -- cgit v1.2.3 From dc235b3d13c1c7a3a11585dcce8adf992bf707f6 Mon Sep 17 00:00:00 2001 From: tricinel Date: Tue, 20 Oct 2015 10:18:08 +0200 Subject: [coffeescript/en] Add coffeescript translation to Romanian --- ro-ro/coffeescript-ro.html.markdown | 101 ++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 ro-ro/coffeescript-ro.html.markdown diff --git a/ro-ro/coffeescript-ro.html.markdown b/ro-ro/coffeescript-ro.html.markdown new file mode 100644 index 00000000..ece502a0 --- /dev/null +++ b/ro-ro/coffeescript-ro.html.markdown @@ -0,0 +1,101 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Bogdan Lazar", "http://twitter.com/tricinel"] +filename: coffeescript.coffee +--- + +CoffeeScript este un limbaj de programare care este compilat in Javascript. Nu exista un interpretator la runtime-ul aplicatiei. Fiind unul din successorii Javascript, CoffeeScript incearca sa compileze Javascript usor de citit si performant. + +Mai cititi si [website-ul CoffeeScript](http://coffeescript.org/), care contine un tutorial complet Coffeescript. + +```coffeescript +# CoffeeScript este un limbaj de hipster. +# Se foloseste de trendurile multor limbaje moderne de programare. +# Comentarii sunt ca in Ruby sau Python. + +### +Comentariile in bloc sunt create cu `###`, iar acestea sunt transformate in `/*` si `*/` pentru Javascript + +Ar trebuie sa intelegeti Javascript pentru a continua cu acest ghid. +### + +# Atribuirea valorilor: +numar = 42 #=> var numar = 42; +opus = true #=> var opus = true; + +# Conditii: +numar = -42 if opus #=> if(opus) { numar = -42; } + +# Functii: +laPatrat = (x) -> x * x #=> var laPatrat = function(x) { return x * x; } + +plin = (recipient, lichid = "cafea") -> + "Umplem #{recipient} cu #{cafea}..." +#=>var plin; +# +#plin = function(recipient, lichid) { +# if (lichid == null) { +# lichid = "cafea"; +# } +# return "Umplem " + recipient + " cu " + lichid + "..."; +#}; + +# Liste: +lista = [1..5] #=> var lista = [1, 2, 3, 4, 5]; + +# Obiecte: +matematica = + radacina: Math.sqrt + laPatrat: laPatrat + cub: (x) -> x * square x +#=> var matematica = { +# "radacina": Math.sqrt, +# "laPatrat": laPatrat, +# "cub": function(x) { return x * square(x); } +# }; + +# Splats: +cursa = (castigator, alergatori...) -> + print castigator, alergatori +#=>cursa = function() { +# var alergatori, castigator; +# castigator = arguments[0], alergatori = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(castigator, alergatori); +# }; + +# Verificarea existentei: +alert "Stiam eu!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Stiam eu!"); } + +# Operatiuni cu matrice: +cuburi = (math.cube num for num in list) +#=>cuburi = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +alimente = ['broccoli', 'spanac', 'ciocolata'] +mananca aliment for aliment in alimente when aliment isnt 'ciocolata' +#=>alimente = ['broccoli', 'spanac', 'ciocolata']; +# +#for (_k = 0, _len2 = alimente.length; _k < _len2; _k++) { +# aliment = alimente[_k]; +# if (aliment !== 'ciocolata') { +# eat(aliment); +# } +#} +``` + +## Resurse aditionale + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From 60a1a43cd3d797d347d06ef4568f542ab473b2dc Mon Sep 17 00:00:00 2001 From: duci9y Date: Tue, 20 Oct 2015 13:53:47 +0530 Subject: [xml/en] Grammar, formatting. Made more 'inlined'. --- xml.html.markdown | 155 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 96 insertions(+), 59 deletions(-) diff --git a/xml.html.markdown b/xml.html.markdown index b95d6088..b4b54330 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -4,18 +4,76 @@ filename: learnxml.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] --- -XML is a markup language designed to store and transport data. +XML is a markup language designed to store and transport data. It is supposed to be both human readable and machine readable. Unlike HTML, XML does not specify how to display or to format data, it just carries it. -* XML Syntax +Distinctions are made between the **content** and the **markup**. In short, content could be anything, markup is defined. + +## Some definitions and introductions + +XML Documents are basically made up of *elements* which can have *attributes* describing them and may contain some textual content or more elements as its children. All XML documents must have a root element, which is the ancestor of all the other elements in the document. + +XML Parsers are designed to be very strict, and will stop parsing malformed documents. Therefore it must be ensured that all XML documents follow the [XML Syntax Rules](http://www.w3schools.com/xml/xml_syntax.asp). ```xml - + + + + + + + +Content + + + + + + + + + + + + + + + + + + + + + + + Text + + + + + + + Text + + +Text +``` + +## An XML document +This is what makes XML versatile. It is human readable too. The following document tells us that it defines a bookstore which sells three books, one of which is Learning XML by Erik T. Ray. All this without having used an XML Parser yet. + +```xml + Everyday Italian @@ -36,85 +94,49 @@ Unlike HTML, XML does not specify how to display or to format data, it just carr 39.95 - - - - - - - - -computer.gif - - ``` -* Well-Formated Document x Validation - -An XML document is well-formatted if it is syntactically correct. -However, it is possible to inject more constraints in the document, -using document definitions, such as DTD and XML Schema. +## Well-formedness and Validation -An XML document which follows a document definition is called valid, -in regards to that document. - -With this tool, you can check the XML data outside the application logic. +A XML document is *well-formed* if it is syntactically correct. However, it is possible to add more constraints to the document, using Document Type Definitions (DTDs). A document whose elements are attributes are declared in a DTD and which follows the grammar specified in that DTD is called *valid* with respect to that DTD, in addition to being well-formed. ```xml - - - + - + + - Everyday Italian + Everyday Italian + Giada De Laurentiis + 2005 30.00 - - - - + + + + + ]> - - - - - + @@ -127,3 +149,18 @@ With this tool, you can check the XML data outside the application logic. ``` + +## DTD Compatibility and XML Schema Definitions + +Support for DTDs is ubiquitous because they are so old. Unfortunately, modern XML features like namespaces are not supported by DTDs. XML Schema Definitions (XSDs) are meant to replace DTDs for defining XML document grammar. + +## Resources + +* [Validate your XML](http://www.xmlvalidation.com) + +## Further Reading + +* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/) +* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp) +* [XML Tutorial](http://www.w3schools.com/xml/default.asp) +* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp) -- cgit v1.2.3 From 76e72653b28590f6aaea9e08ae38f9a812cc65e2 Mon Sep 17 00:00:00 2001 From: duci9y Date: Tue, 20 Oct 2015 14:24:32 +0530 Subject: [json/en] Cut noise, formatting, links. Also removed some duplicate information. --- json.html.markdown | 51 ++++++++++++++++++++++++--------------------------- 1 file changed, 24 insertions(+), 27 deletions(-) diff --git a/json.html.markdown b/json.html.markdown index cde7bc40..a612cffe 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -8,27 +8,24 @@ contributors: - ["Michael Neth", "https://github.com/infernocloud"] --- -As JSON is an extremely simple data-interchange format, this is most likely going to be the simplest Learn X in Y Minutes ever. +JSON is an extremely simple data-interchange format. As [json.org](http://json.org) says, it is easy for humans to read and write and for machines to parse and generate. -JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility. - -For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. - -A JSON value must be a number, a string, an array, an object, or one of the following 3 literal names: true, false, null. - -Supporting browsers are: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+. - -File extension for JSON files is ".json" and the MIME type for JSON text is "application/json". +A piece of JSON must represent either: +* A collection of name/value pairs (`{ }`). In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. +* An ordered list of values (`[ ]`). In various languages, this is realized as an array, vector, list, or sequence. + an array/list/sequence (`[ ]`) or a dictionary/object/associated array (`{ }`). -Many programming languages have support for serializing (encoding) and unserializing (decoding) JSON data into native data structures. Javascript has implicit support for manipulating JSON text as data. +JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility. -More information can be found at http://www.json.org/ +For the purposes of this tutorial, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. -JSON is built on two structures: -* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. -* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. +Supported data types: -An object with various name/value pairs. +* Strings: `"hello"`, `"\"A quote.\""`, `"\u0abe"`, `"Newline.\n"` +* Numbers: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Objects: `{ "key": "value" }` +* Arrays: `["Values"]` +* Miscellaneous: `true`, `false`, `null` ```json { @@ -66,20 +63,20 @@ An object with various name/value pairs. "alternative style": { "comment": "check this out!" - , "comma position": "doesn't matter - as long as it's before the next key, then it's valid" + , "comma position": "doesn't matter, if it's before the next key, it's valid" , "another comment": "how nice" - } -} -``` + }, -A single array of values by itself is also valid JSON. -```json -[1, 2, 3, "text", true] -``` -Objects can be a part of the array as well. + "whitespace": "Does not matter.", -```json -[{"name": "Bob", "age": 25}, {"name": "Jane", "age": 29}, {"name": "Jack", "age": 31}] + + + "that was short": "And done. You now know everything JSON has to offer." +} ``` + +## Further Reading + +* [JSON.org](http://json.org) All of JSON beautifully explained using flowchart-like graphics. -- cgit v1.2.3 From 2f0acd34e28ee46e52391b349ddf3ca86ce95bc7 Mon Sep 17 00:00:00 2001 From: hack1m Date: Tue, 20 Oct 2015 21:01:47 +0800 Subject: [Sass/ms-my] Added Malay (Malaysia) translation for Sass --- ms-my/sass-my.html.markdown | 232 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 ms-my/sass-my.html.markdown diff --git a/ms-my/sass-my.html.markdown b/ms-my/sass-my.html.markdown new file mode 100644 index 00000000..2249a790 --- /dev/null +++ b/ms-my/sass-my.html.markdown @@ -0,0 +1,232 @@ +--- +language: sass +filename: learnsass-my.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +Sass ialah bahasa sambungan CSS yang menambah ciri-ciri seperti pembolehubah, bersarang, mixins dan banyak lagi. +Sass (dan prapemproses lain, seperti [Less](http://lesscss.org/)) membantu pembangun untuk menulis kod mampu diselenggara dan DRY (Don't Repeat Yourself). + +Sass mempunyai dua perbezaan pilihan sintaks untuk dipilih. SCSS, yang mana mempunyai sintaks yang sama seperti CSS tetapi dengan ditambah ciri-ciri Sass. Atau Sass (sintaks asal), yang menggunakan indentasi bukannya tanda kurung dakap dan semikolon. +Tutorial ini ditulis menggunakan SCSS. + +```scss + +//Komen baris tunggal dikeluarkan apabila Sass dikompil ke CSS. + +/*Komen multi dikekalkan. */ + + + +/*Pembolehubah +==============================*/ + + + +/* Anda boleh menyimpan nilai CSS (seperti warna) dalam pembolehubah. +Guna simbol '$' untuk membuat pembolehubah. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Anda boleh mengguna pembolehubah diseluruh lembaran gaya anda. +Kini jika anda ingin mengubah warna, anda hanya perlu membuat perubahan sekali.*/ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Ia akan dikompil kepada: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Ini jauh lebih mampu diselenggara daripada perlu menukar warna +setiap yang ada diseluruh lembaran gaya anda. */ + + + +/*Mixins +==============================*/ + + + +/* Jika anda jumpa yang anda menulis kod yang sama pada lebih dari satu +elemen, anda mungkin ingin menyimpan kod itu di dalam mixin. + +Guna arahan '@mixin', tambah dengan nama untuk mixin anda.*/ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Anda boleh guna mixin bersama '@include' dan nama mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/*Ia akan dikompil kepada: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Anda boleh guna mixins untuk membuat singkatan property. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/*Yang mana anda boleh seru dengan memberi argumen lebar dan tinggi. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Ia dikompil kepada: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + + +/*Extend (Inheritance) +==============================*/ + + + +/*Extend ialah jalan untuk berkongsi sifat dengan satu pemilih dengan yang lain. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Dikompil kepada: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + + + + +/*Bersarang +==============================*/ + + + +/*Sass membenarkan anda untuk sarangkan pemilih dengan pemilih */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' akan digantikan dengan pemilih induk. */ +/* Anda juga boleh sarangkan kelas-pseudo. */ +/* Perlu diingat terlebih bersarang akan membuat kod anda kurang mampu diselenggara. +Sebagai contoh: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Dikompil kepada: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + + +``` + + + +## SASS atau Sass? +Adakah anda tertanya-tanya sama ada Sass adalah akronim atau tidak? Anda mungkin tidak perlu, tetapi saya akan memberitahu. Nama bahasa ini adalah perkataan, "Sass", dan tidak akronim. +Kerana orang sentiasa menulis ia sebagai "Sass", pencipta bahasa bergurau memanggilnya "Syntactically Awesome StyleSheets". + +## Berlatih Sass +Jika anda ingin bermain dengan Sass di pelayar anda, lihat [SassMeister](http://sassmeister.com/). +Anda boleh guna salah satu sintaks, hanya pergi ke tetapan dan pilih sama ada Sass atau SCSS. + + +## Bacaan lanjut +* [Dokumentasi Rasmi](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) menyediakan tutorial (asas-lanjutan) dan artikel. -- cgit v1.2.3 From 17d10c158227270573cb4110fe402ff1c42caee8 Mon Sep 17 00:00:00 2001 From: hack1m Date: Tue, 20 Oct 2015 21:18:43 +0800 Subject: [Bash/ms-my] Added Malay (Malaysia) translation for Bash --- ms-my/bash-my.html.markdown | 284 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 284 insertions(+) create mode 100644 ms-my/bash-my.html.markdown diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown new file mode 100644 index 00000000..51036ad9 --- /dev/null +++ b/ms-my/bash-my.html.markdown @@ -0,0 +1,284 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +filename: LearnBash.sh +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +Bash adalah nama daripada unix shell, yang mana telah diagihkan sebagai shell untuk sistem operasi GNU dan sebagai shell lalai pada Linux dan Mac OS X. Hampir semua contoh di bawah boleh menjadi sebahagian daripada skrip shell atau dijalankan terus dalam shell. + +[Baca lebih lanjut di sini.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Baris pertama daripada skrip ialah shebang yang mana memberitahu sistem bagaimana untuk melaksana +# skrip: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Seperti yang anda sudah gambarkan, komen bermula dengan #. Shebang juga ialah komen. + +# Contoh mudah hello world: +echo Hello world! + +# Setiap arahan bermula pada baris baru, atau selepas semikolon: +echo 'This is the first line'; echo 'This is the second line' + +# Mengisytihar pembolehubah kelihatan seperti ini: +Variable="Some string" + +# Tetapi bukan seperti ini: +Variable = "Some string" +# Bash akan memutuskan yang pembolehubah adalah arahan ia mesti dilaksanakan dan memberi ralat +# kerana ia tidak boleh dijumpai. + +# Atau seperti ini: +Variable= 'Some string' +# Bash akan memutuskan yang ‘Beberapa rentetan’ adalah arahan ia mesti dilaksanakan dan memberi +# ralat kerana ia tidak dijumpai. (Dalam kes ini ‘Variable=' sebahagian dilihat +# sebagai penetapan pembolehubah sah hanya untuk skop ‘Beberapa rentetan’ +# arahan.) + +# Menggunakan pembolehubah: +echo $Variable +echo "$Variable" +echo '$Variable' +# Apabila anda guna pembolehubah itu sendiri - menetapkan, mengeksport, atau lain-lain - anda menulis +# nama ia tanpa $. Atau anda ingin menggunakan nilai pembolehubah, anda mesti guna $. +# Perlu diingatkan ‘(Petikan tunggal) tidak akan memperluaskan pembolehubah! + +# Penggantian rentetan dalam pembolehubah +echo ${Variable/Some/A} +# Ini akan menukarkan sebutan pertama bagi "Some" dengan "A" + +# Subrentetan daripada pembolehubah +Length=7 +echo ${Variable:0:Length} +# Ini akan kembalikan hanya 7 aksara pertama pada nilai + +# Nilai lalai untuk pembolehubah +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# Ini berfungsi untuk null (Foo=) dan rentetan kosong (Foo=“”); sifar (Foo=0) kembali 0. +# Perlu diingatkan ia hanya kembalikan nilai lalai dan tidak mengubah nilai pembolehubah. + +# Pembolehubah terbina: +# Terdapat beberapa pembolehubah terbina berguna, seperti +echo "Last program's return value: $?" +echo "Script's PID: $$" +echo "Number of arguments passed to script: $#" +echo "All arguments passed to script: $@" +echo "Script's arguments separated into different variables: $1 $2..." + +# Membaca nilai dari input: +echo "What's your name?" +read Name # Perlu diingatkan kita tidak perlu isytihar pembolehubah baru +echo Hello, $Name! + +# Kita ada yang biasa jika struktur: +# guna 'man test' untuk maklumat lanjut tentang bersyarat +if [ $Name -ne $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# Terdapat juga pelaksanaan bersyarat +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# Untuk guna & dan || bersama kenyataan ‘if’, anda perlu beberapa pasang daripada tanda kurung siku: +if [ $Name == "Steve" ] && [ $Age -eq 15 ] +then + echo "This will run if $Name is Steve AND $Age is 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "This will run if $Name is Daniya OR Zach." +fi + +# Eskspresi ia ditandai dengan format berikut: +echo $(( 10 + 5 )) + +# Tidak seperti bahasa pengaturcaraan lain, bash adalah shell jadi ia berfungsi dalam konteks +# daripada direktori semasa. Anda boleh menyenaraikan fail dan direktori dalam direktori +# semasa dengan arahan ini: +ls + +# Arahan ini mempunyai opsyen yang mengawal perlaksanaannya: +ls -l # Senarai setiap fail dan direktori pada baris yang berbeza + +# Keputusan arahan sebelum boleh diberikan kepada arahan selepas sebagai input. +# arahan grep menapis input dengan memberi paten. Ini bagaimana kita boleh senaraikan +# fail .txt di dalam direktori semasa: +ls -l | grep "\.txt" + +# Anda boleh mengubah hala arahan input dan output (stdin, stdout, and stderr). +# Baca dari stdin sampai ^EOF$ dan menulis ganti hello.py dengan baris +# antara “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 + +# Jalankan hello.py dengan pelbagai penghantaran semula stdin, stdout, and stderr: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Output ralat akan menulis ganti fail jika ia wujud, +# jika anda ingin menambah sebaliknta, guna ‘>>”: +python hello.py >> "output.out" 2>> "error.err" + +# Menulis ganti output.out, menambah ke error.err, dan mengira baris: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Jalankan arahan dan cetak fail Deskriptor (e.g. /dev/fd/123) +# lihat: man fd +echo <(echo "#helloworld") + +# Menulis ganti output.out dengan “#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Membersihkan fail semantara keseluruhan (tambah ‘-i’ untuk interaktif) +rm -v output.out error.err output-and-error.log + +# Arahan boleh digantikan dalam arahan lain menggunakan $(): +# Arahan berikut memaparkan jumlah fail dan direktori dalam +# direktori semasa. +echo "There are $(ls | wc -l) items here." + +# Perkara yang sama boleh dilakukan dengan menggunakan backticks `` tetapi ia tidak boleh bersarang - cara yang terbaik +# ialah menggunakan $( ). +echo "There are `ls | wc -l` items here." + +# Bash menggunakan penyataan case yang berfungsi sama seperti ‘switch’ pada Java dan C++: +case "$Variable" in + # Senarai paten untuk syarat yang ada ingin ketemui + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# ‘for loops iterate' untuk sebanyak mana argumen yang ditetapkan: +# Kandungan dari $Variable dicetakan tiga kali. +for Variable in {1..3} +do + echo "$Variable" +done + +# Atau tulis ia cara "traditional for loop": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Ia juga boleh digunakan untuk bertindak ke atas fail.. +# Ini akan menjalankan arahan 'cat' pada file1 dan file2 +for Variable in file1 file2 +do + cat "$Variable" +done + +# ..atau output daripada arahan +# Ini akan 'cat' output dari ls. +for Output in $(ls) +do + cat "$Output" +done + +# while loop: +while [ true ] +do + echo "loop body here..." + break +done + +# Anda juga boleh mendefinasikan fungsi +# Definasi: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# atau lebih mudah +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# Memanggil fungsi +foo "My name is" $Name + +# Terdapat banyak arahan yang berguna yang perlu anda belajar: +# cetak 10 baris terakhir dalam file.txt +tail -n 10 file.txt +# cetak 10 baris pertama dalam file.txt +head -n 10 file.txt +# menyusun baris fail.txt +sort file.txt +# laporan atau meninggalkan garisan berulang, dengan -d ia melaporkan +uniq -d file.txt +# cetak hanya kolum pertama sebelum aksara ',' +cut -d ',' -f 1 file.txt +# menggantikan setiap kewujudan 'okay' dengan 'great' dalam file.txt, (serasi regex) +sed -i 's/okay/great/g' file.txt +# cetak ke stdoout semua baris dalam file.txt yang mana sepadan beberapa regex +# contoh cetak baris yang mana bermula dengan “foo” dan berakhir dengan “bar” +grep "^foo.*bar$" file.txt +# beri opsyen “-c” untuk sebaliknya mencetak jumlah baris sepadan regex +grep -c "^foo.*bar$" file.txt +# jika anda secara literal mahu untuk mencari rentetan, +# dan bukannya regexm guna fgrep (atau grep -F) +fgrep "^foo.*bar$" file.txt + + +# Baca dokumentasi Bash shell terbina dengan 'help' terbina: +help +help help +help for +help return +help source +help . + +# Baca dokumentasi Bash manpage dengan man +apropos bash +man 1 bash +man bash + +# Baca info dokumentasi dengan info (? for help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Baca dokumentasi bash info: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From de9539a7775b39328c4bbe5e01efcd826ce8ade2 Mon Sep 17 00:00:00 2001 From: hack1m Date: Tue, 20 Oct 2015 21:34:34 +0800 Subject: Fix some word --- ms-my/bash-my.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown index 51036ad9..3632911d 100644 --- a/ms-my/bash-my.html.markdown +++ b/ms-my/bash-my.html.markdown @@ -96,7 +96,7 @@ fi echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" -# Untuk guna & dan || bersama kenyataan ‘if’, anda perlu beberapa pasang daripada tanda kurung siku: +# Untuk guna && dan || bersama kenyataan ‘if’, anda perlu beberapa pasang daripada tanda kurung siku: if [ $Name == "Steve" ] && [ $Age -eq 15 ] then echo "This will run if $Name is Steve AND $Age is 15." @@ -181,7 +181,7 @@ case "$Variable" in esac # ‘for loops iterate' untuk sebanyak mana argumen yang ditetapkan: -# Kandungan dari $Variable dicetakan tiga kali. +# Kandungan dari $Variable dicetakan sebanyak tiga kali. for Variable in {1..3} do echo "$Variable" @@ -270,7 +270,7 @@ apropos bash man 1 bash man bash -# Baca info dokumentasi dengan info (? for help) +# Baca dokumentasi info dengan info (? for help) apropos info | grep '^info.*(' man info info info -- cgit v1.2.3 From db8d8558809e7a6501f2f91ad3d6b12f16cf369f Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:17:44 -0300 Subject: Paren translation to brazillian portuguese --- pt-br/paren-pt.html.markdown | 196 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 pt-br/paren-pt.html.markdown diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown new file mode 100644 index 00000000..bd0c95e7 --- /dev/null +++ b/pt-br/paren-pt.html.markdown @@ -0,0 +1,196 @@ +--- +language: Paren +filename: learnparen-pt.paren +contributors: + - ["KIM Taegyoon", "https://github.com/kimtg"] +translators: + - ["Claudson Martins", "https://github.com/claudsonm"] +lang: pt-br +--- + +[Paren](https://bitbucket.org/ktg/paren) é um dialeto do Lisp. É projetado para ser uma linguagem embutida. + +Alguns exemplos foram retirados de . + +```scheme +;;; Comentários +# Comentários + +;; Comentários de única linha começam com um ponto e vírgula ou cerquilha + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Tipos de Dados Primitivos e Operadores +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Números +123 ; inteiro +3.14 ; double +6.02e+23 ; double +(int 3.14) ; => 3 : inteiro +(double 123) ; => 123 : double + +;; O uso de funções é feito da seguinte maneira (f x y z ...) +;; onde f é uma função e x, y, z, ... são os operandos +;; Se você quiser criar uma lista literal de dados, use (quote) para impedir +;; que sejam interpretados +(quote (+ 1 2)) ; => (+ 1 2) +;; Agora, algumas operações aritméticas +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(^ 2 3) ; => 8 +(/ 5 2) ; => 2 +(% 5 2) ; => 1 +(/ 5.0 2) ; => 2.5 + +;;; Booleanos +true ; para verdadeiro +false ; para falso +(! true) ; => falso +(&& true false (prn "não chega aqui")) ; => falso +(|| false true (prn "não chega aqui")) ; => verdadeiro + +;;; Caracteres são inteiros. +(char-at "A" 0) ; => 65 +(chr 65) ; => "A" + +;;; Strings são arrays de caracteres de tamanho fixo. +"Olá, mundo!" +"Sebastião \"Tim\" Maia" ; Contra-barra é um caractere de escape +"Foo\tbar\r\n" ; Inclui os escapes da linguagem C: \t \r \n + +;; Strings podem ser concatenadas também! +(strcat "Olá " "mundo!") ; => "Olá mundo!" + +;; Uma string pode ser tratada como uma lista de caracteres +(char-at "Abacaxi" 0) ; => 65 + +;; A impressão é muito fácil +(pr "Isso é" "Paren. ") (prn "Prazer em conhecê-lo!") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variáveis +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Você pode criar ou definir uma variável usando (set) +;; o nome de uma variável pode user qualquer caracter, exceto: ();#" +(set alguma-variavel 5) ; => 5 +alguma-variavel ; => 5 + +;; Acessar uma variável ainda não atribuída gera uma exceção +; x ; => Unknown variable: x : nil + +;; Ligações locais: Utiliza cálculo lambda! +;; 'a' e 'b' estão ligados a '1' e '2' apenas dentro de (fn ...) +((fn (a b) (+ a b)) 1 2) ; => 3 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Coleções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Listas + +;; Listas são estruturas de dados semelhantes a vetores. (A classe de comportamento é O(1).) +(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) +;; 'list' é uma variação conveniente para construir listas +(list 1 2 3) ; => (1 2 3) +;; Um quote também pode ser usado para uma lista de valores literais +(quote (+ 1 2)) ; => (+ 1 2) + +;; Você ainda pode utilizar 'cons' para adicionar um item ao início da lista +(cons 0 (list 1 2 3)) ; => (0 1 2 3) + +;; Listas são um tipo muito básico, portanto existe *enorme* funcionalidade +;; para elas, veja alguns exemplos: +(map inc (list 1 2 3)) ; => (2 3 4) +(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4) +(length (list 1 2 3 4)) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use 'fn' para criar funções. +;; Uma função sempre retorna o valor de sua última expressão +(fn () "Olá Mundo") ; => (fn () Olá Mundo) : fn + +;; Use parênteses para chamar todas as funções, incluindo uma expressão lambda +((fn () "Olá Mundo")) ; => "Olá Mundo" + +;; Atribuir uma função a uma variável +(set ola-mundo (fn () "Olá Mundo")) +(ola-mundo) ; => "Olá Mundo" + +;; Você pode encurtar isso utilizando a definição de função açúcar sintático: +(defn ola-mundo2 () "Olá Mundo") + +;; Os () acima é a lista de argumentos para a função +(set ola + (fn (nome) + (strcat "Olá " nome))) +(ola "Steve") ; => "Olá Steve" + +;; ... ou equivalente, usando a definição açucarada: +(defn ola2 (nome) + (strcat "Olá " name)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Igualdade +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Para números utilize '==' +(== 3 3.0) ; => verdadeiro +(== 2 1) ; => falso + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Controle de Fluxo +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Condicionais + +(if true ; Testa a expressão + "isso é verdade" ; Então expressão + "isso é falso") ; Senão expressão +; => "isso é verdade" + +;;; Laços de Repetição + +;; O laço for é para número +;; (for SÍMBOLO INÍCIO FIM SALTO EXPRESSÃO ..) +(for i 0 10 2 (pr i "")) ; => Imprime 0 2 4 6 8 10 +(for i 0.0 10 2.5 (pr i "")) ; => Imprime 0 2.5 5 7.5 10 + +;; Laço while +((fn (i) + (while (< i 10) + (pr i) + (++ i))) 0) ; => Imprime 0123456789 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutação +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use 'set' para atribuir um novo valor a uma variável ou local +(set n 5) ; => 5 +(set n (inc n)) ; => 6 +n ; => 6 +(set a (list 1 2)) ; => (1 2) +(set (nth 0 a) 3) ; => 3 +a ; => (3 2) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros lhe permitem estender a sintaxe da linguagem. +;; Os macros no Paren são fáceis. +;; Na verdade, (defn) é um macro. +(defmacro setfn (nome ...) (set nome (fn ...))) +(defmacro defn (nome ...) (def nome (fn ...))) + +;; Vamos adicionar uma notação infixa +(defmacro infix (a op ...) (op a ...)) +(infix 1 + 2 (infix 3 * 4)) ; => 15 + +;; Macros não são higiênicos, você pode sobrescrever as variáveis já existentes! +;; Eles são transformações de códigos. +``` -- cgit v1.2.3 From de34d88d94864ecf77151a866b512045ce196d74 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:26:25 -0300 Subject: Translation revision improvements --- pt-br/paren-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/paren-pt.html.markdown b/pt-br/paren-pt.html.markdown index bd0c95e7..464a69d2 100644 --- a/pt-br/paren-pt.html.markdown +++ b/pt-br/paren-pt.html.markdown @@ -72,7 +72,7 @@ false ; para falso ;; 2. Variáveis ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Você pode criar ou definir uma variável usando (set) -;; o nome de uma variável pode user qualquer caracter, exceto: ();#" +;; o nome de uma variável pode conter qualquer caracter, exceto: ();#" (set alguma-variavel 5) ; => 5 alguma-variavel ; => 5 -- cgit v1.2.3 From e8b9f47ce4102217d16707d80d31a663e683f716 Mon Sep 17 00:00:00 2001 From: Jason Yeo Date: Tue, 20 Oct 2015 22:26:37 +0800 Subject: Add a short tutorial for edn --- edn.html.markdown | 107 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 edn.html.markdown diff --git a/edn.html.markdown b/edn.html.markdown new file mode 100644 index 00000000..b8dc4e88 --- /dev/null +++ b/edn.html.markdown @@ -0,0 +1,107 @@ +--- +language: edn +filename: learnedn.edn +contributors: + - ["Jason Yeo", "https://github.com/jsyeo"] +--- + +Extensible Data Notation or EDN for short is a format for serializing data. + +The notation is used internally by Clojure to represent programs and +it is used commonly by Clojure and Clojurescript programs to transfer +data. Though there are implementations of EDN for many other +languages. + +The main benefit of EDN is that it is extensible, which we will see +how it is extended later on. + +```Clojure +; Comments start with a semicolon. +; Anythng after the semicolon is ignored. + +;;;;;;;;;;;;;;;;;;; +;;; Basic Types ;;; +;;;;;;;;;;;;;;;;;;; + +nil ; or aka null + +; Booleans +true +false + +; Strings are enclosed in double quotes +"hungarian breakfast" +"farmer's cheesy omelette" + +; Characters are preceeded by backslashes +\g \r \a \c \e + +; Keywords starts with a colon. They behave like enums. Kinda +; like symbols in ruby land. + +:eggs +:cheese +:olives + +; Symbols are used to represent identifiers. You can namespace symbols by +; using /. Whatever preceeds / is the namespace of the name. +#spoon +#kitchen/spoon ; not the same as #spoon +#kitchen/fork +#github/fork ; you can't eat with this + +; Integers and floats +42 +3.14159 + +; Lists are a sequence of values +(:bun :beef-patty 9 "yum!") + +; Vectors allow random access +[:gelato 1 2 -2] + +; Maps are associative data structures that associates the key with its value +{:eggs 2 + :lemon-juice 3.5 + :butter 1} + +; You're not restricted to using keywords as keys +{[1 2 3 4] "tell the people what she wore", + [5 6 7 8] "the more you see the more you hate"} + +; You may use commas for readability. They are treated as whitespaces. + +; Sets are collections that contain unique elements. +#{:a :b 88 "huat"} + +;;; Tagged Elements + +; EDN can be extended by tagging elements with # symbols. + +#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10} + +; Let me explain this with a clojure example. Suppose I want to transform that +; piece of edn into a MenuItem record. + +(defrecord MenuItem [name rating]) + +; To transform edn to clojure values, I will need to use the built in EDN +; reader, edn/read-string + +(edn/read-string "{:eggs 2 :butter 1 :flour 5}") +; -> {:eggs 2 :butter 1 :flour 5} + +; To transform tagged elements, define the reader function and pass a map +; that maps tags to reader functions to edn/read-string like so + +(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}} + "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}") +; -> #user.MenuItem{:name "eggs-benedict", :rating 10} + +``` + +# References + +- [EDN spec](https://github.com/edn-format/edn) +- [Implementations](https://github.com/edn-format/edn/wiki/Implementations) +- [Tagged Elements](http://www.compoundtheory.com/clojure-edn-walkthrough/) -- cgit v1.2.3 From 5789ae677260840f8239d0054b051b06ef32d98c Mon Sep 17 00:00:00 2001 From: Jason Yeo Date: Tue, 20 Oct 2015 22:35:07 +0800 Subject: Reword the intro, make section more obvious --- edn.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/edn.html.markdown b/edn.html.markdown index b8dc4e88..14bb25b4 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -7,13 +7,12 @@ contributors: Extensible Data Notation or EDN for short is a format for serializing data. -The notation is used internally by Clojure to represent programs and -it is used commonly by Clojure and Clojurescript programs to transfer -data. Though there are implementations of EDN for many other -languages. +The notation is used internally by Clojure to represent programs and it also +used as a data transfer format like JSON. Though it is more commonly used in +Clojure land, there are implementations of EDN for many other languages. -The main benefit of EDN is that it is extensible, which we will see -how it is extended later on. +The main benefit of EDN over JSON and YAML is that it is extensible, which we +will see how it is extended later on. ```Clojure ; Comments start with a semicolon. @@ -37,8 +36,7 @@ false \g \r \a \c \e ; Keywords starts with a colon. They behave like enums. Kinda -; like symbols in ruby land. - +; like symbols in ruby. :eggs :cheese :olives @@ -74,7 +72,9 @@ false ; Sets are collections that contain unique elements. #{:a :b 88 "huat"} -;;; Tagged Elements +;;;;;;;;;;;;;;;;;;;;;;; +;;; Tagged Elements ;;; +;;;;;;;;;;;;;;;;;;;;;;; ; EDN can be extended by tagging elements with # symbols. -- cgit v1.2.3 From e0c81d4cf3b92b1430ffbaa9876f02cdf7beafdc Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:36:05 -0300 Subject: Fixing typing error and quotes inside comments - Fixed some quotes inside comments; - Fixed an typing error for 'syntactic sugar' --- paren.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/paren.html.markdown b/paren.html.markdown index cde14853..f598f8de 100644 --- a/paren.html.markdown +++ b/paren.html.markdown @@ -77,7 +77,7 @@ some-var ; => 5 ;; Accessing a previously unassigned variable is an exception ; x ; => Unknown variable: x : nil -;; Local binding: Use lambda calculus! `a' and `b' are bound to `1' and `2' only within the (fn ...) +;; Local binding: Use lambda calculus! 'a' and 'b' are bound to '1' and '2' only within the (fn ...) ((fn (a b) (+ a b)) 1 2) ; => 3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -88,12 +88,12 @@ some-var ; => 5 ;; Lists are vector-like data structures. (Random access is O(1).) (cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) -;; `list' is a convenience variadic constructor for lists +;; 'list' is a convenience variadic constructor for lists (list 1 2 3) ; => (1 2 3) ;; and a quote can also be used for a literal list value (quote (+ 1 2)) ; => (+ 1 2) -;; Can still use `cons' to add an item to the beginning of a list +;; Can still use 'cons' to add an item to the beginning of a list (cons 0 (list 1 2 3)) ; => (0 1 2 3) ;; Lists are a very basic type, so there is a *lot* of functionality for @@ -106,7 +106,7 @@ some-var ; => 5 ;; 3. Functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Use `fn' to create functions. +;; Use 'fn' to create functions. ;; A function always returns the value of its last expression (fn () "Hello World") ; => (fn () Hello World) : fn @@ -117,7 +117,7 @@ some-var ; => 5 (set hello-world (fn () "Hello World")) (hello-world) ; => "Hello World" -;; You can shorten this using the function definition syntatcic sugae: +;; You can shorten this using the function definition syntactic sugar: (defn hello-world2 () "Hello World") ;; The () in the above is the list of arguments for the function @@ -134,7 +134,7 @@ some-var ; => 5 ;; 4. Equality ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; for numbers use `==' +;; for numbers use '==' (== 3 3.0) ; => true (== 2 1) ; => false @@ -166,7 +166,7 @@ some-var ; => 5 ;; 6. Mutation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Use `set' to assign a new value to a variable or a place +;; Use 'set' to assign a new value to a variable or a place (set n 5) ; => 5 (set n (inc n)) ; => 6 n ; => 6 -- cgit v1.2.3 From 36b2df9c8c9e98d25fead39fd1ea8bb0c8a86f15 Mon Sep 17 00:00:00 2001 From: Claudson Martins Date: Tue, 20 Oct 2015 11:40:45 -0300 Subject: Updating header with contribution name --- paren.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/paren.html.markdown b/paren.html.markdown index f598f8de..701cadfd 100644 --- a/paren.html.markdown +++ b/paren.html.markdown @@ -4,6 +4,7 @@ language: Paren filename: learnparen.paren contributors: - ["KIM Taegyoon", "https://github.com/kimtg"] + - ["Claudson Martins", "https://github.com/claudsonm"] --- [Paren](https://bitbucket.org/ktg/paren) is a dialect of Lisp. It is designed to be an embedded language. -- cgit v1.2.3 From e675c887fe27538805a2b8deddf3f3d37a653d7c Mon Sep 17 00:00:00 2001 From: Dean Becker Date: Tue, 20 Oct 2015 16:32:49 +0100 Subject: Expanded XML Doc example Just an expansion of the XML documentation example, the tag can be very useful in Visual Studio, especially. --- csharp.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index dfdd98de..c844c479 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -24,7 +24,9 @@ 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 /// -//public void MethodOrClassOrOtherWithParsableHelp() {} +/// This is some parameter documentation for firstParam +/// Information on the returned value of a function +//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 Libary -- cgit v1.2.3 From 7c15eaefcdfe21809ebab893f6d8d6321188abf1 Mon Sep 17 00:00:00 2001 From: Chaitya Shah Date: Tue, 20 Oct 2015 11:45:58 -0400 Subject: Fix Spacing Inconsistency Fix spacing inconsistency in PennyFarthing Constructor --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 38c9e490..a78aa9fc 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -519,7 +519,7 @@ class PennyFarthing extends Bicycle { // (Penny Farthings are those bicycles with the big front wheel. // They have no gears.) - public PennyFarthing(int startCadence, int startSpeed){ + public PennyFarthing(int startCadence, int startSpeed) { // Call the parent constructor with super super(startCadence, startSpeed, 0, "PennyFarthing"); } -- cgit v1.2.3 From 1d701fb90d0c34bab5eb61aec8a0fe8be0648bdd Mon Sep 17 00:00:00 2001 From: Cristian Achille Date: Tue, 20 Oct 2015 19:27:09 +0200 Subject: [ruby/it] initial commit --- it-it/ruby-ecosystem-it.html.markdown | 144 ++++++++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) create mode 100644 it-it/ruby-ecosystem-it.html.markdown diff --git a/it-it/ruby-ecosystem-it.html.markdown b/it-it/ruby-ecosystem-it.html.markdown new file mode 100644 index 00000000..92443be4 --- /dev/null +++ b/it-it/ruby-ecosystem-it.html.markdown @@ -0,0 +1,144 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Cristian Achille", "http://github.com/blackdev1l/"] +--- + +Generalmente chi usa ruby ha l'esigenza di avere differenti versioni di Ruby +installate, gestire le proprie gemme, e le loro dipendenze. + +## Manager Ruby + +Alcune piattaforme hanno Ruby pre-installato o disponibile come pacchetto. +Molti sviluppatori Ruby non usano questi pacchetti, o se lo fanno, li usano solo +per installare dei manager Ruby, i quali permettono di installare e gestire più +versioni di Ruby in base al progetto su cui si lavora. + +Di seguito i più famosi manager Ruby: + +* [RVM](https://rvm.io/) - Installa e permette di utilizzare diverse versioni di + Ruby. RVM Ha anche il concetto di gemsets i quali isolano completamente l'ambiente di sviluppo del progetto. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Installa solamente + multiple versioni di ruby. Usa questo se vuoi maggior controllo sull'installazione di Ruby. +* [rbenv](https://github.com/sstephenson/rbenv) - + Permette solo la scelta di quale versione Ruby utilizzare. Usato insieme a ruby-build. + Utilizza questo per un maggior controllo su quale versione di Ruby utilizzare. +* [chruby](https://github.com/postmodern/chruby) - + Permette solo la scelta di quale Ruby utilizzare, simile a rbenv. + +## Ruby Versions + +Ruby fù creato da Yukihiro "Matz" Matsumoto, il [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), +(acronimo inglese che sta per "Benevolo dittatore a vita") , seppur +ultimamente non è più del tutto vera; l'implementazione di Ruby +è detta MRI (Matz' Reference Implementation), e dunque quando si legge di una +versione Ruby, essa si riferisce sempre al rilascio di una MRI + +Le tre maggiori versioni di Ruby in uso sono: + +* 2.0.0 - Rilasciata nel febbraio 2013. La maggior parte delle librerie e + framework supportano la 2.0.0 +* 1.9.3 - Rilasciata nel ottobre 2011. QUesta è la versione che molti + svluppatori usano, il supporto è + [concluso](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Il supporto per Ruby 1.8.7 è + [concluso](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +I cambiamenti tra la 1.8.7 a la 1.9.x sono maggiori di quelli tra la 1.9.3 a la +2.0.0. Per esempio, nella 1.9 vengono introdotti gli encodings e la bytecode VM. +Esistono ancora dei progetti basati sulla 1.8.7, ma stanno diventando una +minoranza, man mano che la community si sta trasferendo alle versioni 1.92 e +1.9.3 + +## Ruby Implementations + +L'ecosistema Ruby gode di molte implementazioni differenti di Ruby, ognuna con +particolari punti di forza, da chiarire che ogni implementazione è scritta con +un linguaggio diverso, ma esse *sono tutte Ruby*. Ogni implementazione ha +feature extra ma tutte esse possono eseguire file ruby. Per esempio, JRuby è +scritto in Java, ma non devi conoscere java per usarlo. + +Implementazioni mature e compatibili: + +* [MRI](https://github.com/ruby/ruby) - Scritto in C, Questa è l'implementazione + standard di Ruby, per definizione è 100% compatibile (con se stessa). Tutte le + altre implemetazioni mantengono la compatibilità con MRI + (vedere [RubySpec](#rubyspec) sotto). +* [JRuby](http://jruby.org/) - Scritto in Java e Ruby, Questa implementazione è + molto veloce e robusta, la forza di JRuby consiste nell'interoperabilità + tra JVM/Java, permettendo l'utilizzo di struemnti Java già esistenti, progetti + e linguaggi +* [Rubinius](http://rubini.us/) - Scritto principalmente in Ruby con un + c++ bytecode VM, molto matura e veloce, permette alcune feature riguardo VM. + +Mediamente mature e compatibili: + +* [Maglev](http://maglev.github.io/) - Sviluppata sui Gemstone, è una Smalltalk +VM, Smalltalk è degli strumenti molto utili, e questo progetto cerca di portare +questi strumenti nello sviluppo Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Porta ruby nello sviluppo iOS. + +Poco mature e compatibili: + +* [Topaz](http://topazruby.com/) - Scritto in RPython (usando PyPy come + toolchain) Topaz è un progetto ancora giovane e non compatibile, ha le + possibilità di diventare una implementazione Ruby molto performante +* [IronRuby](http://ironruby.net/) - Scritto in C# e prendendo di mira la + piattaforma .NET, lo sviluppo sembra fermo da quando Microsoft ha rimosso il + suo supporto. + +Le implementazioni Ruby possono avere una propria versione, ma hanno sempre come +target una specifica versione di MRI. Molte implementazioni hanno l'abilità di +selezionare una versione specifica di MRI. + +##RubySpec + +La maggior parte delle implementazioni Ruby dipendono pesantemente su +[RubySpec](http://rubyspec.org/). Ruby non ha una specifica ufficiale, quindi la +community ha scritto una specifica eseguibile in Ruby per testare la compatibilità +con MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) è un package manager gestito dalla communtiy +per Ruby. Rubygems viene installato con Ruby, quindi non c'è bisogno di +scaricarlo separatamente. + +I pacchetti Ruby sono chiamate "gemme", e possono essere hostate dalla community +su RubyGems.org . Ogni gemma contiene il codice sorgente e del metadata, tra cui +la versione, le dipendenze, autor* e licenz*. + +## Bundler + +[Bundler](http://bundler.io/) è un risolvitore di dipendenze, Esso usa il Gemfile +di un progetto per cercare le dipendenze, dopo di che ottiene le dipendenze delle +dipendenze ricorsivamente, Questo procedimento viene eseguito finchè tutte le +dipendenze sono state risolte e scaricate, o si fermerà se un conflitto verrà +trovato. + +Bundler genererà un error se troverà dipendenze in conflitto, Per esempio, +se la gemma A richiede la versione 3 o maggiore della gemma Z, ma la gemma B +richiede la versione 2, Bundler ti notificherà del conflitto. Questo diventa +di aiuto nel momento in cui si hanno molte gemme nel progetto, il che porta a +un grande grafo di dipendenza da risolvere. + +# Testing + +Il testing è un pezzo fondamentale della cultura Ruby, Ruby viene installato con +il proprio testing framework chiamato minitest (O TestUnit per ruby 1.8.x). +Esistono molte librerie con obiettivi differenti + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Testing frameowrk rilasciato insieme a Ruby 1.8.x +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Testing frameowrk rilasciato insieme a Ruby 1.9/2.0 +* [RSpec](http://rspec.info/) - Un testing framework che si concentra nella chiarezza +* [Cucumber](http://cukes.info/) - Un BDD testing framework che estrapola testo formattato in Gherkin + +## Sii cordiale + +La community Ruby è orgogliosa di essere una communtiy aperta, accogliente e +variegata. Matz stesso è estremamente amichevole, e la generosità degli sviluppatori +Ruby è fantastica. -- cgit v1.2.3 From 02ad0d175b5cf059a5a71558b76bc42770250ca7 Mon Sep 17 00:00:00 2001 From: Cristian Achille Date: Tue, 20 Oct 2015 19:33:33 +0200 Subject: Huge typo --- it-it/ruby-ecosystem-it.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/it-it/ruby-ecosystem-it.html.markdown b/it-it/ruby-ecosystem-it.html.markdown index 92443be4..72ab579d 100644 --- a/it-it/ruby-ecosystem-it.html.markdown +++ b/it-it/ruby-ecosystem-it.html.markdown @@ -32,7 +32,7 @@ Di seguito i più famosi manager Ruby: ## Ruby Versions -Ruby fù creato da Yukihiro "Matz" Matsumoto, il [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), +Ruby fu creato da Yukihiro "Matz" Matsumoto, il [BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), (acronimo inglese che sta per "Benevolo dittatore a vita") , seppur ultimamente non è più del tutto vera; l'implementazione di Ruby è detta MRI (Matz' Reference Implementation), e dunque quando si legge di una @@ -49,9 +49,9 @@ Le tre maggiori versioni di Ruby in uso sono: [concluso](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). I cambiamenti tra la 1.8.7 a la 1.9.x sono maggiori di quelli tra la 1.9.3 a la -2.0.0. Per esempio, nella 1.9 vengono introdotti gli encodings e la bytecode VM. +2.0.0. Per esempio, nella 1.9 vengono introdotti encodings e bytecode VM. Esistono ancora dei progetti basati sulla 1.8.7, ma stanno diventando una -minoranza, man mano che la community si sta trasferendo alle versioni 1.92 e +minoranza man mano che la community si trasferisce alle versioni 1.92 e 1.9.3 ## Ruby Implementations -- cgit v1.2.3 From 8b9c5561e7af0c5caca83ac13d306d756d6f227f Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Mon, 19 Oct 2015 10:54:42 -0500 Subject: [javascript/en] Added setInterval Added the setInterval function provided by most browsers --- javascript.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index d408e885..22a2959c 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -310,6 +310,12 @@ setTimeout(myFunction, 5000); // Note: setTimeout isn't part of the JS language, but is provided by browsers // and Node.js. +// Another function provided by browsers is setInterval +function myFunction(){ + // this code will be called every 5 seconds +} +setInterval(myFunction(), 5000); + // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ -- cgit v1.2.3 From c0171566ba8c9061fb23fc1ab17b11d974cdbb98 Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Mon, 19 Oct 2015 12:42:23 -0500 Subject: removed () --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 22a2959c..81dc09a9 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -314,7 +314,7 @@ setTimeout(myFunction, 5000); function myFunction(){ // this code will be called every 5 seconds } -setInterval(myFunction(), 5000); +setInterval(myFunction, 5000); // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. -- cgit v1.2.3 From f6d070eeac64abce90550f309ab655846115b12e Mon Sep 17 00:00:00 2001 From: Sawyer Charles Date: Mon, 19 Oct 2015 16:00:22 -0500 Subject: Fixed bracket placement --- javascript.html.markdown | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 81dc09a9..a119be88 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -291,12 +291,9 @@ myFunction("foo"); // = "FOO" // Note that the value to be returned must start on the same line as the // `return` keyword, otherwise you'll always return `undefined` due to // automatic semicolon insertion. Watch out for this when using Allman style. -function myFunction() -{ +function myFunction(){ return // <- semicolon automatically inserted here - { - thisIsAn: 'object literal' - } + {thisIsAn: 'object literal'} } myFunction(); // = undefined -- cgit v1.2.3 From c1f573fb33e07fcb4e32b326c7e906b2576f2470 Mon Sep 17 00:00:00 2001 From: Gabriel SoHappy Date: Tue, 20 Oct 2015 23:02:18 +0800 Subject: fix broken link for java code conventions --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 38c9e490..94d266f6 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -709,7 +709,7 @@ The links provided here below are just to get an understanding of the topic, fee * [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) **Online Practice and Tutorials** -- cgit v1.2.3 From c625be3463fb5fdc593635b7f269e6fbea5cb105 Mon Sep 17 00:00:00 2001 From: Gabriel SoHappy Date: Wed, 21 Oct 2015 02:08:54 +0800 Subject: fix java code conventions in the chinese version --- zh-cn/java-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index 12afa59a..a8fd2a4c 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -405,4 +405,4 @@ class PennyFarthing extends Bicycle { * [泛型](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java代码规范](http://www.oracle.com/technetwork/java/codeconv-138413.html) +* [Java代码规范](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) -- cgit v1.2.3 From a76be91a2d45c7c4a834c2ad6d5164ac907c1038 Mon Sep 17 00:00:00 2001 From: Greg Yang Date: Tue, 20 Oct 2015 12:05:16 -0700 Subject: modify function composition example --- haskell.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 369b1b20..c6d97496 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -195,11 +195,11 @@ foo 5 -- 15 -- function composition -- the (.) function chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, --- multiplies the result of that by 5, and then returns the final value. -foo = (*5) . (+10) +-- multiplies the result of that by 4, and then returns the final value. +foo = (*4) . (+10) --- (5 + 10) * 5 = 75 -foo 5 -- 75 +-- (5 + 10) * 4 = 75 +foo 5 -- 60 -- fixing precedence -- Haskell has another operator called `$`. This operator applies a function -- cgit v1.2.3 From 18edced524b790fe3e6c9bb5f69507ca1bfb0553 Mon Sep 17 00:00:00 2001 From: Greg Yang Date: Tue, 20 Oct 2015 12:10:01 -0700 Subject: update the comment in as well --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index c6d97496..e3b29937 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -198,7 +198,7 @@ foo 5 -- 15 -- multiplies the result of that by 4, and then returns the final value. foo = (*4) . (+10) --- (5 + 10) * 4 = 75 +-- (5 + 10) * 4 = 40 foo 5 -- 60 -- fixing precedence -- cgit v1.2.3 From f0bbebe789e310ecd76fcfdfa334291928591fb7 Mon Sep 17 00:00:00 2001 From: Greg Yang Date: Tue, 20 Oct 2015 12:10:50 -0700 Subject: really update the comment --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index e3b29937..08611e63 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -198,7 +198,7 @@ foo 5 -- 15 -- multiplies the result of that by 4, and then returns the final value. foo = (*4) . (+10) --- (5 + 10) * 4 = 40 +-- (5 + 10) * 4 = 60 foo 5 -- 60 -- fixing precedence -- cgit v1.2.3 From 11aab085d656b79482e92a05acbbac81125bfb78 Mon Sep 17 00:00:00 2001 From: Kristin Linn Date: Tue, 20 Oct 2015 16:22:40 -0400 Subject: add statistical analysis section with general linear models --- r.html.markdown | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 101 insertions(+), 4 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index d3d725d3..3d0b9b9e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -3,6 +3,7 @@ language: R contributors: - ["e99n09", "http://github.com/e99n09"] - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["kalinn", "http://github.com/kalinn"] filename: learnr.r --- @@ -196,6 +197,14 @@ class(NaN) # "numeric" # You can do arithmetic on two vectors with length greater than 1, # so long as the larger vector's length is an integer multiple of the smaller c(1,2,3) + c(1,2,3) # 2 4 6 +# Since a single number is a vector of length one, scalars are applied +# elementwise to vectors +(4 * c(1,2,3) - 2) / 2 # 1 3 5 +# Except for scalars, use caution when performing arithmetic on vectors with +# different lengths. Although it can be done, +c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 +# Matching lengths is better practice and easier to read +c(1,2,3,1,2,3) * c(1,2,1,2,1,2) # CHARACTERS # There's no difference between strings and characters in R @@ -234,6 +243,9 @@ class(NA) # "logical" TRUE | FALSE # TRUE # AND TRUE & FALSE # FALSE +# Applying | and & to vectors returns elementwise logic operations +c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE +c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE # You can test if x is TRUE isTRUE(TRUE) # TRUE # Here we get a logical vector with many elements: @@ -663,6 +675,95 @@ write.csv(pets, "pets2.csv") # to make a new .csv file +######################### +# Statistical Analysis +######################### + +# Linear regression! +linearModel <- lm(price ~ time, data = list1) +linearModel # outputs result of regression +# => +# Call: +# lm(formula = price ~ time, data = list1) +# +# Coefficients: +# (Intercept) time +# 0.1453 0.4943 +summary(linearModel) # more verbose output from the regression +# => +# Call: +# lm(formula = price ~ time, data = list1) +# +# Residuals: +# Min 1Q Median 3Q Max +# -8.3134 -3.0131 -0.3606 2.8016 10.3992 +# +# Coefficients: +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.14527 1.50084 0.097 0.923 +# time 0.49435 0.06379 7.749 2.44e-09 *** +# --- +# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 +# +# Residual standard error: 4.657 on 38 degrees of freedom +# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 +# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09 +coef(linearModel) # extract estimated parameters +# => +# (Intercept) time +# 0.1452662 0.4943490 +summary(linearModel)$coefficients # another way to extract results +# => +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 +# time 0.4943490 0.06379348 7.74920901 2.440008e-09 +summary(linearModel)$coefficients[,4] # the p-values +# => +# (Intercept) time +# 9.234021e-01 2.440008e-09 + +# GENERAL LINEAR MODELS +# Logistic regression +set.seed(1) +list1$success = rbinom(length(list1$time), 1, .5) # random binary +glModel <- glm(success ~ time, data = list1, + family=binomial(link="logit")) +glModel # outputs result of logistic regression +# => +# Call: glm(formula = success ~ time, +# family = binomial(link = "logit"), data = list1) +# +# Coefficients: +# (Intercept) time +# 0.17018 -0.01321 +# +# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual +# Null Deviance: 55.35 +# Residual Deviance: 55.12 AIC: 59.12 +summary(glModel) # more verbose output from the regression +# => +# Call: +# glm(formula = success ~ time, +# family = binomial(link = "logit"), data = list1) + +# Deviance Residuals: +# Min 1Q Median 3Q Max +# -1.245 -1.118 -1.035 1.202 1.327 +# +# Coefficients: +# Estimate Std. Error z value Pr(>|z|) +# (Intercept) 0.17018 0.64621 0.263 0.792 +# time -0.01321 0.02757 -0.479 0.632 +# +# (Dispersion parameter for binomial family taken to be 1) +# +# Null deviance: 55.352 on 39 degrees of freedom +# Residual deviance: 55.121 on 38 degrees of freedom +# AIC: 59.121 +# +# Number of Fisher Scoring iterations: 3 + + ######################### # Plots ######################### @@ -670,9 +771,6 @@ write.csv(pets, "pets2.csv") # to make a new .csv file # BUILT-IN PLOTTING FUNCTIONS # Scatterplots! plot(list1$time, list1$price, main = "fake data") -# Regressions! -linearModel <- lm(price ~ time, data = list1) -linearModel # outputs result of regression # Plot regression line on existing plot abline(linearModel, col = "red") # Get a variety of nice diagnostics @@ -696,7 +794,6 @@ pp + geom_point() # ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) - ``` ## How do I get R? -- cgit v1.2.3 From 622e03a141f586e858209fe98c649aa2a4bb9183 Mon Sep 17 00:00:00 2001 From: Kristin Linn Date: Tue, 20 Oct 2015 16:57:36 -0400 Subject: add statistical analysis section with general linear models --- r.html.markdown | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index 61fc7a01..3d0b9b9e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -16,8 +16,7 @@ R is a statistical computing language. It has lots of libraries for uploading an # You can't make multi-line comments, # but you can stack multiple comments like so. -# in Windows you can use CTRL-ENTER to execute a line. -# on Mac it is COMMAND-ENTER +# in Windows or Mac, hit COMMAND-ENTER to execute a line @@ -38,8 +37,8 @@ head(rivers) # peek at the data set length(rivers) # how many rivers were measured? # 141 summary(rivers) # what are some summary statistics? -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 # make a stem-and-leaf plot (a histogram-like data visualization) stem(rivers) @@ -56,14 +55,14 @@ stem(rivers) # 14 | 56 # 16 | 7 # 18 | 9 -# 20 | +# 20 | # 22 | 25 # 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | # 36 | 1 stem(log(rivers)) # Notice that the data are neither normal nor log-normal! @@ -72,7 +71,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # The decimal point is 1 digit(s) to the left of the | # # 48 | 1 -# 50 | +# 50 | # 52 | 15578 # 54 | 44571222466689 # 56 | 023334677000124455789 @@ -87,7 +86,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # 74 | 84 # 76 | 56 # 78 | 4 -# 80 | +# 80 | # 82 | 2 # make a histogram: @@ -110,7 +109,7 @@ sort(discoveries) # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 stem(discoveries, scale=2) -# +# # The decimal point is at the | # # 0 | 000000000 @@ -124,14 +123,14 @@ stem(discoveries, scale=2) # 8 | 0 # 9 | 0 # 10 | 0 -# 11 | +# 11 | # 12 | 0 max(discoveries) # 12 summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 # Roll a die a few times round(runif(7, min=.5, max=6.5)) @@ -275,7 +274,7 @@ class(NULL) # NULL parakeet = c("beak", "feathers", "wings", "eyes") parakeet # => -# [1] "beak" "feathers" "wings" "eyes" +# [1] "beak" "feathers" "wings" "eyes" parakeet <- NULL parakeet # => @@ -292,7 +291,7 @@ as.numeric("Bilbo") # => # [1] NA # Warning message: -# NAs introduced by coercion +# NAs introduced by coercion # Also note: those were just the basic data types # There are many more data types, such as for dates, time series, etc. @@ -432,10 +431,10 @@ mat %*% t(mat) mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix # Again, note what happened! -- cgit v1.2.3 From 81c1b8334cdccd054d4131fc0309eeebebef53f9 Mon Sep 17 00:00:00 2001 From: Kristin Linn Date: Tue, 20 Oct 2015 17:06:41 -0400 Subject: fix spaces at end-of-lines --- r.html.markdown | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index 3d0b9b9e..ce313ecc 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -16,9 +16,8 @@ R is a statistical computing language. It has lots of libraries for uploading an # You can't make multi-line comments, # but you can stack multiple comments like so. -# in Windows or Mac, hit COMMAND-ENTER to execute a line - - +# in Windows you can use CTRL-ENTER to execute a line. +# on Mac it is COMMAND-ENTER ############################################################################# # Stuff you can do without understanding anything about programming @@ -37,8 +36,8 @@ head(rivers) # peek at the data set length(rivers) # how many rivers were measured? # 141 summary(rivers) # what are some summary statistics? -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 # make a stem-and-leaf plot (a histogram-like data visualization) stem(rivers) @@ -55,14 +54,14 @@ stem(rivers) # 14 | 56 # 16 | 7 # 18 | 9 -# 20 | +# 20 | # 22 | 25 # 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | # 36 | 1 stem(log(rivers)) # Notice that the data are neither normal nor log-normal! @@ -71,7 +70,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # The decimal point is 1 digit(s) to the left of the | # # 48 | 1 -# 50 | +# 50 | # 52 | 15578 # 54 | 44571222466689 # 56 | 023334677000124455789 @@ -86,7 +85,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # 74 | 84 # 76 | 56 # 78 | 4 -# 80 | +# 80 | # 82 | 2 # make a histogram: @@ -109,7 +108,7 @@ sort(discoveries) # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 stem(discoveries, scale=2) -# +# # The decimal point is at the | # # 0 | 000000000 @@ -130,7 +129,7 @@ max(discoveries) # 12 summary(discoveries) # Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 +# 0.0 2.0 3.0 3.1 4.0 12.0 # Roll a die a few times round(runif(7, min=.5, max=6.5)) @@ -274,7 +273,7 @@ class(NULL) # NULL parakeet = c("beak", "feathers", "wings", "eyes") parakeet # => -# [1] "beak" "feathers" "wings" "eyes" +# [1] "beak" "feathers" "wings" "eyes" parakeet <- NULL parakeet # => @@ -291,7 +290,7 @@ as.numeric("Bilbo") # => # [1] NA # Warning message: -# NAs introduced by coercion +# NAs introduced by coercion # Also note: those were just the basic data types # There are many more data types, such as for dates, time series, etc. @@ -431,10 +430,10 @@ mat %*% t(mat) mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix # Again, note what happened! -- cgit v1.2.3 From 7ad97c290436d9f01ba9b5dd2a557869995efa0c Mon Sep 17 00:00:00 2001 From: Kristin Linn Date: Tue, 20 Oct 2015 17:10:58 -0400 Subject: fix spaces at end-of-lines again --- r.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/r.html.markdown b/r.html.markdown index ce313ecc..8539b10e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -19,6 +19,8 @@ R is a statistical computing language. It has lots of libraries for uploading an # in Windows you can use CTRL-ENTER to execute a line. # on Mac it is COMMAND-ENTER + + ############################################################################# # Stuff you can do without understanding anything about programming ############################################################################# @@ -122,13 +124,13 @@ stem(discoveries, scale=2) # 8 | 0 # 9 | 0 # 10 | 0 -# 11 | +# 11 | # 12 | 0 max(discoveries) # 12 summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. +# Min. 1st Qu. Median Mean 3rd Qu. Max. # 0.0 2.0 3.0 3.1 4.0 12.0 # Roll a die a few times @@ -793,6 +795,7 @@ pp + geom_point() # ggplot2 has excellent documentation (available http://docs.ggplot2.org/current/) + ``` ## How do I get R? -- cgit v1.2.3 From 401093269d1a5b0db14c54f2e355ff3461b43325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Tue, 20 Oct 2015 23:53:25 -0200 Subject: Pogoscript to pt-br Partial translation to pt-br --- pt-br/pogo.html.markdown | 202 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 202 insertions(+) create mode 100644 pt-br/pogo.html.markdown diff --git a/pt-br/pogo.html.markdown b/pt-br/pogo.html.markdown new file mode 100644 index 00000000..80972c98 --- /dev/null +++ b/pt-br/pogo.html.markdown @@ -0,0 +1,202 @@ +--- +language: pogoscript +contributors: + - ["Tim Macfarlane", "http://github.com/refractalize"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] +filename: learnPogo.pogo +--- + +Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents +e que compila para linguagem Javascript padrão. + +``` javascript +// definindo uma variável +water temperature = 24 + +// reatribuindo o valor de uma variável após a sua definição +water temperature := 26 + +// funções permitem que seus parâmetros sejam colocados em qualquer lugar +temperature at (a) altitude = 32 - a / 100 + +// funções longas são apenas indentadas +temperature at (a) altitude := + if (a < 0) + water temperature + else + 32 - a / 100 + +// chamada de uma função +current temperature = temperature at 3200 altitude + +// essa função cria um novo objeto com métodos +position (x, y) = { + x = x + y = y + + distance from position (p) = + dx = self.x - p.x + dy = self.y - p.y + Math.sqrt (dx * dx + dy * dy) +} + +// `self` é similiar ao `this` no Javascript, com exceção de que `self` não +// é redefinido em cada nova função + +// chamada de métodos +position (7, 2).distance from position (position (5, 1)) + +// assim como no Javascript, objetos também são hashes +position.'x' == position.x == position.('x') + +// arrays +positions = [ + position (1, 1) + position (1, 2) + position (1, 3) +] + +// indexando um array +positions.0.y + +n = 2 +positions.(n).y + +// strings +poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. + Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. + Put on my shirt and took it off in the sun walking the path to lunch. + A dandelion seed floats above the marsh grass with the mosquitos. + At 4 A.M. the two middleaged men sleeping together holding hands. + In the half-light of dawn a few birds warble under the Pleiades. + Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep + cheep cheep.' + +// texto de Allen Ginsburg + +// interpolação +outlook = 'amazing!' +console.log "the weather tomorrow is going to be #(outlook)" + +// expressões regulares +r/(\d+)m/i +r/(\d+) degrees/mg + +// operadores +true @and true +false @or true +@not false +2 < 4 +2 >= 2 +2 > 1 + +// todos do Javascript também são suportados + +// definindo seu próprio operador +(p1) plus (p2) = + position (p1.x + p2.x, p1.y + p2.y) + +// `plus` pode ser usado com um operador +position (1, 1) @plus position (0, 2) +// ou como uma função +(position (1, 1)) plus (position (0, 2)) + +// retorno explícito +(x) times (y) = return (x * y) + +// new +now = @new Date () + +// funções podem receber argumentos opcionais +spark (position, color: 'black', velocity: {x = 0, y = 0}) = { + color = color + position = position + velocity = velocity +} + +red = spark (position 1 1, color: 'red') +fast black = spark (position 1 1, velocity: {x = 10, y = 0}) + +// functions can unsplat arguments too +log (messages, ...) = + console.log (messages, ...) + +// blocks are functions passed to other functions. +// This block takes two parameters, `spark` and `c`, +// the body of the block is the indented code after the +// function call + +render each @(spark) into canvas context @(c) + ctx.begin path () + ctx.stroke style = spark.color + ctx.arc ( + spark.position.x + canvas.width / 2 + spark.position.y + 3 + 0 + Math.PI * 2 + ) + ctx.stroke () + +// asynchronous calls + +// JavaScript both in the browser and on the server (with Node.js) +// makes heavy use of asynchronous IO with callbacks. Async IO is +// amazing for performance and making concurrency simple but it +// quickly gets complicated. +// Pogoscript has a few things to make async IO much much easier + +// Node.js includes the `fs` module for accessing the file system. +// Let's list the contents of a directory + +fs = require 'fs' +directory listing = fs.readdir! '.' + +// `fs.readdir()` is an asynchronous function, so we can call it +// using the `!` operator. The `!` operator allows you to call +// async functions with the same syntax and largely the same +// semantics as normal synchronous functions. Pogoscript rewrites +// it so that all subsequent code is placed in the callback function +// to `fs.readdir()`. + +// to catch asynchronous errors while calling asynchronous functions + +try + another directory listing = fs.readdir! 'a-missing-dir' +catch (ex) + console.log (ex) + +// in fact, if you don't use `try catch`, it will raise the error up the +// stack to the outer-most `try catch` or to the event loop, as you'd expect +// with non-async exceptions + +// all the other control structures work with asynchronous calls too +// here's `if else` +config = + if (fs.stat! 'config.json'.is file ()) + JSON.parse (fs.read file! 'config.json' 'utf-8') + else + { + color: 'red' + } + +// to run two asynchronous calls concurrently, use the `?` operator. +// The `?` operator returns a *future* which can be executed to +// wait for and obtain the result, again using the `!` operator + +// we don't wait for either of these calls to finish +a = fs.stat? 'a.txt' +b = fs.stat? 'b.txt' + +// now we wait for the calls to finish and print the results +console.log "size of a.txt is #(a!.size)" +console.log "size of b.txt is #(b!.size)" + +// futures in Pogoscript are analogous to Promises +``` + +That's it. + +Download [Node.js](http://nodejs.org/) and `npm install pogo`. + +There is plenty of documentation on [http://pogoscript.org/](http://pogoscript.org/), including a [cheat sheet](http://pogoscript.org/cheatsheet.html), a [guide](http://pogoscript.org/guide/), and how [Pogoscript translates to Javascript](http://featurist.github.io/pogo-examples/). Get in touch on the [google group](http://groups.google.com/group/pogoscript) if you have questions! -- cgit v1.2.3 From 0d5701f465d4304cf278d6d3aac3f8fd032fee7e Mon Sep 17 00:00:00 2001 From: hack1m Date: Wed, 21 Oct 2015 14:30:08 +0800 Subject: Fix some word and char --- ms-my/bash-my.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ms-my/bash-my.html.markdown b/ms-my/bash-my.html.markdown index 3632911d..d430fd06 100644 --- a/ms-my/bash-my.html.markdown +++ b/ms-my/bash-my.html.markdown @@ -38,12 +38,12 @@ Variable="Some string" # Tetapi bukan seperti ini: Variable = "Some string" -# Bash akan memutuskan yang pembolehubah adalah arahan ia mesti dilaksanakan dan memberi ralat +# Bash akan memutuskan yang pembolehubah adalah arahan ia mesti laksanakan dan memberi ralat # kerana ia tidak boleh dijumpai. # Atau seperti ini: Variable= 'Some string' -# Bash akan memutuskan yang ‘Beberapa rentetan’ adalah arahan ia mesti dilaksanakan dan memberi +# Bash akan memutuskan yang ‘Beberapa rentetan’ adalah arahan ia mesti laksanakan dan memberi # ralat kerana ia tidak dijumpai. (Dalam kes ini ‘Variable=' sebahagian dilihat # sebagai penetapan pembolehubah sah hanya untuk skop ‘Beberapa rentetan’ # arahan.) @@ -123,7 +123,7 @@ ls -l # Senarai setiap fail dan direktori pada baris yang berbeza # fail .txt di dalam direktori semasa: ls -l | grep "\.txt" -# Anda boleh mengubah hala arahan input dan output (stdin, stdout, and stderr). +# Anda boleh mengubah hala arahan input dan output (stdin, stdout, dan stderr). # Baca dari stdin sampai ^EOF$ dan menulis ganti hello.py dengan baris # antara “EOF": cat > hello.py << EOF @@ -136,14 +136,14 @@ for line in sys.stdin: print(line, file=sys.stdout) EOF -# Jalankan hello.py dengan pelbagai penghantaran semula stdin, stdout, and stderr: +# Jalankan hello.py dengan pelbagai penghantaran semula stdin, stdout, dan stderr: python hello.py < "input.in" python hello.py > "output.out" python hello.py 2> "error.err" python hello.py > "output-and-error.log" 2>&1 python hello.py > /dev/null 2>&1 # Output ralat akan menulis ganti fail jika ia wujud, -# jika anda ingin menambah sebaliknta, guna ‘>>”: +# jika anda ingin menambah sebaliknya, guna ‘>>”: python hello.py >> "output.out" 2>> "error.err" # Menulis ganti output.out, menambah ke error.err, dan mengira baris: @@ -253,7 +253,7 @@ grep "^foo.*bar$" file.txt # beri opsyen “-c” untuk sebaliknya mencetak jumlah baris sepadan regex grep -c "^foo.*bar$" file.txt # jika anda secara literal mahu untuk mencari rentetan, -# dan bukannya regexm guna fgrep (atau grep -F) +# dan bukannya regex, guna fgrep (atau grep -F) fgrep "^foo.*bar$" file.txt -- cgit v1.2.3 From 976d3c1aec5d029e7b5da612b3f9b21325083f67 Mon Sep 17 00:00:00 2001 From: hack1m Date: Wed, 21 Oct 2015 14:39:41 +0800 Subject: [XML/ms-my] Added Malay (Malaysia) translation for XML --- ms-my/xml-my.html.markdown | 130 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 ms-my/xml-my.html.markdown diff --git a/ms-my/xml-my.html.markdown b/ms-my/xml-my.html.markdown new file mode 100644 index 00000000..68de35c9 --- /dev/null +++ b/ms-my/xml-my.html.markdown @@ -0,0 +1,130 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +XML adalah bahasa markup direka untuk menyimpan dan mengangkutan data. + +Tidak seperti HTML, XML tidak menyatakan bagaimana paparan atau mengformat data, hanya membawanya. + +* Sintaks XML + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + +computer.gif + + +``` + +* Dokumen Format sempurna x Pengesahan + +Satu dokumen XML adalah format sempurna jika ia adalah sintaksis yang betul. +Walau bagaimanapun, ia mungkin menyuntik lebih banyak kekangan dalam dokumen itu, +menggunakan definasi dokumen, seperti DTD dan Skema XML. + +Satu dokumen XML yang mana mengikut definasi dokumen dipanggil sah, +mengenai dokumen itu. + +Dengan alat ini, anda boleh menyemak data XML di luar logik aplikasi. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` -- cgit v1.2.3 From 5838e931b715e663482b335b5a20055ce2dcc0b9 Mon Sep 17 00:00:00 2001 From: Gautam Kotian Date: Wed, 21 Oct 2015 11:36:04 +0200 Subject: Improve code comments --- d.html.markdown | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 80c1dc65..4a362372 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -218,7 +218,7 @@ void main() { // from 1 to 100. Easy! // Just pass lambda expressions as template parameters! - // You can pass any old function you like, but lambdas are convenient here. + // You can pass any function you like, but lambdas are convenient here. auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) .reduce!((a, b) => a + b); @@ -228,7 +228,7 @@ void main() { ``` Notice how we got to build a nice Haskellian pipeline to compute num? -That's thanks to a D innovation know as Uniform Function Call Syntax. +That's thanks to a D innovation know as Uniform Function Call Syntax (UFCS). With UFCS, we can choose whether to write a function call as a method or free function call! Walter wrote a nice article on this [here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) @@ -238,21 +238,23 @@ is of some type A on any expression of type A as a method. I like parallelism. Anyone else like parallelism? Sure you do. Let's do some! ```c +// Let's say we want to populate a large array with the square root of all +// consecutive integers starting from 1 (up until the size of the array), and we +// want to do this concurrently taking advantage of as many cores as we have +// available. + import std.stdio; import std.parallelism : parallel; import std.math : sqrt; void main() { - // We want take the square root every number in our array, - // and take advantage of as many cores as we have available. + // Create your large array auto arr = new double[1_000_000]; - // Use an index, and an array element by referece, - // and just call parallel on the array! + // Use an index, access every array element by reference (because we're + // going to change each element) and just call parallel on the array! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); } } - - ``` -- cgit v1.2.3 From 707551a1436daa163c60c8bf7496d17c2a030f32 Mon Sep 17 00:00:00 2001 From: Per Lilja Date: Wed, 21 Oct 2015 13:29:59 +0200 Subject: Added text about static code block. --- java.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 38c9e490..aae64ccf 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -450,6 +450,17 @@ class Bicycle { protected int gear; // Protected: Accessible from the class and subclasses String name; // default: Only accessible from within this package + static String className; // Static class variable + + // Static block + // Java has no implementation of static constructors, but + // has a static block that can be used to initialize class variables + // (static variables). + // This block will be called when the class is loaded. + static { + className = "Bicycle"; + } + // Constructors are a way of creating classes // This is a constructor public Bicycle() { -- cgit v1.2.3 From ef9331fa31ab84e5a04ee024ac490b24a6b5c4dc Mon Sep 17 00:00:00 2001 From: Raphael Nascimento Date: Wed, 21 Oct 2015 09:03:12 -0300 Subject: [java/en] Enum Type --- java.html.markdown | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 8544ecfc..86b0578e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Simon Morgan", "http://sjm.io/"] - ["Zachary Ferguson", "http://github.com/zfergus2"] - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - - ["Raphael Nascimento", "http://github.com/raphaelbn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] filename: LearnJava.java --- @@ -138,7 +138,7 @@ public class LearnJava { // // BigDecimal allows the programmer complete control over decimal // rounding. It is recommended to use BigDecimal with currency values - // and where exact decimal percision is required. + // and where exact decimal precision is required. // // BigDecimal can be initialized with an int, long, double or String // or by initializing the unscaled value (BigInteger) and scale (int). @@ -185,8 +185,12 @@ public class LearnJava { // LinkedLists - Implementation of doubly-linked list. All of the // operations perform as could be expected for a // doubly-linked list. - // Maps - A set of objects that maps keys to values. A map cannot - // contain duplicate keys; each key can map to at most one value. + // Maps - A set of objects that map keys to values. Map is + // an interface and therefore cannot be instantiated. + // The type of keys and values contained in a Map must + // be specified upon instantiation of the implementing + // class. Each key may map to only one corresponding value, + // and each key may appear only once (no duplicates). // HashMaps - This class uses a hashtable to implement the Map // interface. This allows the execution time of basic // operations, such as get and insert element, to remain @@ -251,7 +255,7 @@ public class LearnJava { // If statements are c-like int j = 10; - if (j == 10){ + if (j == 10) { System.out.println("I get printed"); } else if (j > 10) { System.out.println("I don't"); @@ -286,7 +290,18 @@ public class LearnJava { // Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - + + // Nested For Loop Exit with Label + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // breaks out of outer loop instead of only the inner one + } + } + } + // For Each Loop // The for loop is also able to iterate over arrays as well as objects // that implement the Iterable interface. @@ -321,7 +336,7 @@ public class LearnJava { // Starting in Java 7 and above, switching Strings works like this: String myAnswer = "maybe"; - switch(myAnswer){ + switch(myAnswer) { case "yes": System.out.println("You answered yes."); break; -- cgit v1.2.3 From b89c4a82c81ce8b26c14cb5fee8fc97eeb4e9ec1 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 21 Oct 2015 20:36:50 +0800 Subject: Update xml-id.html.markdown --- id-id/xml-id.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown index c1e985aa..8b8d72ae 100644 --- a/id-id/xml-id.html.markdown +++ b/id-id/xml-id.html.markdown @@ -1,6 +1,6 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-id.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: -- cgit v1.2.3 From d226542f37988edd237544142911c67ecdc6b391 Mon Sep 17 00:00:00 2001 From: payet-s Date: Wed, 21 Oct 2015 17:36:46 +0200 Subject: [python/fr] Fix python3 link --- fr-fr/python-fr.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 3f6dcabb..d78291be 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -14,8 +14,7 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] -NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x -Vous pourrez bientôt trouver un article pour Python 3 en Français. Pour le moment vous pouvez jettez un coup d'oeil à l'article [Python 3 en Anglais](http://learnxinyminutes.com/docs/python3/). +N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/). ```python # Une ligne simple de commentaire commence par un dièse -- cgit v1.2.3 From ecbd4540681a99cb83a201f3f09deaf2af3fb58f Mon Sep 17 00:00:00 2001 From: Peter Elmers Date: Wed, 21 Oct 2015 11:48:12 -0500 Subject: Fix a few spots where inconsistently tabs and spaces are used for alignment. --- java.html.markdown | 6 +++--- matlab.html.markdown | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index aae64ccf..efc4407b 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -186,9 +186,9 @@ public class LearnJava { // operations perform as could be expected for a // doubly-linked list. // Maps - A set of objects that map keys to values. Map is - // an interface and therefore cannot be instantiated. - // The type of keys and values contained in a Map must - // be specified upon instantiation of the implementing + // an interface and therefore cannot be instantiated. + // The type of keys and values contained in a Map must + // be specified upon instantiation of the implementing // class. Each key may map to only one corresponding value, // and each key may appear only once (no duplicates). // HashMaps - This class uses a hashtable to implement the Map diff --git a/matlab.html.markdown b/matlab.html.markdown index 4d97834c..ad42d9a9 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -262,7 +262,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure % Create new figure object, with handle h +h = figure % Create new figure object, with handle h figure(h) % Makes the figure corresponding to handle h the current figure close(h) % close figure with handle h close all % close all open figure windows @@ -460,7 +460,7 @@ length % length of a vector sort % sort in ascending order sum % sum of elements prod % product of elements -mode % modal value +mode % modal value median % median value mean % mean value std % standard deviation -- cgit v1.2.3 From 24ff15fe7a327232a0c33600ea70f8bc5c566eb3 Mon Sep 17 00:00:00 2001 From: aceawan Date: Wed, 21 Oct 2015 19:08:03 +0200 Subject: correct indentation --- fr-fr/d.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index 96158683..9eacc2aa 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -88,8 +88,8 @@ struct LinkedList(T) { class BinTree(T) { T data = null; - // Si il n'y a qu'un seul paramètre de template, - // on peut s'abstenir de mettre des parenthèses. + // Si il n'y a qu'un seul paramètre de template, + // on peut s'abstenir de mettre des parenthèses. BinTree!T left; BinTree!T right; } -- cgit v1.2.3 From a15486c2a843c7b1c76f0343da9436bf39d2e227 Mon Sep 17 00:00:00 2001 From: aceawan Date: Wed, 21 Oct 2015 19:08:52 +0200 Subject: correct indentation --- fr-fr/d.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index 9eacc2aa..d9bd9b48 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -248,13 +248,13 @@ import std.parallelism : parallel; import std.math : sqrt; void main() { - // On veut calculer la racine carré de tous les nombres - // dans notre tableau, et profiter de tous les coeurs - // à notre disposition. + // On veut calculer la racine carré de tous les nombres + // dans notre tableau, et profiter de tous les coeurs + // à notre disposition. auto arr = new double[1_000_000]; - // On utilise un index et une référence à chaque élément du tableau. - // On appelle juste la fonction parallel sur notre tableau ! + // On utilise un index et une référence à chaque élément du tableau. + // On appelle juste la fonction parallel sur notre tableau ! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); } -- cgit v1.2.3 From 78693f418632a805ee7d0857a9c771615d971d88 Mon Sep 17 00:00:00 2001 From: Gabriel SoHappy Date: Thu, 22 Oct 2015 02:13:01 +0800 Subject: Initial docs for messagepack using JAVA, RUBY and NODEJS --- messagepack.html.markdown | 171 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 messagepack.html.markdown diff --git a/messagepack.html.markdown b/messagepack.html.markdown new file mode 100644 index 00000000..0ee90742 --- /dev/null +++ b/messagepack.html.markdown @@ -0,0 +1,171 @@ +--- +language: messagepack +filename: learnmessagepack.mpac +contributors: + - ["Gabriel Chuan", "https://github.com/gczh"] +--- + +MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. The benefits over other formats is that it's faster and smaller. + +In MessagePack, small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves. This makes MessagePack useful for efficient transmission over wire. + +``` + +# 0. Understanding The Structure ==== + +JSON, 40 Bytes UTF-8 + +---------------------------------------------- +| {“name“:”John Doe“,”age“:12} | +---------------------------------------------- +| {" | 7B 22 | +| name | 6E 61 6D 65 | +| ":" | 22 3A 22 | +| John Doe | 4A 6F 68 6E 20 44 6F 65 | +| "," | 22 2C 22 | +| age | 61 67 65 | +| ": | 22 3A 20 | +| 12 | 31 32 | +| } | 7D | +---------------------------------------------- + + +MessagePack, 27 Bytes UTF-8 + +---------------------------------------------- +| ‚¤name¨John Doe£age.12 | +---------------------------------------------- +| ‚¤ | 82 84 | +| name | 6E 61 6D 65 | +| ¨ | A8 | +| John Doe | 4A 6F 68 6E 20 44 6F 65 | +| £ | A3 | +| age | 61 67 65 | +| . | 0C | +| 12 | 31 32 | +---------------------------------------------- + +# 1. JAVA ==== + +""" Installing with Maven +""" + + + ... + + org.msgpack + msgpack + ${msgpack.version} + + ... + + + +""" Simple Serialization/Deserialization +""" + +// Create serialize objects. +List src = new ArrayList(); +src.add("msgpack"); +src.add("kumofs"); + +MessagePack msgpack = new MessagePack(); +// Serialize +byte[] raw = msgpack.write(src); + +// Deserialize directly using a template +List dst1 = msgpack.read(raw, Templates.tList(Templates.TString)); +System.out.println(dst1.get(0)); +System.out.println(dst1.get(1)); + +// Or, Deserialze to Value then convert type. +Value dynamic = msgpack.read(raw); +List dst2 = new Converter(dynamic) + .read(Templates.tList(Templates.TString)); +System.out.println(dst2.get(0)); +System.out.println(dst2.get(1)); + + +# 2. RUBY ==== + +""" Installing the Gem +""" + +gem install msgpack + +""" Streaming API +""" + +# serialize a 2-element array [e1, e2] +pk = MessagePack::Packer.new(io) +pk.write_array_header(2).write(e1).write(e2).flush + +# deserialize objects from an IO +u = MessagePack::Unpacker.new(io) +u.each { |obj| ... } + +# event-driven deserialization +def on_read(data) + @u ||= MessagePack::Unpacker.new + @u.feed_each(data) { |obj| ... } +end + +# 3. NODE.JS ==== + +""" Installing with NPM +""" + +npm install msgpack5 --save + +""" Using in Node +""" + +var msgpack = require('msgpack5')() // namespace our extensions + , a = new MyType(2, 'a') + , encode = msgpack.encode + , decode = msgpack.decode + +msgpack.register(0x42, MyType, mytipeEncode, mytipeDecode) + +console.log(encode({ 'hello': 'world' }).toString('hex')) +// 81a568656c6c6fa5776f726c64 +console.log(decode(encode({ 'hello': 'world' }))) +// { hello: 'world' } +console.log(encode(a).toString('hex')) +// d5426161 +console.log(decode(encode(a)) instanceof MyType) +// true +console.log(decode(encode(a))) +// { value: 'a', size: 2 } + +function MyType(size, value) { + this.value = value + this.size = size +} + +function mytipeEncode(obj) { + var buf = new Buffer(obj.size) + buf.fill(obj.value) + return buf +} + +function mytipeDecode(data) { + var result = new MyType(data.length, data.toString('utf8', 0, 1)) + , i + + for (i = 0; i < data.length; i++) { + if (data.readUInt8(0) != data.readUInt8(i)) { + throw new Error('should all be the same') + } + } + + return result +} + +``` + + +# References + +- [MessagePack](http://msgpack.org/index.html) +- [MsgPack vs. JSON: Cut your client-server exchange traffic by 50% with one line of code](http://indiegamr.com/cut-your-data-exchange-traffic-by-up-to-50-with-one-line-of-code-msgpack-vs-json/) \ No newline at end of file -- cgit v1.2.3 From a6d6be3e30a113335fe14aa6248b7b8bff5a1487 Mon Sep 17 00:00:00 2001 From: Gabriel SoHappy Date: Thu, 22 Oct 2015 02:30:37 +0800 Subject: fix double quote formatting --- messagepack.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messagepack.html.markdown b/messagepack.html.markdown index 0ee90742..9291fffc 100644 --- a/messagepack.html.markdown +++ b/messagepack.html.markdown @@ -16,7 +16,7 @@ In MessagePack, small integers are encoded into a single byte, and typical short JSON, 40 Bytes UTF-8 ---------------------------------------------- -| {“name“:”John Doe“,”age“:12} | +| {"name":"John Doe","age":12} | ---------------------------------------------- | {" | 7B 22 | | name | 6E 61 6D 65 | -- cgit v1.2.3 From 89876929cb4181cac29c8aef149ae140a8c570be Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Wed, 21 Oct 2015 21:19:08 +0200 Subject: Add dutch translation of JSON Add dutch translation of JSON --- nl-nl/json-nl.html.markdown | 71 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 nl-nl/json-nl.html.markdown diff --git a/nl-nl/json-nl.html.markdown b/nl-nl/json-nl.html.markdown new file mode 100644 index 00000000..906112ff --- /dev/null +++ b/nl-nl/json-nl.html.markdown @@ -0,0 +1,71 @@ +--- +language: json +filename: learnjson-nl.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +Gezien JSON een zeer eenvouding formaat heeft zal dit een van de simpelste +Learn X in Y Minutes ooit zijn. + +JSON heeft volgens de specificaties geen commentaar, ondanks dat hebben de +meeste parsers support voor C-stijl (`//`, `/* */`) commentaar. +Sommige parsers staan zelfs trailing komma's toe. +(Een komma na het laatste element in een array of ahter de laatste eigenshap van een object). +Het is wel beter om dit soort dingen te vermijden omdat het niet overal zal werken. + +In het voorbeeld zal alleen 100% geldige JSON gebruikt worden. + +Data types gesupport door JSON zijn: nummers, strings, booleans, arrays, objecten en null. +Gesupporte browsers zijn: Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. +De extensie voor JSON bestanden is ".json". De MIME type is "application/json" +Enkele nadelen van JSON zijn het gebrek een type definities en een manier van DTD. + +```json +{ + "sleutel": "waarde", + + "sleutels": "zijn altijd in quotes geplaatst", + "nummers": 0, + "strings": "Hallø, wereld. Alle unicode karakters zijn toegestaan, samen met \"escaping\".", + "boolean": true, + "niks": null, + + "groot nummer": 1.2e+100, + + "objecten": { + "commentaar": "In JSON gebruik je vooral objecten voor je strutuur", + + "array": [0, 1, 2, 3, "Arrays kunnen alles in zich hebben.", 5], + + "nog een object": { + "commentaar": "Objecten kunnen genest worden, erg handig." + } + }, + + "dwaasheid": [ + { + "bronnen van kalium": ["bananen"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternatieve stijl": { + "commentaar": "Kijk dit!" + , "De komma positie": "maakt niet uit zolang het er maar is" + , "nog meer commentaar": "wat leuk" + }, + + "dat was kort": "En nu ben je klaar, dit was alles wat je moet weten over JSON." +} +``` -- cgit v1.2.3 From 5d09bdab933a6fca3eff2227714fac2da6b1538f Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Wed, 21 Oct 2015 21:20:33 +0200 Subject: Add dutch translation of TypeScript Add dutch translation of TypeScript --- nl-nl/typescript-nl.html.markdown | 174 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 nl-nl/typescript-nl.html.markdown diff --git a/nl-nl/typescript-nl.html.markdown b/nl-nl/typescript-nl.html.markdown new file mode 100644 index 00000000..dcea2a4d --- /dev/null +++ b/nl-nl/typescript-nl.html.markdown @@ -0,0 +1,174 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +filename: learntypescript-nl.ts +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +TypeScript is een taal gericht op het versoepelen van de ontwikkeling van +grote applicaties gemaakt in JavaScript. +TypeScript voegt veelgebruikte technieken zoals klassen, modules, interfaces, +generieken en statische typen toe aan JavaScript. +TypeScript is een superset van JavaScript: alle JavaScript code is geldige +TypeScript code waardoor de overgang van JavaScript naar TypeScript wordt versoepeld. + +Dit artikel focust zich alleen op de extra's van TypeScript tegenover [JavaScript] (../javascript-nl/). + +Om de compiler van TypeScript te kunnen proberen kun je naar de [Playground] (http://www.typescriptlang.org/Playground) gaan. +Hier kun je automatisch aangevulde code typen in TypeScript en de JavaScript variant bekijken. + +```js +// Er zijn 3 basis typen in TypeScript +var isKlaar: boolean = false; +var lijnen: number = 42; +var naam: string = "Peter"; + +// Wanneer het type onbekend is gebruik je "Any" +var nietZeker: any = 4; +nietZeker = "misschien een string"; +nietZeker = false; // Toch een boolean + +// Voor collecties zijn er "typed arrays" +var lijst: number[] = [1, 2, 3]; +// of generieke arrays +var lijst: Array = [1, 2, 3]; + +// Voor enumeraties: +enum Kleur {Rood, Groen, Blauw}; +var c: Kleur = Kleur.Groen; + +// Als laatst, "void" wordt gebruikt voor als een functie geen resultaat geeft +function groteVerschrikkelijkeMelding(): void { + alert("Ik ben een vervelende melding!"); +} + +// Functies zijn eersteklas ?, supporten de lambda "fat arrow" syntax en +// gebruiken gebruiken "type inference" + +// Het volgende is allemaal hetzelfde +var f1 = function(i: number): number { return i * i; } +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +var f4 = (i: number) => { return i * i; } +// Omdat we maar 1 lijn gebruiken hoeft het return keyword niet gebruikt te worden +var f5 = (i: number) => i * i; + +// Interfaces zijn structureel, elk object wat de eigenschappen heeft +// is een gebruiker van de interface +interface Persoon { + naam: string; + // Optionele eigenschappen worden gemarkeerd met "?" + leeftijd?: number; + // En natuurlijk functies + verplaats(): void; +} + +// Object die gebruikt maakt van de "Persoon" interface +// Kan gezien worden als persoon sinds het de naam en verplaats eigenschappen bevat +var p: Persoon = { naam: "Bobby", verplaats: () => {} }; +// Object met de optionele leeftijd eigenschap +var geldigPersoon: Persoon = { naam: "Bobby", leeftijd: 42, verplaats: () => {} }; +// Ongeldig persoon vanwege de leeftijds type +var ongeldigPersoon: Persoon = { naam: "Bobby", leeftijd: true }; + +// Interfaces kunnen ook een functie ype beschrijven +interface ZoekFunc { + (bron: string, subString: string): boolean; +} +// Alleen de parameters types zijn belangrijk, namen maken niet uit. +var mySearch: ZoekFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - leden zijn standaard publiek +class Punt { + // Eigenschappen + x: number; + + // Constructor - de publieke / prive trefwoorden in deze context zullen + // eigenschappen in de klasse kunnen aanmaken zonder ze te defineren. + // In dit voorbeeld zal "y" net als "x" gedefineerd worden met minder code. + // Standaard waardes zijn ook gesupport + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Functies + dist(): number { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statische leden + static origin = new Punt(0, 0); +} + +var p1 = new Punt(10 ,20); +var p2 = new Punt(25); // y zal de waarde 0 krijgen + +// Overnemen +class Punt3D extends Punt { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Constructor van ouder aanroepen (Punt) + } + + // Overschrijven + dist(): number { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modules werken ongeveer hetzelfde als namespaces +// met "." kan je submodules defineren +module Geometrie { + export class Vierkant { + constructor(public zijLengte: number = 0) { + } + + oppervlakte() { + return Math.pow(this.zijLengte, 2); + } + } +} + +var s1 = new Geometrie.Vierkant(5); + +// Local alias for referencing a module +import G = Geometrie; + +var s2 = new G.Vierkant(10); + +// Generieken +// Classes +class Tupel { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Paar { + item1: T; + item2: T; +} + +// En functies +var paarNaarTupel = function(p: Paar) { + return new Tupel(p.item1, p.item2); +}; + +var tupel = paarNaarTupel({ item1: "hallo", item2: "wereld" }); + +// Refferentie naar een definitie bestand: +/// + +``` + +## Verder lezen (engels) + * [TypeScript Official website] (http://www.typescriptlang.org/) + * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [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 ac7d33f319dc9a8c9e26f68f558c834aaa3267f1 Mon Sep 17 00:00:00 2001 From: Scott Fisk Date: Wed, 21 Oct 2015 16:12:49 -0500 Subject: Changed wording for comments section Changed wording for overview of comments so it would make more sense to a beginner. Corrected grammar error. --- es-es/javascript-es.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index d475cf42..fdb938a8 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -23,7 +23,9 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js -// Los comentarios son como en C. Los comentarios de una sola línea comienzan con //, +// Los comentarios en JavaScript son los mismos como comentarios en C. + +//Los comentarios de una sola línea comienzan con //, /* y los comentarios multilínea comienzan y terminan con */ -- cgit v1.2.3 From 257533fe5aa5027dc71e78d10833a3ba0febb426 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 21 Oct 2015 23:18:38 +0200 Subject: fix #1726, thanks @fisktech --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index a119be88..c1c59de1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -21,7 +21,7 @@ Feedback would be highly appreciated! You can reach me at [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js -// Comments are like C. Single-line comments start with two slashes, +// Comments are like C's. Single-line comments start with two slashes, /* and multiline comments start with slash-star and end with star-slash */ -- cgit v1.2.3 From ce85711575d8b481d9de1dc8823a1e8c62211248 Mon Sep 17 00:00:00 2001 From: Arashk-A Date: Thu, 22 Oct 2015 02:16:31 +0330 Subject: Edit some translation behavior in links and codes --- fa-ir/css.html.markdown | 62 ++++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/fa-ir/css.html.markdown b/fa-ir/css.html.markdown index 7214bb04..661cc5f2 100644 --- a/fa-ir/css.html.markdown +++ b/fa-ir/css.html.markdown @@ -34,6 +34,7 @@ selector { property: value; /* more properties...*/ }

با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

+ ```CSS * { color:red; } ``` @@ -45,7 +46,8 @@ selector { property: value; /* more properties...*/ } ```

شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

-‍‍```CSS + +```CSS .some-class { } ``` @@ -67,37 +69,37 @@ selector { property: value; /* more properties...*/ } div { } ``` -

یا با استفاده از 'attr'

+

یا با استفاده از `attr`

```CSS [attr] { font-size:smaller; } ``` -

یا با استفاده از ارزشی که برای 'attr' مشخص شده

+

یا با استفاده از ارزشی که برای `attr` مشخص شده

```CSS [attr='value'] { font-size:smaller; } ``` -

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'val' شروع میشود در CSS3

+

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3

```CSS [attr^='val'] { font-size:smaller; } ``` -

با استفاده از ارزشی که برای 'attr' مشخص شده و آن ارزش با 'ue' به پایان میرسد در CSS3

+

با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3

```CSS [attr$='ue'] { font-size:smaller; } ``` -

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست 'otherAttr' بوسیله فاصله از هم جدا شده اند در CSS3

+

یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3

```CSS [attr$='ue'] { font-size:smaller; } ``` -

یا ارزش('value') دقیقاً خود ارزش('value') یا بوسیله '-' که یونیکد (U+002D) از حرف بعدی جدا شود

+

یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود

```CSS [otherAttr|='en'] { font-size:smaller; } @@ -110,14 +112,14 @@ div.some-class[attr$='ue'] { } ```

CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

-

برای مثال دستور زیر همه عناصری را که نام کلاس آنها '.class-name' و دارای پدر و مادری با این مشخصه 'div.some-parent' هستند را انتخاب میکند.

+

برای مثال دستور زیر همه عناصری را که نام کلاس آنها `.class-name` و دارای پدر و مادری با این مشخصه `div.some-parent` هستند را انتخاب میکند.

```CSS div.some-parent > .class-name {} ``` -

یا دستور زیر که همه عناصری را که نام کلاس آنها '.class-name' و داخل عنصری با مشخصه 'div.some-parent' هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان 'div.some-parent' باشند) انتخاب میکند.

+

یا دستور زیر که همه عناصری را که نام کلاس آنها `.class-name` و داخل عنصری با مشخصه `div.some-parent` هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان `div.some-parent` باشند) انتخاب میکند.

```CSS div.some-parent .class-name {} @@ -129,13 +131,13 @@ div.some-parent .class-name {} div.some-parent.class-name {} ``` -

دستور زیر همه عناصری را که نام کلاس آنها '.this-element' و بلافاصله بعد از عنصری با مشخصه '.i-am-before' قرار دارد را انتخاب میکند.

+

دستور زیر همه عناصری را که نام کلاس آنها `.this-element` و بلافاصله بعد از عنصری با مشخصه `.i-am-before` قرار دارد را انتخاب میکند.

```CSS .i-am-before + .this-element { } ``` -

هر خواهر یا برادری که بعد از '.i-am-before' بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

+

هر خواهر یا برادری که بعد از `.i-am-before` بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

```CSS .i-am-any-before ~ .this-element {} @@ -178,8 +180,8 @@ selector { width: 5cm; /* بر اساس سانتیمتر */ min-width: 50mm; /* بر اساس میلیمتر */ max-width: 5in; /* بر اساس اینچ. max-(width|height) */ - height: 0.2vh; /* بر اساس ارتفاع دید 'vh = نسبت به 1٪ از ارتفاع دید' (CSS3) */ - width: 0.4vw; /* بر اساس عرض دید 'vw = نسبت به 1٪ از عرض دید' (CSS3) */ + height: 0.2vh; /* بر اساس ارتفاع دید `vh = نسبت به 1٪ از ارتفاع دید` (CSS3) */ + width: 0.4vw; /* بر اساس عرض دید `vw = نسبت به 1٪ از عرض دید` (CSS3) */ min-height: 0.1vmin; /* بر اساس کوچکترین مقدار از ارتفاع یا عرض دید (CSS3) */ max-width: 0.3vmax; /* مانند مثال بالا برای بیشترین مقدار (CSS3) */ @@ -208,13 +210,13 @@ selector {

نحوه استفاده

هر دستور CSS را که می خواهید در فایلی با پسوند .css ذخیره کنید

-

حالا با استفاده از کد زیر آنرا در قسمت 'head' داخل فایل html خود تعریف کنید

+

حالا با استفاده از کد زیر آنرا در قسمت `head` داخل فایل html خود تعریف کنید

```html ``` -

یا میتوان با استفاده از تگ 'style' درون 'head' دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

+

یا میتوان با استفاده از تگ `style` درون `head` دستورات CSS را به صورت درون برنامه ای تعریف کرد اما توسیه میشود تا جای ممکن از این کار اجتناب کنید.

```html + + +
+
+``` + +## Precedence அல்லது Cascade + +ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் +ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன +இது Cascading Style Sheets என அழைக்கபடுகிறது. + + +கிழே தரப்பட்டுள்ள css இன் படி: + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +அத்துடன் கிழே தரப்பட்டுள்ள கட்டமைப்பின்படியும்: + +```xml +

+``` + + +css முன்னுரிமை பின்வருமாறு +* `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் +* `F` இது இரண்டாவது காரணம் இது inline style. +* `A` இது மூன்றவதாக வருகிறது, காரணம் இது மூன்று காரணிகளை குறிக்கிறது : element(உறுப்பு) பெயர் `p`, அதன் class `class1`, an அதன் பண்பு(attribute) `attr='value'`. +* `C` இது அடுத்த நிலையில் உள்ளது கடைசி. +* `B` இது அடுத்தது. +* `D` இதுவே கடைசி . + +## css அம்சங்களின் பொருந்தகூடிய தன்மை + +பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது. + +## வளங்கள் + +* To run a quick compatibility check, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) + +## மேலும் வாசிக்க + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/ta_in/css.html.markdown b/ta_in/css.html.markdown deleted file mode 100644 index 56f94ed0..00000000 --- a/ta_in/css.html.markdown +++ /dev/null @@ -1,254 +0,0 @@ ---- -language: css -contributors: - - ["Mohammad Valipour", "https://github.com/mvalipour"] - - ["Marco Scannadinari", "https://github.com/marcoms"] - - ["Geoffrey Liu", "https://github.com/g-liu"] - - ["Connor Shea", "https://github.com/connorshea"] - - ["Deepanshu Utkarsh", "https://github.com/duci9y"] -translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: learncss.css -lang:in-ta ---- - - -இணையத்தின் ஆரம்ப காலத்தில் முழுமையாக உரைகளை மட்டுமே கொண்டிருந்தன. -ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன் -கூடிய இணையதளங்கள் உருவாகின. - - -CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது. - -ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது. - -இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது. - -**குறிப்பு:** -CSS ஆனது முற்று முழுதாக visual(காட்சி) மாற்றங்களை தருவதால் அதை நீங்கள் முயற்சிக்க -இதை உபயோகபடுத்தலாம் [dabblet](http://dabblet.com/). -இந்த வழிகாட்டியின் பிரதான நோக்கம் CSS இன் syntax மற்றும் மேலும் சில வழிமுறைகளை -உங்களுக்கு கற்று தருவதாகும் - -```css -/* css இல் குறிப்புகளை இப்படி இடலாம் */ - -/* #################### - ## SELECTORS - #################### */ - -/* ஒரு HTML பக்கத்தில் இருக்கும் உறுப்பை நாம் selector மூலம் தெரிவு செய்யலாம் -selector { property: value; /* more properties...*/ } - -/* -கிழே ஒரு உதாரணம் காட்டப்பட்டுள்ளது: - -

-*/ - -/* நீங்கள் அந்த உறுப்பை அதன் CSS class மூலம் தெரியலாம் */ -.class1 { } - -/* அல்லது இவ்வாறு இரண்டு class மூலம் தெரியலாம்! */ -.class1.class2 { } - -/* அல்லது அதன் பெயரை பாவித்து தெரியலாம் */ -div { } - -/* அல்லது அதன் id ஐ பயன்படுத்தி தெரியலாம்*/ -#anID { } - -/* அல்லது ஒரு உறுப்பின் பண்பு ஒன்றின் மூலம்! */ -[attr] { font-size:smaller; } - -/* அல்லது அந்த பண்பு ஒரு குறிப்பிட்ட பெறுமானத்தை கொண்டு இருப்பின் */ -[attr='value'] { font-size:smaller; } - -/* ஒரு பெறுமதியுடன் ஆரம்பமாகும் போது (CSS 3) */ -[attr^='val'] { font-size:smaller; } - -/* அல்லது ஒரு பெறுமதியுடன் முடிவடையும் போது (CSS 3) */ -[attr$='ue'] { font-size:smaller; } - -/* அல்லது காற்புள்ளியால் பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின் */ -[otherAttr~='foo'] { } -[otherAttr~='bar'] { } - -/* அல்லது `-` பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின், உ.ம்:-, "-" (U+002D) */ -[otherAttr|='en'] { font-size:smaller; } - - -/* நாம் இரண்டு selectors ஐ ஒன்றாக உபயோகித்தும் ஒரு உறுப்பை அணுக முடியும் , -அவற்றுக்கு இடயே இடைவெளி காணப்படகூடாது - */ -div.some-class[attr$='ue'] { } - -/*அல்லது ஒரு உறுப்பினுள் இருக்கும் இன்னொரு உறுப்பை (child element) அணுக */ -div.some-parent > .class-name { } - -/* ஒரு ஒரு பிரதான உறுப்பில் உள்ள உப உறுப்புகளை அணுக*/ -div.some-parent .class-name { } - -/* மேலே குறிபிட்ட அணுகுமுறையில் இடைவெளி காணப்படாது விடின் - அந்த selector வேலை செய்யாது - */ -div.some-parent.class-name { } - -/* அல்லது ஒரு உறுப்புக்கு அடுத்துள்ள */ -.i-am-just-before + .this-element { } - -/* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */ -.i-am-any-element-before ~ .this-element { } - -/* - சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை - குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும் - */ - -/* உதாரணமாக நாம் ஒரு உறுப்பின் மீதாக cursor ஐ நகர்த்தும் போது */ -selector:hover { } - -/* அல்லது ஒரு -பார்வையிட்ட இணைப்பு */ -selector:visited { } - -/* அல்லது ஒரு பார்வையிடபடாத இணைப்பு */ -selected:link { } - -/* அல்லது ஒரு element ஐ focus செய்யும் போது */ -selected:focus { } - -/* - எல்லா elementகளையும் ஒரே நேரத்தில் அணுக `*` -*/ -* { } /* all elements */ -.parent * { } /* all descendants */ -.parent > * { } /* all children */ - -/* #################### - ## பண்புகள் - #################### */ - -selector { - - /* நீளத்தின் அலகுகள் absolute அல்லது relative ஆக இருக்கலாம். */ - - /* Relative units */ - width: 50%; /* percentage of parent element width */ - font-size: 2em; /* multiples of element's original font-size */ - font-size: 2rem; /* or the root element's font-size */ - font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */ - font-size: 2vh; /* or its height */ - font-size: 2vmin; /* whichever of a vh or a vw is smaller */ - font-size: 2vmax; /* or greater */ - - /* Absolute units */ - width: 200px; /* pixels */ - font-size: 20pt; /* points */ - width: 5cm; /* centimeters */ - min-width: 50mm; /* millimeters */ - 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: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */ - - /* Images as backgrounds of elements */ - background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ - - /* Fonts */ - font-family: Arial; - /* if the font family name has a space, it must be quoted */ - font-family: "Courier New"; - /* if the first one is not found, the browser uses the next, and so on */ - font-family: "Courier New", Trebuchet, Arial, sans-serif; -} -``` - -## Usage - -ஒரு css file ஐ save செய்ய `.css`. - -```xml - - - - - - - -
-
-``` - -## Precedence அல்லது Cascade - -ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் -ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன -இது Cascading Style Sheets என அழைக்கபடுகிறது. - - -கிழே தரப்பட்டுள்ள css இன் படி: - -```css -/* A */ -p.class1[attr='value'] - -/* B */ -p.class1 { } - -/* C */ -p.class2 { } - -/* D */ -p { } - -/* E */ -p { property: value !important; } -``` - -அத்துடன் கிழே தரப்பட்டுள்ள கட்டமைப்பின்படியும்: - -```xml -

-``` - - -css முன்னுரிமை பின்வருமாறு -* `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் -* `F` இது இரண்டாவது காரணம் இது inline style. -* `A` இது மூன்றவதாக வருகிறது, காரணம் இது மூன்று காரணிகளை குறிக்கிறது : element(உறுப்பு) பெயர் `p`, அதன் class `class1`, an அதன் பண்பு(attribute) `attr='value'`. -* `C` இது அடுத்த நிலையில் உள்ளது கடைசி. -* `B` இது அடுத்தது. -* `D` இதுவே கடைசி . - -## css அம்சங்களின் பொருந்தகூடிய தன்மை - -பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது. - -## வளங்கள் - -* To run a quick compatibility check, [CanIUse](http://caniuse.com). -* CSS Playground [Dabblet](http://dabblet.com/). -* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) -* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) - -## மேலும் வாசிக்க - -* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) -* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) -* [QuirksMode CSS](http://www.quirksmode.org/css/) -* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing -* [CSS-Tricks](https://css-tricks.com) -- cgit v1.2.3 From 7d4522b5125da0a97ed0fe1f684cb50606e7b12d Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:15:46 +0800 Subject: Rename javascript.html.markdown to javascript-ta.html.markdown --- ta_in/javascript-ta.html.markdown | 594 ++++++++++++++++++++++++++++++++++++++ ta_in/javascript.html.markdown | 594 -------------------------------------- 2 files changed, 594 insertions(+), 594 deletions(-) create mode 100644 ta_in/javascript-ta.html.markdown delete mode 100644 ta_in/javascript.html.markdown diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown new file mode 100644 index 00000000..f0b0a36a --- /dev/null +++ b/ta_in/javascript-ta.html.markdown @@ -0,0 +1,594 @@ +--- +language: javascript +contributors: + - ['Adam Brenecki', 'http://adam.brenecki.id.au'] + - ['Ariel Krakowski', 'http://www.learneroo.com'] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: javascript.js +lang:in-ta +--- + +javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich +என்பவரால் உருவாக்கபட்டது.ஆரம்பத்தில் மிகவும் எளிமையான +ஸ்க்ரிப்டிங் மொழியாக இணையதளங்களில் பயன்படுத்தபட்டது. +இது ஜாவா (java ) வில் உருவாக்கபட்ட மிகவும் சிக்கலான இணைய செயலிகளுக்கு +உதவும் முகமாக உருவாக்கபட்டது. எனினும் இணையதள பக்கங்களில் இதன் முழுதான பயன்பாடு +மற்றும் உலாவிகளில் பயன்படுத்த கூடிய வகையில் இருந்தமையாலும் Java வை விட +இணையதளகளின் முகப்பு உருவாக்கத்தில் இன்றளவில் முன்னிலை பெற்றுள்ளது. + +உலாவிகளுக்கு மட்டும் மட்டுபடுத்தபடவில்லை , Node.js மூலமாக +மிகவும் பிரபல்யமடைந்து வருகின்றது , உதாரணமாக கூகிள்க்ரோம் உலாவியின் +V8 JavaScript engine Node .js உதவியுடன் இயங்குகிறது . + +உங்கள் கருத்துக்கள் மிகவும் வரவேற்கபடுகின்றன , என்னுடன் தொடர்புகொள்ள +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும் + +/* பலவரி குறிப்புக்கள் "/*" ஆரம்பமாகி "/*" இல் முடிவடையும் */ + +// ஒரு கூற்று முற்றுபெற செய்ய ; இடல் வேண்டும் . +doStuff(); + +// ...ஆனால் அரைபுள்ளி இட வேண்டும் என்று அவசியம் இல்லை ஏன் எனில் +// ஒரு வரி புதிதாக இடப்படும் போது அரைபுள்ளிகள் தானாகவே இடப்படும் ஆனால் சில தருணங்களை தவிர . +doStuff() + +// ஆனால் அவ்வாறான தருணங்கள் எதிர்பாராத முடிவுகளை தரலாம் + +// எனவே நாம் தொடர்ந்து ஒரு கூற்று நிறைவடையும் போது அரைபுள்ளி ஒன்றை இடுவோம் . + +/////////////////////////////////// +// 1. எண்கள்(Number) ,சரம் (String),செயற்குறிகள்(Operators) + +// JavaScript ஒரே ஒரு எண்வகை காணப்படுகிறது தசமி (which is a 64-bit IEEE 754 double). +// தசமி எண்வகை (Doubles) 2^ 52 வரை சேமிக்க கூடியது +// முழு எண்வகையின் 9✕10¹⁵ சேமிக்க போதுமானது . +3; // = 3 +1.5; // = 1.5 + +// அடிப்படை கணித பொறிமுறைகள் +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// வகுத்தல் +5 / 2; // = 2.5 + + +//bitwise பொறிமுறையை உபயோகிக்கும் போது +//உங்கள் தசம எண்ணின் பெறுமானமானது ஒரு நேர் அல்லது மறை அல்லது பூசியமாகவுள்ள முழு எண்ணாக +//மாற்றம் பெறுகிறது இது 32 இருமம்(bit) வரை செல்லலாம் + +1 << 2; // = 4 + +// நிரலாக்கத்தில் செயலியை அமுல்படுத்தும் வரிசைமுறையில் அடைப்பு குறிக்கு முன்னிலை வழங்கபடுகிறது +(1 + 3) * 2; // = 8 + +// மெய் எண் அல்லாத மூன்றுபெறுமானங்கள் உள்ளன : +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0, இது எண் அல்ல என்பதை குறிக்கும் + +// தர்க ரீதியில் ஆன கட்டமைப்பு காணப்படுகிறது . +true; +false; + +// சரம் (string) ' அல்லது " குறியீட்டினால் உருவாக்கபடுகிறது +'abc'; +"Hello, world"; + +// ஒரு boolean பெறுமானத்தின் எதிர்மறை பெறுமானத்தை பெற ! குறியீடு பயன்படுத்தபடுகிறது +!true; // = false +!false; // = true + +// சமமா என பார்க்க === +1 === 1; // = true +2 === 1; // = false + +// சமனற்றவையா என பார்க்க !== +1 !== 1; // = false +2 !== 1; // = true + +// மேலும் சில ஒப்பீடுகள் +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// இரண்டு சரங்களை(Strings) ஒன்றாக இணைப்பதற்கு + +"Hello " + "world!"; // = "Hello world!" + +// இரண்டு மாறிகளை/பெறுமானங்களை ஒப்பிட < and > +"a" < "b"; // = true + +// இரண்டு பெறுமானங்கள் / மாறிகள் ஒரேவகையை சேர்ந்தவையா என பார்க்க +"5" == 5; // = true +null == undefined; // = true + +// ...இல்லாவிடின் === +"5" === 5; // = false +null === undefined; // = false + +// ...கிழே உள்ள கூற்றுகள் எதிர்பாராத +வெளியீடுகளை தரலாம் ... +13 + !0; // 14 +"13" + !0; // '13true' + +// ஒரு சரத்தில்(string ) உள்ள எழுத்தை பெற `charAt` +"This is a string".charAt(0); // = 'T' + + +//... ஒரு சரத்தை(string ) சொற்களாக பிரிக்க (substring) `substring +"Hello world".substring(0, 5); // = "Hello" + +// `length` ஒரு சரத்தில்(string) உள்ள சொற்களின் எண்ணிக்கை அல்லது நீளத்தை(length)அறிய +"Hello".length; // = 5 + +// `null` மற்றும் `undefined` இரு பெறுமானங்கள் உள்ளன . +null; // மதிப்பு அற்ற ஒரு பெறுமானத்தை குறிக்கும் +undefined; // பெறுமானம் இன்னும் நிர்ணயிக்க படவில்லை என்பதை குறிக்கும் ( + // `undefined` இருப்பினும் இதுவும் ஒரு பெறுமானமாக கருதபடுகிறது ) + +// ஆகியன தர்க்க ரீதியாக பிழையானவை(false) , மற்றவை யாவும் சரியானவை (true). +// 0 மானது பிழையை (false) குறிக்கும் "0" சரியை (true) குறிக்கும் எனினும் 0 == "0". + +/////////////////////////////////// +// 2. மாறிகள் (Variables),அணிகள் (Arrays) மற்றும் பொருட்கள் (Objects) + +// மாறிகளை உருவாக்க `var ` என்னும் குறியீட்டு சொல் (keyword ) பயன்படுகிறது . +//உருவாக்கப்படும் மாறிகள் எந்த வகையை சார்ந்தன என்பதை JavaScript +//தானாகவே நிர்ணயிக்கும் . மாறிக்கு ஒரு பெறுமானத்தை வழங்க `=` பாவிக்க +var someVar = 5; + +// //நீங்கள் மாறிகளை நிறுவ 'var' குறியீட்டு சொல்லை பயன்படுத்தா விடினும் +//அது தவறில்லை ... +someOtherVar = 10; + +// ...ஆனால் நீங்கள் நிறுவிய மாறி(variable) எல்லா உங்கள் ப்ரோக்ராம் இன் சகல இடங்களிலும் +//அணுக கூடியதாய் அமையும் , இல்லாவிடின் அது ஒரு குறிபிட்ட இடத்திற்கு மட்டும் +//மட்டுபடுத்தபடும் . + +//பெறுமானம் வழங்கபடாத மாறிகளுக்கு ,இயல்பாக/தானாக undefined என்ற பெறுமானம் +//வழங்கப்படும் +var someThirdVar; // = undefined + +// மாறிகளில் கணித செயல்பாடுகளை நடத்த சுருக்கெழுத்து முறைகள் காணப்படுகின்றன : +someVar += 5; // இது someVar = someVar + 5; ஐ ஒத்தது someVar இன் பெறுமானம் இப்போது 10 +someVar *= 10; // someVar இன் பெறுமானம் இப்போது 100 + +//மிகவும் சுருக்கமான சுருகேழுத்து முறை கூட்டல் அல்லது கழித்தல் செயன்முறையை +//மேற்கொள்ள +someVar++; // someVar இன் பெறுமானம் இப்போது is 101 +someVar--; // someVar இன் பெறுமானம் இப்போது 100 + +// அணிகள்(Arrays) எல்லாவகையான பெறுமானங்களையும் உள்ளடக்க கூடியது +var myArray = ["Hello", 45, true]; + +// அணிகள்(Arrays) உறுப்பினர்கள் சதுர அடைப்புக்குறிக்குள் அதன் தான இலக்கத்தை கொண்டு +//அணுகமுடியும் . +// அணிகளில் உள்ள உறுப்புகள் 0 இருந்து ஆரம்பமாகும் . +myArray[1]; // = 45 + +// அணிகள் உள்ள உறுப்புகளை மாற்றமுடியும் அத்துடன் உறுப்புகளின் எண்ணிக்கையும் மாறலாம் . +myArray.push("World"); +myArray.length; // = 4 + +// அணியில்(Array) ஒரு குறிப்பிட்ட இடத்தில உள்ள பெறுமானத்தை மாற்ற . +myArray[3] = "Hello"; + +// JavaScript's பொருள் (objects) அகராதியை ஒத்தன +// ஒழுங்கு படுத்த படாத சேகரிப்பு (collection) ஆகும் இதில் ஒரு சாவியும்(key) +//அதுக்குரிய பெறுமானமும்(value) காணப்படும் . +var myObj = {key1: "Hello", key2: "World"}; + +// விசைகள் சரங்களை, ஆனால் அவர்கள் சரியான என்றால் மேற்கோள் அவசியம் இல்லை +//சாவிகளை உ.ம் : "key" என நிறுவலாம் ஆனால் , மேற்கோள் ஆனது சாவி முன்பே நிறுவபட்டிருப்பின் +//அவசியம் இல்லை +// சாவிகளுக்குரிய பெறுமானங்கள் எந்த வகையாகவும் இருக்கலாம் +var myObj = {myKey: "myValue", "my other key": 4}; + +//பொருள் பண்புகளை சதுர அடைப்புக்குறிக்குள் அதன் சாவியின் பெயரை (key) கொண்டு +//அணுகமுடியும் , +myObj["my other key"]; // = 4 + +// ... அல்லது புள்ளி குறியீட்டை பயன்படுத்தி ,சாவியின் (key is a valid identifier) +//பெயர் மூலம் அணுக முடியும் +myObj.myKey; // = "myValue" + +// பொருட்கள்(ஒப்ஜெக்ட்ஸ்) மாற்றபடகூடியான சாவிகளின் பெறுமதிகளை மாற்ற முடியும் அத்துடன் புதிய +//சாவிகளை(keys) இடவும் முடியும் +myObj.myThirdKey = true; + +//பெறுமதி வரையறுக்கபடாத ஒரு சாவியினை அணுகும் போது +//அது வெளியிடும் பெறுமதி `undefined`. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. தர்க்கம் மற்றும் கட்டுப்பாட்டு கட்டமைப்பு + +// கீழே காட்டப்பட்டுள்ள தொடரியல் ஜாவா வை ஒத்தது + +// The `if` ஒரு குறித்த தர்க்கம் சரியாயின் +//அல்லது என்ற வடிவமைப்பை +var count = 1; +if (count == 3){ + // count இன் பெறுமானம் 3 சமமா என பார்க்கபடுகிறது +} else if (count == 4){ + // count இன் பெறுமானம் 4க்கு சமமா என பார்க்கபடுகிறது +} else { + // count ஆனது 3 அல்ல 4 அல்ல எனின் +} + +// ஒரு குறிப்பிட்ட ஒப்பீடு உண்மையாக இருக்கும் வரை `while`. +while (true){ + // இந்த இருக்கும் கூற்றுகள் முடிவிலி தடவை மறுபடி செயற்படுத்தப்படும் ! +} + +// while போல் அல்லாது do-while ,அவை ஒரு தடவையேனும் அதனுள் உள்ள கூற்றுகள் செயற்படுத்தபடும் +var input; +do { + input = getInput(); +} while (!isValid(input)) + +// for (loop /சுற்று ) C , ஜாவாவை ஒத்தது +//மாறிக்கு பெறுமானத்தை வழங்கல் , மாறியானது தர்க்கத்தை பூர்த்தி செய்கிறதா என பார்த்தல் , +//சுற்றுக்குள் இருக்கும் கூற்றை செயற்படுதல் + +for (var i = 0; i < 5; i++){ + // இந்த சுற்று 5 தடவைகள் தொடர்ந்து செயற்படுத்தபடும் +} + +//for /In சுற்றுகள் prototype சங்கிலியில் உள்ள சகல காரணிகள் ஊடகவும் செல்லும் +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} + +//ஒரு பொருளில் (Object) இடப்பட்ட பண்புகளை (properties) கருத்தில் கொள்ளும் போது +//குறிப்பிட்ட பண்புகளை அந்த Object கொண்டுள்ளதா என பார்க்க +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + if (person.hasOwnProperty(x)){ + description += person[x] + " "; + } +} + +//for /in ஆனது அணியில் உள்ள பண்புகள் ஒழுங்குபடுத்தப்பட்டவிதம் முக்கியம் +//ஆயின் பாவிப்பதை தவிர்க்கவும் ஏனெனில் அது சரியான ஒழுங்கில் +//வெளியீட்டை தரும் என்பது ஐயம் ஆகும் + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default"; + + + +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Scope and Closures + +// JavaScript இல் functions நிறுவ `function` keyword.பயன்படும் +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +//ஒரு பெறுமானத்தை return செய்ய வேண்டும் எனின் இரண்டும் ஒரே வரியில் +//இருக்க வேண்டும் இல்லாவிடின் return ஆனது `undefined ` return செய்யும் +//காற் புள்ளி தானாகவே இடப்படும் , நீங்கள் Allman style உபயோகிக்கும் போது +//அவதானமாக இருக்கவும் +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// JavaScript functions ஆனது first class objects ஆகும் ,எனவே அவற்றை மாறிகளுக்கு +//assign செய்ய முடியும் அதுமட்டும் அல்லது functions களில் arguments ஆக அனுப்பமுடியும் +// உதாரணமாக ஒரு event handler: +function myFunction(){ + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் +} +setTimeout(myFunction, 5000); +// Note: setTimeout ஆனது ஜாவஸ்க்ரிப்ட் சேர்ந்தது அன்று , ஆனால் அந்த வசதி +//உலாவிகளிலும் ,Node .js காணப்படுகிறது + +// Function objects கட்டாயம் பெயரிடப்பட வீண்டும் என்று அவசியம் இல்லை +// அவை anonymous(பெயரிடப்படாமல்) உருவாக்கபடலாம் +setTimeout(function(){ + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் +}, 5000); + +// JavaScript function ஒரு குறிப்பிட்ட scope(எல்லை) கொண்டுள்ளது ; +//functions தமக்கென ஒரு scope கொண்டுள்ளன . + +if (true){ + var i = 5; +} +i; // = 5 - //இது undefined அல்ல + +// இதன் காரணமாக anonymous functions உடனடியாக செயற்படுத்தபடுகின்றன +//இதன் மூலம் தற்காலிக மாறிகள்(variable) குளோபல் scope +//இற்கு மாறுவதை தவிர்க்கலாம் . +(function(){ + var temporary = 5; + //நாங்கள் ஒரு மாறியை எங்கிருந்தும் அணுக (access) அதை "global object" + //ஒன்றுக்கு வழங்க வேண்டும் உலாவியில் அது எப்போதும் `window` ஆகும் . + //உலாவி அல்லாத சூழலில் (Node.js) வேறு பெயருடன் இருக்கும் + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 + +//JavaScript's மிகவும் சக்தி வாய்ந்த ஒரு வசதி closures ஆகும் +//ஒரு function இன்னொரு function உள் உருவாக்கபடின் +//அது உருவாகப்பட்ட function இன் மாறிகளை அணுக முடியும் +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Inner functions ஆனது local scope இல் காணப்படும் + //அது `var ` என்ற குறியீட்டு சொல்லால் நிறுவப்படும் + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + //setTimeout ஆனது background இல் இயங்கும் , எனவே sayHelloInFiveSeconds function, + //செயற்பாடு முடிவடைய ,setTimeout ஆனது inner function call செய்யும். + +} +sayHelloInFiveSeconds("Adam"); // //இது ஒரு popup ஐ ஐந்து செக்கன்களில் காட்டும் + +/////////////////////////////////// +// 5. Objects; Constructors and Prototypes பற்றி மேலும் + +// Objects functions ஐ கொண்டிருக்கலாம் +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +//functions ஆனது objects உடன் இணைக்கப்பட்டுள போது அவை object ஐ அணுக முடியும் +//அவை this என்ற குறியீட்டு சொல்லை பயன்படுத்தி இணைக்கபடுகின்றன +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +//எங்கள் function ஆனது தொழிற் படாமல் போகலாம் அது context(அமைப்பு ) of the object call செய்யபடவிடின் +var myFunc = myObj.myFunc; +myFunc(); // = undefined + + +//function ஆனது ஒரு object உக்கு assign செய்யலாம் பிறகு அதை நாம் அணுகமுடியும் +//`this` மூலம் +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +//ஒரு function ஒரு அமைப்பை நாம் உருவாக்க முடியும் +//அதை நாம் `call` அல்லது `apply` மூலம் செயல்படுத்த முடியும் + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +//apply செயற்பாட்டளவில் ஒத்தன ,ஆனால் அது array (அணி) argument +//ஆக எடுக்கிறது. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +//இது தொடர்ச்சியான arguments ஐ நாம் function ஒன்றுக்குள் pass பண்ண +//வேண்டும் எனில் மிகவும் உபயோகமானது + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +//ஆனால் `call ` ,`apply ` இரண்டும் தற்காலிகமானவை +//அவற்றை நிரந்தரமாக்க bind function ஐ பயன்படுத்தவும் + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +//`bind ` ஐ உபயோகித்து ஒரு function ஐ பகுதியாக apply செய்ய முடியும் + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + + +//ஒரு function ஐ நாம் new என்ற குறியீட்டு சொல்லை பயன்படுத்தி +//அழைக்கும் போது புதிய object உருவாக்கப்படும் .இவ்வாறான functions +//constructors என அழைக்கப்படும் + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +//ஒவ்வொரு JavaScript object உம் ஒரு `prototype ` கொண்டுள்ளது +//நீங்கள் object ஒன்றின் ஒரு property ஐ அணுகும் போது +//அந்த property இல்லாவிடின் interpreter ஆனது +//அதன் prototype உள்ளதா என பார்க்கும் + +//JS இன் சில செயலாக்கங்கள் ஒரு object இன் protoype ஐ +//இலகுவாக `__proto__` மூலம் access செய்ய முடியும் . +//இது prototype பாவணை யை இலகுவாக்கினாலும் +//இது சரியான ஒரு முறை அல்ல +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// This works for functions, too. +myObj.myFunc(); // = "hello world!" + +//உங்கள் property prototype இல் இல்லது இருப்பின் , protype இன் +//prototype search செய்யப்படும் +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +//ஒவ்வொரு object உம் அதன் protype க்கும் reference (மேற்கோள் ) ஒன்றை வைத்திருக்கும் +//நாம் ஒரு protype இணை மாற்றினால் அதன் மாற்றங்கள் எல்லா இடத்திலும் (program இல் ) +//பிரதிபலிக்கும் +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + + +//நாம் முன்பு கூறியது போல் `__proto__` பயன்படுத்துவது சரியான முறை அல்ல +//எனவே நாம் ஒரு protype ஐ object இல் உருவாக்க இரண்டு வழிமுறைகள் +//உள்ளன + +// முதல் முறை Object.create இது அண்மையில் அறிமுகம் செய்ய பட்ட ஒன்று +//எனவே சில இடங்களில் இந்த முறை இன்னும் அறிமுகம் ஆகவில்லை + +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + + +// இரண்டாவது முறை , இது சகல இடங்களிலும் வேலைசெய்யும், இது constructors மூலம். +//constructors prototype என்னும் ஒரு காரணியை கொண்டுள்ளது , இது constructor function +//இன் prototype அன்று. ,இது நாம் new என்ற குறியீட்டு சொல்லையும் அந்த constructor உபயோகித்து +//உருவாக்கபடுகிறது + +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Built-in types like strings and numbers also have constructors that create +// equivalent wrapper objects. +// JavaScript இல் உள்ள strings மற்றும் numbers வகைகளும் constructors கொண்டுள்ளன +//இவை wrapper objects ஐ ஒத்தன + +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + + +//இவை மிக சிறிய அளவில் ஒத்தவை +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // இந்த கூற்றானது செயல்படுத்தபடாது ஏனெனில் ௦ false ஆகும் +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. + +//இருப்பினும் wrapper objects மற்றும் regular builtins ஆகியன prototype ஒன்றை கொண்டுள்ளன +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +//இந்த முறையானது "polyfilling" இல் உபயோகபடுத்தபடுகிறது. +//புதிய சில வசதிகளை JavaScript பழைய JavaScript பிரதிகளில் இல் உருவாக்குகிறது. +//இது பழைய சூழல்களில் உபயோகிகப்படும். + + +//நாங்கள் முன்பு கூறி இருந்தோம் Object.create சில இடங்களில் இந்த முறை இன்னும் +//அறிமுகம் ஆகவில்லை என்று ஆனால் இதை polyfill ஐ பயன்படுத்தி உருவாக்க +//முடியும் + +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +## மேலும் JavaScript பற்றி கற்க + +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides +excellent documentation for JavaScript as it's used in browsers. Plus, it's a +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +covers much of the concepts covered here in more detail. This guide has quite +deliberately only covered the JavaScript language itself; if you want to learn +more about how to use JavaScript in web pages, start by learning about the +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +guide of all the counter-intuitive parts of the language. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. + +In addition to direct contributors to this article, some content is adapted +from Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. diff --git a/ta_in/javascript.html.markdown b/ta_in/javascript.html.markdown deleted file mode 100644 index f0b0a36a..00000000 --- a/ta_in/javascript.html.markdown +++ /dev/null @@ -1,594 +0,0 @@ ---- -language: javascript -contributors: - - ['Adam Brenecki', 'http://adam.brenecki.id.au'] - - ['Ariel Krakowski', 'http://www.learneroo.com'] -translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: javascript.js -lang:in-ta ---- - -javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich -என்பவரால் உருவாக்கபட்டது.ஆரம்பத்தில் மிகவும் எளிமையான -ஸ்க்ரிப்டிங் மொழியாக இணையதளங்களில் பயன்படுத்தபட்டது. -இது ஜாவா (java ) வில் உருவாக்கபட்ட மிகவும் சிக்கலான இணைய செயலிகளுக்கு -உதவும் முகமாக உருவாக்கபட்டது. எனினும் இணையதள பக்கங்களில் இதன் முழுதான பயன்பாடு -மற்றும் உலாவிகளில் பயன்படுத்த கூடிய வகையில் இருந்தமையாலும் Java வை விட -இணையதளகளின் முகப்பு உருவாக்கத்தில் இன்றளவில் முன்னிலை பெற்றுள்ளது. - -உலாவிகளுக்கு மட்டும் மட்டுபடுத்தபடவில்லை , Node.js மூலமாக -மிகவும் பிரபல்யமடைந்து வருகின்றது , உதாரணமாக கூகிள்க்ரோம் உலாவியின் -V8 JavaScript engine Node .js உதவியுடன் இயங்குகிறது . - -உங்கள் கருத்துக்கள் மிகவும் வரவேற்கபடுகின்றன , என்னுடன் தொடர்புகொள்ள -[@adambrenecki](https://twitter.com/adambrenecki), or -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). - -```js -// குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும் - -/* பலவரி குறிப்புக்கள் "/*" ஆரம்பமாகி "/*" இல் முடிவடையும் */ - -// ஒரு கூற்று முற்றுபெற செய்ய ; இடல் வேண்டும் . -doStuff(); - -// ...ஆனால் அரைபுள்ளி இட வேண்டும் என்று அவசியம் இல்லை ஏன் எனில் -// ஒரு வரி புதிதாக இடப்படும் போது அரைபுள்ளிகள் தானாகவே இடப்படும் ஆனால் சில தருணங்களை தவிர . -doStuff() - -// ஆனால் அவ்வாறான தருணங்கள் எதிர்பாராத முடிவுகளை தரலாம் - -// எனவே நாம் தொடர்ந்து ஒரு கூற்று நிறைவடையும் போது அரைபுள்ளி ஒன்றை இடுவோம் . - -/////////////////////////////////// -// 1. எண்கள்(Number) ,சரம் (String),செயற்குறிகள்(Operators) - -// JavaScript ஒரே ஒரு எண்வகை காணப்படுகிறது தசமி (which is a 64-bit IEEE 754 double). -// தசமி எண்வகை (Doubles) 2^ 52 வரை சேமிக்க கூடியது -// முழு எண்வகையின் 9✕10¹⁵ சேமிக்க போதுமானது . -3; // = 3 -1.5; // = 1.5 - -// அடிப்படை கணித பொறிமுறைகள் -1 + 1; // = 2 -0.1 + 0.2; // = 0.30000000000000004 -8 - 1; // = 7 -10 * 2; // = 20 -35 / 5; // = 7 - -// வகுத்தல் -5 / 2; // = 2.5 - - -//bitwise பொறிமுறையை உபயோகிக்கும் போது -//உங்கள் தசம எண்ணின் பெறுமானமானது ஒரு நேர் அல்லது மறை அல்லது பூசியமாகவுள்ள முழு எண்ணாக -//மாற்றம் பெறுகிறது இது 32 இருமம்(bit) வரை செல்லலாம் - -1 << 2; // = 4 - -// நிரலாக்கத்தில் செயலியை அமுல்படுத்தும் வரிசைமுறையில் அடைப்பு குறிக்கு முன்னிலை வழங்கபடுகிறது -(1 + 3) * 2; // = 8 - -// மெய் எண் அல்லாத மூன்றுபெறுமானங்கள் உள்ளன : -Infinity; // result of e.g. 1/0 --Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0, இது எண் அல்ல என்பதை குறிக்கும் - -// தர்க ரீதியில் ஆன கட்டமைப்பு காணப்படுகிறது . -true; -false; - -// சரம் (string) ' அல்லது " குறியீட்டினால் உருவாக்கபடுகிறது -'abc'; -"Hello, world"; - -// ஒரு boolean பெறுமானத்தின் எதிர்மறை பெறுமானத்தை பெற ! குறியீடு பயன்படுத்தபடுகிறது -!true; // = false -!false; // = true - -// சமமா என பார்க்க === -1 === 1; // = true -2 === 1; // = false - -// சமனற்றவையா என பார்க்க !== -1 !== 1; // = false -2 !== 1; // = true - -// மேலும் சில ஒப்பீடுகள் -1 < 10; // = true -1 > 10; // = false -2 <= 2; // = true -2 >= 2; // = true - -// இரண்டு சரங்களை(Strings) ஒன்றாக இணைப்பதற்கு + -"Hello " + "world!"; // = "Hello world!" - -// இரண்டு மாறிகளை/பெறுமானங்களை ஒப்பிட < and > -"a" < "b"; // = true - -// இரண்டு பெறுமானங்கள் / மாறிகள் ஒரேவகையை சேர்ந்தவையா என பார்க்க -"5" == 5; // = true -null == undefined; // = true - -// ...இல்லாவிடின் === -"5" === 5; // = false -null === undefined; // = false - -// ...கிழே உள்ள கூற்றுகள் எதிர்பாராத -வெளியீடுகளை தரலாம் ... -13 + !0; // 14 -"13" + !0; // '13true' - -// ஒரு சரத்தில்(string ) உள்ள எழுத்தை பெற `charAt` -"This is a string".charAt(0); // = 'T' - - -//... ஒரு சரத்தை(string ) சொற்களாக பிரிக்க (substring) `substring -"Hello world".substring(0, 5); // = "Hello" - -// `length` ஒரு சரத்தில்(string) உள்ள சொற்களின் எண்ணிக்கை அல்லது நீளத்தை(length)அறிய -"Hello".length; // = 5 - -// `null` மற்றும் `undefined` இரு பெறுமானங்கள் உள்ளன . -null; // மதிப்பு அற்ற ஒரு பெறுமானத்தை குறிக்கும் -undefined; // பெறுமானம் இன்னும் நிர்ணயிக்க படவில்லை என்பதை குறிக்கும் ( - // `undefined` இருப்பினும் இதுவும் ஒரு பெறுமானமாக கருதபடுகிறது ) - -// ஆகியன தர்க்க ரீதியாக பிழையானவை(false) , மற்றவை யாவும் சரியானவை (true). -// 0 மானது பிழையை (false) குறிக்கும் "0" சரியை (true) குறிக்கும் எனினும் 0 == "0". - -/////////////////////////////////// -// 2. மாறிகள் (Variables),அணிகள் (Arrays) மற்றும் பொருட்கள் (Objects) - -// மாறிகளை உருவாக்க `var ` என்னும் குறியீட்டு சொல் (keyword ) பயன்படுகிறது . -//உருவாக்கப்படும் மாறிகள் எந்த வகையை சார்ந்தன என்பதை JavaScript -//தானாகவே நிர்ணயிக்கும் . மாறிக்கு ஒரு பெறுமானத்தை வழங்க `=` பாவிக்க -var someVar = 5; - -// //நீங்கள் மாறிகளை நிறுவ 'var' குறியீட்டு சொல்லை பயன்படுத்தா விடினும் -//அது தவறில்லை ... -someOtherVar = 10; - -// ...ஆனால் நீங்கள் நிறுவிய மாறி(variable) எல்லா உங்கள் ப்ரோக்ராம் இன் சகல இடங்களிலும் -//அணுக கூடியதாய் அமையும் , இல்லாவிடின் அது ஒரு குறிபிட்ட இடத்திற்கு மட்டும் -//மட்டுபடுத்தபடும் . - -//பெறுமானம் வழங்கபடாத மாறிகளுக்கு ,இயல்பாக/தானாக undefined என்ற பெறுமானம் -//வழங்கப்படும் -var someThirdVar; // = undefined - -// மாறிகளில் கணித செயல்பாடுகளை நடத்த சுருக்கெழுத்து முறைகள் காணப்படுகின்றன : -someVar += 5; // இது someVar = someVar + 5; ஐ ஒத்தது someVar இன் பெறுமானம் இப்போது 10 -someVar *= 10; // someVar இன் பெறுமானம் இப்போது 100 - -//மிகவும் சுருக்கமான சுருகேழுத்து முறை கூட்டல் அல்லது கழித்தல் செயன்முறையை -//மேற்கொள்ள -someVar++; // someVar இன் பெறுமானம் இப்போது is 101 -someVar--; // someVar இன் பெறுமானம் இப்போது 100 - -// அணிகள்(Arrays) எல்லாவகையான பெறுமானங்களையும் உள்ளடக்க கூடியது -var myArray = ["Hello", 45, true]; - -// அணிகள்(Arrays) உறுப்பினர்கள் சதுர அடைப்புக்குறிக்குள் அதன் தான இலக்கத்தை கொண்டு -//அணுகமுடியும் . -// அணிகளில் உள்ள உறுப்புகள் 0 இருந்து ஆரம்பமாகும் . -myArray[1]; // = 45 - -// அணிகள் உள்ள உறுப்புகளை மாற்றமுடியும் அத்துடன் உறுப்புகளின் எண்ணிக்கையும் மாறலாம் . -myArray.push("World"); -myArray.length; // = 4 - -// அணியில்(Array) ஒரு குறிப்பிட்ட இடத்தில உள்ள பெறுமானத்தை மாற்ற . -myArray[3] = "Hello"; - -// JavaScript's பொருள் (objects) அகராதியை ஒத்தன -// ஒழுங்கு படுத்த படாத சேகரிப்பு (collection) ஆகும் இதில் ஒரு சாவியும்(key) -//அதுக்குரிய பெறுமானமும்(value) காணப்படும் . -var myObj = {key1: "Hello", key2: "World"}; - -// விசைகள் சரங்களை, ஆனால் அவர்கள் சரியான என்றால் மேற்கோள் அவசியம் இல்லை -//சாவிகளை உ.ம் : "key" என நிறுவலாம் ஆனால் , மேற்கோள் ஆனது சாவி முன்பே நிறுவபட்டிருப்பின் -//அவசியம் இல்லை -// சாவிகளுக்குரிய பெறுமானங்கள் எந்த வகையாகவும் இருக்கலாம் -var myObj = {myKey: "myValue", "my other key": 4}; - -//பொருள் பண்புகளை சதுர அடைப்புக்குறிக்குள் அதன் சாவியின் பெயரை (key) கொண்டு -//அணுகமுடியும் , -myObj["my other key"]; // = 4 - -// ... அல்லது புள்ளி குறியீட்டை பயன்படுத்தி ,சாவியின் (key is a valid identifier) -//பெயர் மூலம் அணுக முடியும் -myObj.myKey; // = "myValue" - -// பொருட்கள்(ஒப்ஜெக்ட்ஸ்) மாற்றபடகூடியான சாவிகளின் பெறுமதிகளை மாற்ற முடியும் அத்துடன் புதிய -//சாவிகளை(keys) இடவும் முடியும் -myObj.myThirdKey = true; - -//பெறுமதி வரையறுக்கபடாத ஒரு சாவியினை அணுகும் போது -//அது வெளியிடும் பெறுமதி `undefined`. -myObj.myFourthKey; // = undefined - -/////////////////////////////////// -// 3. தர்க்கம் மற்றும் கட்டுப்பாட்டு கட்டமைப்பு - -// கீழே காட்டப்பட்டுள்ள தொடரியல் ஜாவா வை ஒத்தது - -// The `if` ஒரு குறித்த தர்க்கம் சரியாயின் -//அல்லது என்ற வடிவமைப்பை -var count = 1; -if (count == 3){ - // count இன் பெறுமானம் 3 சமமா என பார்க்கபடுகிறது -} else if (count == 4){ - // count இன் பெறுமானம் 4க்கு சமமா என பார்க்கபடுகிறது -} else { - // count ஆனது 3 அல்ல 4 அல்ல எனின் -} - -// ஒரு குறிப்பிட்ட ஒப்பீடு உண்மையாக இருக்கும் வரை `while`. -while (true){ - // இந்த இருக்கும் கூற்றுகள் முடிவிலி தடவை மறுபடி செயற்படுத்தப்படும் ! -} - -// while போல் அல்லாது do-while ,அவை ஒரு தடவையேனும் அதனுள் உள்ள கூற்றுகள் செயற்படுத்தபடும் -var input; -do { - input = getInput(); -} while (!isValid(input)) - -// for (loop /சுற்று ) C , ஜாவாவை ஒத்தது -//மாறிக்கு பெறுமானத்தை வழங்கல் , மாறியானது தர்க்கத்தை பூர்த்தி செய்கிறதா என பார்த்தல் , -//சுற்றுக்குள் இருக்கும் கூற்றை செயற்படுதல் - -for (var i = 0; i < 5; i++){ - // இந்த சுற்று 5 தடவைகள் தொடர்ந்து செயற்படுத்தபடும் -} - -//for /In சுற்றுகள் prototype சங்கிலியில் உள்ள சகல காரணிகள் ஊடகவும் செல்லும் -var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; -for (var x in person){ - description += person[x] + " "; -} - -//ஒரு பொருளில் (Object) இடப்பட்ட பண்புகளை (properties) கருத்தில் கொள்ளும் போது -//குறிப்பிட்ட பண்புகளை அந்த Object கொண்டுள்ளதா என பார்க்க -var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; -for (var x in person){ - if (person.hasOwnProperty(x)){ - description += person[x] + " "; - } -} - -//for /in ஆனது அணியில் உள்ள பண்புகள் ஒழுங்குபடுத்தப்பட்டவிதம் முக்கியம் -//ஆயின் பாவிப்பதை தவிர்க்கவும் ஏனெனில் அது சரியான ஒழுங்கில் -//வெளியீட்டை தரும் என்பது ஐயம் ஆகும் - -// && is logical and, || is logical or -if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear"; -} -if (colour == "red" || colour == "blue"){ - // colour is either red or blue -} - -// && and || "short circuit", which is useful for setting default values. -var name = otherName || "default"; - - - -grade = 'B'; -switch (grade) { - case 'A': - console.log("Great job"); - break; - case 'B': - console.log("OK job"); - break; - case 'C': - console.log("You can do better"); - break; - default: - console.log("Oy vey"); - break; -} - - -/////////////////////////////////// -// 4. Functions, Scope and Closures - -// JavaScript இல் functions நிறுவ `function` keyword.பயன்படும் -function myFunction(thing){ - return thing.toUpperCase(); -} -myFunction("foo"); // = "FOO" - -//ஒரு பெறுமானத்தை return செய்ய வேண்டும் எனின் இரண்டும் ஒரே வரியில் -//இருக்க வேண்டும் இல்லாவிடின் return ஆனது `undefined ` return செய்யும் -//காற் புள்ளி தானாகவே இடப்படும் , நீங்கள் Allman style உபயோகிக்கும் போது -//அவதானமாக இருக்கவும் -function myFunction() -{ - return // <- semicolon automatically inserted here - { - thisIsAn: 'object literal' - } -} -myFunction(); // = undefined - -// JavaScript functions ஆனது first class objects ஆகும் ,எனவே அவற்றை மாறிகளுக்கு -//assign செய்ய முடியும் அதுமட்டும் அல்லது functions களில் arguments ஆக அனுப்பமுடியும் -// உதாரணமாக ஒரு event handler: -function myFunction(){ - //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் -} -setTimeout(myFunction, 5000); -// Note: setTimeout ஆனது ஜாவஸ்க்ரிப்ட் சேர்ந்தது அன்று , ஆனால் அந்த வசதி -//உலாவிகளிலும் ,Node .js காணப்படுகிறது - -// Function objects கட்டாயம் பெயரிடப்பட வீண்டும் என்று அவசியம் இல்லை -// அவை anonymous(பெயரிடப்படாமல்) உருவாக்கபடலாம் -setTimeout(function(){ - //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் -}, 5000); - -// JavaScript function ஒரு குறிப்பிட்ட scope(எல்லை) கொண்டுள்ளது ; -//functions தமக்கென ஒரு scope கொண்டுள்ளன . - -if (true){ - var i = 5; -} -i; // = 5 - //இது undefined அல்ல - -// இதன் காரணமாக anonymous functions உடனடியாக செயற்படுத்தபடுகின்றன -//இதன் மூலம் தற்காலிக மாறிகள்(variable) குளோபல் scope -//இற்கு மாறுவதை தவிர்க்கலாம் . -(function(){ - var temporary = 5; - //நாங்கள் ஒரு மாறியை எங்கிருந்தும் அணுக (access) அதை "global object" - //ஒன்றுக்கு வழங்க வேண்டும் உலாவியில் அது எப்போதும் `window` ஆகும் . - //உலாவி அல்லாத சூழலில் (Node.js) வேறு பெயருடன் இருக்கும் - window.permanent = 10; -})(); -temporary; // raises ReferenceError -permanent; // = 10 - -//JavaScript's மிகவும் சக்தி வாய்ந்த ஒரு வசதி closures ஆகும் -//ஒரு function இன்னொரு function உள் உருவாக்கபடின் -//அது உருவாகப்பட்ட function இன் மாறிகளை அணுக முடியும் -function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!"; - // Inner functions ஆனது local scope இல் காணப்படும் - //அது `var ` என்ற குறியீட்டு சொல்லால் நிறுவப்படும் - function inner(){ - alert(prompt); - } - setTimeout(inner, 5000); - //setTimeout ஆனது background இல் இயங்கும் , எனவே sayHelloInFiveSeconds function, - //செயற்பாடு முடிவடைய ,setTimeout ஆனது inner function call செய்யும். - -} -sayHelloInFiveSeconds("Adam"); // //இது ஒரு popup ஐ ஐந்து செக்கன்களில் காட்டும் - -/////////////////////////////////// -// 5. Objects; Constructors and Prototypes பற்றி மேலும் - -// Objects functions ஐ கொண்டிருக்கலாம் -var myObj = { - myFunc: function(){ - return "Hello world!"; - } -}; -myObj.myFunc(); // = "Hello world!" - -//functions ஆனது objects உடன் இணைக்கப்பட்டுள போது அவை object ஐ அணுக முடியும் -//அவை this என்ற குறியீட்டு சொல்லை பயன்படுத்தி இணைக்கபடுகின்றன -myObj = { - myString: "Hello world!", - myFunc: function(){ - return this.myString; - } -}; -myObj.myFunc(); // = "Hello world!" - -//எங்கள் function ஆனது தொழிற் படாமல் போகலாம் அது context(அமைப்பு ) of the object call செய்யபடவிடின் -var myFunc = myObj.myFunc; -myFunc(); // = undefined - - -//function ஆனது ஒரு object உக்கு assign செய்யலாம் பிறகு அதை நாம் அணுகமுடியும் -//`this` மூலம் -var myOtherFunc = function(){ - return this.myString.toUpperCase(); -} -myObj.myOtherFunc = myOtherFunc; -myObj.myOtherFunc(); // = "HELLO WORLD!" - -//ஒரு function ஒரு அமைப்பை நாம் உருவாக்க முடியும் -//அதை நாம் `call` அல்லது `apply` மூலம் செயல்படுத்த முடியும் - -var anotherFunc = function(s){ - return this.myString + s; -} -anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" - -//apply செயற்பாட்டளவில் ஒத்தன ,ஆனால் அது array (அணி) argument -//ஆக எடுக்கிறது. - -anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" - -//இது தொடர்ச்சியான arguments ஐ நாம் function ஒன்றுக்குள் pass பண்ண -//வேண்டும் எனில் மிகவும் உபயோகமானது - -Math.min(42, 6, 27); // = 6 -Math.min([42, 6, 27]); // = NaN (uh-oh!) -Math.min.apply(Math, [42, 6, 27]); // = 6 - -//ஆனால் `call ` ,`apply ` இரண்டும் தற்காலிகமானவை -//அவற்றை நிரந்தரமாக்க bind function ஐ பயன்படுத்தவும் - -var boundFunc = anotherFunc.bind(myObj); -boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" - -//`bind ` ஐ உபயோகித்து ஒரு function ஐ பகுதியாக apply செய்ய முடியும் - -var product = function(a, b){ return a * b; } -var doubler = product.bind(this, 2); -doubler(8); // = 16 - - -//ஒரு function ஐ நாம் new என்ற குறியீட்டு சொல்லை பயன்படுத்தி -//அழைக்கும் போது புதிய object உருவாக்கப்படும் .இவ்வாறான functions -//constructors என அழைக்கப்படும் - -var MyConstructor = function(){ - this.myNumber = 5; -} -myNewObj = new MyConstructor(); // = {myNumber: 5} -myNewObj.myNumber; // = 5 - -//ஒவ்வொரு JavaScript object உம் ஒரு `prototype ` கொண்டுள்ளது -//நீங்கள் object ஒன்றின் ஒரு property ஐ அணுகும் போது -//அந்த property இல்லாவிடின் interpreter ஆனது -//அதன் prototype உள்ளதா என பார்க்கும் - -//JS இன் சில செயலாக்கங்கள் ஒரு object இன் protoype ஐ -//இலகுவாக `__proto__` மூலம் access செய்ய முடியும் . -//இது prototype பாவணை யை இலகுவாக்கினாலும் -//இது சரியான ஒரு முறை அல்ல -var myObj = { - myString: "Hello world!" -}; -var myPrototype = { - meaningOfLife: 42, - myFunc: function(){ - return this.myString.toLowerCase() - } -}; - -myObj.__proto__ = myPrototype; -myObj.meaningOfLife; // = 42 - -// This works for functions, too. -myObj.myFunc(); // = "hello world!" - -//உங்கள் property prototype இல் இல்லது இருப்பின் , protype இன் -//prototype search செய்யப்படும் -myPrototype.__proto__ = { - myBoolean: true -}; -myObj.myBoolean; // = true - -//ஒவ்வொரு object உம் அதன் protype க்கும் reference (மேற்கோள் ) ஒன்றை வைத்திருக்கும் -//நாம் ஒரு protype இணை மாற்றினால் அதன் மாற்றங்கள் எல்லா இடத்திலும் (program இல் ) -//பிரதிபலிக்கும் -myPrototype.meaningOfLife = 43; -myObj.meaningOfLife; // = 43 - - -//நாம் முன்பு கூறியது போல் `__proto__` பயன்படுத்துவது சரியான முறை அல்ல -//எனவே நாம் ஒரு protype ஐ object இல் உருவாக்க இரண்டு வழிமுறைகள் -//உள்ளன - -// முதல் முறை Object.create இது அண்மையில் அறிமுகம் செய்ய பட்ட ஒன்று -//எனவே சில இடங்களில் இந்த முறை இன்னும் அறிமுகம் ஆகவில்லை - -var myObj = Object.create(myPrototype); -myObj.meaningOfLife; // = 43 - - -// இரண்டாவது முறை , இது சகல இடங்களிலும் வேலைசெய்யும், இது constructors மூலம். -//constructors prototype என்னும் ஒரு காரணியை கொண்டுள்ளது , இது constructor function -//இன் prototype அன்று. ,இது நாம் new என்ற குறியீட்டு சொல்லையும் அந்த constructor உபயோகித்து -//உருவாக்கபடுகிறது - -MyConstructor.prototype = { - myNumber: 5, - getMyNumber: function(){ - return this.myNumber; - } -}; -var myNewObj2 = new MyConstructor(); -myNewObj2.getMyNumber(); // = 5 -myNewObj2.myNumber = 6 -myNewObj2.getMyNumber(); // = 6 - -// Built-in types like strings and numbers also have constructors that create -// equivalent wrapper objects. -// JavaScript இல் உள்ள strings மற்றும் numbers வகைகளும் constructors கொண்டுள்ளன -//இவை wrapper objects ஐ ஒத்தன - -var myNumber = 12; -var myNumberObj = new Number(12); -myNumber == myNumberObj; // = true - - -//இவை மிக சிறிய அளவில் ஒத்தவை -typeof myNumber; // = 'number' -typeof myNumberObj; // = 'object' -myNumber === myNumberObj; // = false -if (0){ - // இந்த கூற்றானது செயல்படுத்தபடாது ஏனெனில் ௦ false ஆகும் -} - -// However, the wrapper objects and the regular builtins share a prototype, so -// you can actually add functionality to a string, for instance. - -//இருப்பினும் wrapper objects மற்றும் regular builtins ஆகியன prototype ஒன்றை கொண்டுள்ளன -String.prototype.firstCharacter = function(){ - return this.charAt(0); -} -"abc".firstCharacter(); // = "a" - -// This fact is often used in "polyfilling", which is implementing newer -// features of JavaScript in an older subset of JavaScript, so that they can be -// used in older environments such as outdated browsers. - -//இந்த முறையானது "polyfilling" இல் உபயோகபடுத்தபடுகிறது. -//புதிய சில வசதிகளை JavaScript பழைய JavaScript பிரதிகளில் இல் உருவாக்குகிறது. -//இது பழைய சூழல்களில் உபயோகிகப்படும். - - -//நாங்கள் முன்பு கூறி இருந்தோம் Object.create சில இடங்களில் இந்த முறை இன்னும் -//அறிமுகம் ஆகவில்லை என்று ஆனால் இதை polyfill ஐ பயன்படுத்தி உருவாக்க -//முடியும் - -if (Object.create === undefined){ // don't overwrite it if it exists - Object.create = function(proto){ - // make a temporary constructor with the right prototype - var Constructor = function(){}; - Constructor.prototype = proto; - // then use it to create a new, appropriately-prototyped object - return new Constructor(); - } -} -``` - -## மேலும் JavaScript பற்றி கற்க - -The [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides -excellent documentation for JavaScript as it's used in browsers. Plus, it's a -wiki, so as you learn more you can help others out by sharing your own -knowledge. - -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -covers much of the concepts covered here in more detail. This guide has quite -deliberately only covered the JavaScript language itself; if you want to learn -more about how to use JavaScript in web pages, start by learning about the -[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) - -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. - -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. - -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. - -In addition to direct contributors to this article, some content is adapted -from Louie Dinh's Python tutorial on this site, and the [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -on the Mozilla Developer Network. -- cgit v1.2.3 From 32d040d3b4c4f1e8b022e27614531a462c9bb344 Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:15:57 +0800 Subject: Rename json.html.markdown to json-ta.html.markdown --- ta_in/json-ta.html.markdown | 86 +++++++++++++++++++++++++++++++++++++++++++++ ta_in/json.html.markdown | 86 --------------------------------------------- 2 files changed, 86 insertions(+), 86 deletions(-) create mode 100644 ta_in/json-ta.html.markdown delete mode 100644 ta_in/json.html.markdown diff --git a/ta_in/json-ta.html.markdown b/ta_in/json-ta.html.markdown new file mode 100644 index 00000000..d85e0d82 --- /dev/null +++ b/ta_in/json-ta.html.markdown @@ -0,0 +1,86 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +lang: ta-in +--- + +ஜேசன் ஒரு ஒரு மிக எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். +Learn X in Y Minutes இதுவே மிகவும் இலகுவான பகுதியாக அமைய போகிறது. + + +ஜேசன் இன் எளிமையான கட்டமைப்பில் குறிப்புக்கள் (Comments) இல்லை , எனினும் +பெரும்பாலான பாகுபடுத்திகளில் C - style முறையிலான (`//`, `/* */`) குறிப்புகளை இட முடியும். +சில பாகுபடுத்திகள்(interpreter) குறிப்புகளுக்கு (comments)தொடர்ச்சியாக வரும் + காற்புள்ளியை அனுமதிக்கின்றன (உதாரணமாக ஒரு அணியை (array) அடுத்துவரும் காற்புள்ளி + அல்லது ஒரு பொருளில் (object)உள்ள கடைசி உறுப்பை/சொத்தை( last property) அடுத்து வரும் காற்புள்ளி ) +எனினும் சகல இடங்களிலும் ஜேசன் பயன்படுத்த பட வேண்டும் எனில் மேற்கூறிய குறிப்புகளை தவிர்த்தல் நல்லது .\ + + +ஜேசன் 100% மிக சரியாக அமைவது மட்டும் இன்றி +இலகுவாக புரியக் கூடிய எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். + + +ஜேசன் அனுமதிக்கும் தரவு வகைகள் : சரம் (string),முழு (int),பூலியன் (தர்க ரீதியில் ஆன கட்டமைப்பு), +அணி (array ),கழி (null ),பொருள் (object). + +ஜேசன் அனுமதிக்கும் அல்லது பாவனைக்கு உட்படுத்த கூடிய உலாவிகள் (browsers): +Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. + +ஜேசனின் கோப்புவகை(filetype) ".json " ஆகும் . + +ஜேசன் உரைக்கான MIME வகை "application/json" ஆகும். +ஜேசன் இல் காணப்படும் பிரதான பின்னடைவு தரவு இனம் இதுவென்று வரையறுக்க +படாமை ஆகும் . + +ஒரு ஜேசன் இன் எளிய கட்டமைப்பு கீழே காட்டப்பட்டுள்ளது + +```json +{ + "key": "ஒரு சாவிக்கு ஒரு பெறுமதி உள்ளது ", + + "keys": "சாவிகள் , மற்றும் பெறுமானங்கள் மேற்கோள் குறிக்குள் இடல் வேண்டும்", + "numbers": 0, + "strings": "Hellø, wørld. எல்லாவகையான unicode உம் அனுமதிக்கப்படும், அத்துடன் \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "பெரும்பாலான கட்டமைப்புகள் objects இல் இருந்தே வருகின்றன", + + "array": [0, 1, 2, 3, "array யானது எல்லாவகையான பெறுமானங்களையும் கொண்டிருக்கும்", 5], + + "another object": { + "comment": "இவை ஒன்றுக்குள் இன்னொன்றை எழுத முடியும்" + } + }, + + "silliness": [ + { + "sources of potassium": ["வாழைபழம்"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternative style": { + "comment": "இதை பார்க்கவும்" + , "comma position": "doesn't matter - as long as it's before the value, then it's valid" + , "another comment": "how nice" + }, + + "that was short": "நீங்கள் ஜேசன் பற்றி யாவற்றையும் கற்றுள்ளீர்கள்" +} +``` + diff --git a/ta_in/json.html.markdown b/ta_in/json.html.markdown deleted file mode 100644 index d85e0d82..00000000 --- a/ta_in/json.html.markdown +++ /dev/null @@ -1,86 +0,0 @@ ---- -language: json -filename: learnjson.json -contributors: - - ["Anna Harren", "https://github.com/iirelu"] - - ["Marco Scannadinari", "https://github.com/marcoms"] - - ["himanshu", "https://github.com/himanshu81494"] -translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] -lang: ta-in ---- - -ஜேசன் ஒரு ஒரு மிக எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். -Learn X in Y Minutes இதுவே மிகவும் இலகுவான பகுதியாக அமைய போகிறது. - - -ஜேசன் இன் எளிமையான கட்டமைப்பில் குறிப்புக்கள் (Comments) இல்லை , எனினும் -பெரும்பாலான பாகுபடுத்திகளில் C - style முறையிலான (`//`, `/* */`) குறிப்புகளை இட முடியும். -சில பாகுபடுத்திகள்(interpreter) குறிப்புகளுக்கு (comments)தொடர்ச்சியாக வரும் - காற்புள்ளியை அனுமதிக்கின்றன (உதாரணமாக ஒரு அணியை (array) அடுத்துவரும் காற்புள்ளி - அல்லது ஒரு பொருளில் (object)உள்ள கடைசி உறுப்பை/சொத்தை( last property) அடுத்து வரும் காற்புள்ளி ) -எனினும் சகல இடங்களிலும் ஜேசன் பயன்படுத்த பட வேண்டும் எனில் மேற்கூறிய குறிப்புகளை தவிர்த்தல் நல்லது .\ - - -ஜேசன் 100% மிக சரியாக அமைவது மட்டும் இன்றி -இலகுவாக புரியக் கூடிய எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். - - -ஜேசன் அனுமதிக்கும் தரவு வகைகள் : சரம் (string),முழு (int),பூலியன் (தர்க ரீதியில் ஆன கட்டமைப்பு), -அணி (array ),கழி (null ),பொருள் (object). - -ஜேசன் அனுமதிக்கும் அல்லது பாவனைக்கு உட்படுத்த கூடிய உலாவிகள் (browsers): -Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. - -ஜேசனின் கோப்புவகை(filetype) ".json " ஆகும் . - -ஜேசன் உரைக்கான MIME வகை "application/json" ஆகும். -ஜேசன் இல் காணப்படும் பிரதான பின்னடைவு தரவு இனம் இதுவென்று வரையறுக்க -படாமை ஆகும் . - -ஒரு ஜேசன் இன் எளிய கட்டமைப்பு கீழே காட்டப்பட்டுள்ளது - -```json -{ - "key": "ஒரு சாவிக்கு ஒரு பெறுமதி உள்ளது ", - - "keys": "சாவிகள் , மற்றும் பெறுமானங்கள் மேற்கோள் குறிக்குள் இடல் வேண்டும்", - "numbers": 0, - "strings": "Hellø, wørld. எல்லாவகையான unicode உம் அனுமதிக்கப்படும், அத்துடன் \"escaping\".", - "has bools?": true, - "nothingness": null, - - "big number": 1.2e+100, - - "objects": { - "comment": "பெரும்பாலான கட்டமைப்புகள் objects இல் இருந்தே வருகின்றன", - - "array": [0, 1, 2, 3, "array யானது எல்லாவகையான பெறுமானங்களையும் கொண்டிருக்கும்", 5], - - "another object": { - "comment": "இவை ஒன்றுக்குள் இன்னொன்றை எழுத முடியும்" - } - }, - - "silliness": [ - { - "sources of potassium": ["வாழைபழம்"] - }, - [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, "neo"], - [0, 0, 0, 1] - ] - ], - - "alternative style": { - "comment": "இதை பார்க்கவும்" - , "comma position": "doesn't matter - as long as it's before the value, then it's valid" - , "another comment": "how nice" - }, - - "that was short": "நீங்கள் ஜேசன் பற்றி யாவற்றையும் கற்றுள்ளீர்கள்" -} -``` - -- cgit v1.2.3 From c677ba561290866ef791c2cb813afaf1aae09a32 Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:16:12 +0800 Subject: Rename xml.html.markdown to xml-ta.html.markdown --- ta_in/xml-ta.html.markdown | 145 +++++++++++++++++++++++++++++++++++++++++++++ ta_in/xml.html.markdown | 145 --------------------------------------------- 2 files changed, 145 insertions(+), 145 deletions(-) create mode 100644 ta_in/xml-ta.html.markdown delete mode 100644 ta_in/xml.html.markdown diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown new file mode 100644 index 00000000..a9bfa9cd --- /dev/null +++ b/ta_in/xml-ta.html.markdown @@ -0,0 +1,145 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +lang:in-ta +--- + + +XML ஆனது ஒரு கட்டமைப்பு மொழி ஆகும் இது தகவலை சேமிக்கவும் +தகவலை பரிமாறவும் உருவாக்கபட்டுள்ளது + + +HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது +* XML வாக்கிய அமைப்பு + + +```xml + + + + + + Everyday Italian + Giada De Laurentiis + 2005 + 30.00 + + + Harry Potter + J K. Rowling + 2005 + 29.99 + + + Learning XML + Erik T. Ray + 2003 + 39.95 + + + + + + + + + + +computer.gif + + +``` + +* சரியான முறையில் ஒழுகுபடுத்தபட்ட X document + + +ஒரு XML document ஆனது சரியான முறையில் எழுத பட்டிருப்பின் மட்டுமே அது +சிறந்த வகையில் வடிவமைக்கபட்டுள்ளது,எனினும் மேலும் பல கட்டுபாடுகளை +நாம் ஒரு xml document உக்கு இட முடியும் உ.ம்:-DTD மற்றும் XML Schema. + + +ஒரு xml document ஆனது ஒரு வரையறுக்கபட்டிருப்பின் மட்டுமே +அது சரி என கொள்ளப்படும் + + +With this tool, you can check the XML data outside the application logic. +இந்த கருவியை உபயோகித்து xml தகவல்களை சோதிக்க முடியும் + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` diff --git a/ta_in/xml.html.markdown b/ta_in/xml.html.markdown deleted file mode 100644 index a9bfa9cd..00000000 --- a/ta_in/xml.html.markdown +++ /dev/null @@ -1,145 +0,0 @@ ---- -language: xml -filename: learnxml.xml -contributors: - - ["João Farias", "https://github.com/JoaoGFarias"] -translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] -lang:in-ta ---- - - -XML ஆனது ஒரு கட்டமைப்பு மொழி ஆகும் இது தகவலை சேமிக்கவும் -தகவலை பரிமாறவும் உருவாக்கபட்டுள்ளது - - -HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது -* XML வாக்கிய அமைப்பு - - -```xml - - - - - - Everyday Italian - Giada De Laurentiis - 2005 - 30.00 - - - Harry Potter - J K. Rowling - 2005 - 29.99 - - - Learning XML - Erik T. Ray - 2003 - 39.95 - - - - - - - - - - -computer.gif - - -``` - -* சரியான முறையில் ஒழுகுபடுத்தபட்ட X document - - -ஒரு XML document ஆனது சரியான முறையில் எழுத பட்டிருப்பின் மட்டுமே அது -சிறந்த வகையில் வடிவமைக்கபட்டுள்ளது,எனினும் மேலும் பல கட்டுபாடுகளை -நாம் ஒரு xml document உக்கு இட முடியும் உ.ம்:-DTD மற்றும் XML Schema. - - -ஒரு xml document ஆனது ஒரு வரையறுக்கபட்டிருப்பின் மட்டுமே -அது சரி என கொள்ளப்படும் - - -With this tool, you can check the XML data outside the application logic. -இந்த கருவியை உபயோகித்து xml தகவல்களை சோதிக்க முடியும் - -```xml - - - - - - - - Everyday Italian - 30.00 - - - - - - - - - - -]> - - - - - - - - - - - - - -]> - - - - Everyday Italian - 30.00 - - -``` -- cgit v1.2.3 From 897159a9392b3c9be6a548c9cd0d85b6c4e20f37 Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:16:49 +0800 Subject: Rename brainfuck.html.markdown to brainfuck-fa.html.markdown --- fa-ir/brainfuck-fa.html.markdown | 81 ++++++++++++++++++++++++++++++++++++++++ fa-ir/brainfuck.html.markdown | 81 ---------------------------------------- 2 files changed, 81 insertions(+), 81 deletions(-) create mode 100644 fa-ir/brainfuck-fa.html.markdown delete mode 100644 fa-ir/brainfuck.html.markdown diff --git a/fa-ir/brainfuck-fa.html.markdown b/fa-ir/brainfuck-fa.html.markdown new file mode 100644 index 00000000..ef2bcba3 --- /dev/null +++ b/fa-ir/brainfuck-fa.html.markdown @@ -0,0 +1,81 @@ +--- +language: brainfuck +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +lang: fa-ir +--- + +

برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت

+

دستور است.

+ +

هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود.

+ + +`>` `<` `+` `-` `.` `,` `[` `]` + +

برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند.

+

همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند.

+ +

در زیر هشت دستور این زبان شرح داده شده است:

+ +

`+` : یک عدد به خانه ی فعلی اضافه می کند. +

`-` : یک عدد از خانه ی فعلی کم می کند.

+

`>` : اشاره گر به خانه ی بعدی میرود -- به راست

+

`<` : اشاره گر به خانه ی قبلی میرود -- به چپ

+

`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A

+

`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند.

+

`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود.

+

در غیر این صورت به دستور بعدی میرود.

+

`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب

+ +

دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند.

+ +

در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید.

+ +``` +++++++ [ > ++++++++++ < - ] > +++++ . +``` + +

این برنامه کارکتر A را بر روی خروجی چاپ میکند.

+

در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A

+

ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار

+

تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند.

+

-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود

+

بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند.

+ +``` +, [ > + < - ] > . +``` + +

در این برنامه ابتدا یک کارکتر از ورودی خوانده می شود. سپس یک حلقه به تعداد بار مقدار

+

عددی کارکتر، یک عدد به خانه ی دوم اضافه می کند. با این کار در واقع برنامه مقدار ورودی را در خانه ی

+

دوم کپی می کند. و در نهایت آن را برروی خروجی چاپ می کند.

+ +

توجه داشته باشید که ردر بالا فواصل بین دستور ها فقط برای خوانایی بیشتر گذاشته شده اند.

+

در واقع برنامه بالا به شکل زیر صحیح می باشد.

+ +``` +,[>+<-]>. +``` + +

حال سعی کنید ببینید که برنامه ی زیر چه کاری انجام می دهد؟

+ +``` +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> +``` + +

این برنامه دو عدد را از ورودی خوانده و با هم ضرب می کند.

+ +

ابتدا دو عدد از ورودی خوانده می شوند. سپس حلقه ی بیرونی بر روی خانه شماره یک شروع میشود.

+

و درون آن حلقه ی دیگری بر روی خانه ی دوم شروع میشود که خانه ی 3 را زیاد میکند.

+

ولی مشکلی که در اینجا به وجود می آید اینست که در پایان حلقه ی دوم مقدار خانه ی 2 صفر شده

+

و مقدار اولیه ی آن از دست رفته است. برای حل این مشکل خانه ی شماره چهار هم زیاد میشود

+

و در پایان حلقه مقدار آن به خانه 2 کپی میشود.

+

در پایان خانه ی شماره 2 حاوی حاصلضرب خواهد بود.

+ +
+ +

و این همه ی برین فاک بود! خیلی ساده برای یادگیری ولی سنگین برای به کار بردن.

+

حال می توانید برای تفریح مشغول نوشتن برنامه ی های مختلف با آن شوید.

+

و یا یک اجرا کننده برین فاک را با یک زبان دیگر پیاده سازی کنید.

+

و یا اگر خیلی دوست داشتید یک اجرا کننده ی برین فاک با برین فاک بنویسید!!

diff --git a/fa-ir/brainfuck.html.markdown b/fa-ir/brainfuck.html.markdown deleted file mode 100644 index ef2bcba3..00000000 --- a/fa-ir/brainfuck.html.markdown +++ /dev/null @@ -1,81 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Mohammad Valipour", "https://github.com/mvalipour"] -lang: fa-ir ---- - -

برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت

-

دستور است.

- -

هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود.

- - -`>` `<` `+` `-` `.` `,` `[` `]` - -

برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند.

-

همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند.

- -

در زیر هشت دستور این زبان شرح داده شده است:

- -

`+` : یک عدد به خانه ی فعلی اضافه می کند. -

`-` : یک عدد از خانه ی فعلی کم می کند.

-

`>` : اشاره گر به خانه ی بعدی میرود -- به راست

-

`<` : اشاره گر به خانه ی قبلی میرود -- به چپ

-

`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A

-

`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند.

-

`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود.

-

در غیر این صورت به دستور بعدی میرود.

-

`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب

- -

دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند.

- -

در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید.

- -``` -++++++ [ > ++++++++++ < - ] > +++++ . -``` - -

این برنامه کارکتر A را بر روی خروجی چاپ میکند.

-

در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A

-

ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار

-

تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند.

-

-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود

-

بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند.

- -``` -, [ > + < - ] > . -``` - -

در این برنامه ابتدا یک کارکتر از ورودی خوانده می شود. سپس یک حلقه به تعداد بار مقدار

-

عددی کارکتر، یک عدد به خانه ی دوم اضافه می کند. با این کار در واقع برنامه مقدار ورودی را در خانه ی

-

دوم کپی می کند. و در نهایت آن را برروی خروجی چاپ می کند.

- -

توجه داشته باشید که ردر بالا فواصل بین دستور ها فقط برای خوانایی بیشتر گذاشته شده اند.

-

در واقع برنامه بالا به شکل زیر صحیح می باشد.

- -``` -,[>+<-]>. -``` - -

حال سعی کنید ببینید که برنامه ی زیر چه کاری انجام می دهد؟

- -``` -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -``` - -

این برنامه دو عدد را از ورودی خوانده و با هم ضرب می کند.

- -

ابتدا دو عدد از ورودی خوانده می شوند. سپس حلقه ی بیرونی بر روی خانه شماره یک شروع میشود.

-

و درون آن حلقه ی دیگری بر روی خانه ی دوم شروع میشود که خانه ی 3 را زیاد میکند.

-

ولی مشکلی که در اینجا به وجود می آید اینست که در پایان حلقه ی دوم مقدار خانه ی 2 صفر شده

-

و مقدار اولیه ی آن از دست رفته است. برای حل این مشکل خانه ی شماره چهار هم زیاد میشود

-

و در پایان حلقه مقدار آن به خانه 2 کپی میشود.

-

در پایان خانه ی شماره 2 حاوی حاصلضرب خواهد بود.

- -
- -

و این همه ی برین فاک بود! خیلی ساده برای یادگیری ولی سنگین برای به کار بردن.

-

حال می توانید برای تفریح مشغول نوشتن برنامه ی های مختلف با آن شوید.

-

و یا یک اجرا کننده برین فاک را با یک زبان دیگر پیاده سازی کنید.

-

و یا اگر خیلی دوست داشتید یک اجرا کننده ی برین فاک با برین فاک بنویسید!!

-- cgit v1.2.3 From 5cbf6497b954ab97a89f207a4bdf69e77771c981 Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:17:06 +0800 Subject: Rename javascript.html.markdown to javascript-fa.html.markdown --- fa-ir/javascript-fa.html.markdown | 553 ++++++++++++++++++++++++++++++++++++++ fa-ir/javascript.html.markdown | 553 -------------------------------------- 2 files changed, 553 insertions(+), 553 deletions(-) create mode 100644 fa-ir/javascript-fa.html.markdown delete mode 100644 fa-ir/javascript.html.markdown diff --git a/fa-ir/javascript-fa.html.markdown b/fa-ir/javascript-fa.html.markdown new file mode 100644 index 00000000..fe3555af --- /dev/null +++ b/fa-ir/javascript-fa.html.markdown @@ -0,0 +1,553 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] +translators: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +filename: javascript-fa.js +lang: fa-ir +--- + +

+جاوااسکریپت توسط برندن ایش از شرکت NetScape در سال 1995 ساخته شد. در ابتدا به عنوان یک زبان اسکریپت‌نویسی در کنار جاوا (که برای موارد پیچیده تر در طراحی وب در نظر گرفته میشد) مورد استفاده بود، ولی در پی نفوذ بسیار گسترده آن در وب و همچنین پشتیبانی پیش-ساخته آن در مرورگر ها، امروزه به مراتب بیشتر از جاوا در برنامه نویسی سمت-کاربر در وب به کار برده میشود. +با این حال جاوااسکریپت فقط محدود به مرورگر های وب نمیشود. Node.js پروژه ایست که یک نسخه ی مستقل از اجراکننده ی موتور جاوااسکریپت V8 از گوگل کروم را در اختیار قرار میده که هر روزه درحال محبوب تر شدن نیز هست. +

+ +

+قدر دان نظرات سازنده شما هستم! شما میتوانید از طریق زیر با من تماس بگیرید: +

+ +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +

+// توضیحات همانند C هستند. توضیحات یک خطی با دو خط مورب شروع میشوند., +

+ +

+/* و توضیحات چند خطی با خط مورب-ستاره شروع، + و با ستاره-خط مورب ختم میشوند */ +

+ +```js +// Comments are like C. Single-line comments start with two slashes, +/* and multiline comments start with slash-star + and end with star-slash */ +``` +

+گزاره ها را میتوانید با نقطه ویرگول پایان دهید ; +

+```js +doStuff(); +``` +

+ولی لزومی به این کار نیست. نقطه ویرگول به صورت خودکار در نظر گرفته میشوند. +

+

+وقتی که خط جدیدی شروع میشود. مگر در موارد خاص. +

+```js +doStuff() +``` +

برای اینگه درگیر آن موارد خاص نشویم، در اینجا از اون ها

+

صرف نظر میکنیم.

+ +

1. اعداد، رشته ها و عملگرها

+ +

جاوااسکریپت فقط یک نوع عدد دارد و آن عدد اعشاری 64 بیتی IEEE 754 است.

+

نترسید! و نگران اعداد صحیح نباشید! این اعداد اعشاری دارای 54 بیت مانتیس هستند که قابلیت ذخیره ی

+

دقیق اعداد صحیح تا مقدار تقریبی 9x10¹⁵ را دارند.

+```js +3; // = 3 +1.5; // = 1.5 +``` +

+تمامی عملگر های محاسباتی آن طوری که انتظارش را دارید عمل خواهند کرد. +

+```js +1 + 1; // = 2 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 +``` +

و این حتی شامل تقسیم هم میشود.

+```js +5 / 2; // = 2.5 +``` +

عملگر های بیتی هم به همین شکل. وقتی از یک عملگر بیتی استفاده میکنید، عدد اعشاری شما

+

به عدد صحیح علامت دار *تا 32 بیت* تبدیل میشود.

+```js +1 << 2; // = 4 +``` +

عملیات داخل پرانتز تقدم بالاتری دارند.

+```js +(1 + 3) * 2; // = 8 +``` +

سه مقدار خاص وجود دارند که در واقع مقادیر عددی نیستند:

+```js +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 +``` +

مقادیر بولی هم تعریف شده هستند:

+```js +true; +false; +``` +

رشته ها با آپستروف و یا گیومه تعریف میشوند.

+```js +'abc'; +"Hello, world"; +``` +

و منفی کردن شرط با علامت تعجب

+```js +!true; // = false +!false; // = true +``` +

تساوی دو مقدار با ==

+```js +1 == 1; // = true +2 == 1; // = false +``` +

و عدم تساوی با !=

+```js +1 != 1; // = false +2 != 1; // = true +``` +

و سایر عمیلات های مقایسه

+```js +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true +``` +

رشته ها با علامت جمع به یکدیگر متصل میشوند

+```js +"Hello " + "world!"; // = "Hello world!" +``` +

و با علامت برگتر و یا کوچکتر با یکدیگر مقایسه میشوند.

+```js +"a" < "b"; // = true +``` +

نوع متغیر برای عملیات مقایسه تطبیق داده میشود

+```js +"5" == 5; // = true +``` +

مگر اینکه از سه مساوی استفاده شود!

+```js +"5" === 5; // = false +``` +

با استفاده از charAt میتوانید به کارکتر های یک رشته دسترسی پیدا کنید.

+```js +"This is a string".charAt(0); +``` +

از null برای نشان دادن عمدی مقدار هیج استفاده میشود.

+

و از undefined برای نشان دادن اینکه در حال حاظر مقدار موجود نمی باشد، هرچند خود undefined یک مقدار محسوب میشود.

+```js +null; // used to indicate a deliberate non-value +undefined; // used to indicate a value is not currently present (although undefined + // is actually a value itself) +``` +

false, null, undefined, NaN, 0 و "" مقدار نادرست و هر چیز دیگر مقدار درست طلقی میشوند.

+

توجه داشته باشید که 0 نادرست و "0" درست طلقی میشوند حتی در عبارت 0=="0".

+ +

2. متغیر ها، آرایه ها و شئ ها

+ +

متغیر ها با کلید واژه var تعریف میشوند. اشیا در جاوااسکریپت دارای نوع پویا هستند،

+

بدین شکل که برای تعریف نیازی به مشخص کردن نوع متعیر نیست.

+

برای مقدار دهی از علامت مساوی استفاده میشود.

+```js +var someVar = 5; +``` + +

اگر کلید واژه var را قرار ندهید، هیچ خطایی دریافت نخواهید کرد...

+```js +someOtherVar = 10; +``` + +

در عوض متغیر شما در گستره ی کل برنامه تعریف شده خواهد بود.

+ +

متغیر هایی که تعریف شده ولی مقدار دهی نشوند، دارای مقدار undefined خواهند بود.

+```js +var someThirdVar; // = undefined +``` + +

برای اعمال عملگر های محاسباتی، میانبر هایی وجود دارند:

+```js +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 +``` + +

حتی از این هم کوتاهتر برای اضافه یا کم کردن یک عدد با مقدار یک.

+```js +someVar++; // now someVar is 101 +someVar--; // back to 100 +``` + +

آرایه ها در واقع لیستی مرتب شده از مقادیر مختلف از هر نوعی هستند.

+```js +var myArray = ["Hello", 45, true]; +``` + +

به اعضای یک آرایه میتوان از طریق قرار دادن کروشه در جلوی نام آن دسترسی پیدا کرد.

+

نمایه ی آرایه از صفر شروع میشود.

+```js +myArray[1]; // = 45 +``` + +

آرایه ها ناپایدار و دارای طول قابل تغییر هستند

+```js +myArray.push("World"); +myArray.length; // = 4 +``` + +

در جاوااسکریپت، اشیاء چیزی شبیه دیکشنری و یا نقشه در زبان های دیگر هستند:

+

یک مجموعه ی نامرتب از جفت های کلید-مقدار.

+```js +var myObj = {key1: "Hello", key2: "World"}; +``` + +

کلید ها از نوع رشته هستند ولی در صورتی که مقدار معتبری برای اسم گزاری باشند نیازی به آوردن آنها درون گیومه نیست.

+```js +var myObj = {myKey: "myValue", "my other key": 4}; +``` + +

اعضای یک شئ را نیز میتوانید با استفاده از کروشه در مقابل نام آنها استخراج کنید.

+```js +myObj["my other key"]; // = 4 +``` + +

...و یا از طریق نقطه در صورتی که اسم عضو مورد نظر اسم معتبری برای اسم گزاری باشد.

+```js +myObj.myKey; // = "myValue" +``` + +

اشیاء ناپایدار و قابل اضافه کردن عضو جدید هستند.

+```js +myObj.myThirdKey = true; +``` + +

اگر سعی کنید عضوی را که وجود ندارد استخراج کنید، مقدار undefined را دریافت خواهید کرد.

+```js +myObj.myFourthKey; // = undefined +``` + +

3. منطق و ساختار کنترل

+ +

ساختار if به شکلی که انتظارش را دارید کار میکند.

+```js +var count = 1; +if (count == 3){ + // evaluated if count is 3 +} else if (count == 4) { + // evaluated if count is 4 +} else { + // evaluated if it's not either 3 or 4 +} +``` + +

و همینطور حلقه while

+```js +while (true) { + // An infinite loop! +} +``` + +

حلقه do-while شبیه while است با این تفاوت که حداقل یکبار اجرا میشود.

+```js +var input +do { + input = getInput(); +} while (!isValid(input)) +``` + +

حلقه for همانند زبان C و جاوا کار می کند.

+

مقدار دهی اولیه; شرط ادامه; چرخش حلقه

+```js +for (var i = 0; i < 5; i++){ + // will run 5 times +} +``` + +

عملگر && و || به ترتیب "و" و "یا" ی منطقی هستند.

+```js +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} +``` + +

از || همچنین میتوان برای تعیین مقدار پیشفرض استفاده کرد.

+```js +var name = otherName || "default"; +``` + +

4. توابع و مفاهیم گستره و بستار

+ +

توابع در جاوااسکریپت با استفاده از کلیدواژه ی function تعریف میشوند.

+```js +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" +``` + +

توابع در جاوااسکریپت نوعی شئ پایه محسوب میشوند، بنابر این می توانید آنها را به اشیاء مختلف

+

اضافه کنید و یا به عنوان پارامتر به توابع دیگر ارسال کنید.

+

- برای مثال وقتی که با یک رویداد کار میکنید.

+```js +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000); +``` + +

توجه کنید که setTimeout تابعی تعریف شده در جاوااسکریپت نیست، ولی مرورگر ها و node.js از آن پشتیبانی میکنند.

+ + +

توابع نیازی به داشتن اسم ندارند. برای مثال وقتی تابعی را به تابعی دیگر ارسال میکنید

+

میتوانید آنرا به صورت بینام تعریف کنید.

+```js +setTimeout(function(){ + // this code will be called in 5 seconds' time +}, 5000); +``` + +

توابع دارای محدوده ی متغیر های خود هستند.

+

بر خلاف دیگر ساختار ها - مانند if

+```js +if (true){ + var i = 5; +} +i; // = 5 - not undefined as you'd expect in a block-scoped language +``` + +

به همین دلیل الگوی خاصی به نام "تابعی که بلافاصله صدا زده میشود" پدید آمده

+

تا از اضافه شدن متغیر های قسمتی از برنامه به گستره ی کلی برنامه جلوگیری شود.

+```js +(function(){ + var temporary = 5; + // We can access the global scope by assiging to the 'global object', which + // in a web browser is always 'window'. The global object may have a + // different name in non-browser environments such as Node.js. + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 +``` + +

یکی از برترین ویژگی های جاوااسکریپت مفهومی با نام بستار است

+

بدین شکل که اگر تابعی درون تابع دیگری تعریف شود، تابع درونی به تمام متغیر های تابع خارجی دسترسی

+

خواهد داشت، حتی بعد از اینکه تابع خارجی به اتمام رسیده باشد.

+```js +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will + // exit immediately, and setTimeout will call inner afterwards. However, + // because inner is "closed over" sayHelloInFiveSeconds, inner still has + // access to the 'prompt' variable when it is finally called. +} +sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s +``` + +

5. دیگر اشیاء، سازنده ها و پیش‌نمونه ها

+ +

اشیاء میتوانند تابع داشته باشند.

+```js +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" +``` + +

وقتی تابع یک شی صدا زده می شود، تابع میتواند به سایر مقادیر درون آن شی

+

از طریق کلید واژه ی this دسترسی داشته باشد.

+```js +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" +``` + + +

اینکه مقدار this چه باشد بستگی به این دارد که تابع چگونه صدا زده شود

+

نه اینکه تابع کجا تعریف شده است.

+

بنابر این تابع بالا اگر بدین شکل صدا زده شود کار نخواهد کرد

+```js +var myFunc = myObj.myFunc; +myFunc(); // = undefined +``` + + +

به همین شکل، تابعی که در جای دیگر تعریف شده را میتوانید به یک شی الحاق کنید

+

و بدین ترتیب تابع میتواند به مقادیر درون شی از طریق this دسترسی پیدا کند.

+```js +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" +``` + + +

اگر تابعی با کلید new صدا زده شوند، شی جدیدی ایجاد شده و تابع در گستره ی آن صدا زده میشود.

+

توابعی که بدین شکل صدا زده شوند در واقع نقش سازنده را ایفا می کنند.

+```js +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 +``` + + +

تمامی اشیاء در جاوااسکریپت دارای یک پیش نمونه هستند

+

به شکلی که اگر تابع صدا زده شده بر روی شی مستقیما روی آن تعریف نشده باشد

+

اجرا کننده ی برنامه در لیست پیش نمونه به دنبال آن تابع خواهد گشت

+ +

برخی اجرا کننده های جاوااسکریپت به شما اجازه ی دسترسی به پیش نمونه های یک شی را از

+

طریق عضو جادویی __proto__ میدهند.

+

هرچند این به شناخت پیش نمونه ها کمک میکند ولی در حیطه ی جاوااسکریپت استاندارد قرار نمیگیرد.

+

در ادامه شکل استاندارد پیش نمونه ها مورد بررسی قرار میگیرند.

+```js +var myObj = { + myString: "Hello world!", +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 +``` + +

این موضوع در مورد توابع نیز صدق میکند.

+```js +myObj.myFunc(); // = "hello world!" +``` + + +

اگر عضو مورد نظر در پیش نمونه ی شی یافت نشود، پیش نمونه ی پیش نمونه جستجو شده و الی آخر

+```js +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true +``` + + +

توجه داشته باشید که پیش نمونه ها کپی نمی شوند و هر شی جدید به پیش نمونه موجود اشاره میکند

+

بدین ترتیب اگر تابعی به پیش نمونه اضافه شود تمامی اشیاء میتوانند به آن دسترسی پیدا کنند.

+```js +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 +``` + +

پیش تر اشاره شد که __proto__ راه استانداردی برای دسترسی به پیش نمونه نیست و هیچ استانداردی نیز برای دسترسی به پیش نمونه ی یک شی موجود پیش بینی نشده است

+

ولی دو راه برای ارائه پیش نمونه برای اشیاء جدید وجود دارد.

+ +

اولی وقتیست که از تابع Object.create استفاده میشود - که اخیرا به زبان اضافه شده است و بنابراین بر روی همه ی پیاده سازی های آن وجود ندارد.

+```js +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 +``` + + +

راه دوم - که همه جا قابل استفاده است - مربوط به سازنده ها می شود.

+

سازنده ها دارای عضوی با نام prototype هستند. این پیش نمونه ی خود سازنده نیست

+

بلکه پیش نمونه ایست که به تمامی اشیاء ساخته شده توسط این سازنده الحاق میشود.

+```js +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 +``` + + +

رشته ها و سایر سازنده های پیش ساخته ی زبان نیز دارای این ویژگی هستند.

+```js +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true +``` + + +

به جز این که این سازنده ها دقیقا مانند سازنده های دیگر نیستند.

+```js +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +``` + + +

ولی به هر حال هم اشیاء عادی و هم اشیاء پیش ساخته هر دو در داشتن پیش نمونه مشترک هستند

+

بنابر این شما میتوانید ویژگی و تابع جدیدی به رشته ها - به عنوان مثال - اضافه کنید.

+ + +

گاها به از این خاصیت با عنوان پلی فیل و برای اضافه کردن ویژگی های جدید به مجموعه ای از اشیاء فعلی زبان استفاده میشود

+

که کاربرد فراوانی در پشتیبانی از نسخه های قدیمیتر مرورگر ها دارد.

+```js +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" +``` + + +

برای مثال، پیشتر اشاره کردیم که Object.create در نسخه های جدید پشتیبانی نشده است

+

ولی میتوان آن را به صورت پلی فیل استفاده کرد.

+```js +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +

منابع دیگر

+ +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) +

مرجعی بسیار خوب برای جاوااسکریپت به شکلی که در مرورگر ها مورد استفاده قرار گرفته است.

+

از آنجایی که این منبع یک ویکی میباشد همانطور که مطالب بیشتری یاد میگیرید میتوانید به دیگران نیز در یادگیری آن کمک کنید.

+ +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +

مشابه مطالبی که اینجا مطرح شده با جزییات بیشتر. در اینجا به شکل عمدی جاوااسکریپت فقط از دیدگاه زبان برنامه نویسی مورد بررسی قرار گرفته

+

در حالی که در این منبع میتوانید بیشتر از کاربرد آن در صفحات وب آشنایی پیدا کنید.

+[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) +

راهنمای دقیقی از قسمت های غیر ملموس زبان.

+ +

اضافه بر این در ویرایش این مقاله، قسمت هایی از سایت زیر مورد استفاده قرار گرفته است.

+Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown deleted file mode 100644 index fe3555af..00000000 --- a/fa-ir/javascript.html.markdown +++ /dev/null @@ -1,553 +0,0 @@ ---- -language: javascript -contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] -translators: - - ["Mohammad Valipour", "https://github.com/mvalipour"] -filename: javascript-fa.js -lang: fa-ir ---- - -

-جاوااسکریپت توسط برندن ایش از شرکت NetScape در سال 1995 ساخته شد. در ابتدا به عنوان یک زبان اسکریپت‌نویسی در کنار جاوا (که برای موارد پیچیده تر در طراحی وب در نظر گرفته میشد) مورد استفاده بود، ولی در پی نفوذ بسیار گسترده آن در وب و همچنین پشتیبانی پیش-ساخته آن در مرورگر ها، امروزه به مراتب بیشتر از جاوا در برنامه نویسی سمت-کاربر در وب به کار برده میشود. -با این حال جاوااسکریپت فقط محدود به مرورگر های وب نمیشود. Node.js پروژه ایست که یک نسخه ی مستقل از اجراکننده ی موتور جاوااسکریپت V8 از گوگل کروم را در اختیار قرار میده که هر روزه درحال محبوب تر شدن نیز هست. -

- -

-قدر دان نظرات سازنده شما هستم! شما میتوانید از طریق زیر با من تماس بگیرید: -

- -[@adambrenecki](https://twitter.com/adambrenecki), or -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). - -

-// توضیحات همانند C هستند. توضیحات یک خطی با دو خط مورب شروع میشوند., -

- -

-/* و توضیحات چند خطی با خط مورب-ستاره شروع، - و با ستاره-خط مورب ختم میشوند */ -

- -```js -// Comments are like C. Single-line comments start with two slashes, -/* and multiline comments start with slash-star - and end with star-slash */ -``` -

-گزاره ها را میتوانید با نقطه ویرگول پایان دهید ; -

-```js -doStuff(); -``` -

-ولی لزومی به این کار نیست. نقطه ویرگول به صورت خودکار در نظر گرفته میشوند. -

-

-وقتی که خط جدیدی شروع میشود. مگر در موارد خاص. -

-```js -doStuff() -``` -

برای اینگه درگیر آن موارد خاص نشویم، در اینجا از اون ها

-

صرف نظر میکنیم.

- -

1. اعداد، رشته ها و عملگرها

- -

جاوااسکریپت فقط یک نوع عدد دارد و آن عدد اعشاری 64 بیتی IEEE 754 است.

-

نترسید! و نگران اعداد صحیح نباشید! این اعداد اعشاری دارای 54 بیت مانتیس هستند که قابلیت ذخیره ی

-

دقیق اعداد صحیح تا مقدار تقریبی 9x10¹⁵ را دارند.

-```js -3; // = 3 -1.5; // = 1.5 -``` -

-تمامی عملگر های محاسباتی آن طوری که انتظارش را دارید عمل خواهند کرد. -

-```js -1 + 1; // = 2 -8 - 1; // = 7 -10 * 2; // = 20 -35 / 5; // = 7 -``` -

و این حتی شامل تقسیم هم میشود.

-```js -5 / 2; // = 2.5 -``` -

عملگر های بیتی هم به همین شکل. وقتی از یک عملگر بیتی استفاده میکنید، عدد اعشاری شما

-

به عدد صحیح علامت دار *تا 32 بیت* تبدیل میشود.

-```js -1 << 2; // = 4 -``` -

عملیات داخل پرانتز تقدم بالاتری دارند.

-```js -(1 + 3) * 2; // = 8 -``` -

سه مقدار خاص وجود دارند که در واقع مقادیر عددی نیستند:

-```js -Infinity; // result of e.g. 1/0 --Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0 -``` -

مقادیر بولی هم تعریف شده هستند:

-```js -true; -false; -``` -

رشته ها با آپستروف و یا گیومه تعریف میشوند.

-```js -'abc'; -"Hello, world"; -``` -

و منفی کردن شرط با علامت تعجب

-```js -!true; // = false -!false; // = true -``` -

تساوی دو مقدار با ==

-```js -1 == 1; // = true -2 == 1; // = false -``` -

و عدم تساوی با !=

-```js -1 != 1; // = false -2 != 1; // = true -``` -

و سایر عمیلات های مقایسه

-```js -1 < 10; // = true -1 > 10; // = false -2 <= 2; // = true -2 >= 2; // = true -``` -

رشته ها با علامت جمع به یکدیگر متصل میشوند

-```js -"Hello " + "world!"; // = "Hello world!" -``` -

و با علامت برگتر و یا کوچکتر با یکدیگر مقایسه میشوند.

-```js -"a" < "b"; // = true -``` -

نوع متغیر برای عملیات مقایسه تطبیق داده میشود

-```js -"5" == 5; // = true -``` -

مگر اینکه از سه مساوی استفاده شود!

-```js -"5" === 5; // = false -``` -

با استفاده از charAt میتوانید به کارکتر های یک رشته دسترسی پیدا کنید.

-```js -"This is a string".charAt(0); -``` -

از null برای نشان دادن عمدی مقدار هیج استفاده میشود.

-

و از undefined برای نشان دادن اینکه در حال حاظر مقدار موجود نمی باشد، هرچند خود undefined یک مقدار محسوب میشود.

-```js -null; // used to indicate a deliberate non-value -undefined; // used to indicate a value is not currently present (although undefined - // is actually a value itself) -``` -

false, null, undefined, NaN, 0 و "" مقدار نادرست و هر چیز دیگر مقدار درست طلقی میشوند.

-

توجه داشته باشید که 0 نادرست و "0" درست طلقی میشوند حتی در عبارت 0=="0".

- -

2. متغیر ها، آرایه ها و شئ ها

- -

متغیر ها با کلید واژه var تعریف میشوند. اشیا در جاوااسکریپت دارای نوع پویا هستند،

-

بدین شکل که برای تعریف نیازی به مشخص کردن نوع متعیر نیست.

-

برای مقدار دهی از علامت مساوی استفاده میشود.

-```js -var someVar = 5; -``` - -

اگر کلید واژه var را قرار ندهید، هیچ خطایی دریافت نخواهید کرد...

-```js -someOtherVar = 10; -``` - -

در عوض متغیر شما در گستره ی کل برنامه تعریف شده خواهد بود.

- -

متغیر هایی که تعریف شده ولی مقدار دهی نشوند، دارای مقدار undefined خواهند بود.

-```js -var someThirdVar; // = undefined -``` - -

برای اعمال عملگر های محاسباتی، میانبر هایی وجود دارند:

-```js -someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now -someVar *= 10; // now someVar is 100 -``` - -

حتی از این هم کوتاهتر برای اضافه یا کم کردن یک عدد با مقدار یک.

-```js -someVar++; // now someVar is 101 -someVar--; // back to 100 -``` - -

آرایه ها در واقع لیستی مرتب شده از مقادیر مختلف از هر نوعی هستند.

-```js -var myArray = ["Hello", 45, true]; -``` - -

به اعضای یک آرایه میتوان از طریق قرار دادن کروشه در جلوی نام آن دسترسی پیدا کرد.

-

نمایه ی آرایه از صفر شروع میشود.

-```js -myArray[1]; // = 45 -``` - -

آرایه ها ناپایدار و دارای طول قابل تغییر هستند

-```js -myArray.push("World"); -myArray.length; // = 4 -``` - -

در جاوااسکریپت، اشیاء چیزی شبیه دیکشنری و یا نقشه در زبان های دیگر هستند:

-

یک مجموعه ی نامرتب از جفت های کلید-مقدار.

-```js -var myObj = {key1: "Hello", key2: "World"}; -``` - -

کلید ها از نوع رشته هستند ولی در صورتی که مقدار معتبری برای اسم گزاری باشند نیازی به آوردن آنها درون گیومه نیست.

-```js -var myObj = {myKey: "myValue", "my other key": 4}; -``` - -

اعضای یک شئ را نیز میتوانید با استفاده از کروشه در مقابل نام آنها استخراج کنید.

-```js -myObj["my other key"]; // = 4 -``` - -

...و یا از طریق نقطه در صورتی که اسم عضو مورد نظر اسم معتبری برای اسم گزاری باشد.

-```js -myObj.myKey; // = "myValue" -``` - -

اشیاء ناپایدار و قابل اضافه کردن عضو جدید هستند.

-```js -myObj.myThirdKey = true; -``` - -

اگر سعی کنید عضوی را که وجود ندارد استخراج کنید، مقدار undefined را دریافت خواهید کرد.

-```js -myObj.myFourthKey; // = undefined -``` - -

3. منطق و ساختار کنترل

- -

ساختار if به شکلی که انتظارش را دارید کار میکند.

-```js -var count = 1; -if (count == 3){ - // evaluated if count is 3 -} else if (count == 4) { - // evaluated if count is 4 -} else { - // evaluated if it's not either 3 or 4 -} -``` - -

و همینطور حلقه while

-```js -while (true) { - // An infinite loop! -} -``` - -

حلقه do-while شبیه while است با این تفاوت که حداقل یکبار اجرا میشود.

-```js -var input -do { - input = getInput(); -} while (!isValid(input)) -``` - -

حلقه for همانند زبان C و جاوا کار می کند.

-

مقدار دهی اولیه; شرط ادامه; چرخش حلقه

-```js -for (var i = 0; i < 5; i++){ - // will run 5 times -} -``` - -

عملگر && و || به ترتیب "و" و "یا" ی منطقی هستند.

-```js -if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear"; -} -if (colour == "red" || colour == "blue"){ - // colour is either red or blue -} -``` - -

از || همچنین میتوان برای تعیین مقدار پیشفرض استفاده کرد.

-```js -var name = otherName || "default"; -``` - -

4. توابع و مفاهیم گستره و بستار

- -

توابع در جاوااسکریپت با استفاده از کلیدواژه ی function تعریف میشوند.

-```js -function myFunction(thing){ - return thing.toUpperCase(); -} -myFunction("foo"); // = "FOO" -``` - -

توابع در جاوااسکریپت نوعی شئ پایه محسوب میشوند، بنابر این می توانید آنها را به اشیاء مختلف

-

اضافه کنید و یا به عنوان پارامتر به توابع دیگر ارسال کنید.

-

- برای مثال وقتی که با یک رویداد کار میکنید.

-```js -function myFunction(){ - // this code will be called in 5 seconds' time -} -setTimeout(myFunction, 5000); -``` - -

توجه کنید که setTimeout تابعی تعریف شده در جاوااسکریپت نیست، ولی مرورگر ها و node.js از آن پشتیبانی میکنند.

- - -

توابع نیازی به داشتن اسم ندارند. برای مثال وقتی تابعی را به تابعی دیگر ارسال میکنید

-

میتوانید آنرا به صورت بینام تعریف کنید.

-```js -setTimeout(function(){ - // this code will be called in 5 seconds' time -}, 5000); -``` - -

توابع دارای محدوده ی متغیر های خود هستند.

-

بر خلاف دیگر ساختار ها - مانند if

-```js -if (true){ - var i = 5; -} -i; // = 5 - not undefined as you'd expect in a block-scoped language -``` - -

به همین دلیل الگوی خاصی به نام "تابعی که بلافاصله صدا زده میشود" پدید آمده

-

تا از اضافه شدن متغیر های قسمتی از برنامه به گستره ی کلی برنامه جلوگیری شود.

-```js -(function(){ - var temporary = 5; - // We can access the global scope by assiging to the 'global object', which - // in a web browser is always 'window'. The global object may have a - // different name in non-browser environments such as Node.js. - window.permanent = 10; -})(); -temporary; // raises ReferenceError -permanent; // = 10 -``` - -

یکی از برترین ویژگی های جاوااسکریپت مفهومی با نام بستار است

-

بدین شکل که اگر تابعی درون تابع دیگری تعریف شود، تابع درونی به تمام متغیر های تابع خارجی دسترسی

-

خواهد داشت، حتی بعد از اینکه تابع خارجی به اتمام رسیده باشد.

-```js -function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!"; - function inner(){ - alert(prompt); - } - setTimeout(inner, 5000); - // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will - // exit immediately, and setTimeout will call inner afterwards. However, - // because inner is "closed over" sayHelloInFiveSeconds, inner still has - // access to the 'prompt' variable when it is finally called. -} -sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s -``` - -

5. دیگر اشیاء، سازنده ها و پیش‌نمونه ها

- -

اشیاء میتوانند تابع داشته باشند.

-```js -var myObj = { - myFunc: function(){ - return "Hello world!"; - } -}; -myObj.myFunc(); // = "Hello world!" -``` - -

وقتی تابع یک شی صدا زده می شود، تابع میتواند به سایر مقادیر درون آن شی

-

از طریق کلید واژه ی this دسترسی داشته باشد.

-```js -myObj = { - myString: "Hello world!", - myFunc: function(){ - return this.myString; - } -}; -myObj.myFunc(); // = "Hello world!" -``` - - -

اینکه مقدار this چه باشد بستگی به این دارد که تابع چگونه صدا زده شود

-

نه اینکه تابع کجا تعریف شده است.

-

بنابر این تابع بالا اگر بدین شکل صدا زده شود کار نخواهد کرد

-```js -var myFunc = myObj.myFunc; -myFunc(); // = undefined -``` - - -

به همین شکل، تابعی که در جای دیگر تعریف شده را میتوانید به یک شی الحاق کنید

-

و بدین ترتیب تابع میتواند به مقادیر درون شی از طریق this دسترسی پیدا کند.

-```js -var myOtherFunc = function(){ - return this.myString.toUpperCase(); -} -myObj.myOtherFunc = myOtherFunc; -myObj.myOtherFunc(); // = "HELLO WORLD!" -``` - - -

اگر تابعی با کلید new صدا زده شوند، شی جدیدی ایجاد شده و تابع در گستره ی آن صدا زده میشود.

-

توابعی که بدین شکل صدا زده شوند در واقع نقش سازنده را ایفا می کنند.

-```js -var MyConstructor = function(){ - this.myNumber = 5; -} -myNewObj = new MyConstructor(); // = {myNumber: 5} -myNewObj.myNumber; // = 5 -``` - - -

تمامی اشیاء در جاوااسکریپت دارای یک پیش نمونه هستند

-

به شکلی که اگر تابع صدا زده شده بر روی شی مستقیما روی آن تعریف نشده باشد

-

اجرا کننده ی برنامه در لیست پیش نمونه به دنبال آن تابع خواهد گشت

- -

برخی اجرا کننده های جاوااسکریپت به شما اجازه ی دسترسی به پیش نمونه های یک شی را از

-

طریق عضو جادویی __proto__ میدهند.

-

هرچند این به شناخت پیش نمونه ها کمک میکند ولی در حیطه ی جاوااسکریپت استاندارد قرار نمیگیرد.

-

در ادامه شکل استاندارد پیش نمونه ها مورد بررسی قرار میگیرند.

-```js -var myObj = { - myString: "Hello world!", -}; -var myPrototype = { - meaningOfLife: 42, - myFunc: function(){ - return this.myString.toLowerCase() - } -}; -myObj.__proto__ = myPrototype; -myObj.meaningOfLife; // = 42 -``` - -

این موضوع در مورد توابع نیز صدق میکند.

-```js -myObj.myFunc(); // = "hello world!" -``` - - -

اگر عضو مورد نظر در پیش نمونه ی شی یافت نشود، پیش نمونه ی پیش نمونه جستجو شده و الی آخر

-```js -myPrototype.__proto__ = { - myBoolean: true -}; -myObj.myBoolean; // = true -``` - - -

توجه داشته باشید که پیش نمونه ها کپی نمی شوند و هر شی جدید به پیش نمونه موجود اشاره میکند

-

بدین ترتیب اگر تابعی به پیش نمونه اضافه شود تمامی اشیاء میتوانند به آن دسترسی پیدا کنند.

-```js -myPrototype.meaningOfLife = 43; -myObj.meaningOfLife; // = 43 -``` - -

پیش تر اشاره شد که __proto__ راه استانداردی برای دسترسی به پیش نمونه نیست و هیچ استانداردی نیز برای دسترسی به پیش نمونه ی یک شی موجود پیش بینی نشده است

-

ولی دو راه برای ارائه پیش نمونه برای اشیاء جدید وجود دارد.

- -

اولی وقتیست که از تابع Object.create استفاده میشود - که اخیرا به زبان اضافه شده است و بنابراین بر روی همه ی پیاده سازی های آن وجود ندارد.

-```js -var myObj = Object.create(myPrototype); -myObj.meaningOfLife; // = 43 -``` - - -

راه دوم - که همه جا قابل استفاده است - مربوط به سازنده ها می شود.

-

سازنده ها دارای عضوی با نام prototype هستند. این پیش نمونه ی خود سازنده نیست

-

بلکه پیش نمونه ایست که به تمامی اشیاء ساخته شده توسط این سازنده الحاق میشود.

-```js -MyConstructor.prototype = { - myNumber: 5, - getMyNumber: function(){ - return this.myNumber; - } -}; -var myNewObj2 = new MyConstructor(); -myNewObj2.getMyNumber(); // = 5 -myNewObj2.myNumber = 6 -myNewObj2.getMyNumber(); // = 6 -``` - - -

رشته ها و سایر سازنده های پیش ساخته ی زبان نیز دارای این ویژگی هستند.

-```js -var myNumber = 12; -var myNumberObj = new Number(12); -myNumber == myNumberObj; // = true -``` - - -

به جز این که این سازنده ها دقیقا مانند سازنده های دیگر نیستند.

-```js -typeof myNumber; // = 'number' -typeof myNumberObj; // = 'object' -myNumber === myNumberObj; // = false -if (0){ - // This code won't execute, because 0 is falsy. -} -``` - - -

ولی به هر حال هم اشیاء عادی و هم اشیاء پیش ساخته هر دو در داشتن پیش نمونه مشترک هستند

-

بنابر این شما میتوانید ویژگی و تابع جدیدی به رشته ها - به عنوان مثال - اضافه کنید.

- - -

گاها به از این خاصیت با عنوان پلی فیل و برای اضافه کردن ویژگی های جدید به مجموعه ای از اشیاء فعلی زبان استفاده میشود

-

که کاربرد فراوانی در پشتیبانی از نسخه های قدیمیتر مرورگر ها دارد.

-```js -String.prototype.firstCharacter = function(){ - return this.charAt(0); -} -"abc".firstCharacter(); // = "a" -``` - - -

برای مثال، پیشتر اشاره کردیم که Object.create در نسخه های جدید پشتیبانی نشده است

-

ولی میتوان آن را به صورت پلی فیل استفاده کرد.

-```js -if (Object.create === undefined){ // don't overwrite it if it exists - Object.create = function(proto){ - // make a temporary constructor with the right prototype - var Constructor = function(){}; - Constructor.prototype = proto; - // then use it to create a new, appropriately-prototyped object - return new Constructor(); - } -} -``` - -

منابع دیگر

- -The [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) -

مرجعی بسیار خوب برای جاوااسکریپت به شکلی که در مرورگر ها مورد استفاده قرار گرفته است.

-

از آنجایی که این منبع یک ویکی میباشد همانطور که مطالب بیشتری یاد میگیرید میتوانید به دیگران نیز در یادگیری آن کمک کنید.

- -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -

مشابه مطالبی که اینجا مطرح شده با جزییات بیشتر. در اینجا به شکل عمدی جاوااسکریپت فقط از دیدگاه زبان برنامه نویسی مورد بررسی قرار گرفته

-

در حالی که در این منبع میتوانید بیشتر از کاربرد آن در صفحات وب آشنایی پیدا کنید.

-[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) - -[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) -

راهنمای دقیقی از قسمت های غیر ملموس زبان.

- -

اضافه بر این در ویرایش این مقاله، قسمت هایی از سایت زیر مورد استفاده قرار گرفته است.

-Louie Dinh's Python tutorial on this site, and the [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -on the Mozilla Developer Network. -- cgit v1.2.3 From 3cf044d1232f605f99df148dfc55e712020481c2 Mon Sep 17 00:00:00 2001 From: sholland1 Date: Tue, 27 Oct 2015 18:54:39 -0500 Subject: change language in examples back to csharp parser does not support fsharp syntax highlighting --- fsharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 4cc233e3..b5c47ed7 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -16,7 +16,7 @@ The syntax of F# is different from C-style languages: 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. -```fsharp +```csharp // single line comments use a double slash (* multi line comments use (* . . . *) pair -- cgit v1.2.3 From 61aa6a3e0146faed45230111b0bdcf1b0c2209f8 Mon Sep 17 00:00:00 2001 From: Corban Mailloux Date: Tue, 27 Oct 2015 22:18:02 -0400 Subject: "wan't" -> "want" --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index dc573b0e..b54434e0 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -145,7 +145,7 @@ someOtherVar = 10; // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined -// if you wan't to declare a couple of variables, then you could use a comma +// if you want to declare a couple of variables, then you could use a comma // separator var someFourthVar = 2, someFifthVar = 4; -- cgit v1.2.3 From a8d5105fab5e40923d834fb5848aabf561bc1701 Mon Sep 17 00:00:00 2001 From: Corban Mailloux Date: Tue, 27 Oct 2015 22:47:03 -0400 Subject: [javascript/en] Spacing and capitalization of comments ... and a few grammar fixes. --- javascript.html.markdown | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index b54434e0..5bac3aa7 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -136,7 +136,7 @@ undefined; // used to indicate a value is not currently present (although // character. var someVar = 5; -// if you leave the var keyword off, you won't get an error... +// If you leave the var keyword off, you won't get an error... someOtherVar = 10; // ...but your variable will be created in the global scope, not in the scope @@ -145,7 +145,7 @@ someOtherVar = 10; // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined -// if you want to declare a couple of variables, then you could use a comma +// If you want to declare a couple of variables, then you could use a comma // separator var someFourthVar = 2, someFifthVar = 4; @@ -223,15 +223,15 @@ for (var i = 0; i < 5; i++){ // will run 5 times } -//The For/In statement loops iterates over every property across the entire prototype chain +// The for/in statement iterates over every property across the entire prototype chain. var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ description += person[x] + " "; } -//If only want to consider properties attached to the object itself, -//and not its prototypes use hasOwnProperty() check +// To only consider properties attached to the object itself +// and not its prototypes, use the `hasOwnProperty()` check. var description = ""; var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ @@ -240,8 +240,9 @@ for (var x in person){ } } -//for/in should not be used to iterate over an Array where the index order is important. -//There is no guarantee that for/in will return the indexes in any particular order +// For/in should not be used to iterate over an Array where the index order +// is important, as there is no guarantee that for/in will return the indexes +// in any particular order. // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ @@ -256,7 +257,7 @@ var name = otherName || "default"; // The `switch` statement checks for equality with `===`. -// use 'break' after each case +// Use 'break' after each case // or the cases after the correct one will be executed too. grade = 'B'; switch (grade) { -- cgit v1.2.3 From c83eb6c6bca63b28a11b975cc64db5723e94b240 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 28 Oct 2015 13:26:24 +1030 Subject: [javascript/en] Move comparisons to other languages into preamble --- javascript.html.markdown | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 5bac3aa7..3f9eb641 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -16,9 +16,14 @@ JavaScript isn't just limited to web browsers, though: Node.js, a project that provides a standalone runtime for Google Chrome's V8 JavaScript engine, is becoming more and more popular. +JavaScript has a C-like syntax, so if you've used languages like C or Java, +a lot of the basic syntax will already be familiar. Despite this, and despite +the similarity in name, JavaScript's object model is significantly different to +Java's. + ```js -// Comments are like C's. Single-line comments start with two slashes, -/* and multiline comments start with slash-star +// Single-line comments start with two slashes. +/* Multiline comments start with slash-star, and end with star-slash */ // Statements can be terminated by ; @@ -145,7 +150,7 @@ someOtherVar = 10; // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined -// If you want to declare a couple of variables, then you could use a comma +// If you want to declare a couple of variables, then you could use a comma // separator var someFourthVar = 2, someFifthVar = 4; @@ -194,8 +199,6 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures -// The syntax for this section is almost identical to Java's. - // The `if` structure works as you'd expect. var count = 1; if (count == 3){ -- cgit v1.2.3 From d4d471ef50fb2e84dc8f1656a7037795bd44a89a Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 28 Oct 2015 13:27:48 +1030 Subject: [javascript/en] Formatting fix --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 3f9eb641..b5c3a3c8 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -41,7 +41,7 @@ doStuff() // JavaScript has one number type (which is a 64-bit IEEE 754 double). // Doubles have a 52-bit mantissa, which is enough to store integers -// up to about 9✕10¹⁵ precisely. +// up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 -- cgit v1.2.3 From c3a66e60a61de0b98ea3e86568dfddf76eae1069 Mon Sep 17 00:00:00 2001 From: Adam Brenecki Date: Wed, 28 Oct 2015 13:48:53 +1030 Subject: [javascript/en] Re-add note about truthiness of wrapped primitives Previous incarnations of this section had `Number(0)` instead of `new Number(0)`, which actually returns `0` due to the absence of the `new` keyword; this commit re-adds that section and better still, makes it actually correct! --- javascript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index b5c3a3c8..cd75b0d2 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -507,6 +507,10 @@ myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } +if (new Number(0)){ + // This code will execute, because wrapped numbers are objects, and objects + // are always truthy. +} // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. -- cgit v1.2.3 From 2c99b0a9553f25a7ac43b04a14c4e2d78fe2b318 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Wed, 28 Oct 2015 08:18:27 +0100 Subject: [scala/de] Fix ``` usage --- de-de/scala-de.html.markdown | 518 ++++++++++++++++++++++--------------------- 1 file changed, 271 insertions(+), 247 deletions(-) diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown index 7fd299b4..456403a2 100644 --- a/de-de/scala-de.html.markdown +++ b/de-de/scala-de.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] - ["Ha-Duong Nguyen", "http://reference-error.org"] + - ["Dennis Keller", "github.com/denniskeller"] translators: - ["Christian Albrecht", "https://github.com/coastalchief"] filename: learnscala-de.scala @@ -16,167 +17,172 @@ für die Java Virtual Machine (JVM), um allgemeine Programmieraufgaben zu erledigen. Scala hat einen akademischen Hintergrund und wurde an der EPFL (Lausanne / Schweiz) unter der Leitung von Martin Odersky entwickelt. - -# 0. Umgebung einrichten +```scala +/* Scala Umgebung einrichten: 1. Scala binaries herunterladen- http://www.scala-lang.org/downloads 2. Unzip/untar in ein Verzeichnis 3. das bin Unterverzeichnis der `PATH` Umgebungsvariable hinzufügen 4. Mit dem Kommando `scala` wird die REPL gestartet und zeigt als Prompt: -``` + scala> -``` Die REPL (Read-Eval-Print Loop) ist der interaktive Scala Interpreter. Hier kann man jeden Scala Ausdruck verwenden und das Ergebnis wird direkt ausgegeben. Als nächstes beschäftigen wir uns mit ein paar Scala Basics. +*/ -# 1. Basics -Einzeilige Kommentare beginnen mit zwei vorwärts Slash +///////////////////////////////////////////////// +// 1. Basics +///////////////////////////////////////////////// + +// Einzeilige Kommentare beginnen mit zwei Slashes /* - Mehrzeilige Kommentare, werden starten - mit Slash-Stern und enden mit Stern-Slash + Mehrzeilige Kommentare, starten + mit einem Slash-Stern und enden mit einem Stern-Slash */ // Einen Wert, und eine zusätzliche neue Zeile ausgeben -``` + println("Hello world!") println(10) -``` + // Einen Wert, ohne eine zusätzliche neue Zeile ausgeben -``` + print("Hello world") -``` -// Variablen werden entweder mit var oder val deklariert. -// Deklarationen mit val sind immutable, also unveränderlich -// Deklarationen mit var sind mutable, also veränderlich -// Immutability ist gut. -``` +/* + Variablen werden entweder mit var oder val deklariert. + Deklarationen mit val sind immutable, also unveränderlich + Deklarationen mit var sind mutable, also veränderlich + Immutability ist gut. +*/ val x = 10 // x ist 10 x = 20 // error: reassignment to val var y = 10 y = 20 // y ist jetzt 20 -``` -Scala ist eine statisch getypte Sprache, auch wenn in dem o.g. Beispiel +/* +Scala ist eine statisch getypte Sprache, auch wenn wir in dem o.g. Beispiel keine Typen an x und y geschrieben haben. -In Scala ist etwas eingebaut, was sich Type Inference nennt. D.h. das der -Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine ist, -so dass der Typ nicht jedes mal angegeben werden soll. +In Scala ist etwas eingebaut, was sich Type Inference nennt. Das heißt das der +Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine Variable ist, +so dass der Typ nicht jedes mal angegeben werden muss. Einen Typ gibt man bei einer Variablendeklaration wie folgt an: -``` +*/ val z: Int = 10 val a: Double = 1.0 -``` + // Bei automatischer Umwandlung von Int auf Double wird aus 10 eine 10.0 -``` + val b: Double = 10 -``` + // Boolean Werte -``` + true false -``` + // Boolean Operationen -``` + !true // false !false // true true == false // false 10 > 5 // true -``` + // Mathematische Operationen sind wie gewohnt -``` + 1 + 1 // 2 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 6 / 4 // 1 6.0 / 4 // 1.5 -``` + // Die Auswertung eines Ausdrucks in der REPL gibt den Typ // und das Ergebnis zurück. -``` + scala> 1 + 7 res29: Int = 8 -``` +/* Das bedeutet, dass das Resultat der Auswertung von 1 + 7 ein Objekt von Typ Int ist und einen Wert 0 hat. "res29" ist ein sequentiell generierter name, um das Ergebnis des Ausdrucks zu speichern. Dieser Wert kann bei Dir anders sein... - +*/ "Scala strings werden in doppelten Anführungszeichen eingeschlossen" 'a' // A Scala Char // 'Einzeln ge-quotete strings gibt es nicht!' <= This causes an error // Für Strings gibt es die üblichen Java Methoden -``` + "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") -``` + // Zusätzlich gibt es noch extra Scala Methoden // siehe: scala.collection.immutable.StringOps -``` + "hello world".take(5) "hello world".drop(5) -``` + // String interpolation: prefix "s" -``` + val n = 45 s"We have $n apples" // => "We have 45 apples" -``` -// Ausdrücke im innern von interpolierten Strings gibt es auch -``` + +// Ausdrücke im Innern von interpolierten Strings gibt es auch + val a = Array(11, 9, 6) val n = 100 s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" -``` + // Formatierung der interpolierten Strings mit dem prefix "f" -``` + f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" -``` + // Raw Strings, ignorieren Sonderzeichen. -``` + raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -``` + // Manche Zeichen müssen "escaped" werden, z.B. // ein doppeltes Anführungszeichen in innern eines Strings. -``` + "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -``` + // Dreifache Anführungszeichen erlauben es, dass ein String über mehrere Zeilen geht // und Anführungszeichen enthalten kann. -``` + val html = """

Press belo', Joe

""" -``` -# 2. Funktionen + +///////////////////////////////////////////////// +// 2. Funktionen +///////////////////////////////////////////////// // Funktionen werden so definiert // @@ -184,74 +190,74 @@ val html = """
// // Beachte: Es gibt kein return Schlüsselwort. In Scala ist der letzte Ausdruck // in einer Funktion der Rückgabewert. -``` + def sumOfSquares(x: Int, y: Int): Int = { val x2 = x * x val y2 = y * y x2 + y2 } -``` + // Die geschweiften Klammern können weggelassen werden, wenn // die Funktion nur aus einem einzigen Ausdruck besteht: -``` + def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y -``` + // Syntax für Funktionsaufrufe: -``` + sumOfSquares(3, 4) // => 25 -``` + // In den meisten Fällen (mit Ausnahme von rekursiven Funktionen), können // Rückgabetypen auch weggelassen werden, da dieselbe Typ Inference, wie bei // Variablen, auch bei Funktionen greift: -``` + def sq(x: Int) = x * x // Compiler errät, dass der return type Int ist -``` + // Funktionen können default parameter haben: -``` + def addWithDefault(x: Int, y: Int = 5) = x + y addWithDefault(1, 2) // => 3 addWithDefault(1) // => 6 -``` + // Anonyme Funktionen sehen so aus: -``` + (x: Int) => x * x -``` + // Im Gegensatz zu def bei normalen Funktionen, kann bei anonymen Funktionen // sogar der Eingabetyp weggelassen werden, wenn der Kontext klar ist. // Beachte den Typ "Int => Int", dies beschreibt eine Funktion, // welche Int als Parameter erwartet und Int zurückgibt. -``` + val sq: Int => Int = x => x * x -``` + // Anonyme Funktionen benutzt man ganz normal: -``` + sq(10) // => 100 -``` + // Wenn ein Parameter einer anonymen Funktion nur einmal verwendet wird, // bietet Scala einen sehr kurzen Weg diesen Parameter zu benutzen, // indem die Parameter als Unterstrich "_" in der Parameterreihenfolge // verwendet werden. Diese anonymen Funktionen werden sehr häufig // verwendet. -``` + val addOne: Int => Int = _ + 1 val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) addOne(5) // => 6 weirdSum(2, 4) // => 16 -``` + // Es gibt einen keyword return in Scala. Allerdings ist seine Verwendung // nicht immer ratsam und kann fehlerbehaftet sein. "return" gibt nur aus // dem innersten def, welches den return Ausdruck umgibt, zurück. // "return" hat keinen Effekt in anonymen Funktionen: -``` + def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) @@ -261,28 +267,30 @@ def foo(x: Int): Int = { } anonFunc(x) // Zeile ist der return Wert von foo } -``` -# 3. Flow Control -## Wertebereiche und Schleifen -``` +///////////////////////////////////////////////// +// 3. Flow Control +///////////////////////////////////////////////// + +// Wertebereiche und Schleifen + 1 to 5 val r = 1 to 5 r.foreach(println) r foreach println (5 to 1 by -1) foreach (println) -``` -// Scala ist syntaktisch sehr grosszügig, Semikolons am Zeilenende + +// Scala ist syntaktisch sehr großzügig, Semikolons am Zeilenende // sind optional, beim Aufruf von Methoden können die Punkte // und Klammern entfallen und Operatoren sind im Grunde austauschbare Methoden // while Schleife -``` + var i = 0 while (i < 10) { println("i " + i); i += 1 } i // i ausgeben, res3: Int = 10 -``` + // Beachte: while ist eine Schleife im klassischen Sinne - // Sie läuft sequentiell ab und verändert die loop-Variable. @@ -291,28 +299,28 @@ i // i ausgeben, res3: Int = 10 // und zu parellelisieren. // Ein do while Schleife -``` + do { println("x ist immer noch weniger wie 10") x += 1 } while (x < 10) -``` + // Endrekursionen sind ideomatisch um sich wiederholende // Dinge in Scala zu lösen. Rekursive Funtionen benötigen explizit einen // return Typ, der Compiler kann ihn nicht erraten. // Unit, in diesem Beispiel. -``` + def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) } showNumbersInRange(1, 14) -``` -## Conditionals -``` + +// Conditionals + val x = 10 if (x == 1) println("yeah") if (x == 10) println("yeah") @@ -320,186 +328,193 @@ if (x == 11) println("yeah") if (x == 11) println ("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -``` -# 4. Daten Strukturen (Array, Map, Set, Tuples) -## Array -``` +///////////////////////////////////////////////// +// 4. Daten Strukturen (Array, Map, Set, Tuples) +///////////////////////////////////////////////// + +// Array + val a = Array(1, 2, 3, 5, 8, 13) a(0) a(3) a(21) // Exception -``` -## Map - Speichert Key-Value-Paare -``` + +// Map - Speichert Key-Value-Paare + val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") m("bottle") // Exception val safeM = m.withDefaultValue("no lo se") safeM("bottle") -``` -## Set - Speichert Unikate, unsortiert (sortiert -> SortedSet) -``` + +// Set - Speichert Unikate, unsortiert (sortiert -> SortedSet) + val s = Set(1, 3, 7) s(0) //false s(1) //true val s = Set(1,1,3,3,7) s: scala.collection.immutable.Set[Int] = Set(1, 3, 7) -``` -## Tuple - Speichert beliebige Daten und "verbindet" sie miteinander + +// Tuple - Speichert beliebige Daten und "verbindet" sie miteinander // Ein Tuple ist keine Collection. -``` + (1, 2) (4, 3, 2) (1, 2, "three") (a, 2, "three") -``` + // Hier ist der Rückgabewert der Funktion ein Tuple // Die Funktion gibt das Ergebnis, so wie den Rest zurück. -``` + val divideInts = (x: Int, y: Int) => (x / y, x % y) divideInts(10, 3) -``` + // Um die Elemente eines Tuples anzusprechen, benutzt man diese // Notation: _._n wobei n der index des Elements ist (Index startet bei 1) -``` + val d = divideInts(10, 3) d._1 d._2 -``` -# 5. Objekt Orientierte Programmierung -Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar -zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in -einem Scala file selten alleine zu finden sind. -Die einzigen Top-Level Konstrukte in Scala sind nämlich: -- Klassen (classes) -- Objekte (objects) -- case classes -- traits +///////////////////////////////////////////////// +// 5. Objektorientierte Programmierung +///////////////////////////////////////////////// + +/* + Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar + zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in + einem Scala file selten alleine zu finden sind. + Die einzigen Top-Level Konstrukte in Scala sind nämlich: + + - Klassen (classes) + - Objekte (objects) + - case classes + - traits -Diesen Sprachelemente wenden wir uns jetzt zu. + Diesen Sprachelemente wenden wir uns jetzt zu. +*/ -## Klassen +// Klassen // Zum Erstellen von Objekten benötigt man eine Klasse, wie in vielen // anderen Sprachen auch. // erzeugt Klasse mit default Konstruktor -``` + class Hund scala> val t = new Hund t: Hund = Hund@7103745 -``` + // Der Konstruktor wird direkt hinter dem Klassennamen deklariert. -``` + class Hund(sorte: String) scala> val t = new Hund("Dackel") t: Hund = Hund@14be750c scala> t.sorte //error: value sorte is not a member of Hund -``` + // Per val wird aus dem Attribut ein unveränderliches Feld der Klasse // Per var wird aus dem Attribut ein veränderliches Feld der Klasse -``` + class Hund(val sorte: String) scala> val t = new Hund("Dackel") t: Hund = Hund@74a85515 scala> t.sorte res18: String = Dackel -``` + // Methoden werden mit def geschrieben -``` + def bark = "Woof, woof!" -``` + // Felder und Methoden können public, protected und private sein // default ist public // private ist nur innerhalb des deklarierten Bereichs sichtbar -``` + class Hund { private def x = ... def y = ... } -``` + // protected ist nur innerhalb des deklarierten und aller // erbenden Bereiche sichtbar -``` + class Hund { protected def x = ... } class Dackel extends Hund { // x ist sichtbar } -``` -## Object -Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog. -"companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so -ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse -benutzen ohne ein Objekt instanziieren zu müssen. -Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn -es genauso heisst und in derselben Datei wie die Klasse definiert wurde. -``` + +// Object +// Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog. +// "companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so +// ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse +// benutzen ohne ein Objekt instanziieren zu müssen. +// Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn +// es genauso heisst und in derselben Datei wie die Klasse definiert wurde. + object Hund { def alleSorten = List("Pitbull", "Dackel", "Retriever") def createHund(sorte: String) = new Hund(sorte) } -``` -## Case classes -Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra -Funktionalität erweitern. Mit Case Klassen bekommt man ein paar -Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B. -ein companion object mit den entsprechenden Methoden, -Hilfsmethoden wie toString(), equals() und hashCode() und auch noch -Getter für unsere Attribute (das Angeben von val entfällt dadurch) -``` + +// Case classes +// Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra +// Funktionalität erweitern. Mit Case Klassen bekommt man ein paar +// Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B. +// ein companion object mit den entsprechenden Methoden, +// Hilfsmethoden wie toString(), equals() und hashCode() und auch noch +// Getter für unsere Attribute (das Angeben von val entfällt dadurch) + class Person(val name: String) class Hund(val sorte: String, val farbe: String, val halter: Person) -``` + // Es genügt das Schlüsselwort case vor die Klasse zu schreiben. -``` + case class Person(name: String) case class Hund(sorte: String, farbe: String, halter: Person) -``` + // Für neue Instanzen brauch man kein "new" -``` + val dackel = Hund("dackel", "grau", Person("peter")) val dogge = Hund("dogge", "grau", Person("peter")) -``` + // getter -``` + dackel.halter // => Person = Person(peter) -``` + // equals -``` + dogge == dackel // => false -``` + // copy // otherGeorge == Person("george", "9876") -``` + val otherGeorge = george.copy(phoneNumber = "9876") -``` -## Traits -Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp -und Methodensignaturen. Scala erlaubt allerdings das teilweise -implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt. -Traits können von anderen Traits oder Klassen erben, aber nur von -parameterlosen. -``` + +// Traits +// Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp +// und Methodensignaturen. Scala erlaubt allerdings das teilweise +// implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt. +// Traits können von anderen Traits oder Klassen erben, aber nur von +// parameterlosen. + trait Hund { def sorte: String def farbe: String @@ -511,9 +526,9 @@ class Bernhardiner extends Hund{ val farbe = "braun" def beissen = false } -``` + -``` + scala> b res0: Bernhardiner = Bernhardiner@3e57cd70 scala> b.sorte @@ -522,10 +537,10 @@ scala> b.bellen res2: Boolean = true scala> b.beissen res3: Boolean = false -``` + // Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden -``` + trait Bellen { def bellen: String = "Woof" } @@ -541,25 +556,27 @@ scala> val b = new Bernhardiner b: Bernhardiner = Bernhardiner@7b69c6ba scala> b.bellen res0: String = Woof -``` -# 6. Pattern Matching -Pattern matching in Scala ist ein sehr nützliches und wesentlich -mächtigeres Feature als Vergleichsfunktionen in Java. In Scala -benötigt ein case Statement kein "break", ein fall-through gibt es nicht. -Mehrere Überprüfungen können mit einem Statement gemacht werden. -Pattern matching wird mit dem Schlüsselwort "match" gemacht. -``` +///////////////////////////////////////////////// +// 6. Pattern Matching +///////////////////////////////////////////////// + +// Pattern matching in Scala ist ein sehr nützliches und wesentlich +// mächtigeres Feature als Vergleichsfunktionen in Java. In Scala +// benötigt ein case Statement kein "break", ein fall-through gibt es nicht. +// Mehrere Überprüfungen können mit einem Statement gemacht werden. +// Pattern matching wird mit dem Schlüsselwort "match" gemacht. + val x = ... x match { case 2 => case 3 => case _ => } -``` + // Pattern Matching kann auf beliebige Typen prüfen -``` + val any: Any = ... val gleicht = any match { case 2 | 3 | 5 => "Zahl" @@ -568,19 +585,19 @@ val gleicht = any match { case 45.35 => "Double" case _ => "Unbekannt" } -``` + // und auf Objektgleichheit -``` + def matchPerson(person: Person): String = person match { case Person("George", nummer) => "George! Die Nummer ist " + number case Person("Kate", nummer) => "Kate! Die Nummer ist " + nummer case Person(name, nummer) => "Irgendjemand: " + name + ", Telefon: " + nummer } -``` + // Und viele mehr... -``` + val email = "(.*)@(.*)".r // regex def matchEverything(obj: Any): String = obj match { // Werte: @@ -600,18 +617,21 @@ def matchEverything(obj: Any): String = obj match { // Patterns kann man ineinander schachteln: case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" } -``` + // Jedes Objekt mit einer "unapply" Methode kann per Pattern geprüft werden // Ganze Funktionen können Patterns sein -``` + val patternFunc: Person => String = { case Person("George", number) => s"George's number: $number" case Person(name, number) => s"Random person's number: $number" } -``` -# 7. Higher-order functions + +///////////////////////////////////////////////// +// 37. Higher-order functions +///////////////////////////////////////////////// + Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen higher-order functions @@ -621,116 +641,117 @@ Nennenswerte sind: "filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall" ## List -``` + def isGleichVier(a:Int) = a == 4 val list = List(1, 2, 3, 4) val resultExists4 = list.exists(isEqualToFour) -``` + ## map // map nimmt eine Funktion und führt sie auf jedem Element aus und erzeugt // eine neue Liste // Funktion erwartet ein Int und returned ein Int -``` + val add10: Int => Int = _ + 10 -``` + // add10 wird auf jedes Element angewendet -``` + List(1, 2, 3) map add10 // => List(11, 12, 13) -``` + // Anonyme Funktionen können anstatt definierter Funktionen verwendet werden -``` + List(1, 2, 3) map (x => x + 10) -``` + // Der Unterstrich wird anstelle eines Parameters einer anonymen Funktion // verwendet. Er wird an die Variable gebunden. -``` + List(1, 2, 3) map (_ + 10) -``` + // Wenn der anonyme Block und die Funtion beide EIN Argument erwarten, // kann sogar der Unterstrich weggelassen werden. -``` + List("Dom", "Bob", "Natalia") foreach println -``` -## filter + +// filter // filter nimmt ein Prädikat (eine Funktion von A -> Boolean) und findet // alle Elemente die auf das Prädikat passen -``` + List(1, 2, 3) filter (_ > 2) // => List(3) case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) ).filter(_.age > 25) // List(Person("Bob", 30)) -``` -## reduce + +// reduce // reduce nimmt zwei Elemente und kombiniert sie zu einem Element, // und zwar solange bis nur noch ein Element da ist. -## foreach +// foreach // foreach gibt es für einige Collections -``` + val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println -``` -## For comprehensions + +// For comprehensions // Eine for-comprehension definiert eine Beziehung zwischen zwei Datensets. // Dies ist keine for-Schleife. -``` + for { n <- s } yield sq(n) val nSquared2 = for { n <- s } yield sq(n) for { n <- nSquared2 if n < 10 } yield n for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared -``` + ///////////////////////////////////////////////// -# 8. Implicits +// 8. Implicits ///////////////////////////////////////////////// -**ACHTUNG:** -Implicits sind ein sehr mächtiges Sprachfeature von Scala. Es sehr einfach -sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am -besten erst dann benutzen, wenn man versteht wie sie funktionieren. -Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle -vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles -machen kann. -Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren. +// **ACHTUNG:** +// Implicits sind ein sehr mächtiges Sprachfeature von Scala. +// Es sehr einfach +// sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am +// besten erst dann benutzen, wenn man versteht wie sie funktionieren. +// Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle +// vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles +// machen kann. +// Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren. // Mit dem Schlüsselwort implicit können Methoden, Werte, Funktion, Objekte // zu "implicit Methods" werden. -``` + implicit val myImplicitInt = 100 implicit def myImplicitFunction(sorte: String) = new Hund("Golden " + sorte) -``` + // implicit ändert nicht das Verhalten eines Wertes oder einer Funktion -``` + myImplicitInt + 2 // => 102 myImplicitFunction("Pitbull").sorte // => "Golden Pitbull" -``` + // Der Unterschied ist, dass diese Werte ausgewählt werden können, wenn ein // anderer Codeteil einen implicit Wert benötigt, zum Beispiel innerhalb von // implicit Funktionsparametern // Diese Funktion hat zwei Parameter: einen normalen und einen implicit -``` + def sendGreetings(toWhom: String)(implicit howMany: Int) = s"Hello $toWhom, $howMany blessings to you and yours!" -``` + // Werden beide Parameter gefüllt, verhält sich die Funktion wie erwartet -``` + sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" -``` + // Wird der implicit Parameter jedoch weggelassen, wird ein anderer // implicit Wert vom gleichen Typ genommen. Der Compiler sucht im @@ -739,66 +760,69 @@ sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours! // geforderten Typ konvertieren kann. // Hier also: "myImplicitInt", da ein Int gesucht wird -``` + sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" -``` + // bzw. "myImplicitFunction" // Der String wird erst mit Hilfe der Funktion in Hund konvertiert, und // dann wird die Methode aufgerufen -``` + "Retriever".sorte // => "Golden Retriever" -``` -# 9. Misc -## Importe -``` + +///////////////////////////////////////////////// +// 19. Misc +///////////////////////////////////////////////// +// Importe + import scala.collection.immutable.List -``` + // Importiere alle Unterpackages -``` + import scala.collection.immutable._ -``` + // Importiere verschiedene Klassen mit einem Statement -``` + import scala.collection.immutable.{List, Map} -``` + // Einen Import kann man mit '=>' umbenennen -``` + import scala.collection.immutable.{List => ImmutableList} -``` + // Importiere alle Klasses, mit Ausnahem von.... // Hier ohne: Map and Set: -``` + import scala.collection.immutable.{Map => _, Set => _, _} -``` -## Main -``` + +// Main + object Application { def main(args: Array[String]): Unit = { - // stuff goes here. + // Sachen kommen hierhin } } -``` -## I/O + +// I/O // Eine Datei Zeile für Zeile lesen -``` + import scala.io.Source for(line <- Source.fromFile("myfile.txt").getLines()) println(line) -``` + // Eine Datei schreiben -``` + val writer = new PrintWriter("myfile.txt") writer.write("Schreibe Zeile" + util.Properties.lineSeparator) writer.write("Und noch eine Zeile" + util.Properties.lineSeparator) writer.close() + ``` ## Weiterführende Hinweise -- cgit v1.2.3 From 7a6d3b15490b882cd387f7eeb9b14d5ab20c55b1 Mon Sep 17 00:00:00 2001 From: Saurabh Sandav Date: Wed, 28 Oct 2015 13:16:13 +0530 Subject: [elisp/en] Fix typo --- lua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua.html.markdown b/lua.html.markdown index 3d95c146..2cd4d7bb 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -190,7 +190,7 @@ end -------------------------------------------------------------------------------- -- A table can have a metatable that gives the table operator-overloadish --- behavior. Later we'll see how metatables support js-prototypey behaviour. +-- behaviour. Later we'll see how metatables support js-prototypey behaviour. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} -- cgit v1.2.3 From 4ff79b2554ca3d16e4b64d0d4b367191cdc31887 Mon Sep 17 00:00:00 2001 From: Jason Yeo Date: Wed, 28 Oct 2015 17:46:57 +0800 Subject: Fix minor typographical errors --- edn.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/edn.html.markdown b/edn.html.markdown index 14bb25b4..b303d63c 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -22,7 +22,7 @@ will see how it is extended later on. ;;; Basic Types ;;; ;;;;;;;;;;;;;;;;;;; -nil ; or aka null +nil ; also known in other languages as null ; Booleans true @@ -35,14 +35,15 @@ false ; Characters are preceeded by backslashes \g \r \a \c \e -; Keywords starts with a colon. They behave like enums. Kinda -; like symbols in ruby. +; Keywords start with a colon. They behave like enums. Kinda +; like symbols in Ruby. :eggs :cheese :olives -; Symbols are used to represent identifiers. You can namespace symbols by -; using /. Whatever preceeds / is the namespace of the name. +; Symbols are used to represent identifiers. They start with #. +; You can namespace symbols by using /. Whatever preceeds / is +; the namespace of the name. #spoon #kitchen/spoon ; not the same as #spoon #kitchen/fork @@ -52,7 +53,7 @@ false 42 3.14159 -; Lists are a sequence of values +; Lists are sequences of values (:bun :beef-patty 9 "yum!") ; Vectors allow random access -- cgit v1.2.3 From 5f6d0d030001c465656661632fbea540a54bae69 Mon Sep 17 00:00:00 2001 From: Jason Yeo Date: Wed, 28 Oct 2015 17:51:18 +0800 Subject: Kinda -> Kind of --- edn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/edn.html.markdown b/edn.html.markdown index b303d63c..655c20f1 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -35,7 +35,7 @@ false ; Characters are preceeded by backslashes \g \r \a \c \e -; Keywords start with a colon. They behave like enums. Kinda +; Keywords start with a colon. They behave like enums. Kind of ; like symbols in Ruby. :eggs :cheese -- cgit v1.2.3 From 951a51379aaf95eac83e6df2fdb8717ff0e64ec0 Mon Sep 17 00:00:00 2001 From: Morgan Date: Wed, 28 Oct 2015 11:52:21 +0100 Subject: [livescript/fr] Correct the translator github repository --- fr-fr/livescript-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown index 9c3b8003..13bbffe5 100644 --- a/fr-fr/livescript-fr.html.markdown +++ b/fr-fr/livescript-fr.html.markdown @@ -4,7 +4,7 @@ filename: learnLivescript-fr.ls contributors: - ["Christina Whyte", "http://github.com/kurisuwhyte/"] translators: - - ["Morgan Bohn", "https://github.com/morganbohn"] + - ["Morgan Bohn", "https://github.com/dotmobo"] lang: fr-fr --- -- cgit v1.2.3 From db903ac5b6c80fa4b0e8502fb4b3abfd1bed07ee Mon Sep 17 00:00:00 2001 From: Srinivasan R Date: Wed, 28 Oct 2015 16:25:54 +0530 Subject: Add one more string formatting example --- python.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/python.html.markdown b/python.html.markdown index 753d6e8c..3d63183c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -128,6 +128,7 @@ not False # => True # A newer way to format strings is the format method. # This method is the preferred way +"{} is a {}".format("This", "placeholder") "{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count. "{name} wants to eat {food}".format(name="Bob", food="lasagna") -- cgit v1.2.3 From de581a070c4711a92b9cffb26a28be876067100b Mon Sep 17 00:00:00 2001 From: Lidenburg Date: Wed, 28 Oct 2015 18:49:05 +0100 Subject: [brainfuck/sv] Create swedish branch and add brainfuck Created swedish branch and created brainfuck translation --- sv-sv/brainfuck-sv.html.markdown | 85 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 sv-sv/brainfuck-sv.html.markdown diff --git a/sv-sv/brainfuck-sv.html.markdown b/sv-sv/brainfuck-sv.html.markdown new file mode 100644 index 00000000..dc65da06 --- /dev/null +++ b/sv-sv/brainfuck-sv.html.markdown @@ -0,0 +1,85 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Richard Lindberg", "https://github.com/Lidenburg"] +lang: sv-sv +--- + +Brainfuck (ej versaliserat förutom vid ny mening) är ett extremt +minimalistiskt Turing-komplett programmeringsspråk med endast 8 kommandon. + +Du kan testa brainfuck i din webbläsare via [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Alla karaktärer förutom "><+-.,[]" (inte inkluderat citattecken) ignoreras. + +Brainfuck är representerat av ett fält med 30 000 celler initialiserade till +noll och en data pekare som pekar på den valda cellen. + +Det finns åtta kommandon: ++ : Ökar värdet av den valda cellen med ett. +- : Minskar värdet av den valda cellen med ett. +> : Flyttar data pekaren till nästa cell (cellen till höger). +< : Flyttar data pekaren till förra cellen (cellen till vänster). +. : Skriver ut ASCII värdet av den valda cellen (t.ex. 65 = 'A'). +, : Läser in en karaktär till den valda cellen. +[ : Om värdet vid den valda cellen är noll, hoppa till matchande ]. + Annars fortsätts till nästa instruktion. +] : Om värdet vid den valda cellen är noll, fortsätt till nästa instruktion. + Annars, gå tillbaka till matchande ]. + +[ och ] formar en while loop. + +Nedan är ett exempel på ett simpelt brainfuck program. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Programmet skriver ut bokstaven 'A'. Först ökar den värdet av cell #1 till 6. +Cell #1 kommer att användas för att loopa. Sen börjar den loopen (vid '[') och +flyttar till cell #2. Den ökar värdet av cell #2 10 gånger, går tillbaka till +cell #1 och minskar den med 1. Den gör det här 6 gånger (så många iterationer +det tar för cell #1 att bli noll). + +Nu är programmet på cell #1, vilket har ett värde av 0 och cell #2 har värdet 60. +Programmet flyttar pekaren till cell #2 och ökar värdet med 5, vilket leder till +att cell #2 har ett värde av 65 (vilket är bokstaven 'A' i ASCII), sedan skriver +den ut cell #2 och bokstaven 'A' skrivs ut till skärmen. + + +, [ > + < - ] > . + +Det här programmet läser en karaktär från användaren och kopierar karaktären +till cell #1. Sedan startas en loop. Pekaren flyttas till cell #2, värder ökas +med ett, pekaren flyttas tillbaka till cell #1 och minskar värdet med ett. +Det här fortsätter tills cell #1 innehåller noll och cell #2 innehåller det +värde som cell #1 innehöll från början. Eftersom att programmet vid slutet av +loopen är på cell #1 flyttas pekaren till cell #2 och sedan skriver den ut +värdet av cell #2 i ASCII. + +Värt att kommaihåg är att programmet ovan kan skrivas utan mellanslag också: + +,[>+<-]>. + + +Försök och lista ut vad det här programmet gör: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Programmet tar två nummer som indata, och multiplicerar dem. + +Kärnan av det är att den först läser in två tal/bokstäver. Sedan startar +den yttre loopen som beror på cell #1. Sedan går den vidare till cell #2 och +startar den innre loopen som beror på cell #2 och ökar cell #3. Men det uppstår +ett problem: Vid slutet av den innre loopen är cell #2 noll. Vilket betyder att +den inre loopen inte kommer att fungera tills nästa gång. För att lösa det här +problemet ökas också cell #4 som sedan kopieras till cell #2. +Sedan är resultatet i cell #3. +``` + +Och det är brainfuck. Inte så svårt va? För skojs skull kan du skriva dina egna +brainfuck program, eller skriva en egen brainfuck interpretator i ett annat +språk. interpretatorn är ganska simpel att implementera, men om man är en +masochist, testa att skriva en brainfuck interpretator… i brainfuck. -- cgit v1.2.3 From 6fec7490ade632cb22f2f22cd999e4f797f75eef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Puente=20Sarr=C3=ADn?= Date: Wed, 28 Oct 2015 15:52:29 -0500 Subject: Minor edit. --- es-es/python-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index 83341682..a27203d1 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -48,7 +48,7 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl # Resultado de la división de enteros truncada para positivos y negativos 5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # funciona con números en coma flotante +5.0 // 3.0 # => 1.0 # funciona con números de coma flotante -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -- cgit v1.2.3 From 08e6aa4e6e0344082517ad94d29fb33b81e827a9 Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Wed, 28 Oct 2015 17:25:44 -0400 Subject: Adding a small blurb to extend upon string concatination --- javascript.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index cd75b0d2..e285ca4e 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -101,6 +101,10 @@ false; // Strings are concatenated with + "Hello " + "world!"; // = "Hello world!" +// ... which works with more than just strings +"1, 2, " + 3; // = "1, 2, 3" +"Hello " + ["world", "!"] // = "Hello world,!" + // and are compared with < and > "a" < "b"; // = true -- cgit v1.2.3 From 4f2a9eb51a4084512f87246712cb592a60c5523c Mon Sep 17 00:00:00 2001 From: Sam van Kampen Date: Wed, 28 Oct 2015 22:37:54 +0100 Subject: Fix incorrect word (koffie -> vloeistof) --- nl-nl/coffeescript-nl.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown index dc0b1e19..bb46eb9b 100644 --- a/nl-nl/coffeescript-nl.html.markdown +++ b/nl-nl/coffeescript-nl.html.markdown @@ -43,7 +43,7 @@ getal = -42 if tegengestelde #=> if(tegengestelde) { getal = -42; } kwadraat = (x) -> x * x #=> var kwadraat = function(x) { return x * x; } vul = (houder, vloeistof = "koffie") -> - "Nu de #{houder} met #{koffie} aan het vullen..." + "Nu de #{houder} met #{vloeistof} aan het vullen..." #=>var vul; # #vul = function(houder, vloeistof) { -- cgit v1.2.3 From dc3c1ce2f58da378dd354f6c34233123fa6e3d44 Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 22:43:07 +0100 Subject: add Hungarian translation --- hu-hu/coffeescript-hu.html.markdown | 106 ++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 hu-hu/coffeescript-hu.html.markdown diff --git a/hu-hu/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown new file mode 100644 index 00000000..111a0a85 --- /dev/null +++ b/hu-hu/coffeescript-hu.html.markdown @@ -0,0 +1,106 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Tamás Diószegi", "http://github.com/ditam"] +filename: coffeescript.coffee +--- + +A CoffeeScript egy apró nyelv ami egy-az-egyben egyenértékű Javascript kódra fordul, és így futásidőben már nem szükséges interpretálni. +Mint a JavaScript egyik követője, a CoffeeScript mindent megtesz azért, hogy olvasható, jól formázott és jól futó JavaScript kódot állítson elő, ami minden JavaScript futtatókörnyezetben jól működik. + +Rézletekért lásd még a [CoffeeScript weboldalát](http://coffeescript.org/), ahol egy teljes CoffeScript tutorial is található. + +```coffeescript +# A CoffeeScript egy hipszter nyelv. +# Követi több modern nyelv trendjeit. +# Így a kommentek, mint Ruby-ban és Python-ban, a szám szimbólummal kezdődnek. + +### +A komment blokkok ilyenek, és közvetlenül '/ *' és '* /' jelekre fordítódnak +az eredményül kapott JavaScript kódban. + +Mielőtt tovább olvasol, jobb, ha a JavaScript alapvető szemantikájával +tisztában vagy. + +(A kód példák alatt kommentként látható a fordítás után kapott JavaScript kód.) +### + +# Értékadás: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Feltételes utasítások: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Függvények: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "coffee") -> + "Filling the #{container} with #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Filling the " + container + " with " + liquid + "..."; +#}; + +# Szám tartományok: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objektumok: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +# }; + +# "Splat" jellegű függvény-paraméterek: +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +# }; + +# Létezés-vizsgálat: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Tömb értelmezések: (array comprehensions) +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} +``` + +## További források + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) \ No newline at end of file -- cgit v1.2.3 From 06490d1d1642eb7ef5ed6b7e891d0179137b6f0a Mon Sep 17 00:00:00 2001 From: Sam van Kampen Date: Wed, 28 Oct 2015 23:07:20 +0100 Subject: Fix a couple of other tiny mistakes --- nl-nl/coffeescript-nl.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown index bb46eb9b..390e6572 100644 --- a/nl-nl/coffeescript-nl.html.markdown +++ b/nl-nl/coffeescript-nl.html.markdown @@ -6,6 +6,7 @@ contributors: translators: - ["Jelle Besseling", "https://github.com/Jell-E"] - ["D.A.W. de Waal", "http://github.com/diodewaal"] + - ["Sam van Kampen", "http://tehsvk.net"] filename: coffeescript-nl.coffee lang: nl-nl --- @@ -13,10 +14,10 @@ lang: nl-nl CoffeeScript is een kleine programmeertaal die direct compileert naar JavaScript en er is geen interpretatie tijdens het uitvoeren. CoffeeScript probeert om leesbare, goed geformatteerde en goed draaiende -JavaScript code te genereren, die in elke JavaScript runtime werkt, als een +JavaScript code te genereren, die in elke JavaScript-runtime werkt, als een opvolger van JavaScript. -Op [de CoffeeScript website](http://coffeescript.org/), staat een +Op [de CoffeeScript-website](http://coffeescript.org/), staat een volledigere tutorial voor CoffeeScript. ``` coffeescript @@ -26,7 +27,7 @@ volledigere tutorial voor CoffeeScript. ### Blokken commentaar maak je zo, ze vertalen naar JavaScripts */ en /* -in de uitvoer van de CoffeeScript compiler. +in de uitvoer van de CoffeeScript-compiler. Het is belangrijk dat je ongeveer snapt hoe JavaScript werkt voordat je verder gaat. @@ -80,7 +81,7 @@ wedstrijd = (winnaar, lopers...) -> alert "Ik wist het!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } -# Lijst abstractie: +# Lijstabstracties: derdemachten = (wiskunde.derdemacht num for num in lijst) #=>derdemachten = (function() { # var _i, _len, _results; -- cgit v1.2.3 From 35a1cd4eeb96557c70de57b972b0000c94245f13 Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 23:31:15 +0100 Subject: add Hungarian translation --- hu-hu/yaml-hu.html.markdown | 146 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) create mode 100644 hu-hu/yaml-hu.html.markdown diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown new file mode 100644 index 00000000..eeafbfb3 --- /dev/null +++ b/hu-hu/yaml-hu.html.markdown @@ -0,0 +1,146 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +--- + +A YAML egy adat sorosító nyelv amit úgy terveztek, hogy közvetlenül is +olvasható és írható legyen emberi szemmel. + +A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt +szintaktikai jelentéssel bíró sortörésekkel és indentációval, +a Python-hoz hasonlóan. A Python-nal ellentétben azonban a YAML nem engedélyezi +a közvetlen tab karakterek jelenlétét. + +Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő, +a kódolást a tartalomban explicit nem kell (és nem is lehet) feltüntetni. + +```yaml +# A kommentek YAML-ban így néznek ki. + +################## +# Skalár típusok # +################## + +# A gyökér objektumunk (az egész dokumentumra értve) egy map, +# ami a más nyelvekből ismert dictionary, hash vagy object típusokkal egyenértékű. +kulcs: érték +masik_kulcs: Másik érték jön ide. +egy_szam: 100 +tudomanyos_jelolessel: 1e+12 +boolean: true +null_value: null +kulcs benne szóközökkel: érték +# Látható, hogy a sztringeket nem szükséges idézőjelek közé zárni, bár szabad. +Továbbá: "Idézőjelekkel megadott sztring." +"A kulcs is lehet idézőjeles.": "Hasznos lehet, ha ':'-ot akarsz a kulcsban." + +# Többsoros sztringek írhatóak 'literal block'-ként ('|' jelet használva) +# vagy 'folded block'-ként is ('>' jelet használva). +literal_block: | + Ez az egész szöveg-blokk lesz az értéke a literal_block kulcsnak, + a sortöréseket megtartva. + + Az ilyen sztringet az indentáció visszahúzása zárja le, a behúzás pedig + eltávolításra kerül. + + A 'még jobban' behúzott részek megtartják a behúzásukat - + ezeknek a soroknak 4 szóköz behúzása lesz. +folded_style: > + Az az egész szöveg-blokk lesz az értéke a 'folded_style' kulcsnak, de + ezúttal minden sortörés egy szóközre lesz cserélve. + + Az üres sorok, mint a fenti, új sor karakterre cserélődnek. + + A 'még jobban' behúzott sorok megtartják a sortöréseiket, - + ez a szöveg két sorban jelenik meg. + +###################### +# Gyűjtemény típusok # +###################### + +# Egymásba ágyazás a behúzás változtatásával érhető el. +beagyazott_map: + key: value + another_key: Another Value + masik_beagyazott_map: + hello: hello + +# A mapeknek nem csak sztring kulcsaik lehetnek. +0.25: lebegőpontos kulcs + +# A kulcsok lehetnek többsoros objektumok is, ? jellel jelezve a kulcs kezdetét +? | + Ez itt egy + többsoros kulcs +: és ez az értéke + +# Szintén engedélyezett a kollekció típusok használata kulcsként, de egyéb +# nyelvekben ez gyakran problémákat fog okozni. + +# Szekvenciák (listákkal vagy tömbökkel egyenértékűek) így néznek ki: +egy_szekvencia: + - Item 1 + - Item 2 + - 0.5 # Többféle típust is tartalmazhat + - Item 4 + - key: value + another_key: another_value + - + - Ez egy szekvencia + - egy másik szekvenciába ágyazva + +# Mivel a YAML a JSON befoglaló halmazát alkotja, JSON szintaxisú +# mapek és szekvenciák is használhatóak: +json_map: {"key": "value"} +json_seq: [3, 2, 1, "takeoff"] + +######################### +# EXTRA YAML KÉPESSÉGEK # +######################### + +# A YAML-ben ún. 'anchor'-ök segítségével könnyen lehet duplikálni +# tartalmakat a dokumentumon belül. A következő kulcsok azonos értékkel bírnak: +anchored_tartalom: &anchor_neve Ez a sztring két kulcs értéke is lesz. +másik_anchor: *anchor_neve + +# Vannak a YAML-ben tagek is, amivel explicit lehet típusokat jelölni. +explicit_string: !!str 0.5 +# Bizonyos implementációk nyelv-specifikus tageket tartalmaznak, mint +# például ez a Python komplex szám típusának jelölésére: +python_complex_number: !!python/complex 1+2j + +###################### +# EXTRA YAML TÍPUSOK # +###################### + +# Nem a sztringek és a számok az egyedüli skalár típusok YAML-ben. +# ISO-formátumú dátumok és dátumot jelölő literal kifejezések is értelmezettek. +datetime: 2001-12-15T02:59:43.1Z +datetime_with_spaces: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 + +# A !!binary tag jelöli, hogy egy sztring valójában base64-kódolású +# reprezentációja egy bináris blob-nak +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= + +# Létezik a YAML-ban egy halmaz típus (set) is, ami így néz ki: +set: + ? elem1 + ? elem2 + ? elem3 + +# Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti +# halmaz egyenértékű a következővel: +set2: + item1: null + item2: null + item3: null +``` \ No newline at end of file -- cgit v1.2.3 From 78dee8ef7505e8ebc34bb8bf3d6be124231ee1a7 Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 23:36:48 +0100 Subject: fix small typos and grammar. --- hu-hu/yaml-hu.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown index eeafbfb3..757b8417 100644 --- a/hu-hu/yaml-hu.html.markdown +++ b/hu-hu/yaml-hu.html.markdown @@ -7,12 +7,12 @@ translators: - ["Tamás Diószegi", "https://github.com/ditam"] --- -A YAML egy adat sorosító nyelv amit úgy terveztek, hogy közvetlenül is +A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is olvasható és írható legyen emberi szemmel. A JSON formátum egy szigorú befoglaló halmazát alkotja, kiegészítve azt szintaktikai jelentéssel bíró sortörésekkel és indentációval, -a Python-hoz hasonlóan. A Python-nal ellentétben azonban a YAML nem engedélyezi +a Pythonhoz hasonlóan. A Pythonnal ellentétben azonban a YAML nem engedélyezi a közvetlen tab karakterek jelenlétét. Megjegyzés: UTF-8 ékezetes betűk használhatóak, ha a fájl kódlása megfelelő, @@ -140,7 +140,7 @@ set: # Mint Pythonban, a halmazok null értékekkel feltöltött mapek, vagyis a fenti # halmaz egyenértékű a következővel: set2: - item1: null - item2: null - item3: null + elem1: null + elem2: null + elem3: null ``` \ No newline at end of file -- cgit v1.2.3 From 360bd6ef9b5b1b6779d1d86bd57e12e97239007a Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 23:45:15 +0100 Subject: add language suffix to filename --- hu-hu/coffeescript-hu.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hu-hu/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown index 111a0a85..267db4d0 100644 --- a/hu-hu/coffeescript-hu.html.markdown +++ b/hu-hu/coffeescript-hu.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Xavier Yao", "http://github.com/xavieryao"] translators: - ["Tamás Diószegi", "http://github.com/ditam"] -filename: coffeescript.coffee +filename: coffeescript-hu.coffee --- A CoffeeScript egy apró nyelv ami egy-az-egyben egyenértékű Javascript kódra fordul, és így futásidőben már nem szükséges interpretálni. -- cgit v1.2.3 From 3b1940b9cc9c0e46a9275b2ae64e4c5996d7de75 Mon Sep 17 00:00:00 2001 From: Alex Luehm Date: Wed, 28 Oct 2015 17:45:31 -0500 Subject: [C/en] Added tidbit about fall-though in switch statements. Another pitfall, as not all languages have fall-through in switches. --- c.html.markdown | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 3d632eab..2a5e460f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -76,7 +76,7 @@ int main (int argc, char** argv) /////////////////////////////////////// // Types /////////////////////////////////////// - + // All variables MUST be declared at the top of the current block scope // we declare them dynamically along the code for the sake of the tutorial @@ -318,6 +318,12 @@ int main (int argc, char** argv) case 1: printf("Huh, 'a' equals 1!\n"); break; + // Be careful - without a "break", execution continues until the + // next "break" is reached. + case 3: + case 4: + printf("Look at that.. 'a' is either 3, or 4\n"); + break; default: // if `some_integral_expression` didn't match any of the labels fputs("error!\n", stderr); @@ -345,8 +351,8 @@ int main (int argc, char** argv) https://ideone.com/GuPhd6 this will print out "Error occured at i = 52 & j = 99." */ - - + + /////////////////////////////////////// // Typecasting /////////////////////////////////////// @@ -445,7 +451,7 @@ int main (int argc, char** argv) for (xx = 0; xx < 20; xx++) { *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints) - + // Note that there is no standard way to get the length of a // dynamically allocated array in C. Because of this, if your arrays are // going to be passed around your program a lot, you need another variable @@ -721,13 +727,13 @@ typedef void (*my_fnp_type)(char *); /******************************* Header Files ********************************** -Header files are an important part of c as they allow for the connection of c -source files and can simplify code and definitions by seperating them into +Header files are an important part of c as they allow for the connection of c +source files and can simplify code and definitions by seperating them into seperate files. -Header files are syntaxtically similar to c source files but reside in ".h" -files. They can be included in your c source file by using the precompiler -command #include "example.h", given that example.h exists in the same directory +Header files are syntaxtically similar to c source files but reside in ".h" +files. They can be included in your c source file by using the precompiler +command #include "example.h", given that example.h exists in the same directory as the c file. */ -- cgit v1.2.3 From d0ab5fc7729062d24b8f3aac1d8578e914a5955a Mon Sep 17 00:00:00 2001 From: ditam Date: Wed, 28 Oct 2015 23:47:41 +0100 Subject: add language suffix to filename --- hu-hu/yaml-hu.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown index 757b8417..aca6cd37 100644 --- a/hu-hu/yaml-hu.html.markdown +++ b/hu-hu/yaml-hu.html.markdown @@ -1,6 +1,6 @@ --- language: yaml -filename: learnyaml.yaml +filename: learnyaml-hu.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: -- cgit v1.2.3 From 769bcba250efeeadb3f7723adec09c73d7c512f2 Mon Sep 17 00:00:00 2001 From: Frank van Gemeren Date: Thu, 29 Oct 2015 01:30:15 +0100 Subject: [xml/nl] --- nl-nl/xml-nl.html.markdown | 134 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 nl-nl/xml-nl.html.markdown diff --git a/nl-nl/xml-nl.html.markdown b/nl-nl/xml-nl.html.markdown new file mode 100644 index 00000000..930f7cf4 --- /dev/null +++ b/nl-nl/xml-nl.html.markdown @@ -0,0 +1,134 @@ +--- +language: xml +filename: learnxml-nl.xml +contributors: + - ["Joo Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Frank van Gemeren", "https://github.com/frvge"] +lang: nl-nl +--- + +XML is een markuptaal die ontwikkeld is om data in te bewaren en data mee te +verzenden. + +Anders dan HTML specificeert XML niet hoe data getoond of geformatteerd moet worden. +Het bevat de data slechts. + +* XML Syntax + +```xml + + + + + + Alledaags Italiaans</titel> + <auteur>Giada De Laurentiis</auteur> + <jaar>2005</jaar> + <prijs>30.00</prijs> + </boek> + <boek categorie="KINDEREN"> + <titel taal="nl">Harry Potter</titel> + <auteur>J K. Rowling</auteur> + <jaar>2005</jaar> + <prijs>29.99</prijs> + </boek> + <boek categorie="WEB"> + <titel taal="en">Learning XML</titel> + <auteur>Erik T. Ray</auteur> + <jaar>2003</jaar> + <prijs>39.95</prijs> + </boek> +</boekenwinkel> + +<!-- Hierboven staat een standaard XML bestand. + Het begint met een declaratie die optionele metadata bevat. + + XML werkt met een boomstructuur. De stamknoop hierboven is 'boekenwinkel'. + Deze heeft drie kinderen die allemaal 'boek' zijn. Deze knopen hebben op + hun beurt weer kinderen, enzovoort... + + Knopen hebben open- en sluittags. Kinderen zijn knopen die zich tussen de + open- en sluittags van hun ouders bevinden. --> + +<!-- XML bevat two soorten data: + 1 - Attributen -> Dit is metadata van een knoop. + Deze informatie wordt meestal door de XML parser gebruikt om de data op + de juiste manier op te slaan. Je herkent het door de syntax in de vorm + van naam="waarde" in de open tag. + 2 - Elementen -> Dit is de pure data + Deze gegevens worden door de parser uit het XML bestand gehaald. + Elementen staan tussen de open- en sluittags. --> + + +<!-- Hieronder staat een element met twee attributen --> +<bestand type="gif" id="4293">computer.gif</bestand> + + +``` + +* Grammaticaal correcte documenten x Validatie + +Een XML document is "grammaticaal correct" of "well-formatted" als de +syntax correct is. Het is ook mogelijk om meer structuur in het document +aan te brengen met document definities zoals DTD en XML Schema. + +Een XML document dat aan een document definitie voldoet wordt "valide" volgens +die document definitie genoemd. + +Met deze gereedschappen kan je de XML data buiten je applicatie logica +controleren. + +```xml + +<!-- Hieronder staat een versimpelde versie voor een boekenwinkel document, + met een toevoeging van een DTD definitie. --> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "boekenwinkel.dtd"> +<boekenwinkel> + <boek categorie="KOKEN"> + <titel>Alledaags Italiaans</titel> + <prijs>30.00</prijs> + </boek> +</boekenwinkel> + +<!-- De DTD kan er als volgt uitzien:--> + +<!DOCTYPE note +[ +<!ELEMENT boekenwinkel (boek+)> +<!ELEMENT boek (titel,prijs)> +<!ATTLIST boek categorie CDATA "Literatuur"> +<!ELEMENT titel (#PCDATA)> +<!ELEMENT prijs (#PCDATA)> +]> + + +<!-- De DTD begint met een declaratie. + Hierna volgt de declaratie van de stamknoop, die 1 of meer 'boek' kinderen + moet bevatten. + Elk 'boek' moet precies 1 'titel' en 'prijs' element bevatten en een attribuut + 'categorie' hebben waarvan 'Literatuur' de standaard waarde is. + De 'titel' en 'prijs' knopen bevatten parsed character data.--> + +<!-- De DTD kan ook in het XML bestand zelf gedeclareerd worden.--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT boekenwinkel (boek+)> +<!ELEMENT boek (titel,prijs)> +<!ATTLIST boek categorie CDATA "Literatuur"> +<!ELEMENT titel (#PCDATA)> +<!ELEMENT prijs (#PCDATA)> +]> + +<boekenwinkel> + <boek categorie="KOKEN"> + <titel>Alledaags Italiaans</titel> + <prijs>30.00</prijs> + </boek> +</boekenwinkel> +``` \ No newline at end of file -- cgit v1.2.3 From 69d709a2dbfcaf4304d4481f9cb21c7ed8286b22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Wed, 28 Oct 2015 23:09:00 -0200 Subject: Haml translation Partial haml translation to pt-br --- pt-br/haml-pt.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pt-br/haml-pt.html.markdown b/pt-br/haml-pt.html.markdown index bff4bdee..77e0fc0f 100644 --- a/pt-br/haml-pt.html.markdown +++ b/pt-br/haml-pt.html.markdown @@ -6,8 +6,7 @@ contributors: translators: - ["Cássio Böck", "https://github.com/cassiobsilva"] --- - -Haml is a markup language predominantly used with Ruby that cleanly and simply describes the HTML of any web document without the use of inline code. It is a popular alternative to using Rails templating language (.erb) and allows you to embed Ruby code into your markup. +Haml é uma linguagem de marcação predominantemente usada em conjunto com Ruby, ela descrever de forma simples e clara o código HTML das páginas sem a utilização de código inline. É uma alternativa popular ao uso da linguagem de templating (.erb) e que permite o uso de código Ruby em sua marcação. It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. -- cgit v1.2.3 From cf6f3fe0156fb23e66e15a26589987b187a7202a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Wed, 28 Oct 2015 23:14:43 -0200 Subject: Add new external reference New reference to a free book about Java and oriented object programming --- pt-br/java-pt.html.markdown | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index a884f273..75ba42ac 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -214,42 +214,42 @@ public class LearnJava { //Iteração feita 10 vezes, fooFor 0->9 } System.out.println("Valor do fooFor: " + fooFor); - - // O Loop For Each + + // O Loop For Each // Itera automaticamente por um array ou lista de objetos. int[] fooList = {1,2,3,4,5,6,7,8,9}; //estrutura do loop for each => for(<objeto> : <array_de_objeto>) //lê-se: para cada objeto no array //nota: o tipo do objeto deve ser o mesmo do array. - + for( int bar : fooList ){ //System.out.println(bar); //Itera 9 vezes e imprime 1-9 em novas linhas } - + // Switch // Um switch funciona com os tipos de dados: byte, short, char e int // Ele também funciona com tipos enumerados (vistos em tipos Enum) // como também a classe String e algumas outras classes especiais // tipos primitivos: Character, Byte, Short e Integer - int mes = 3; - String mesString; - switch (mes){ + int mes = 3; + String mesString; + switch (mes){ case 1: - mesString = "Janeiro"; + mesString = "Janeiro"; break; case 2: - mesString = "Fevereiro"; + mesString = "Fevereiro"; break; case 3: - mesString = "Março"; + mesString = "Março"; break; default: - mesString = "Algum outro mês"; + mesString = "Algum outro mês"; break; } System.out.println("Resultado do Switch: " + mesString); - + // Condição de forma abreviada. // Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas. // Lê-se "Se (declaração) é verdadeira, use <primeiro valor> @@ -287,9 +287,9 @@ public class LearnJava { // Classes e Métodos /////////////////////////////////////// - System.out.println("\n->Classes e Métodos"); + System.out.println("\n->Classes e Métodos"); - // (segue a definição da classe Bicicleta) + // (segue a definição da classe Bicicleta) // Use o new para instanciar uma classe Bicicleta caloi = new Bicicleta(); // Objeto caloi criado. @@ -318,9 +318,9 @@ class Bicicleta { // Atributos/Variáveis da classe Bicicleta. public int ritmo; // Public: Pode ser acessada em qualquer lugar. - private int velocidade; // Private: Apenas acessível a classe. + private int velocidade; // Private: Apenas acessível a classe. protected int catraca; // Protected: Acessível a classe e suas subclasses. - String nome; // default: Apenas acessível ao pacote. + String nome; // default: Apenas acessível ao pacote. // Construtores são uma forma de criação de classes // Este é o construtor padrão. @@ -388,7 +388,7 @@ class Bicicleta { // Velocipede é uma subclasse de bicicleta. class Velocipede extends Bicicleta { // (Velocípedes são bicicletas com rodas dianteiras grandes - // Elas não possuem catraca.) + // Elas não possuem catraca.) public Velocipede(int ritmoInicial, int velocidadeInicial){ // Chame o construtor do pai (construtor de Bicicleta) com o comando super. @@ -413,11 +413,11 @@ Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, u Outros tópicos para pesquisar: -* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) +* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) * [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) -* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): +* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) @@ -433,3 +433,7 @@ Outros tópicos para pesquisar: Livros: * [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/) + +Apostila: + +* [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/) -- cgit v1.2.3 From 1a094d5a481f660dee073ddf73dc5b44025e93ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Wed, 28 Oct 2015 23:25:54 -0200 Subject: Revert "Add new external reference" This reverts commit cf6f3fe0156fb23e66e15a26589987b187a7202a. --- pt-br/java-pt.html.markdown | 42 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index 75ba42ac..a884f273 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -214,42 +214,42 @@ public class LearnJava { //Iteração feita 10 vezes, fooFor 0->9 } System.out.println("Valor do fooFor: " + fooFor); - - // O Loop For Each + + // O Loop For Each // Itera automaticamente por um array ou lista de objetos. int[] fooList = {1,2,3,4,5,6,7,8,9}; //estrutura do loop for each => for(<objeto> : <array_de_objeto>) //lê-se: para cada objeto no array //nota: o tipo do objeto deve ser o mesmo do array. - + for( int bar : fooList ){ //System.out.println(bar); //Itera 9 vezes e imprime 1-9 em novas linhas } - + // Switch // Um switch funciona com os tipos de dados: byte, short, char e int // Ele também funciona com tipos enumerados (vistos em tipos Enum) // como também a classe String e algumas outras classes especiais // tipos primitivos: Character, Byte, Short e Integer - int mes = 3; - String mesString; - switch (mes){ + int mes = 3; + String mesString; + switch (mes){ case 1: - mesString = "Janeiro"; + mesString = "Janeiro"; break; case 2: - mesString = "Fevereiro"; + mesString = "Fevereiro"; break; case 3: - mesString = "Março"; + mesString = "Março"; break; default: - mesString = "Algum outro mês"; + mesString = "Algum outro mês"; break; } System.out.println("Resultado do Switch: " + mesString); - + // Condição de forma abreviada. // Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas. // Lê-se "Se (declaração) é verdadeira, use <primeiro valor> @@ -287,9 +287,9 @@ public class LearnJava { // Classes e Métodos /////////////////////////////////////// - System.out.println("\n->Classes e Métodos"); + System.out.println("\n->Classes e Métodos"); - // (segue a definição da classe Bicicleta) + // (segue a definição da classe Bicicleta) // Use o new para instanciar uma classe Bicicleta caloi = new Bicicleta(); // Objeto caloi criado. @@ -318,9 +318,9 @@ class Bicicleta { // Atributos/Variáveis da classe Bicicleta. public int ritmo; // Public: Pode ser acessada em qualquer lugar. - private int velocidade; // Private: Apenas acessível a classe. + private int velocidade; // Private: Apenas acessível a classe. protected int catraca; // Protected: Acessível a classe e suas subclasses. - String nome; // default: Apenas acessível ao pacote. + String nome; // default: Apenas acessível ao pacote. // Construtores são uma forma de criação de classes // Este é o construtor padrão. @@ -388,7 +388,7 @@ class Bicicleta { // Velocipede é uma subclasse de bicicleta. class Velocipede extends Bicicleta { // (Velocípedes são bicicletas com rodas dianteiras grandes - // Elas não possuem catraca.) + // Elas não possuem catraca.) public Velocipede(int ritmoInicial, int velocidadeInicial){ // Chame o construtor do pai (construtor de Bicicleta) com o comando super. @@ -413,11 +413,11 @@ Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, u Outros tópicos para pesquisar: -* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) +* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) * [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) -* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): +* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) @@ -433,7 +433,3 @@ Outros tópicos para pesquisar: Livros: * [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/) - -Apostila: - -* [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/) -- cgit v1.2.3 From 0c092c1ef09ee0749e75c1418bafd8f7658248df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Wed, 28 Oct 2015 23:26:30 -0200 Subject: Revert "Revert "Add new external reference"" This reverts commit 1a094d5a481f660dee073ddf73dc5b44025e93ba. --- pt-br/java-pt.html.markdown | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index a884f273..75ba42ac 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -214,42 +214,42 @@ public class LearnJava { //Iteração feita 10 vezes, fooFor 0->9 } System.out.println("Valor do fooFor: " + fooFor); - - // O Loop For Each + + // O Loop For Each // Itera automaticamente por um array ou lista de objetos. int[] fooList = {1,2,3,4,5,6,7,8,9}; //estrutura do loop for each => for(<objeto> : <array_de_objeto>) //lê-se: para cada objeto no array //nota: o tipo do objeto deve ser o mesmo do array. - + for( int bar : fooList ){ //System.out.println(bar); //Itera 9 vezes e imprime 1-9 em novas linhas } - + // Switch // Um switch funciona com os tipos de dados: byte, short, char e int // Ele também funciona com tipos enumerados (vistos em tipos Enum) // como também a classe String e algumas outras classes especiais // tipos primitivos: Character, Byte, Short e Integer - int mes = 3; - String mesString; - switch (mes){ + int mes = 3; + String mesString; + switch (mes){ case 1: - mesString = "Janeiro"; + mesString = "Janeiro"; break; case 2: - mesString = "Fevereiro"; + mesString = "Fevereiro"; break; case 3: - mesString = "Março"; + mesString = "Março"; break; default: - mesString = "Algum outro mês"; + mesString = "Algum outro mês"; break; } System.out.println("Resultado do Switch: " + mesString); - + // Condição de forma abreviada. // Você pode usar o operador '?' para atribuições rápidas ou decisões lógicas. // Lê-se "Se (declaração) é verdadeira, use <primeiro valor> @@ -287,9 +287,9 @@ public class LearnJava { // Classes e Métodos /////////////////////////////////////// - System.out.println("\n->Classes e Métodos"); + System.out.println("\n->Classes e Métodos"); - // (segue a definição da classe Bicicleta) + // (segue a definição da classe Bicicleta) // Use o new para instanciar uma classe Bicicleta caloi = new Bicicleta(); // Objeto caloi criado. @@ -318,9 +318,9 @@ class Bicicleta { // Atributos/Variáveis da classe Bicicleta. public int ritmo; // Public: Pode ser acessada em qualquer lugar. - private int velocidade; // Private: Apenas acessível a classe. + private int velocidade; // Private: Apenas acessível a classe. protected int catraca; // Protected: Acessível a classe e suas subclasses. - String nome; // default: Apenas acessível ao pacote. + String nome; // default: Apenas acessível ao pacote. // Construtores são uma forma de criação de classes // Este é o construtor padrão. @@ -388,7 +388,7 @@ class Bicicleta { // Velocipede é uma subclasse de bicicleta. class Velocipede extends Bicicleta { // (Velocípedes são bicicletas com rodas dianteiras grandes - // Elas não possuem catraca.) + // Elas não possuem catraca.) public Velocipede(int ritmoInicial, int velocidadeInicial){ // Chame o construtor do pai (construtor de Bicicleta) com o comando super. @@ -413,11 +413,11 @@ Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, u Outros tópicos para pesquisar: -* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) +* [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) * [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) -* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): +* [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) @@ -433,3 +433,7 @@ Outros tópicos para pesquisar: Livros: * [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/) + +Apostila: + +* [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/) -- cgit v1.2.3 From 4da6d7bd809797a1115edc8b5bde1f8bccfb8a5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Wed, 28 Oct 2015 23:27:35 -0200 Subject: Removed file Removed file from another branch --- pt-br/pogo-pt.html.markdown | 203 -------------------------------------------- 1 file changed, 203 deletions(-) delete mode 100644 pt-br/pogo-pt.html.markdown diff --git a/pt-br/pogo-pt.html.markdown b/pt-br/pogo-pt.html.markdown deleted file mode 100644 index 80dcfcd5..00000000 --- a/pt-br/pogo-pt.html.markdown +++ /dev/null @@ -1,203 +0,0 @@ ---- -language: pogoscript -contributors: - - ["Tim Macfarlane", "http://github.com/refractalize"] -translators: - - ["Cássio Böck", "https://github.com/cassiobsilva"] -filename: learnPogo-pt-br.pogo -lang: pt-br ---- - -Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents -e que compila para linguagem Javascript padrão. - -``` javascript -// definindo uma variável -water temperature = 24 - -// reatribuindo o valor de uma variável após a sua definição -water temperature := 26 - -// funções permitem que seus parâmetros sejam colocados em qualquer lugar -temperature at (a) altitude = 32 - a / 100 - -// funções longas são apenas indentadas -temperature at (a) altitude := - if (a < 0) - water temperature - else - 32 - a / 100 - -// declarando uma função -current temperature = temperature at 3200 altitude - -// essa função cria um novo objeto com métodos -position (x, y) = { - x = x - y = y - - distance from position (p) = - dx = self.x - p.x - dy = self.y - p.y - Math.sqrt (dx * dx + dy * dy) -} - -// `self` é similiar ao `this` do Javascript, com exceção de que `self` não -// é redefinido em cada nova função - -// declaração de métodos -position (7, 2).distance from position (position (5, 1)) - -// assim como no Javascript, objetos também são hashes -position.'x' == position.x == position.('x') - -// arrays -positions = [ - position (1, 1) - position (1, 2) - position (1, 3) -] - -// indexando um array -positions.0.y - -n = 2 -positions.(n).y - -// strings -poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. - Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. - Put on my shirt and took it off in the sun walking the path to lunch. - A dandelion seed floats above the marsh grass with the mosquitos. - At 4 A.M. the two middleaged men sleeping together holding hands. - In the half-light of dawn a few birds warble under the Pleiades. - Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep - cheep cheep.' - -// texto de Allen Ginsburg - -// interpolação -outlook = 'amazing!' -console.log "the weather tomorrow is going to be #(outlook)" - -// expressões regulares -r/(\d+)m/i -r/(\d+) degrees/mg - -// operadores -true @and true -false @or true -@not false -2 < 4 -2 >= 2 -2 > 1 - -// os operadores padrão do Javascript também são suportados - -// definindo seu próprio operador -(p1) plus (p2) = - position (p1.x + p2.x, p1.y + p2.y) - -// `plus` pode ser usado com um operador -position (1, 1) @plus position (0, 2) -// ou como uma função -(position (1, 1)) plus (position (0, 2)) - -// retorno explícito -(x) times (y) = return (x * y) - -// new -now = @new Date () - -// funções podem receber argumentos opcionais -spark (position, color: 'black', velocity: {x = 0, y = 0}) = { - color = color - position = position - velocity = velocity -} - -red = spark (position 1 1, color: 'red') -fast black = spark (position 1 1, velocity: {x = 10, y = 0}) - -// funções também podem ser utilizadas para realizar o "unsplat" de argumentos -log (messages, ...) = - console.log (messages, ...) - -// blocos são funções passadas para outras funções. -// Este bloco recebe dois parâmetros, `spark` e `c`, -// o corpo do bloco é o código indentado após a declaração da função - -render each @(spark) into canvas context @(c) - ctx.begin path () - ctx.stroke style = spark.color - ctx.arc ( - spark.position.x + canvas.width / 2 - spark.position.y - 3 - 0 - Math.PI * 2 - ) - ctx.stroke () - -// chamadas assíncronas - -// O Javascript, tanto no navegador quanto no servidor (através do Node.js) -// realiza um uso massivo de funções assíncronas de E/S (entrada/saída) com -// chamadas de retorno (callbacks). A E/S assíncrona é ótima para a performance e -// torna a utilização da concorrência simples, porém pode rapidamente se tornar -// algo complicado. -// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono muito -// mais fácil - -// O Node.js inclui o móduolo `fs` para acessar o sistema de arquivos. -// Vamos listar o conteúdo de um diretório - -fs = require 'fs' -directory listing = fs.readdir! '.' - -// `fs.readdir()` é uma função assíncrona, então nos a chamamos usando o -// operador `!`. O operador `!` permite que você chame funções assíncronas -// com a mesma sintaxe e a mesma semântica do que as demais funções síncronas. -// O Pogoscript reescreve a função para que todo código inserido após o -// operador seja inserido em uma função de callback para o `fs.readdir()`. - -// obtendo erros ao utilizar funções assíncronas - -try - another directory listing = fs.readdir! 'a-missing-dir' -catch (ex) - console.log (ex) - -// na verdade, se você não usar o `try catch`, o erro será passado para o -// `try catch` mais externo do evento, assim como é feito em exceções síncronas - -// todo o controle de estrutura também funciona com chamadas assíncronas -// aqui um exemplo de `if else` -config = - if (fs.stat! 'config.json'.is file ()) - JSON.parse (fs.read file! 'config.json' 'utf-8') - else - { - color: 'red' - } - -// para executar duas chamadas assíncronas de forma concorrente, use o -// operador `?`. -// O operador `?` retorna um *future*, que pode ser executado para -// aguardar o resultado, novamente utilizando o operador `!` - -// nós não esperamos nenhuma dessas chamadas serem concluídas -a = fs.stat? 'a.txt' -b = fs.stat? 'b.txt' - -// agora nos aguardamos o término das chamadas e escrevemos os resultados -console.log "size of a.txt is #(a!.size)" -console.log "size of b.txt is #(b!.size)" - -// no Pogoscript, futures são semelhantes a Promises -``` -E encerramos por aqui. - -Baixe o [Node.js](http://nodejs.org/) e execute `npm install pogo`. - -Há bastante documentação em [http://pogoscript.org/](http://pogoscript.org/), incluindo um material para [consulta rápida](http://pogoscript.org/cheatsheet.html), um [guia](http://pogoscript.org/guide/), e como o [Pogoscript é traduzido para o Javascript](http://featurist.github.io/pogo-examples/). Entre em contato através do [grupo do Google](http://groups.google.com/group/pogoscript) se você possui dúvidas! -- cgit v1.2.3 From 2d435c5f65ec493841ab257f3868e3fdebf5bf6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Wed, 28 Oct 2015 23:28:40 -0200 Subject: File removed Another file removed (haml-pt) --- pt-br/haml-pt.html.markdown | 181 -------------------------------------------- 1 file changed, 181 deletions(-) delete mode 100644 pt-br/haml-pt.html.markdown diff --git a/pt-br/haml-pt.html.markdown b/pt-br/haml-pt.html.markdown deleted file mode 100644 index 77e0fc0f..00000000 --- a/pt-br/haml-pt.html.markdown +++ /dev/null @@ -1,181 +0,0 @@ ---- -language: haml -filename: learnhaml.haml -contributors: - - ["Simon Neveu", "https://github.com/sneveu"] -translators: - - ["Cássio Böck", "https://github.com/cassiobsilva"] ---- -Haml é uma linguagem de marcação predominantemente usada em conjunto com Ruby, ela descrever de forma simples e clara o código HTML das páginas sem a utilização de código inline. É uma alternativa popular ao uso da linguagem de templating (.erb) e que permite o uso de código Ruby em sua marcação. - -It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read. - -You can also use Haml on a project independent of Ruby, by installing the Haml gem on your machine and using the command line to convert it to html. - -$ haml input_file.haml output_file.html - - -```haml -/ ------------------------------------------- -/ Indenting -/ ------------------------------------------- - -/ - Because of the importance indentation has on how your code is rendered, the - indents should be consistent throughout the document. Any differences in - indentation will throw an error. It's common-practice to use two spaces, - but it's really up to you, as long as they're constant. - - -/ ------------------------------------------- -/ Comments -/ ------------------------------------------- - -/ This is what a comment looks like in Haml. - -/ - To write a multi line comment, indent your commented code to be - wrapped by the forward slash - --# This is a silent comment, which means it wont be rendered into the doc at all - - -/ ------------------------------------------- -/ Html elements -/ ------------------------------------------- - -/ To write your tags, use the percent sign followed by the name of the tag -%body - %header - %nav - -/ Notice no closing tags. The above code would output - <body> - <header> - <nav></nav> - </header> - </body> - -/ The div tag is the default element, so they can be written simply like this -.foo - -/ To add content to a tag, add the text directly after the declaration -%h1 Headline copy - -/ To write multiline content, nest it instead -%p - This is a lot of content that we could probably split onto two - separate lines. - -/ - You can escape html by using the ampersand and equals sign ( &= ). This - converts html-sensitive characters (&, /, :) into their html encoded - equivalents. For example - -%p - &= "Yes & yes" - -/ would output 'Yes & yes' - -/ You can unescape html by using the bang and equals sign ( != ) -%p - != "This is how you write a paragraph tag <p></p>" - -/ which would output 'This is how you write a paragraph tag <p></p>' - -/ CSS classes can be added to your tags either by chaining .classnames to the tag -%div.foo.bar - -/ or as part of a Ruby hash -%div{:class => 'foo bar'} - -/ Attributes for any tag can be added in the hash -%a{:href => '#', :class => 'bar', :title => 'Bar'} - -/ For boolean attributes assign the value 'true' -%input{:selected => true} - -/ To write data-attributes, use the :data key with its value as another hash -%div{:data => {:attribute => 'foo'}} - - -/ ------------------------------------------- -/ Inserting Ruby -/ ------------------------------------------- - -/ - To output a Ruby value as the contents of a tag, use an equals sign followed - by the Ruby code - -%h1= book.name - -%p - = book.author - = book.publisher - - -/ To run some Ruby code without rendering it to the html, use a hyphen instead -- books = ['book 1', 'book 2', 'book 3'] - -/ Allowing you to do all sorts of awesome, like Ruby blocks -- books.shuffle.each_with_index do |book, index| - %h1= book - - if book do - %p This is a book - -/ Adding ordered / unordered list -%ul - %li - =item1 - =item2 - -/ - Again, no need to add the closing tags to the block, even for the Ruby. - Indentation will take care of that for you. - -/ ------------------------------------------- -/ Inserting Table with bootstrap classes -/ ------------------------------------------- - -%table.table.table-hover - %thead - %tr - %th Header 1 - %th Header 2 - - %tr - %td Value1 - %td value2 - - %tfoot - %tr - %td - Foot value - - -/ ------------------------------------------- -/ Inline Ruby / Ruby interpolation -/ ------------------------------------------- - -/ Include a Ruby variable in a line of plain text using #{} -%p Your highest scoring game is #{best_game} - - -/ ------------------------------------------- -/ Filters -/ ------------------------------------------- - -/ - Use the colon to define Haml filters, one example of a filter you can - use is :javascript, which can be used for writing inline js - -:javascript - console.log('This is inline <script>'); - -``` - -## Additional resources - -- [What is HAML?](http://haml.info/) - A good introduction that does a much better job of explaining the benefits of using HAML. -- [Official Docs](http://haml.info/docs/yardoc/file.REFERENCE.html) - If you'd like to go a little deeper. -- cgit v1.2.3 From 835ec3eb075385ea44f5bd283fe535707944e315 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Wed, 28 Oct 2015 23:34:52 -0200 Subject: Added new book Added new book about Java for web development --- pt-br/java-pt.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index 75ba42ac..fdb9b558 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -437,3 +437,5 @@ Livros: Apostila: * [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/) + +* [Java para Desenvolvimento Web] (https://www.caelum.com.br/apostila-java-web/) -- cgit v1.2.3 From cdd64ecee34af20ed101ba5dc8d7dc73a8189c15 Mon Sep 17 00:00:00 2001 From: Vipul Sharma <vipulsharma936@gmail.com> Date: Thu, 29 Oct 2015 15:23:37 +0530 Subject: 80 char and proper commenting --- python.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 01e5d481..ff4471e9 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -124,7 +124,8 @@ not False # => True "This is a string"[0] # => 'T' #String formatting with % -#Even though the % string operator will be deprecated on Python 3.1 and removed later at some time, it may still be #good to know how it works. +#Even though the % string operator will be deprecated on Python 3.1 and removed +#later at some time, it may still be good to know how it works. x = 'apple' y = 'lemon' z = "The items in the basket are %s and %s" % (x,y) -- cgit v1.2.3 From 7a9787755b4e0f0ca99487833835b081c9d4de8a Mon Sep 17 00:00:00 2001 From: Nasgul <nasguling@gmail.com> Date: Thu, 29 Oct 2015 16:05:27 +0200 Subject: Delete unnecessary line on english. Delete unnecessary line on english. --- ru-ru/php-ru.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 5672aa90..dc254bf8 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -420,8 +420,6 @@ include_once 'my-file.php'; require 'my-file.php'; require_once 'my-file.php'; -// Same as include(), except require() will cause a fatal error if the -// file cannot be included. // Действует также как и include(), но если файл не удалось подключить, // функция выдает фатальную ошибку -- cgit v1.2.3 From eb5d2d62616219837ad447dd4cb585a6e75bb89a Mon Sep 17 00:00:00 2001 From: Kyle Mendes <kmendes@fuzzproductions.com> Date: Thu, 29 Oct 2015 10:05:36 -0400 Subject: [sass/en] Cleaning up wording and formatting --- sass.html.markdown | 203 ++++++++++++++++++++++++++--------------------------- 1 file changed, 100 insertions(+), 103 deletions(-) diff --git a/sass.html.markdown b/sass.html.markdown index 02bec47f..4d4ece71 100644 --- a/sass.html.markdown +++ b/sass.html.markdown @@ -4,40 +4,41 @@ filename: learnsass.scss contributors: - ["Laura Kyle", "https://github.com/LauraNK"] - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] --- -Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. -Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers to write maintainable and DRY (Don't Repeat Yourself) code. +Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. +Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers write maintainable and DRY (Don't Repeat Yourself) code. -Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons. +Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons. This tutorial is written using SCSS. -If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling options but rather the tools to write your CSS more efficiently and make maintenance much easier. +If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling properties but rather the tools to write your CSS more efficiently and make maintenance much easier. ```scss - + //Single line comments are removed when Sass is compiled to CSS. -/*Multi line comments are preserved. */ - - - -/*Variables -==============================*/ - - +/* Multi line comments are preserved. */ + + + +/* Variables +============================== */ + + /* You can store a CSS value (such as a color) in a variable. Use the '$' symbol to create a variable. */ - + $primary-color: #A3A4FF; $secondary-color: #51527F; -$body-font: 'Roboto', sans-serif; +$body-font: 'Roboto', sans-serif; + +/* You can use the variables throughout your stylesheet. +Now if you want to change a color, you only have to make the change once. */ -/* You can use the variables throughout your stylesheet. -Now if you want to change a color, you only have to make the change once.*/ - body { background-color: $primary-color; color: $secondary-color; @@ -54,18 +55,18 @@ body { /* This is much more maintainable than having to change the color each time it appears throughout your stylesheet. */ - -/*Mixins -==============================*/ + +/* Mixins +============================== */ /* If you find you are writing the same code for more than one element, you might want to store that code in a mixin. -Use the '@mixin' directive, plus a name for your mixin.*/ +Use the '@mixin' directive, plus a name for your mixin. */ @mixin center { display: block; @@ -82,7 +83,7 @@ div { background-color: $primary-color; } -/*Which would compile to: */ +/* Which would compile to: */ div { display: block; margin-left: auto; @@ -99,8 +100,8 @@ div { width: $width; height: $height; } - -/*Which you can invoke by passing width and height arguments. */ + +/* Which you can invoke by passing width and height arguments. */ .rectangle { @include size(100px, 60px); @@ -110,31 +111,31 @@ div { @include size(40px, 40px); } -/* This compiles to: */ +/* Compiles to: */ .rectangle { width: 100px; - height: 60px; + height: 60px; } .square { width: 40px; - height: 40px; + height: 40px; } -/*Functions -==============================*/ - - - -/* Sass provides functions that can be used to accomplish a variety of +/* Functions +============================== */ + + + +/* Sass provides functions that can be used to accomplish a variety of tasks. Consider the following */ -/* Functions can be invoked by using their name and passing in the +/* Functions can be invoked by using their name and passing in the required arguments */ body { - width: round(10.25px); + width: round(10.25px); } .footer { @@ -149,18 +150,18 @@ body { .footer { background-color: rgba(0, 0, 0, 0.75); -} - -/* You may also define your own functions. Functions are very similar to +} + +/* You may also define your own functions. Functions are very similar to mixins. When trying to choose between a function or a mixin, remember - that mixins are best for generating CSS while functions are better for - logic that might be used throughout your Sass code. The examples in - the Math Operators' section are ideal candidates for becoming a reusable + that mixins are best for generating CSS while functions are better for + logic that might be used throughout your Sass code. The examples in + the Math Operators' section are ideal candidates for becoming a reusable function. */ -/* This function will take a target size and the parent size and calculate +/* This function will take a target size and the parent size and calculate and return the percentage */ - + @function calculate-percentage($target-size, $parent-size) { @return $target-size / $parent-size * 100%; } @@ -187,12 +188,12 @@ $main-content: calculate-percentage(600px, 960px); -/*Extend (Inheritance) -==============================*/ +/* Extend (Inheritance) +============================== */ -/*Extend is a way to share the properties of one selector with another. */ +/* Extend is a way to share the properties of one selector with another. */ .display { @include size(5em, 5em); @@ -208,36 +209,36 @@ $main-content: calculate-percentage(600px, 960px); .display, .display-success { width: 5em; height: 5em; - border: 5px solid #51527F; + border: 5px solid #51527F; } .display-success { - border-color: #22df56; + border-color: #22df56; } -/* Extending a CSS statement is preferable to creating a mixin - because of the way it groups together the classes that all share - the same base styling. If this was done with a mixin, the width, - height, and border would be duplicated for each statement that +/* Extending a CSS statement is preferable to creating a mixin + because of the way Sass groups together the classes that all share + the same base styling. If this was done with a mixin, the width, + height, and border would be duplicated for each statement that called the mixin. While it won't affect your workflow, it will add unnecessary bloat to the files created by the Sass compiler. */ - -/*Nesting -==============================*/ + +/* Nesting +============================== */ -/*Sass allows you to nest selectors within selectors */ +/* Sass allows you to nest selectors within selectors */ ul { list-style-type: none; margin-top: 2em; - + li { - background-color: #FF0000; - } + background-color: #FF0000; + } } /* '&' will be replaced by the parent selector. */ @@ -249,18 +250,18 @@ For example: */ ul { list-style-type: none; margin-top: 2em; - + li { background-color: red; - + &:hover { background-color: blue; } - + a { color: white; } - } + } } /* Compiles to: */ @@ -284,17 +285,17 @@ ul li a { -/*Partials and Imports -==============================*/ - - - +/* Partials and Imports +============================== */ + + + /* Sass allows you to create partial files. This can help keep your Sass code modularized. Partial files should begin with an '_', e.g. _reset.css. Partials are not generated into CSS. */ - + /* Consider the following CSS which we'll put in a file called _reset.css */ - + html, body, ul, @@ -302,14 +303,14 @@ ol { margin: 0; padding: 0; } - + /* Sass offers @import which can be used to import partials into a file. - This differs from the traditional CSS @import statement which makes - another HTTP request to fetch the imported file. Sass takes the + This differs from the traditional CSS @import statement which makes + another HTTP request to fetch the imported file. Sass takes the imported file and combines it with the compiled code. */ - + @import 'reset'; - + body { font-size: 16px; font-family: Helvetica, Arial, Sans-serif; @@ -320,25 +321,25 @@ body { html, body, ul, ol { margin: 0; padding: 0; -} +} body { font-size: 16px; font-family: Helvetica, Arial, Sans-serif; } - - -/*Placeholder Selectors -==============================*/ - - - + + +/* Placeholder Selectors +============================== */ + + + /* Placeholders are useful when creating a CSS statement to extend. If you wanted to create a CSS statement that was exclusively used with @extend, you can do so using a placeholder. Placeholders begin with a '%' instead of '.' or '#'. Placeholders will not appear in the compiled CSS. */ - + %content-window { font-size: 14px; padding: 10px; @@ -364,18 +365,18 @@ body { background-color: #0000ff; } - - -/*Math Operations -==============================*/ - - - + + +/* Math Operations +============================== */ + + + /* Sass provides the following operators: +, -, *, /, and %. These can be useful for calculating values directly in your Sass files instead of using values that you've already calculated by hand. Below is an example of a setting up a simple two column design. */ - + $content-area: 960px; $main-content: 600px; $sidebar-content: 300px; @@ -418,14 +419,11 @@ body { width: 6.25%; } - -``` - - +``` ## SASS or Sass? -Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym. -Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets". +Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym. +Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets". ## Practice Sass @@ -434,14 +432,13 @@ You can use either syntax, just go into the settings and select either Sass or S ## Compatibility - Sass can be used in any project as long as you have a program to compile it into CSS. You'll want to verify that the CSS you're using is compatible -with your target browsers. +with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility. -[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility. - ## Further reading * [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) * [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles. -- cgit v1.2.3 From 03ef96b2f11133701a3db64b9133f634a9709e94 Mon Sep 17 00:00:00 2001 From: Raphael Nascimento <raphaelbn10@gmail.com> Date: Thu, 29 Oct 2015 12:46:59 -0300 Subject: [java/en] Enum Type --- java.html.markdown | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 86b0578e..1813f81c 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -186,9 +186,9 @@ public class LearnJava { // operations perform as could be expected for a // doubly-linked list. // Maps - A set of objects that map keys to values. Map is - // an interface and therefore cannot be instantiated. - // The type of keys and values contained in a Map must - // be specified upon instantiation of the implementing + // an interface and therefore cannot be instantiated. + // The type of keys and values contained in a Map must + // be specified upon instantiation of the implementing // class. Each key may map to only one corresponding value, // and each key may appear only once (no duplicates). // HashMaps - This class uses a hashtable to implement the Map @@ -450,6 +450,17 @@ class Bicycle { protected int gear; // Protected: Accessible from the class and subclasses String name; // default: Only accessible from within this package + static String className; // Static class variable + + // Static block + // Java has no implementation of static constructors, but + // has a static block that can be used to initialize class variables + // (static variables). + // This block will be called when the class is loaded. + static { + className = "Bicycle"; + } + // Constructors are a way of creating classes // This is a constructor public Bicycle() { @@ -767,7 +778,7 @@ The links provided here below are just to get an understanding of the topic, fee * [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) **Online Practice and Tutorials** -- cgit v1.2.3 From 54c67dfb38d1bb2a9dc004b3244d2ae3102107f3 Mon Sep 17 00:00:00 2001 From: bk2dcradle <ankitsultana@gmail.com> Date: Thu, 29 Oct 2015 22:13:24 +0530 Subject: [c++] Added Lambda Expressions and Range for --- c++.html.markdown | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index d03092e5..6033ca06 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -801,6 +801,106 @@ void doSomethingWithAFile(const std::string& filename) // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock +/////////////////////////////////////// +// Lambda Expressions (C++11 and above) +/////////////////////////////////////// + +// lambdas are a convenient way of defining an anonymous function +// object right at the location where it is invoked or passed as +// an argument to a function. + +// Example consider sorting a vector of pairs using the second +// value of the pair + +vector<pair<int, int> > tester; +tester.push_back(make_pair(3, 6)); +tester.push_back(make_pair(1, 9)); +tester.push_back(make_pair(5, 0)); + +// Pass a lambda expression as third argument to the sort function +// sort is from the <algorithm> header + +sort(tester.begin(), tester.end(), [](const pair<int, int> &lhs, const pair<int, int> &rhs) { + return lhs.second < rhs.second; + }); + +// Notice the syntax of the lambda expression, +// [] in the lambda is used to "capture" variables. +// For Example: + +vector<int> dog_ids; +// number_of_dogs = 3; +for(int i = 0; i < 3; i++){ + dog_ids.push_back(i); +} + +int weight[3]; +weight[0] = 30, weight[1] = 50, weight[2] = 10; + +// Say you want to sort dog_ids according to the dogs' weights +// So dog_ids should in the end become: [2, 0, 1] + +// Here's where lambda expressions come in handy + +sort(dog_ids.begin(), dog_ids.end(), [weight](const int &lhs, const int &rhs) { + return weight[lhs] < weight[rhs]; + }); +// Note we captured "weight" in the above example. + +// lambda are really useful for the case of structs +// You can use lambda expressions instead of overloading +// the "<" operator + +struct dog{ + int weight, age; +}dogs[3]; + +dogs[0].weight = 30, dogs[0].age = 4; +dogs[1].weight = 40, dogs[1].age = 10; +dogs[2].weight = 20, dogs[2].age = 9; + +// Say I want to sort the dogs array by the dogs' weights + +sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { + return lhs.weight < rhs.weight; + }); +// dogs is now sorted according to their weight + +// Do something with the dogs + +// Now I want to sort the dogs by in descending order of their age + +sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { + return lhs.age > rhs.age; + }); +// dogs is now sorted in descending order of their age + + +/////////////////////////////// +// Range For (C++11 and above) +/////////////////////////////// + +// You can use a range for loop to iterate over a container +int arr[] = {1, 10, 3}; + +for(int elem: arr){ + cout<<elem<<'\n'; +} + +// You can use "auto" and not worry about the type of the elements of the container +// Caveat: Don't assign inside the range for loop +// For example: + +for(auto elem: arr) { + elem = -1; +} + +// "arr" remains unchanged + +// Why doesn't it change? +// What actually is happening is that the value of "arr[i]" is stored in +// the variable "elem" in every iteration. So assigning "elem" doesn't assign "arr[i]". +// For more, checkout: http://en.cppreference.com/w/cpp/language/range-for ///////////////////// // Fun stuff -- cgit v1.2.3 From d94d88cd2031b7322c2c2886fa54b26ef1c461be Mon Sep 17 00:00:00 2001 From: Michal Martinek <martinek8@gmail.com> Date: Thu, 29 Oct 2015 19:21:48 +0100 Subject: Czech translation for Sass --- cs-cz/sass.html.markdown | 439 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 439 insertions(+) create mode 100644 cs-cz/sass.html.markdown diff --git a/cs-cz/sass.html.markdown b/cs-cz/sass.html.markdown new file mode 100644 index 00000000..e890debe --- /dev/null +++ b/cs-cz/sass.html.markdown @@ -0,0 +1,439 @@ +--- +language: sass +filename: learnsass.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] +translators: + - ["Michal Martinek", "https://github.com/MichalMartinek"] + +--- + +Sass je rozšíření jazyka CSS, který přidává nové vlastnosti jako proměnné, zanořování, mixiny a další. +Sass (a další preprocesory, jako [Less](http://lesscss.org/)) pomáhají vývojářům psát udržovatelný a neopakující (DRY) kód. + +Sass nabízí dvě možnosti syntaxe. SCSS, které je stejná jako CSS, akorát obsahuje nové vlastnosti Sassu. Nebo Sass, který používá odsazení místo složených závorek a středníků. +Tento tutoriál bude používat syntaxi CSS. + + +Pokud jste již obeznámeni s CSS3, budete schopni používat Sass relativně rychle. Nezprostředkovává nějaké úplně nové stylové možnosti, spíše nátroje, jak psát Vás CSS kód více efektivně, udržitelně a jednoduše. + +```scss + + +//Jednořádkové komentáře jsou ze Sassu při kompilaci vymazány + +/*Víceřádkové komentáře jsou naopak zachovány */ + + + +/*Proměnné +==============================*/ + + + +/* Můžete uložit CSS hodnotu (jako třeba barvu) do proměnné. +Použijte symbol '$' k jejímu vytvoření. */ + +$hlavni-barva: #A3A4FF; +$sekundarni-barva: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Můžete používat proměnné napříč vaším souborem. +Teď, když chcete změnit barvu, stačí ji změnit pouze jednou.*/ + +body { + background-color: $hlavni-barva; + color: $sekundarni-barva; + font-family: $body-font; +} + +/* Toto se zkompiluje do: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Toto je o hodně více praktické, než měnit každý výskyt barvy. */ + + + +/*Mixiny +==============================*/ + + + +/* Pokud zjistíte, že píšete kód pro více než jeden element, můžete jej uložit do mixinu. + +Použijte '@mixin' direktivu, plus jméno vašeho mixinu.*/ + +@mixin na-stred { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Mixin vložíte pomocí '@include' a jména mixinu */ + +div { + @include na-stred; + background-color: $hlavni-barva; +} + +/*Což se zkompiluje do: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Můžete využít mixiny i třeba pro takovéto ušetření práce: */ + +@mixin velikost($sirka, $vyska) { + width: $sirka; + height: $vyska; +} + +/*Stačí vložit argumenty: */ + +.obdelnik { + @include velikost(100px, 60px); +} + +.ctverec { + @include velikost(40px, 40px); +} + +/* Toto se zkompiluje do: */ +.obdelnik { + width: 100px; + height: 60px; +} + +.ctverec { + width: 40px; + height: 40px; +} + + + +/*Funkce +==============================*/ + + + +/* Sass obsahuje funkce, které vám pomůžou splnit různé úkoly. */ + +/* Funkce se spouštějí pomocí jejich jména, které následuje seznam argumentů uzavřený v kulatých závorkách. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Se zkompiluje do: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Můžete také definovat vlastní funkce. Funkce jsou velmi podobné mixinům. + Když se snažíte vybrat mezi funkcí a mixinem, mějte na paměti, že mixiny + jsou lepší pro generování CSS kódu, zatímco funkce jsou lepší pro logiku. + Příklady ze sekce Matematické operátory jsou skvělí kandidáti na + znovupoužitelné funkce. */ + +/* Tato funkce vrací poměr k velikosti rodiče v procentech. +@function vypocitat-pomer($velikost, $velikost-rodice) { + @return $velikost / $velikost-rodice * 100%; +} + +$hlavni obsah: vypocitat-pomer(600px, 960px); + +.hlavni-obsah { + width: $hlavni-obsah; +} + +.sloupec { + width: vypocitat-pomer(300px, 960px); +} + +/* Zkompiluje do: */ + +.hlavni-obsah { + width: 62.5%; +} + +.sloupec { + width: 31.25%; +} + + + +/*Dědění +==============================*/ + + + +/*Dědění je způsob jak používat vlastnosti pro jeden selektor ve druhém. */ + +.oznameni { + @include velikost(5em, 5em); + border: 5px solid $sekundarni-barva; +} + +.oznameni-uspech { + @extend .oznameni; + border-color: #22df56; +} + +/* Zkompiluje do: */ +.oznameni, .oznameni-uspech { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.oznameni-uspech { + border-color: #22df56; +} + + +/* Dědění CSS výrazů je preferováno před vytvořením mixinu kvůli způsobu, + jakým způsobem Sass dává dohromady třídy, které sdílejí stejný kód. + Kdyby to bylo udělané pomocí mixinu, tak výška, šířka, rámeček by byl v + každém výrazu, který by volal mixin. I když tohle neovlivní vaše workflow, + přidá to kód navíc do souborů. */ + + +/*Zanořování +==============================*/ + + + +/*Sass vám umožňuje zanořovat selektory do selektorů */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' nahradí rodičovský element. */ +/* Můžete také zanořovat pseudo třídy. */ +/* Pamatujte, že moc velké zanoření do hloubky snižuje čitelnost. + Doporučuje se používat maximálně trojité zanoření. + Na příklad: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Zkompiluje do: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/*Částečné soubory a importy +==============================*/ + + + +/* Sass umožňuje vytvářet částečné soubory. Tyto soubory pomahájí udržovat váš + kód modulární. Tyto soubory by měli začínat vždy '_', např. _reset.css. + Částečné soubory se nepřevádí do CSS. */ + +/* Toto je kód, který si uložíme do souboru _reset.css */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass obsahuje @import, které může být použit pro import částečných souborů. + Toto se liší od klasického CSS @import, který dělá HTTP požadavek na stáhnutí + souboru. Sass vezme importovaný soubor a vloží ho do kompilovaného kódu. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Zkompiluje do: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/*Zástupné selektory +==============================*/ + + + +/* Zástupné selektory jsou užitečné, když vytváříte CSS výraz, ze kterého + chcete později dědit. Když chcete vytvořit výraz, ze kterého je možné pouze + dědit pomocí @extend, vytvořte zástupný selektor s CSS výrazem. Ten začíná + symbolem '%' místo '.' nebo '#'. Tyto výrazy se neobjeví ve výsledném CSS */ + +%okno-obsahu { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.okno-zpravy { + @extend %okno-obsahu; + background-color: #0000ff; +} + +/* Zkompiluje do: */ + +.okno-zpravy { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.okno-zpravy { + background-color: #0000ff; +} + + + +/*Matematické operace +==============================*/ + + + +/* Sass obsahuje následující operátory: +, -, *, /, and %. Tyto operátory + můžou být velmi užitečné pro počítání hodnot přímo ve vašem souboru Sass. + Níže je příklad, jak udělat jednoduchý dvousloupcový layout. */ + +$oblast-obsahu: 960px; +$hlavni-obsah: 600px; +$vedlejsi-sloupec: 300px; + +$obsah-velikost: $hlavni-obsah / $oblast-obsahu * 100%; +$vedlejsi-sloupec-velikost: $vedlejsi-sloupec / $oblast-obsahu * 100%; +$zbytek-velikost: 100% - ($main-size + $vedlejsi-sloupec-size); + +body { + width: 100%; +} + +.hlavni-obsah { + width: $obsah-velikost; +} + +.vedlejsi-sloupec { + width: $vedlejsi-sloupec-velikost; +} + +.zbytek { + width: $zbytek-velikost; +} + +/* Zkompiluje do: */ + +body { + width: 100%; +} + +.hlavni-obsah { + width: 62.5%; +} + +.vedlejsi-sloupec { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + + + +## SASS nebo Sass? +Divili jste se někdy, jestli je Sass zkratka nebo ne? Pravděpodobně ne, ale řeknu vám to stejně. Jméno tohoto jazyka je slovo, "Sass", a ne zkratka. +Protože to lidé konstatně píší jako "SASS", nazval ho autor jazyka jako "Syntactically Awesome StyleSheets" (Syntaktický úžasně styly). + + +## Procvičování Sassu +Pokud si chcete hrát se Sassem ve vašem prohlížeči, navštivte [SassMeister](http://sassmeister.com/). +Můžete používát oba dva způsoby zápisu, stačí si vybrat v nastavení SCSS nebo SASS. + + +## Kompatibilita + +Sass může být použit v jakémkoliv projektu, jakmile máte program, pomocí kterého ho zkompilujete do CSS. Pokud si chcete ověřit, že CSS, které Sass produkuje je kompatibilní s prohlížeči: + +[QuirksMode CSS](http://www.quirksmode.org/css/) a [CanIUse](http://caniuse.com) jsou skvělé stránky pro kontrolu kompatibility. + + +## Kam dál? +* [Oficiální dokumentace](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) obsahuje tutoriál a řadu skvělých článků -- cgit v1.2.3 From b27ddf1bd65c0d62293934eee085fafe340937d4 Mon Sep 17 00:00:00 2001 From: meinkej <jerome.meinke@googlemail.com> Date: Thu, 29 Oct 2015 19:44:21 +0100 Subject: [go/de] More infos, reformulation and typo fixes for Go. --- de-de/go-de.html.markdown | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index d3a192fe..099927b6 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -4,17 +4,16 @@ filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] - ["Dennis Keller", "https://github.com/denniskeller"] + - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de --- -Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in -der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in -der realen Welt zu lösen. - -Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung -und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu -verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern -Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große -Programmierprojekte. +Die Sprache Go (auch golang) wurde von Google entwickelt und wird seit 2007 +benutzt. Go ähnelt in der Syntax der Sprache C, bietet darüber hinaus aber viele +Vorteile. Einerseits verzichtet Gp auf Speicherarithmetik und +benutzt einen Garbabe Collector. Andererseits enthält Go native Sprachelemente +für die Unterstützung von Nebenläufigkeit. Durch den Fokus auf einen schnellen +Kompilierprozess wird außerdem die Softwareentwicklung in Großprojekten +erleichtert. Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine aktive Community. @@ -24,7 +23,7 @@ aktive Community. /* Mehr- zeiliger Kommentar */ -// Eine jede Quelldatei beginnt mit einer Paket-Klausel. +// Wie bei Java gehört jede Quelldatei einem Paket an (Modularisierung). // "main" ist ein besonderer Paketname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. @@ -40,7 +39,7 @@ import ( // Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier // ist der Name wieder besonders. "main" markiert den Eintrittspunkt des -// Programms. Vergessen Sie nicht die geschweiften Klammern! +// Programms. func main() { // Println gibt eine Zeile zu stdout aus. // Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt. @@ -50,8 +49,8 @@ func main() { beyondHello() } -// Funktionen können Parameter akzeptieren, diese werden in Klammern deklariert, -// die aber auch bei keinen Parametern erforderlich sind. +// Funktionen können Parameter akzeptieren. Siese werden in Klammern deklariert, +// die aber auch ohne Parameter erforderlich sind. func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. @@ -306,14 +305,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ``` ## Weitere Resourcen -Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). -Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel -Dokumentation lesen. +Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/). +Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor +allem aber Dokumentation zur Sprache und den Paketen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr -kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen -ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). -Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil -verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen +kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen +ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/) +einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil +verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). - -- cgit v1.2.3 From e5a02057227506b95630658971caabb30b64f705 Mon Sep 17 00:00:00 2001 From: meinkej <jerome.meinke@googlemail.com> Date: Thu, 29 Oct 2015 19:50:17 +0100 Subject: Fix a typo introduced in the previous commit. Reformatted some lines. --- de-de/go-de.html.markdown | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 099927b6..94f48e65 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -49,7 +49,7 @@ func main() { beyondHello() } -// Funktionen können Parameter akzeptieren. Siese werden in Klammern deklariert, +// Funktionen können Parameter akzeptieren. Diese werden in Klammern deklariert, // die aber auch ohne Parameter erforderlich sind. func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. @@ -98,7 +98,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // "slices" haben eine dynamische Größe. Arrays und Slices haben beide ihre // Vorzüge, aber slices werden viel häufiger verwendet s3 := []int{4, 5, 9} // Vergleichen Sie mit a3, hier: keine Ellipse - s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Initialwert 0 + s4 := make([]int, 4) // Weist Speicher für 4 ints zu, alle mit Wert 0 var d2 [][]float64 // Nur eine Deklaration, keine Speicherzuweisung bs := []byte("eine slice") // Umwandlungs-Syntax @@ -200,7 +200,8 @@ type pair struct { x, y int } -// Definiere eine Methode von "pair". Dieser Typ erfüllt jetzt das Stringer interface. +// Definiere eine Methode von "pair". +// Dieser Typ erfüllt jetzt das Stringer interface. func (p pair) String() string { // p ist der Empfänger // Sprintf ist eine weitere öffentliche Funktion von fmt. // Der Syntax mit Punkt greift auf die Felder zu. @@ -254,8 +255,9 @@ func learnConcurrency() { // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für // maps, slices und Kanäle. c := make(chan int) - // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) - // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal. + // Starte drei parallele "Goroutines". + // Die Zahlen werden parallel (concurrently) erhöht. + // Alle drei senden ihr Ergebnis in den gleichen Kanal. go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) -- cgit v1.2.3 From fe1c5e86ede2786580c414bf608bb09d5c7ceb40 Mon Sep 17 00:00:00 2001 From: Nasgul <nasguling@gmail.com> Date: Thu, 29 Oct 2015 22:15:40 +0200 Subject: Edit descriptions for function setdefault. Edit descriptions for function setdefault. --- ru-ru/python-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index 3852a550..43142eff 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -280,7 +280,7 @@ filled_dict.get("four", 4) #=> 4 # Присваивайте значение ключам так же, как и в списках filled_dict["four"] = 4 # теперь filled_dict["four"] => 4 -# Метод setdefault вставляет() пару ключ-значение, только если такого ключа нет +# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 -- cgit v1.2.3 From eef69b0d092a0b1396ff2494984b07b9aa76d020 Mon Sep 17 00:00:00 2001 From: Nasgul <nasguling@gmail.com> Date: Thu, 29 Oct 2015 22:25:00 +0200 Subject: Edit translate for creating object. Edit translate for creating new object of class using new. --- ru-ru/php-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index dc254bf8..37b6a86e 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -483,7 +483,7 @@ echo MyClass::MY_CONST; // Выведет 'value'; echo MyClass::$staticVar; // Выведет 'static'; MyClass::myStaticMethod(); // Выведет 'I am static'; -// Новый экземпляр класса используя new +// Создание нового экземпляра класса используя new $my_class = new MyClass('An instance property'); // Если аргументы отсутствуют, можно не ставить круглые скобки -- cgit v1.2.3 From 36c551affb006583bf7960b7a613b45699a819cc Mon Sep 17 00:00:00 2001 From: Nasgul <nasguling@gmail.com> Date: Thu, 29 Oct 2015 22:38:04 +0200 Subject: Edit Title for 5 part. Edit Title for 5 part. --- ru-ru/javascript-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 8655ae4a..54499f46 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -330,7 +330,7 @@ function sayHelloInFiveSeconds(name) { sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!» /////////////////////////////////// -// 5. Подробнее об объектах; конструкторы и прототипы +// 5. Подробнее об объектах; Конструкторы и Прототипы // Объекты могут содержать в себе функции. var myObj = { -- cgit v1.2.3 From 7e90054b5cb91c5df3cbae38c0ae0e29fe114d0e Mon Sep 17 00:00:00 2001 From: Nasgul <nasguling@gmail.com> Date: Thu, 29 Oct 2015 22:57:17 +0200 Subject: Fix typo. Fix typo. --- ru-ru/java-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 005495cc..b24ad555 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -451,7 +451,7 @@ public class Fruit implements Edible, Digestible { } } -// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать +// В Java Вы можете наследовать только один класс, однако можете реализовывать // несколько интерфейсов. Например: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { public void InterfaceOneMethod() { -- cgit v1.2.3 From 14c85ba0ffbb66d9c2a056006cedaa90df8f22f4 Mon Sep 17 00:00:00 2001 From: yihong <yihong@exmaple.com> Date: Fri, 30 Oct 2015 05:04:41 +0800 Subject: add more details on truthiness --- python.html.markdown | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 42a52bcf..7055689e 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -63,7 +63,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt # to carry out normal division with just one '/'. from __future__ import division 11/4 # => 2.75 ...normal division -11//4 # => 2 ...floored division +11//4 # => 2 ...floored division # Modulo operation 7 % 3 # => 1 @@ -144,8 +144,16 @@ None is None # => True # very useful when dealing with primitive values, but is # very useful when dealing with objects. -# None, 0, and empty strings/lists all evaluate to False. -# All other values are True +# Any object can be used in a Boolean context. +# The following values are considered falsey: +# - None +# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) +# - empty sequences (e.g., '', (), []) +# - empty containers (e.g., {}, set()) +# - instances of user-defined classes meeting certain conditions +# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# All other values are truthy (using the bool() function on them returns True). bool(0) # => False bool("") # => False -- cgit v1.2.3 From d35663f1752c0815ee48fb6b66f0b6c6d7deaab9 Mon Sep 17 00:00:00 2001 From: Victor <victor@victor-RV411.(none)> Date: Thu, 29 Oct 2015 22:09:43 -0200 Subject: fixing selector(color) name that was improperly translated --- pt-br/css-pt.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown index ed6f6c4c..b1fbd961 100644 --- a/pt-br/css-pt.html.markdown +++ b/pt-br/css-pt.html.markdown @@ -159,11 +159,11 @@ seletor {     color: # FF66EE; /* Formato hexadecimal longo */     color: tomato; /* Uma cor nomeada */     color: rgb (255, 255, 255); /* Como valores rgb */ -    cor: RGB (10%, 20%, 50%); /* Como porcentagens rgb */ -    cor: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */ +    color: RGB (10%, 20%, 50%); /* Como porcentagens rgb */ +    color: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */     color: transparent; /* Equivale a definir o alfa a 0 */ -    cor: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */ -    cor: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */ +    color: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */ +    color: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */     /* Imagens como fundos de elementos */     background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */ -- cgit v1.2.3 From c013b2c95732022c0a4a56152489e6d45e44695d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Thu, 29 Oct 2015 23:17:09 -0200 Subject: English content removed The pt-br file had english content after translation. That content is now removed. --- pt-br/pogo-pt.html.markdown | 203 -------------------------------------------- pt-br/sass-pt.html.markdown | 27 +----- 2 files changed, 1 insertion(+), 229 deletions(-) delete mode 100644 pt-br/pogo-pt.html.markdown diff --git a/pt-br/pogo-pt.html.markdown b/pt-br/pogo-pt.html.markdown deleted file mode 100644 index 80dcfcd5..00000000 --- a/pt-br/pogo-pt.html.markdown +++ /dev/null @@ -1,203 +0,0 @@ ---- -language: pogoscript -contributors: - - ["Tim Macfarlane", "http://github.com/refractalize"] -translators: - - ["Cássio Böck", "https://github.com/cassiobsilva"] -filename: learnPogo-pt-br.pogo -lang: pt-br ---- - -Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents -e que compila para linguagem Javascript padrão. - -``` javascript -// definindo uma variável -water temperature = 24 - -// reatribuindo o valor de uma variável após a sua definição -water temperature := 26 - -// funções permitem que seus parâmetros sejam colocados em qualquer lugar -temperature at (a) altitude = 32 - a / 100 - -// funções longas são apenas indentadas -temperature at (a) altitude := - if (a < 0) - water temperature - else - 32 - a / 100 - -// declarando uma função -current temperature = temperature at 3200 altitude - -// essa função cria um novo objeto com métodos -position (x, y) = { - x = x - y = y - - distance from position (p) = - dx = self.x - p.x - dy = self.y - p.y - Math.sqrt (dx * dx + dy * dy) -} - -// `self` é similiar ao `this` do Javascript, com exceção de que `self` não -// é redefinido em cada nova função - -// declaração de métodos -position (7, 2).distance from position (position (5, 1)) - -// assim como no Javascript, objetos também são hashes -position.'x' == position.x == position.('x') - -// arrays -positions = [ - position (1, 1) - position (1, 2) - position (1, 3) -] - -// indexando um array -positions.0.y - -n = 2 -positions.(n).y - -// strings -poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. - Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. - Put on my shirt and took it off in the sun walking the path to lunch. - A dandelion seed floats above the marsh grass with the mosquitos. - At 4 A.M. the two middleaged men sleeping together holding hands. - In the half-light of dawn a few birds warble under the Pleiades. - Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep - cheep cheep.' - -// texto de Allen Ginsburg - -// interpolação -outlook = 'amazing!' -console.log "the weather tomorrow is going to be #(outlook)" - -// expressões regulares -r/(\d+)m/i -r/(\d+) degrees/mg - -// operadores -true @and true -false @or true -@not false -2 < 4 -2 >= 2 -2 > 1 - -// os operadores padrão do Javascript também são suportados - -// definindo seu próprio operador -(p1) plus (p2) = - position (p1.x + p2.x, p1.y + p2.y) - -// `plus` pode ser usado com um operador -position (1, 1) @plus position (0, 2) -// ou como uma função -(position (1, 1)) plus (position (0, 2)) - -// retorno explícito -(x) times (y) = return (x * y) - -// new -now = @new Date () - -// funções podem receber argumentos opcionais -spark (position, color: 'black', velocity: {x = 0, y = 0}) = { - color = color - position = position - velocity = velocity -} - -red = spark (position 1 1, color: 'red') -fast black = spark (position 1 1, velocity: {x = 10, y = 0}) - -// funções também podem ser utilizadas para realizar o "unsplat" de argumentos -log (messages, ...) = - console.log (messages, ...) - -// blocos são funções passadas para outras funções. -// Este bloco recebe dois parâmetros, `spark` e `c`, -// o corpo do bloco é o código indentado após a declaração da função - -render each @(spark) into canvas context @(c) - ctx.begin path () - ctx.stroke style = spark.color - ctx.arc ( - spark.position.x + canvas.width / 2 - spark.position.y - 3 - 0 - Math.PI * 2 - ) - ctx.stroke () - -// chamadas assíncronas - -// O Javascript, tanto no navegador quanto no servidor (através do Node.js) -// realiza um uso massivo de funções assíncronas de E/S (entrada/saída) com -// chamadas de retorno (callbacks). A E/S assíncrona é ótima para a performance e -// torna a utilização da concorrência simples, porém pode rapidamente se tornar -// algo complicado. -// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono muito -// mais fácil - -// O Node.js inclui o móduolo `fs` para acessar o sistema de arquivos. -// Vamos listar o conteúdo de um diretório - -fs = require 'fs' -directory listing = fs.readdir! '.' - -// `fs.readdir()` é uma função assíncrona, então nos a chamamos usando o -// operador `!`. O operador `!` permite que você chame funções assíncronas -// com a mesma sintaxe e a mesma semântica do que as demais funções síncronas. -// O Pogoscript reescreve a função para que todo código inserido após o -// operador seja inserido em uma função de callback para o `fs.readdir()`. - -// obtendo erros ao utilizar funções assíncronas - -try - another directory listing = fs.readdir! 'a-missing-dir' -catch (ex) - console.log (ex) - -// na verdade, se você não usar o `try catch`, o erro será passado para o -// `try catch` mais externo do evento, assim como é feito em exceções síncronas - -// todo o controle de estrutura também funciona com chamadas assíncronas -// aqui um exemplo de `if else` -config = - if (fs.stat! 'config.json'.is file ()) - JSON.parse (fs.read file! 'config.json' 'utf-8') - else - { - color: 'red' - } - -// para executar duas chamadas assíncronas de forma concorrente, use o -// operador `?`. -// O operador `?` retorna um *future*, que pode ser executado para -// aguardar o resultado, novamente utilizando o operador `!` - -// nós não esperamos nenhuma dessas chamadas serem concluídas -a = fs.stat? 'a.txt' -b = fs.stat? 'b.txt' - -// agora nos aguardamos o término das chamadas e escrevemos os resultados -console.log "size of a.txt is #(a!.size)" -console.log "size of b.txt is #(b!.size)" - -// no Pogoscript, futures são semelhantes a Promises -``` -E encerramos por aqui. - -Baixe o [Node.js](http://nodejs.org/) e execute `npm install pogo`. - -Há bastante documentação em [http://pogoscript.org/](http://pogoscript.org/), incluindo um material para [consulta rápida](http://pogoscript.org/cheatsheet.html), um [guia](http://pogoscript.org/guide/), e como o [Pogoscript é traduzido para o Javascript](http://featurist.github.io/pogo-examples/). Entre em contato através do [grupo do Google](http://groups.google.com/group/pogoscript) se você possui dúvidas! diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown index 105896b2..3d91f1ca 100644 --- a/pt-br/sass-pt.html.markdown +++ b/pt-br/sass-pt.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Sean Corrales", "https://github.com/droidenator"] translators: - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] lang: pt-br --- @@ -155,16 +156,6 @@ body { background-color: rgba(0, 0, 0, 0.75); } -/* You may also define your own functions. Functions are very similar to - mixins. When trying to choose between a function or a mixin, remember - that mixins are best for generating CSS while functions are better for - logic that might be used throughout your Sass code. The examples in - the Math Operators' section are ideal candidates for becoming a reusable - function. */ - -/* This function will take a target size and the parent size and calculate - and return the percentage */ - /* Você também pode definir suas próprias funções. As funções são muito semelhantes aos    mixins. Ao tentar escolher entre uma função ou um mixin, lembre-    que mixins são os melhores para gerar CSS enquanto as funções são melhores para @@ -319,11 +310,6 @@ ol { padding: 0; } -/* Sass offers @import which can be used to import partials into a file. - This differs from the traditional CSS @import statement which makes - another HTTP request to fetch the imported file. Sass takes the - imported file and combines it with the compiled code. */ - /* Sass oferece @import que pode ser usado para importar parciais em um arquivo.    Isso difere da declaração CSS @import tradicional, que faz    outra solicitação HTTP para buscar o arquivo importado. Sass converte os @@ -354,12 +340,6 @@ body { ==============================*/ - -/* Placeholders are useful when creating a CSS statement to extend. If you - wanted to create a CSS statement that was exclusively used with @extend, - you can do so using a placeholder. Placeholders begin with a '%' instead - of '.' or '#'. Placeholders will not appear in the compiled CSS. */ - /* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você    queria criar uma instrução CSS que foi usado exclusivamente com @extend,    Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez @@ -396,11 +376,6 @@ body { ============================== * / -/* Sass provides the following operators: +, -, *, /, and %. These can - be useful for calculating values directly in your Sass files instead - of using values that you've already calculated by hand. Below is an example - of a setting up a simple two column design. */ - /* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem    ser úteis para calcular os valores diretamente no seu Sass arquivos em vez    de usar valores que você já calculados pela mão. Abaixo está um exemplo -- cgit v1.2.3 From 762af2de245ab665af0e4b1397acc960d25932f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= <cassio.bock@gmail.com> Date: Thu, 29 Oct 2015 23:29:46 -0200 Subject: Fixing typos Fixing pt-br typos --- pt-br/c-pt.html.markdown | 71 ++++++++-------- pt-br/pogo-pt.html.markdown | 203 -------------------------------------------- 2 files changed, 36 insertions(+), 238 deletions(-) delete mode 100644 pt-br/pogo-pt.html.markdown diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index 43688724..2c274f12 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -7,29 +7,30 @@ contributors: translators: - ["João Farias", "https://github.com/JoaoGFarias"] - ["Elton Viana", "https://github.com/eltonvs"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] lang: pt-br filename: c-pt.el --- Ah, C. Ainda é **a** linguagem de computação de alta performance. -C é a liguangem de mais baixo nível que a maioria dos programadores -irão usar, e isso dá a ela uma grande velocidade bruta. Apenas fique -antento que este manual de gerenciamento de memória e C vai levanter-te -tão longe quanto você precisa. +C é a linguagem de mais baixo nível que a maioria dos programadores +utilizarão, e isso dá a ela uma grande velocidade bruta. Apenas fique +atento se este manual de gerenciamento de memória e C vai te levar +tão longe quanto precisa. ```c // Comentários de uma linha iniciam-se com // - apenas disponível a partir do C99 /* -Comentários de multiplas linhas se parecem com este. +Comentários de múltiplas linhas se parecem com este. Funcionam no C89 também. */ // Constantes: #define <palavra-chave> #definie DAY_IN_YEAR 365 -//enumarações também são modos de definir constantes. +//enumerações também são modos de definir constantes. enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB}; // SEG recebe 2 automaticamente, TER recebe 3, etc. @@ -54,13 +55,13 @@ int soma_dois_ints(int x1, int x2); // protótipo de função // O ponto de entrada do teu programa é uma função // chamada main, com tipo de retorno inteiro int main() { - // Usa-se printf para escrever na tela, + // Usa-se printf para escrever na tela, // para "saída formatada" // %d é um inteiro, \n é uma nova linha printf("%d\n", 0); // => Imprime 0 // Todos as declarações devem acabar com // ponto e vírgula - + /////////////////////////////////////// // Tipos /////////////////////////////////////// @@ -78,7 +79,7 @@ int main() { // longs tem entre 4 e 8 bytes; longs long tem garantia // de ter pelo menos 64 bits long x_long = 0; - long long x_long_long = 0; + long long x_long_long = 0; // floats são normalmente números de ponto flutuante // com 32 bits @@ -93,7 +94,7 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; - // caracteres dentro de aspas simples são inteiros + // caracteres dentro de aspas simples são inteiros // no conjunto de caracteres da máquina. '0' // => 48 na tabela ASCII. 'A' // => 65 na tabela ASCII. @@ -104,7 +105,7 @@ int main() { // Se o argumento do operador `sizeof` é uma expressão, então seus argumentos // não são avaliados (exceto em VLAs (veja abaixo)). - // O valor devolve, neste caso, é uma constante de tempo de compilação. + // O valor devolve, neste caso, é uma constante de tempo de compilação. int a = 1; // size_t é um inteiro sem sinal com pelo menos 2 bytes que representa // o tamanho de um objeto. @@ -120,7 +121,7 @@ int main() { // Você pode inicializar um array com 0 desta forma: char meu_array[20] = {0}; - // Indexar um array é semelhante a outras linguages + // Indexar um array é semelhante a outras linguagens // Melhor dizendo, outras linguagens são semelhantes a C meu_array[0]; // => 0 @@ -129,7 +130,7 @@ int main() { printf("%d\n", meu_array[1]); // => 2 // No C99 (e como uma features opcional em C11), arrays de tamanho variável - // VLA (do inglês), podem ser declarados também. O tamanho destes arrays + // VLA (do inglês), podem ser declarados também. O tamanho destes arrays // não precisam ser uma constante de tempo de compilação: printf("Entre o tamanho do array: "); // Pergunta ao usuário pelo tamanho char buf[0x100]; @@ -144,14 +145,14 @@ int main() { // > Entre o tamanho do array: 10 // > sizeof array = 40 - // String são apenas arrays de caracteres terminados por um + // String são apenas arrays de caracteres terminados por um // byte nulo (0x00), representado em string pelo caracter especial '\0'. // (Não precisamos incluir o byte nulo em literais de string; o compilador // o insere ao final do array para nós.) - char uma_string[20] = "Isto é uma string"; + char uma_string[20] = "Isto é uma string"; // Observe que 'é' não está na tabela ASCII // A string vai ser salva, mas a saída vai ser estranha - // Porém, comentários podem conter acentos + // Porém, comentários podem conter acentos printf("%s\n", uma_string); // %s formata a string printf("%d\n", uma_string[17]); // => 0 @@ -175,7 +176,7 @@ int main() { /////////////////////////////////////// // Atalho para multiplas declarações: - int i1 = 1, i2 = 2; + int i1 = 1, i2 = 2; float f1 = 1.0, f2 = 2.0; int a, b, c; @@ -206,7 +207,7 @@ int main() { 2 <= 2; // => 1 2 >= 2; // => 1 - // C não é Python - comparações não se encadeam. + // C não é Python - comparações não se encadeiam. int a = 1; // Errado: int entre_0_e_2 = 0 < a < 2; @@ -231,7 +232,7 @@ int main() { char *s = "iLoveC"; int j = 0; s[j++]; // => "i". Retorna o j-ésimo item de s E DEPOIS incrementa o valor de j. - j = 0; + j = 0; s[++j]; // => "L". Incrementa o valor de j. E DEPOIS retorna o j-ésimo item de s. // o mesmo com j-- e --j @@ -308,7 +309,7 @@ int main() { exit(-1); break; } - + /////////////////////////////////////// // Cast de tipos @@ -327,8 +328,8 @@ int main() { // Tipos irão ter overflow sem aviso printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 se char tem 8 bits) - // Para determinar o valor máximo de um `char`, de um `signed char` e de - // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX + // Para determinar o valor máximo de um `char`, de um `signed char` e de + // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX // e UCHAR_MAX de <limits.h> // Tipos inteiros podem sofrer cast para pontos-flutuantes e vice-versa. @@ -341,7 +342,7 @@ int main() { /////////////////////////////////////// // Um ponteiro é uma variável declarada para armazenar um endereço de memória. - // Seu declaração irá também dizer o tipo de dados para o qual ela aponta. Você + // Sua declaração irá também dizer o tipo de dados para o qual ela aponta. Você // Pode usar o endereço de memória de suas variáveis, então, brincar com eles. int x = 0; @@ -363,13 +364,13 @@ int main() { printf("%d\n", *px); // => Imprime 0, o valor de x // Você também pode mudar o valor que o ponteiro está apontando. - // Teremo que cercar a de-referência entre parenteses, pois + // Temos que cercar a de-referência entre parênteses, pois // ++ tem uma precedência maior que *. (*px)++; // Incrementa o valor que px está apontando por 1 printf("%d\n", *px); // => Imprime 1 printf("%d\n", x); // => Imprime 1 - // Arrays são um boa maneira de alocar um bloco contínuo de memória + // Arrays são uma boa maneira de alocar um bloco contínuo de memória int x_array[20]; // Declara um array de tamanho 20 (não pode-se mudar o tamanho int xx; for (xx = 0; xx < 20; xx++) { @@ -379,7 +380,7 @@ int main() { // Declara um ponteiro do tipo int e inicialize ele para apontar para x_array int* x_ptr = x_array; // x_ptr agora aponta para o primeiro elemento do array (o inteiro 20). - // Isto funciona porque arrays são apenas ponteiros para seu primeiros elementos. + // Isto funciona porque arrays são apenas ponteiros para seus primeiros elementos. // Por exemplo, quando um array é passado para uma função ou é atribuído a um // ponteiro, ele transforma-se (convertido implicitamente) em um ponteiro. // Exceções: quando o array é o argumento de um operador `&` (endereço-de): @@ -395,7 +396,7 @@ int main() { printf("%zu, %zu\n", sizeof arr, sizeof ptr); // provavelmente imprime "40, 4" ou "40, 8" // Ponteiros podem ser incrementados ou decrementados baseado no seu tipo - // (isto é chamado aritimética de ponteiros + // (isto é chamado aritmética de ponteiros printf("%d\n", *(x_ptr + 1)); // => Imprime 19 printf("%d\n", x_array[1]); // => Imprime 19 @@ -413,9 +414,9 @@ int main() { // "resultados imprevisíveis" - o programa é dito ter um "comportamento indefinido" printf("%d\n", *(my_ptr + 21)); // => Imprime quem-sabe-o-que? Talvez até quebre o programa. - // Quando termina-se de usar um bloco de memória alocado, você pode liberá-lo, + // Quando se termina de usar um bloco de memória alocado, você pode liberá-lo, // ou ninguém mais será capaz de usá-lo até o fim da execução - // (Isto cham-se "memory leak"): + // (Isto chama-se "memory leak"): free(my_ptr); // Strings são arrays de char, mas elas geralmente são representadas @@ -537,7 +538,7 @@ int area(retan r) return r.largura * r.altura; } -// Se você tiver structus grande, você pode passá-las "por ponteiro" +// Se você tiver structus grande, você pode passá-las "por ponteiro" // para evitar cópia de toda a struct: int area(const retan *r) { @@ -554,8 +555,8 @@ conhecidos. Ponteiros para funções são como qualquer outro ponteiro diretamente e passá-las para por toda parte. Entretanto, a sintaxe de definição por ser um pouco confusa. -Exemplo: use str_reverso através de um ponteiro -*/ +Exemplo: use str_reverso através de um ponteiro +*/ void str_reverso_através_ponteiro(char *str_entrada) { // Define uma variável de ponteiro para função, nomeada f. void (*f)(char *); //Assinatura deve ser exatamente igual à função alvo. @@ -575,7 +576,7 @@ typedef void (*minha_função_type)(char *); // Declarando o ponteiro: // ... -// minha_função_type f; +// minha_função_type f; //Caracteres especiais: '\a' // Alerta (sino) @@ -586,7 +587,7 @@ typedef void (*minha_função_type)(char *); '\r' // Retorno de carroça '\b' // Backspace '\0' // Caracter nulo. Geralmente colocado ao final de string em C. - // oi\n\0. \0 é usado por convenção para marcar o fim da string. + // oi\n\0. \0 é usado por convenção para marcar o fim da string. '\\' // Barra invertida '\?' // Interrogação '\'' // Aspas simples @@ -606,7 +607,7 @@ typedef void (*minha_função_type)(char *); "%p" // ponteiro "%x" // hexadecimal "%o" // octal -"%%" // imprime % +"%%" // imprime % /////////////////////////////////////// // Ordem de avaliação diff --git a/pt-br/pogo-pt.html.markdown b/pt-br/pogo-pt.html.markdown deleted file mode 100644 index 80dcfcd5..00000000 --- a/pt-br/pogo-pt.html.markdown +++ /dev/null @@ -1,203 +0,0 @@ ---- -language: pogoscript -contributors: - - ["Tim Macfarlane", "http://github.com/refractalize"] -translators: - - ["Cássio Böck", "https://github.com/cassiobsilva"] -filename: learnPogo-pt-br.pogo -lang: pt-br ---- - -Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents -e que compila para linguagem Javascript padrão. - -``` javascript -// definindo uma variável -water temperature = 24 - -// reatribuindo o valor de uma variável após a sua definição -water temperature := 26 - -// funções permitem que seus parâmetros sejam colocados em qualquer lugar -temperature at (a) altitude = 32 - a / 100 - -// funções longas são apenas indentadas -temperature at (a) altitude := - if (a < 0) - water temperature - else - 32 - a / 100 - -// declarando uma função -current temperature = temperature at 3200 altitude - -// essa função cria um novo objeto com métodos -position (x, y) = { - x = x - y = y - - distance from position (p) = - dx = self.x - p.x - dy = self.y - p.y - Math.sqrt (dx * dx + dy * dy) -} - -// `self` é similiar ao `this` do Javascript, com exceção de que `self` não -// é redefinido em cada nova função - -// declaração de métodos -position (7, 2).distance from position (position (5, 1)) - -// assim como no Javascript, objetos também são hashes -position.'x' == position.x == position.('x') - -// arrays -positions = [ - position (1, 1) - position (1, 2) - position (1, 3) -] - -// indexando um array -positions.0.y - -n = 2 -positions.(n).y - -// strings -poem = 'Tail turned to red sunset on a juniper crown a lone magpie cawks. - Mad at Oryoki in the shrine-room -- Thistles blossomed late afternoon. - Put on my shirt and took it off in the sun walking the path to lunch. - A dandelion seed floats above the marsh grass with the mosquitos. - At 4 A.M. the two middleaged men sleeping together holding hands. - In the half-light of dawn a few birds warble under the Pleiades. - Sky reddens behind fir trees, larks twitter, sparrows cheep cheep cheep - cheep cheep.' - -// texto de Allen Ginsburg - -// interpolação -outlook = 'amazing!' -console.log "the weather tomorrow is going to be #(outlook)" - -// expressões regulares -r/(\d+)m/i -r/(\d+) degrees/mg - -// operadores -true @and true -false @or true -@not false -2 < 4 -2 >= 2 -2 > 1 - -// os operadores padrão do Javascript também são suportados - -// definindo seu próprio operador -(p1) plus (p2) = - position (p1.x + p2.x, p1.y + p2.y) - -// `plus` pode ser usado com um operador -position (1, 1) @plus position (0, 2) -// ou como uma função -(position (1, 1)) plus (position (0, 2)) - -// retorno explícito -(x) times (y) = return (x * y) - -// new -now = @new Date () - -// funções podem receber argumentos opcionais -spark (position, color: 'black', velocity: {x = 0, y = 0}) = { - color = color - position = position - velocity = velocity -} - -red = spark (position 1 1, color: 'red') -fast black = spark (position 1 1, velocity: {x = 10, y = 0}) - -// funções também podem ser utilizadas para realizar o "unsplat" de argumentos -log (messages, ...) = - console.log (messages, ...) - -// blocos são funções passadas para outras funções. -// Este bloco recebe dois parâmetros, `spark` e `c`, -// o corpo do bloco é o código indentado após a declaração da função - -render each @(spark) into canvas context @(c) - ctx.begin path () - ctx.stroke style = spark.color - ctx.arc ( - spark.position.x + canvas.width / 2 - spark.position.y - 3 - 0 - Math.PI * 2 - ) - ctx.stroke () - -// chamadas assíncronas - -// O Javascript, tanto no navegador quanto no servidor (através do Node.js) -// realiza um uso massivo de funções assíncronas de E/S (entrada/saída) com -// chamadas de retorno (callbacks). A E/S assíncrona é ótima para a performance e -// torna a utilização da concorrência simples, porém pode rapidamente se tornar -// algo complicado. -// O Pogoscript possui algumas coisas que tornam o uso de E/S assíncrono muito -// mais fácil - -// O Node.js inclui o móduolo `fs` para acessar o sistema de arquivos. -// Vamos listar o conteúdo de um diretório - -fs = require 'fs' -directory listing = fs.readdir! '.' - -// `fs.readdir()` é uma função assíncrona, então nos a chamamos usando o -// operador `!`. O operador `!` permite que você chame funções assíncronas -// com a mesma sintaxe e a mesma semântica do que as demais funções síncronas. -// O Pogoscript reescreve a função para que todo código inserido após o -// operador seja inserido em uma função de callback para o `fs.readdir()`. - -// obtendo erros ao utilizar funções assíncronas - -try - another directory listing = fs.readdir! 'a-missing-dir' -catch (ex) - console.log (ex) - -// na verdade, se você não usar o `try catch`, o erro será passado para o -// `try catch` mais externo do evento, assim como é feito em exceções síncronas - -// todo o controle de estrutura também funciona com chamadas assíncronas -// aqui um exemplo de `if else` -config = - if (fs.stat! 'config.json'.is file ()) - JSON.parse (fs.read file! 'config.json' 'utf-8') - else - { - color: 'red' - } - -// para executar duas chamadas assíncronas de forma concorrente, use o -// operador `?`. -// O operador `?` retorna um *future*, que pode ser executado para -// aguardar o resultado, novamente utilizando o operador `!` - -// nós não esperamos nenhuma dessas chamadas serem concluídas -a = fs.stat? 'a.txt' -b = fs.stat? 'b.txt' - -// agora nos aguardamos o término das chamadas e escrevemos os resultados -console.log "size of a.txt is #(a!.size)" -console.log "size of b.txt is #(b!.size)" - -// no Pogoscript, futures são semelhantes a Promises -``` -E encerramos por aqui. - -Baixe o [Node.js](http://nodejs.org/) e execute `npm install pogo`. - -Há bastante documentação em [http://pogoscript.org/](http://pogoscript.org/), incluindo um material para [consulta rápida](http://pogoscript.org/cheatsheet.html), um [guia](http://pogoscript.org/guide/), e como o [Pogoscript é traduzido para o Javascript](http://featurist.github.io/pogo-examples/). Entre em contato através do [grupo do Google](http://groups.google.com/group/pogoscript) se você possui dúvidas! -- cgit v1.2.3 From 76bf016f82133ecdb53e02975014d10a34fefce9 Mon Sep 17 00:00:00 2001 From: Victor Caldas <victorcaldas@gmail.com> Date: Fri, 30 Oct 2015 00:12:29 -0200 Subject: translating java to pt-br --- pt-br/java-pt.html.markdown | 213 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 213 insertions(+) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index a884f273..3c9512aa 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -405,6 +405,219 @@ class Velocipede extends Bicicleta { } +// Interfaces +// Sintaxe de declaração de Interface +// <nível de acesso> Interface <nome-da-interface> extends <super-interfaces> { +// // Constantes +// // Declarações de método +//} + +// Exemplo - Comida: +public interface Comestivel { + public void comer(); // Qualquer classe que implementa essa interface, deve +                        // Implementar este método. +} + +public interface Digestivel { + public void digerir(); +} + + +// Agora podemos criar uma classe que implementa ambas as interfaces. +public class Fruta implements Comestivel, Digestivel { + + @Override + public void comer() { + // ... + } + + @Override + public void digerir() { + // ... + } +} + +// Em Java, você pode estender somente uma classe, mas você pode implementar muitas +// Interfaces. Por exemplo: +public class ClasseExemplo extends ExemploClassePai implements InterfaceUm, + InterfaceDois { + + @Override + public void InterfaceUmMetodo() { + } + + @Override + public void InterfaceDoisMetodo() { + } + +} + +// Classes abstratas + +// Sintaxe de declaração de classe abstrata +// <Nível de acesso> abstract <nome-da-classe-abstrata> extends <estende super-abstratas-classes> { +// // Constantes e variáveis +// // Declarações de método +//} + +// Marcar uma classe como abstrata significa que ela contém métodos abstratos que devem +// ser definido em uma classe filha. Semelhante às interfaces, classes abstratas não podem +// ser instanciadas, ao invés disso devem ser extendidas e os métodos abstratos +// definidos. Diferente de interfaces, classes abstratas podem conter uma mistura de +// métodos concretos e abstratos. Métodos em uma interface não podem ter um corpo, +// a menos que o método seja estático, e as variáveis sejam finais, por padrão, ao contrário de um +// classe abstrata. Classes abstratas também PODEM ter o método "main". + +public abstract class Animal +{ + public abstract void fazerSom(); + + // Método pode ter um corpo + public void comer() + { + System.out.println("Eu sou um animal e estou comendo."); + //Nota: Nós podemos acessar variáveis privadas aqui. + idade = 30; + } + + // Não há necessidade de inicializar, no entanto, em uma interface +    // a variável é implicitamente final e, portanto, tem +    // de ser inicializado. + protected int idade; + + public void mostrarIdade() + { + System.out.println(idade); + } + + //Classes abstratas podem ter o método main. + public static void main(String[] args) + { + System.out.println("Eu sou abstrata"); + } +} + +class Cachorro extends Animal +{ + + // Nota: ainda precisamos substituir os métodos abstratos na +    // classe abstrata + @Override + public void fazerSom() + { + System.out.println("Bark"); + // idade = 30; ==> ERRO! idade é privada de Animal + } + + // NOTA: Você receberá um erro se usou a +    // anotação Override aqui, uma vez que java não permite +    // sobrescrita de métodos estáticos. +    // O que está acontecendo aqui é chamado de "esconder o método". +    // Vejá também este impressionante SO post: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Cachorro pluto = new Cachorro(); + pluto.fazerSom(); + pluto.comer(); + pluto.mostrarIdade(); + } +} + +// Classes Finais + +// Sintaxe de declaração de classe final +// <nível de acesso> final <nome-da-classe-final> { +// // Constantes e variáveis +// // Declarações de método +//} + +// Classes finais são classes que não podem ser herdadas e são, portanto, um +// filha final. De certa forma, as classes finais são o oposto de classes abstratas +// Porque classes abstratas devem ser estendidas, mas as classes finais não pode ser +// estendidas. +public final class TigreDenteDeSabre extends Animal +{ + // Nota: Ainda precisamos substituir os métodos abstratos na +     // classe abstrata. + @Override + public void fazerSom(); + { + System.out.println("Roar"); + } +} + +// Métodos Finais +public abstract class Mamifero() +{ + // Sintaxe de Métodos Finais: + // <modificador-de-acesso> final <tipo-de-retorno> <nome-do-método>(<argumentos>) + + // Métodos finais, como, classes finais não podem ser substituídas por uma classe filha, +    // e são, portanto, a implementação final do método. + public final boolean EImpulsivo() + { + return true; + } +} + + +// Tipo Enum +// +// Um tipo enum é um tipo de dado especial que permite a uma variável ser um conjunto de constantes predefinidas. A +// variável deve ser igual a um dos valores que foram previamente definidos para ela. +// Por serem constantes, os nomes dos campos de um tipo de enumeração estão em letras maiúsculas. +// Na linguagem de programação Java, você define um tipo de enumeração usando a palavra-chave enum. Por exemplo, você poderia +// especificar um tipo de enum dias-da-semana como: + +public enum Dia { + DOMINGO, SEGUNDA, TERÇA, QUARTA, + QUINTA, SEXTA, SABADO +} + +// Nós podemos usar nosso enum Dia assim: + +public class EnumTeste { + + // Variável Enum + Dia dia; + + public EnumTeste(Dia dia) { + this.dia = dia; + } + + public void digaComoE() { + switch (dia) { + case SEGUNDA: + System.out.println("Segundas são ruins."); + break; + + case SEXTA: + System.out.println("Sextas são melhores."); + break; + + case SABADO: + case DOMINGO: + System.out.println("Finais de semana são os melhores."); + break; + + default: + System.out.println("Dias no meio da semana são mais ou menos."); + break; + } + } + + public static void main(String[] args) { + EnumTeste primeiroDia = new EnumTeste(Dia.SEGUNDA); + primeiroDia.digaComoE(); // => Segundas-feiras são ruins. + EnumTeste terceiroDia = new EnumTeste(Dia.QUARTA); + terceiroDia.digaComoE(); // => Dias no meio da semana são mais ou menos. + } +} + +// Tipos Enum são muito mais poderosos do que nós mostramos acima. +// O corpo de um enum pode incluir métodos e outros campos. +// Você pode ver mais em https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + ``` ## Leitura Recomendada -- cgit v1.2.3 From bc91d2ce920c8e68cdc882cb6af2c15e7d54352e Mon Sep 17 00:00:00 2001 From: "Elizabeth \"Lizzie\" Siegle" <esiegle@brynmawr.edu> Date: Fri, 30 Oct 2015 01:20:12 -0400 Subject: Update make.html.markdown --- make.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index 563139d1..e8cfd2b5 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -234,10 +234,8 @@ bar = 'hello' endif ``` - ### More Resources + [gnu make documentation](https://www.gnu.org/software/make/manual/) + [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) + learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) - -- cgit v1.2.3 From 3c43328a899f7996b0edb593092906057330aa98 Mon Sep 17 00:00:00 2001 From: Nasgul <nasguling@gmail.com> Date: Fri, 30 Oct 2015 14:52:23 +0200 Subject: Delete unused double quote. Delete unused double quote. --- ru-ru/clojure-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 2f508a00..451da312 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -144,7 +144,7 @@ Clojure, это представитель семейства Lisp-подобн ;;;;;;;;;;;;;;;;;;;;; ; Функция создается специальной формой fn. -; "Тело"" функции может состоять из нескольких форм, +; "Тело" функции может состоять из нескольких форм, ; но результатом вызова функции всегда будет результат вычисления ; последней из них. (fn [] "Hello World") ; => fn -- cgit v1.2.3 From ec601c168aa50368822411d7487e81027388db53 Mon Sep 17 00:00:00 2001 From: Jake Faris <jake.faris@alphasights.com> Date: Fri, 30 Oct 2015 10:17:15 -0400 Subject: Adds combined comparison operator to Ruby --- ruby.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 998b4bf7..6114c14e 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -77,6 +77,11 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true +# Combined comparison operator +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + # Logical operators true && false #=> false true || false #=> true -- cgit v1.2.3 From 33337d045d5af8155e9ef3418f6f766298977a15 Mon Sep 17 00:00:00 2001 From: Jake Faris <jake.faris@alphasights.com> Date: Fri, 30 Oct 2015 10:22:23 -0400 Subject: Adds bitwise operators (AND, OR, XOR) --- ruby.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 998b4bf7..f13b77ac 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -41,7 +41,11 @@ You shouldn't either 35 / 5 #=> 7 2**5 #=> 32 5 % 3 #=> 2 -5 ^ 6 #=> 3 + +# Bitwise operators +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 # Arithmetic is just syntactic sugar # for calling a method on an object -- cgit v1.2.3 From 71ee28e132fbbade39568fb2332b10e81c07f68a Mon Sep 17 00:00:00 2001 From: Jacob Ward <jacobward1898@gmail.com> Date: Fri, 30 Oct 2015 08:32:32 -0600 Subject: easier to read? --- markdown.html.markdown | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 2333110f..8b218473 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -2,45 +2,53 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] + - ["Jacob Ward", "http://github.com/JacobCWard/"] filename: markdown.md --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). - -Give me as much feedback as you want! / Feel free to fork and pull request! +Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -```markdown -<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that +Markdown is a superset of HTML, so any HTML file is valid Markdown, that means we can use HTML elements in Markdown, such as the comment element, and they won't be affected by a markdown parser. However, if you create an HTML element in your markdown file, you cannot use markdown syntax within that -element's contents. --> +element's contents. -<!-- Markdown also varies in implementation from one parser to a next. This +Markdown also varies in implementation from one parser to a next. This guide will attempt to clarify when features are universal or when they are -specific to a certain parser. --> +specific to a certain parser. + +- [Headings](#headings) +- [Simple Text Styles](#simple-text-styles) -<!-- Headers --> -<!-- You can create HTML elements <h1> through <h6> easily by prepending the -text you want to be in that element by a number of hashes (#) --> +## Headings + +You can create HTML elements `<h1>` through `<h6>` easily by prepending the +text you want to be in that element by a number of hashes (#). + +```markdown # This is an <h1> ## This is an <h2> ### This is an <h3> #### This is an <h4> ##### This is an <h5> ###### This is an <h6> +``` +Markdown also provides us with two alternative ways of indicating h1 and h2. -<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 --> +```markdown This is an h1 ============= This is an h2 ------------- +``` +## Simple text styles -<!-- Simple text styles --> -<!-- Text can be easily styled as italic or bold using markdown --> +Text can be easily styled as italic or bold using markdown. +```markdown *This text is in italics.* _And so is this text._ @@ -50,10 +58,11 @@ __And so is this text.__ ***This text is in both.*** **_As is this!_** *__And this!__* +``` -<!-- In Github Flavored Markdown, which is used to render markdown files on -Github, we also have strikethrough: --> - +In Github Flavored Markdown, which is used to render markdown files on +Github, we also have strikethrough: +```markdown ~~This text is rendered with strikethrough.~~ <!-- Paragraphs are a one or multiple adjacent lines of text separated by one or @@ -83,7 +92,9 @@ There's a <br /> above me! > You can also use more than one level >> of indentation? > How neat is that? +``` +```markdown <!-- Lists --> <!-- Unordered lists can be made using asterisks, pluses, or hyphens --> -- cgit v1.2.3 From 8aff0a65dc106f4718b8d5da27178757e4f41eba Mon Sep 17 00:00:00 2001 From: Anton Pastukhoff <pastuhov85@gmail.com> Date: Fri, 30 Oct 2015 20:10:22 +0500 Subject: Update d-ru.html.markdown --- ru-ru/d-ru.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 33bff3b7..cbd5b127 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -39,7 +39,7 @@ module app; import std.stdio; // можно импортировать только нужные части, не обязательно модуль целиком -import std.exception : assert; +import std.exception : enforce; // точка входа в программу — функция main, аналогично C/C++ void main() @@ -60,7 +60,7 @@ double с = 56.78; // тип с плавающей точкой (64 бита) комплексных чисел, могут быть беззнаковыми. В этом случае название типа начинается с префикса "u" */ -uint d = 10, ulong e = 11.12; +uint d = 10; ulong e = 11; bool b = true; // логический тип char d = 'd'; // UTF-символ, 8 бит. D поддерживает UTF "из коробки" wchar = 'é'; // символ UTF-16 @@ -146,7 +146,7 @@ x++; // 10 ++x; // 11 x *= 2; // 22 x /= 2; // 11 -x ^^ 2; // 121 (возведение в степень) +x = x ^^ 2; // 121 (возведение в степень) x ^^= 2; // 1331 (то же самое) string str1 = "Hello"; @@ -160,7 +160,7 @@ arr ~= 4; // [1, 2, 3, 4] - добавление элемента в конец /*** Логика и сравнения ***/ -int x = 0, int y = 1; +int x = 0; int y = 1; x == y; // false x > y; // false -- cgit v1.2.3 From 9a152c0490ba38e791ba1444d74dcf184d3c847e Mon Sep 17 00:00:00 2001 From: Jacob Ward <jacobward1898@gmail.com> Date: Fri, 30 Oct 2015 09:24:49 -0600 Subject: Revert "easier to read?" This reverts commit 71ee28e132fbbade39568fb2332b10e81c07f68a. --- markdown.html.markdown | 45 +++++++++++++++++---------------------------- 1 file changed, 17 insertions(+), 28 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 8b218473..2333110f 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -2,53 +2,45 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] - - ["Jacob Ward", "http://github.com/JacobCWard/"] filename: markdown.md --- - Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -Markdown is a superset of HTML, so any HTML file is valid Markdown, that +Give me as much feedback as you want! / Feel free to fork and pull request! + + +```markdown +<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that means we can use HTML elements in Markdown, such as the comment element, and they won't be affected by a markdown parser. However, if you create an HTML element in your markdown file, you cannot use markdown syntax within that -element's contents. +element's contents. --> -Markdown also varies in implementation from one parser to a next. This +<!-- Markdown also varies in implementation from one parser to a next. This guide will attempt to clarify when features are universal or when they are -specific to a certain parser. - -- [Headings](#headings) -- [Simple Text Styles](#simple-text-styles) +specific to a certain parser. --> -## Headings - -You can create HTML elements `<h1>` through `<h6>` easily by prepending the -text you want to be in that element by a number of hashes (#). - -```markdown +<!-- Headers --> +<!-- You can create HTML elements <h1> through <h6> easily by prepending the +text you want to be in that element by a number of hashes (#) --> # This is an <h1> ## This is an <h2> ### This is an <h3> #### This is an <h4> ##### This is an <h5> ###### This is an <h6> -``` -Markdown also provides us with two alternative ways of indicating h1 and h2. -```markdown +<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 --> This is an h1 ============= This is an h2 ------------- -``` -## Simple text styles -Text can be easily styled as italic or bold using markdown. +<!-- Simple text styles --> +<!-- Text can be easily styled as italic or bold using markdown --> -```markdown *This text is in italics.* _And so is this text._ @@ -58,11 +50,10 @@ __And so is this text.__ ***This text is in both.*** **_As is this!_** *__And this!__* -``` -In Github Flavored Markdown, which is used to render markdown files on -Github, we also have strikethrough: -```markdown +<!-- In Github Flavored Markdown, which is used to render markdown files on +Github, we also have strikethrough: --> + ~~This text is rendered with strikethrough.~~ <!-- Paragraphs are a one or multiple adjacent lines of text separated by one or @@ -92,9 +83,7 @@ There's a <br /> above me! > You can also use more than one level >> of indentation? > How neat is that? -``` -```markdown <!-- Lists --> <!-- Unordered lists can be made using asterisks, pluses, or hyphens --> -- cgit v1.2.3 From 5afca01bdfb7dab2e6086a63bb80444aae9831cb Mon Sep 17 00:00:00 2001 From: Liam Demafelix <liamdemafelix.n@gmail.com> Date: Fri, 30 Oct 2015 23:26:49 +0800 Subject: [php/en] Line 159 - echo isn't a function, print() is Line 337 - unneeded semicolon (it's a pre-test loop) --- php.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 0504ced2..7b0cf61c 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -3,6 +3,7 @@ language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] + - [ Liam Demafelix , https://liamdemafelix.com/] filename: learnphp.php --- @@ -156,14 +157,13 @@ unset($array[3]); * Output */ -echo('Hello World!'); +echo 'Hello World!'; // Prints Hello World! to stdout. // Stdout is the web page if running in a browser. print('Hello World!'); // The same as echo -// echo and print are language constructs too, so you can drop the parentheses -echo 'Hello World!'; +// print is a language construct too, so you can drop the parentheses print 'Hello World!'; $paragraph = 'paragraph'; @@ -335,7 +335,7 @@ switch ($x) { $i = 0; while ($i < 5) { echo $i++; -}; // Prints "01234" +} // Prints "01234" echo "\n"; -- cgit v1.2.3 From 08b43e21f1a273d5ca471e0accdf46ba706a4cd5 Mon Sep 17 00:00:00 2001 From: Jacob Ward <jacobward1898@gmail.com> Date: Fri, 30 Oct 2015 09:32:51 -0600 Subject: Changed headers to headings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Relabeled the section called “headers” to “headings” because a header is a specific tag separate from the h1-h6 ‘heading’ tags. --- markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 2333110f..d5ed284b 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -21,7 +21,7 @@ element's contents. --> guide will attempt to clarify when features are universal or when they are specific to a certain parser. --> -<!-- Headers --> +<!-- Headings --> <!-- You can create HTML elements <h1> through <h6> easily by prepending the text you want to be in that element by a number of hashes (#) --> # This is an <h1> -- cgit v1.2.3 From 55101d6ca7bd51b3b3c850ad51f24d7980a288d6 Mon Sep 17 00:00:00 2001 From: IvanEh <ivanehreshi@gmail.com> Date: Fri, 30 Oct 2015 17:53:40 +0200 Subject: Add Ukrainian translation to javascript guide --- ua-ua/javascript-ua.html.markdown | 501 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 501 insertions(+) create mode 100644 ua-ua/javascript-ua.html.markdown diff --git a/ua-ua/javascript-ua.html.markdown b/ua-ua/javascript-ua.html.markdown new file mode 100644 index 00000000..fedbf5ac --- /dev/null +++ b/ua-ua/javascript-ua.html.markdown @@ -0,0 +1,501 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ru.js +translators: + - ["Alexey Gonchar", "http://github.com/finico"] + - ["Andre Polykanine", "https://github.com/Oire"] +lang: ru-ru +--- + +JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape. +Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java +для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і +вбудована підтримка браузерами призвела до того, що JavaScript став популярніший +за власне Java. + +Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js, +програмна платформа, що дозволяє виконувати JavaScript код з використанням +рушія V8 від браузера Google Chrome, стає все більш і більш популярною. + +```js +// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш) +/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і + закінчуються символами зірочка-слеш */ + +Інструкції можуть закінчуватися крапкою з комою ; +doStuff(); + +// ... але не обов’язково, тому що крапка з комою автоматично вставляється на +// місці символу нового рядка, крім деяких випадків. +doStuff() + +// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці +// винятки можуть призвести до неочікуваних результатів + +/////////////////////////////////// +// 1. Числа, Рядки і Оператори + +// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double) +// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з +// точністю до 9✕10¹⁵. +3; // = 3 +1.5; // = 1.5 + +// Деякі прості арифметичні операції працють так, як ми очікуємо. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні) +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// В тому числі ділення з остачою +5 / 2; // = 2.5 + +// В JavaScript є побітові операції; коли ви виконуєте таку операцію, +// число з плаваючою точкою переводиться в ціле зі знаком +// довжиною *до* 32 розрядів. +1 << 2; // = 4 + +// Пріоритет у виразах можна задати явно круглими дужками +(1 + 3) * 2; // = 8 + +// Є три спеціальні значення, які не є реальними числами: +Infinity; // "нескінченність", наприклад, як результат ділення на 0 +-Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0 +NaN; // "не число", наприклад, ділення 0/0 + +// Логічні типи +true; +false; + +// Рядки створюються за допомогою подвійних та одинарних лапок +'абв'; +"Hello, world!"; + +// Для логічного заперечення використовується знак оклику. +!true; // = false +!false; // = true + +// Строга рівність === +1 === 1; // = true +2 === 1; // = false + +// Строга нерівність !== +1 !== 1; // = false +2 !== 1; // = true + +// Інші оператори порівняння +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Рядки об’єднуються за допомогою оператор + +"hello, " + "world!"; // = "hello, world!" + +// І порівнюються за допомогою > і < +"a" < "b"; // = true + +// Перевірка на рівність з приведнням типів здійснюється оператором == +"5" == 5; // = true +null == undefined; // = true + +// ... але приведення не виконується при === +"5" === 5; // = false +null === undefined; // = false + +// ... приведення типів може призвести до дивних результатів +13 + !0; // 14 +"13" + !0; // '13true' + +// Можна отримати доступ до будь-якого символа рядка за допомгою charAt +"Это строка".charAt(0); // = 'Э' + +// ... або використати метод substring, щоб отримати більший кусок +"Hello, world".substring(0, 5); // = "Hello" + +// length - це не метод, а поле +"Hello".length; // = 5 + +// Типи null и undefined +null; // навмисна відсутність результату +undefined; // використовується для позначення відсутності присвоєного значення + +// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина. +// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що: +// 0 == "0". + +/////////////////////////////////// +// 2. Змінні, Масиви, Об’єкти + +// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з +// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння +// значення змінної використовується символ = +var someVar = 5; + +// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ... +someOtherVar = 10; + +// ... але ваша змінна буде створення в глобальному контексті, а не там, де +// ви її оголосили + +// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined +var someThirdVar; // = undefined + +// У математичних операцій є скорочені форми: +someVar += 5; // як someVar = someVar + 5; +someVar *= 10; // тепер someVar = 100 + +// Інкремент і декремент +someVar++; // тепер someVar дорівнює 101 +someVar--; // а зараз 100 + +// Масиви — це нумеровані списку, які зберігають значення будь-якого типу. +var myArray = ["Hello", 45, true]; + +// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками +// Індексація починається з нуля +myArray[1]; // = 45 + +// Массивы можно изменять, как и их длину, +myArray.push("Мир"); +myArray.length; // = 4 + +// додавання і редагування елементів +myArray[3] = "Hello"; + +// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах +var myObj = {key1: "Hello", key2: "World"}; + +// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє +// правилам формування назв змінних. Значення можуть бути будь-яких типів. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Атрибути можна отримати використовуючи квадратні дужки +myObj["my other key"]; // = 4 + +// Або через точку, якщо ключ є правильним ідентифікатором +myObj.myKey; // = "myValue" + +// Об’єкти можна динамічно змінювати й додавати нові поля +myObj.myThirdKey = true; + +// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Управляючі конструкції + +// Синтаксис для цього розділу майже такий самий, як у Java + +// Умовна конструкція +var count = 1; +if (count == 3) { + // виконується, якщо count дорівнює 3 +} else if (count == 4) { + // .. +} else { + // ... +} + +// ... цикл while. +while (true){ + // Нескінченний цикл! +} + +// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// цикл for такий самий, кяк в C і Java: +// ініціалізація; умова; крок. +for (var i = 0; i < 5; i++) { + // виконається 5 разів +} + +// && — логічне І, || — логічне АБО +if (house.size == "big" && house.color == "blue") { + house.contains = "bear"; +} +if (color == "red" || color == "blue") { + // колір червоний або синій +} + +// && і || використовують скорочене обчислення +// тому їх можна використовувати для задання значень за замовчуванням. +var name = otherName || "default"; + +// Оператор switch виконує перевірку на рівність за допомогою === +// використовуйте break, щоб призупити виконання наступного case, +grade = 4; +switch (grade) { + case 5: + console.log("Відмінно"); + break; + case 4: + console.log("Добре"); + break; + case 3: + console.log("Можна краще"); + break; + default: + console.log("Погано!"); + break; +} + + +/////////////////////////////////// +// 4. Функції, область видимості і замикання + +// Функції в JavaScript оголошуються за допомогою ключового слова function. +function myFunction(thing) { + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж +// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined +// із-за автоматичної вставки крапки з комою +function myFunction() +{ + return // <- крапка з комою вставляється автоматично + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися +// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник +// події. +function myFunction() { + // код буде виконано через 5 сек. +} +setTimeout(myFunction, 5000); +// setTimeout не є частиною мови, але реалізований в браузерах і Node.js + +// Функции не обязательно должны иметь имя при объявлении — вы можете написать +// анонимное определение функции непосредственно в аргументе другой функции. +// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати +// анонімну функцію прямо в якості аргумента іншої функції +setTimeout(function() { + // Цей код буде виконано через п’ять секунд +}, 5000); + +// В JavaScript реалізована концепція області видимості; функції мають свою +// область видимости, а інші блоки не мають +if (true) { + var i = 5; +} +i; // = 5, а не undefined, як це звичайно буває в інших мова + +// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе" +// що дозволяє уникнути проникнення змінних в глобальну область видимості +(function() { + var temporary = 5; + // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати + // змінні до глобальної області + window.permanent = 10; +})(); +temporary; // повідомлення про помилку ReferenceError +permanent; // = 10 + +// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция +// определена внутри другой функции, то внутренняя функция имеет доступ к +// переменным внешней функции даже после того, как контекст выполнения выйдет из +// внешней функции. +// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена +// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої +// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції +function sayHelloInFiveSeconds(name) { + var prompt = "Hello, " + name + "!"; + // Внутрішня функція зберігається в локальній області так, + // ніби функція була оголошена за допомогою ключового слова var + function inner() { + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться, + // після чого setTimeout викличе функцію inner. Але функція inner + // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt +} +sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!» + +/////////////////////////////////// +// 5. Об’єкти: конструктори і прототипи + +// Об’єкти можуть містити функції +var myObj = { + myFunc: function() { + return "Hello, world!"; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за +// допомогою ключового слова this. +myObj = { + myString: "Hello, world!", + myFunc: function() { + return this.myString; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Значення this залежить від того, як функція викликається +// а не від того, де вона визначена. Таким чином наша функція не працює, якщо +// вона викликана не в контексті об’єкта +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до +// цього об’єкта через this +var myOtherFunc = function() { +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO, WORLD!" + +// Контекст виконання функції можна задати за допомогою сall або apply +var anotherFunc = function(s) { + return this.myString + s; +} +anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!" + +// Функцiя apply приймає в якості аргументу масив +anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!" + +// apply можна використати, коли функція працює послідовністю аргументів, а +// ви хочете передати масив +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (Ой-ой!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт +// використовують bind +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" Hello!"); // = "Hello world, Hello!" + +// Bind можна використати для задання аргументів +var product = function(a, b) { return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт, +// доступний функції за допомогою this. Такі функції називають конструкторами. +var MyConstructor = function() { + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому +// об’єктів, інтерпретатор буде шукати поле в прототипі + +// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через +// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують +// стандартні способи використання прототипів, які ми побачимо пізніше +var myObj = { + myString: "Hello, world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function() { + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Аналогічно для функцій +myObj.myFunc(); // = "Hello, world!" + +// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук +// в прототипі прототипа і так далі +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити +// наш прототип, і наші зміни будуть всюди відображені. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу +// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим +// прототипом + +// Перший спосіб — це Object.create, який з’явився JavaScript недавно, +// а тому в деяких реалізаціях може бути не доступним. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не* +// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені +// цим конструктором і ключового слова new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function() { + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні +// об’єкти-обгортки +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Але вони не ідентичні +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0) { + // Этот код не выполнится, потому что 0 - это ложь. +} + +// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому +// ви можете розширити функціонал рядків: +String.prototype.firstCharacter = function() { + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості +// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих +// середовищах + +// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо +// використати функції за допомогою наступного поліфіла: +if (Object.create === undefined) { // не перезаписываем метод, если он существует + Object.create = function(proto) { + // Створюємо правильний конструктор з правильним прототипом + var Constructor = function(){}; + Constructor.prototype = proto; + + return new Constructor(); + } +} +``` + +## Що почитати + +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: http://eloquentjavascript.net/ +[9]: http://jstherightway.org/ -- cgit v1.2.3 From a4842767094537dfee57698edc3bcc2b74f1ecee Mon Sep 17 00:00:00 2001 From: Andrew <andrew.taylor@boxuk.com> Date: Fri, 30 Oct 2015 19:58:33 +0000 Subject: Adds documentation for revert command Also mentions graph flag for the log command --- git.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/git.html.markdown b/git.html.markdown index bedc9853..e7ca07d6 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Leo Rudberg" , "http://github.com/LOZORD"] - ["Betsy Lorton" , "http://github.com/schbetsy"] - ["Bruno Volcov", "http://github.com/volcov"] + - ["Andrew Taylor", "http://github.com/andrewjt71"] filename: LearnGit.txt --- @@ -333,6 +334,9 @@ $ git log --oneline # Show merge commits only $ git log --merges + +# Show all commits represented by an ASCII graph +$ git log --graph ``` ### merge @@ -499,6 +503,16 @@ $ git reset 31f2bb1 # after the specified commit). $ git reset --hard 31f2bb1 ``` +### revert + +Revert can be used to undo a commit. It should not be confused with reset which restores +the state of a project to a previous point. Revert will add a new commit which is the +inverse of the specified commit, thus reverting it. + +```bash +# Revert a specified commit +$ git revert <commit> +``` ### rm -- cgit v1.2.3 From 9530122a1c956a25adb71bfd9cc1c516ff67d2f3 Mon Sep 17 00:00:00 2001 From: Fernando Valverde <fdov88@gmail.com> Date: Fri, 30 Oct 2015 22:43:44 +0100 Subject: Include MARK style and two collection declarations Added MARK with separator and a couple of mutable explicit declarations of empty Array/Dictionary --- swift.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/swift.html.markdown b/swift.html.markdown index f451288d..1ca81bc2 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -25,6 +25,7 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark +// MARK: - Section mark with a separator line // TODO: Do something soon // FIXME: Fix this code @@ -128,6 +129,7 @@ shoppingList[1] = "bottle of water" let emptyArray = [String]() // let == immutable let emptyArray2 = Array<String>() // same as above var emptyMutableArray = [String]() // var == mutable +var explicitEmptyMutableStringArray: [String] = [] // same as above // Dictionary @@ -139,6 +141,7 @@ occupations["Jayne"] = "Public Relations" let emptyDictionary = [String: Float]() // let == immutable let emptyDictionary2 = Dictionary<String, Float>() // same as above var emptyMutableDictionary = [String: Float]() // var == mutable +var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above // -- cgit v1.2.3 From 0717fcfdc774a877020b9d194dc40924aa5dd528 Mon Sep 17 00:00:00 2001 From: Fernando Valverde <fdov88@gmail.com> Date: Fri, 30 Oct 2015 22:57:55 +0100 Subject: Added pragma mark information `#pragma mark` is very useful and widely recommended to "abuse" it for method/variable grouping since it improves readability. --- objective-c.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index f130ea0c..36b4f3e9 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -20,6 +20,10 @@ It is a general-purpose, object-oriented programming language that adds Smalltal Multi-line comments look like this */ +// XCode supports pragma mark directive that improve jump bar readability +#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions' +#pragma mark - Navigation Functions // Same tag, now with a separator + // Imports the Foundation headers with #import // Use <> to import global files (in general frameworks) // Use "" to import local files (from project) -- cgit v1.2.3 From ee835c28a942c85c5c32d24dde35239a8d07e7e2 Mon Sep 17 00:00:00 2001 From: Aybuke Ozdemir <aybuke.147@gmail.com> Date: Sat, 31 Oct 2015 00:49:23 +0200 Subject: the comments were translated into Turkish --- tr-tr/c-tr.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 128901de..2d4240ed 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -91,9 +91,9 @@ int main() { // Örneğin, printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words) - // If the argument of the `sizeof` operator an expression, then its argument - // is not evaluated (except VLAs (see below)). - // The value it yields in this case is a compile-time constant. + // Eger arguman düzenli ifae olan sizeof operatoru ise degerlendirilmez. + // VLAs hariç asagiya bakiniz). + // Bu durumda verimliligin degeri derleme-zamani sabitidir. int a = 1; // size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir @@ -101,7 +101,7 @@ int main() { size_t size = sizeof(a++); // a++ is not evaluated printf("sizeof(a++) = %zu where a = %d\n", size, a); - // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture) + // yazdirilan "sizeof(a++) = 4 where a = 1" (32-bit mimaride) // Diziler somut bir boyut ile oluşturulmalıdır. char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar @@ -119,19 +119,19 @@ int main() { my_array[1] = 2; printf("%d\n", my_array[1]); // => 2 - // In C99 (and as an optional feature in C11), variable-length arrays (VLAs) - // can be declared as well. The size of such an array need not be a compile - // time constant: - printf("Enter the array size: "); // ask the user for an array size + // C99'da (ve C11 istege bagli bir ozellik olarak), değidken-uzunluklu diziler (VLAs) bildirilebilirler. + // Böyle bir dizinin boyuunu derlenmesi gerekmez + // zaman sabiti: + printf("Enter the array size: "); // dizi boyutu kullaniciya soruluyor char buf[0x100]; fgets(buf, sizeof buf, stdin); - // strtoul parses a string to an unsigned integer + // strtoul isaretsiz integerlar icin string ayiricisidir. size_t size = strtoul(buf, NULL, 10); int var_length_array[size]; // declare the VLA printf("sizeof array = %zu\n", sizeof var_length_array); - // A possible outcome of this program may be: + // Bu programın olası bir sonucu olabilir: // > Enter the array size: 10 // > sizeof array = 40 @@ -151,8 +151,8 @@ int main() { printf("%d\n", a_string[16]); // => 0 // i.e., byte #17 is 0 (as are 18, 19, and 20) - // If we have characters between single quotes, that's a character literal. - // It's of type `int`, and *not* `char` (for historical reasons). + // Tek tirnak arasinda karakterlere sahipsek, bu karakterler degismezdir. + // Tip `int` ise, `char` *degildir* (tarihsel sebeplerle). int cha = 'a'; // fine char chb = 'a'; // fine too (implicit conversion from int to char) @@ -201,10 +201,10 @@ int main() { 0x01 << 1; // => 0x02 (bitwise left shift (by 1)) 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) - // Be careful when shifting signed integers - the following are undefined: - // - shifting into the sign bit of a signed integer (int a = 1 << 32) - // - left-shifting a negative number (int a = -1 << 2) - // - shifting by an offset which is >= the width of the type of the LHS: + // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir: + // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32) + // - negatif sayilarda sol kaydirma (int a = -1 << 2) + // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma: // int a = 1 << 32; // UB if int is 32 bits wide /////////////////////////////////////// @@ -485,4 +485,4 @@ Readable code is better than clever code and fast code. For a good, sane coding Diğer taraftan google sizin için bir arkadaş olabilir. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member -- cgit v1.2.3 From 77a16fc34b056843b0fda4c29547b8f575c72823 Mon Sep 17 00:00:00 2001 From: Francisco Marques <kiko96kiko@gmail.com> Date: Fri, 30 Oct 2015 23:41:21 +0000 Subject: Fixed sentences that didn't make sense (at all) --- pt-br/json-pt.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index e4f10a61..d4eed0c1 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -3,6 +3,7 @@ language: json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Francisco Marques", "https://github.com/ToFran"] translators: - ["Miguel Araújo", "https://github.com/miguelarauj1o"] lang: pt-br @@ -12,10 +13,8 @@ filename: learnjson-pt.json Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o "Learn X in Y minutes" mais simples existente. -JSON na sua forma mais pura não tem comentários em reais, mas a maioria dos analisadores -aceitarão comentários no estilo C (//, /\* \*/). Para os fins do presente, no entanto, -tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. - +JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores +aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade. ```json { -- cgit v1.2.3 From 5de94e16901270de8d584b022d8e9557bba8adc1 Mon Sep 17 00:00:00 2001 From: Francisco Marques <kiko96kiko@gmail.com> Date: Fri, 30 Oct 2015 23:45:00 +0000 Subject: Added more info. As I'm already editing this, added more detail (translated from the en version). --- pt-br/json-pt.html.markdown | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index d4eed0c1..f57cd383 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -16,6 +16,14 @@ Como JSON é um formato de intercâmbio de dados, este será, muito provavelment JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade. +Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null. + +Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+. + +A extensão dos ficheiros JSON é “.json” e o tipo de mídia de Internet (MIME) é “application/json”. + +Mais informação em: http://www.json.org/ + ```json { "chave": "valor", -- cgit v1.2.3 From 3b9de3c441d583242a7229ce534a446945b8085a Mon Sep 17 00:00:00 2001 From: Francisco Marques <kiko96kiko@gmail.com> Date: Fri, 30 Oct 2015 23:47:10 +0000 Subject: Removed dot from the last line. There was a misplaced dot (".") in the last line of the example. --- pt-br/json-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index f57cd383..fd822c03 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -64,6 +64,6 @@ Mais informação em: http://www.json.org/ , "outro comentário": "que bom" }, - "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.". + "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer." } ``` -- cgit v1.2.3 From c042b7c45e14fa1737a74673c1858c41dd8b9f4f Mon Sep 17 00:00:00 2001 From: Kevin Morris <kevin@morrisreport.com> Date: Fri, 30 Oct 2015 20:15:06 -0400 Subject: [coldfusion/en] Adds information about CFScript and documentation --- coldfusion.html.markdown | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index 70804a1e..d49ad254 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -3,13 +3,17 @@ language: coldfusion filename: learncoldfusion.cfm contributors: - ["Wayne Boka", "http://wboka.github.io"] + - ["Kevin Morris", "https://twitter.com/kevinmorris"] --- ColdFusion is a scripting language for web development. [Read more here.](http://www.adobe.com/products/coldfusion-family.html) -```html +### CFML +_**C**old**F**usion **M**arkup **L**anguage_ +ColdFusion started as a tag-based language. Almost all functionality is available using tags. +```html <em>HTML tags have been provided for output readability</em> <!--- Comments start with "<!---" and end with "--->" ---> @@ -314,8 +318,13 @@ ColdFusion is a scripting language for web development. <cfoutput><p>#getWorld()#</p></cfoutput> ``` +### CFScript +_**C**old**F**usion **S**cript_ +In recent years, the ColdFusion language has added script syntax to mirror tag functionality. When using an up-to-date CF server, almost all functionality is available using scrypt syntax. + ## Further Reading The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. 1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html) +2. [Open Source Documentation](http://cfdocs.org/) -- cgit v1.2.3 From 93d3ab4578cd7c6e27f4d2b9468179528d326a22 Mon Sep 17 00:00:00 2001 From: Liam Demafelix <liamdemafelix.n@gmail.com> Date: Sat, 31 Oct 2015 08:26:09 +0800 Subject: [vb/en] Additional note for select statements --- visualbasic.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index bdfdcc10..accdbf56 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -32,6 +32,9 @@ Module Module1 Console.WriteLine("50. About") Console.WriteLine("Please Choose A Number From The Above List") Dim selection As String = Console.ReadLine + ' The "Case" in the Select statement is optional. + ' For example, "Select selection" instead of "Select Case selection" + ' will also work. Select Case selection Case "1" 'HelloWorld Output Console.Clear() 'Clears the application and opens the private sub -- cgit v1.2.3 From a72017573d893b9c0b17e7342dbe39630ba4a5d0 Mon Sep 17 00:00:00 2001 From: bureken <berkgureken@gmail.com> Date: Sat, 31 Oct 2015 03:33:13 +0300 Subject: Typo fix --- edn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/edn.html.markdown b/edn.html.markdown index 655c20f1..0a0dc9b5 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -16,7 +16,7 @@ will see how it is extended later on. ```Clojure ; Comments start with a semicolon. -; Anythng after the semicolon is ignored. +; Anything after the semicolon is ignored. ;;;;;;;;;;;;;;;;;;; ;;; Basic Types ;;; -- cgit v1.2.3 From b2b274df08f65a62f5f4c65701b043a69bd77964 Mon Sep 17 00:00:00 2001 From: bureken <berkgureken@gmail.com> Date: Sat, 31 Oct 2015 04:00:03 +0300 Subject: Turkish typo fix --- tr-tr/brainfuck-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown index baca4217..bd842b17 100644 --- a/tr-tr/brainfuck-tr.html.markdown +++ b/tr-tr/brainfuck-tr.html.markdown @@ -19,7 +19,7 @@ gözardı edilir. Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir dizidir. İşaretçi ilk hücreyi işaret eder. -Sekik komut vardır: +Sekiz komut vardır: + : Geçerli hücrenin değerini bir artırır. - : Geçerli hücrenin değerini bir azaltır. > : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). -- cgit v1.2.3 From d30215bfaf2420bd974eabbd561699ea664df259 Mon Sep 17 00:00:00 2001 From: Gordon Senesac Jr <gsenesac@gmail.com> Date: Fri, 30 Oct 2015 20:21:30 -0500 Subject: Added a couple functions to the matlab doc. --- matlab.html.markdown | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index ad42d9a9..9d78978e 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -123,6 +123,7 @@ x(2:end) % ans = 32 53 7 1 x = [4; 32; 53; 7; 1] % Column vector x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 +x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9 % Matrices A = [1 2 3; 4 5 6; 7 8 9] @@ -205,6 +206,8 @@ transpose(A) % Transpose the matrix, which is the same as: A one ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) +A' % Concise version of complex transpose +A.' % Concise version of transpose (without taking complex conjugate) @@ -254,6 +257,8 @@ axis equal % Set aspect ratio so data units are the same in every direction scatter(x, y); % Scatter-plot hist(x); % Histogram +stem(x); % Plot values as stems, useful for displaying discrete data +bar(x); % Plot bar graph z = sin(x); plot3(x,y,z); % 3D line plot @@ -400,7 +405,7 @@ exp(x) sqrt(x) log(x) log10(x) -abs(x) +abs(x) %If x is complex, returns magnitude min(x) max(x) ceil(x) @@ -411,6 +416,14 @@ rand % Uniformly distributed pseudorandom numbers randi % Uniformly distributed pseudorandom integers randn % Normally distributed pseudorandom numbers +%Complex math operations +abs(x) % Magnitude of complex variable x +phase(x) % Phase (or angle) of complex variable x +real(x) % Returns the real part of x (i.e returns a if x = a +jb) +imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb) +conj(x) % Returns the complex conjugate + + % Common constants pi NaN @@ -465,6 +478,9 @@ median % median value mean % mean value std % standard deviation perms(x) % list all permutations of elements of x +find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators, + % i.e. find( x == 3 ) returns indexes of elements that are equal to 3 + % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3 % Classes -- cgit v1.2.3 From 4508ee45d8924ee7b17ec1fa856f4e273c1ca5c1 Mon Sep 17 00:00:00 2001 From: Ben Pious <benpious@gmail.com> Date: Fri, 30 Oct 2015 21:40:19 -0700 Subject: Adds description of how to define generic classes in Xcode 7.0 --- objective-c.html.markdown | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index f130ea0c..05bb5c6a 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -599,6 +599,52 @@ int main (int argc, const char * argv[]) { @end +// Starting in Xcode 7.0, you can create Generic classes, +// allowing you to provide greater type safety and clarity +// without writing excessive boilerplate. +@interface Result<__covariant A> : NSObject + +- (void)handleSuccess:(void(^)(A))success + failure:(void(^)(NSError *))failure; + +@property (nonatomic) A object; + +@end + +// we can now declare instances of this class like +Result<NSNumber *> *result; +Result<NSArray *> *result; + +// Each of these cases would be equivalent to rewriting Result's interface +// and substituting the appropriate type for A +@interface Result : NSObject +- (void)handleSuccess:(void(^)(NSArray *))success + failure:(void(^)(NSError *))failure; +@property (nonatomic) NSArray * object; +@end + +@interface Result : NSObject +- (void)handleSuccess:(void(^)(NSNumber *))success + failure:(void(^)(NSError *))failure; +@property (nonatomic) NSNumber * object; +@end + +// It should be obvious, however, that writing one +// Class to solve a problem is always preferable to writing two + +// Note that Clang will not accept generic types in @implementations, +// so your @implemnation of Result would have to look like this: + +@implementation Result + +- (void)handleSuccess:(void (^)(id))success + failure:(void (^)(NSError *))failure { + // Do something +} + +@end + + /////////////////////////////////////// // Protocols /////////////////////////////////////// -- cgit v1.2.3 From 59e85e2f37373145bcde8025da2bde93eb49ec28 Mon Sep 17 00:00:00 2001 From: Willie Zhu <zhuwillie11@gmail.com> Date: Sat, 31 Oct 2015 00:40:37 -0400 Subject: Make whitespace more consistent --- fsharp.html.markdown | 74 ++++++++++++++++++++++++++-------------------------- 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index b5c47ed7..d63b9f1d 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -31,14 +31,14 @@ If you want to try out the code below, you can go to [tryfsharp.org](http://www. // The "let" keyword defines an (immutable) value let myInt = 5 let myFloat = 3.14 -let myString = "hello" //note that no types needed +let myString = "hello" // note that no types needed // ------ Lists ------ -let twoToFive = [2;3;4;5] // Square brackets create a list with +let twoToFive = [2; 3; 4; 5] // Square brackets create a list with // semicolon delimiters. let oneToFive = 1 :: twoToFive // :: creates list with new 1st element -// The result is [1;2;3;4;5] -let zeroToFive = [0;1] @ twoToFive // @ concats two lists +// The result is [1; 2; 3; 4; 5] +let zeroToFive = [0; 1] @ twoToFive // @ concats two lists // IMPORTANT: commas are never used as delimiters, only semicolons! @@ -53,7 +53,7 @@ add 2 3 // Now run the function. // to define a multiline function, just use indents. No semicolons needed. let evens list = - let isEven x = x%2 = 0 // Define "isEven" as a sub function + let isEven x = x % 2 = 0 // Define "isEven" as a sub function List.filter isEven list // List.filter is a library function // with two parameters: a boolean function // and a list to work on @@ -75,7 +75,7 @@ let sumOfSquaresTo100piped = // you can define lambdas (anonymous functions) using the "fun" keyword let sumOfSquaresTo100withFun = - [1..100] |> List.map (fun x -> x*x) |> List.sum + [1..100] |> List.map (fun x -> x * x) |> List.sum // In F# there is no "return" keyword. A function always // returns the value of the last expression used. @@ -109,7 +109,7 @@ optionPatternMatch invalidValue // The printf/printfn functions are similar to the // Console.Write/WriteLine functions in C#. printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true -printfn "A string %s, and something generic %A" "hello" [1;2;3;4] +printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4] // There are also sprintf/sprintfn functions for formatting data // into a string, similar to String.Format in C#. @@ -131,19 +131,19 @@ module FunctionExamples = // basic usage of a function let a = add 1 2 - printfn "1+2 = %i" a + printfn "1 + 2 = %i" a // partial application to "bake in" parameters let add42 = add 42 let b = add42 1 - printfn "42+1 = %i" b + printfn "42 + 1 = %i" b // composition to combine functions let add1 = add 1 let add2 = add 2 let add3 = add1 >> add2 let c = add3 7 - printfn "3+7 = %i" c + printfn "3 + 7 = %i" c // higher order functions [1..10] |> List.map add3 |> printfn "new list is %A" @@ -151,7 +151,7 @@ module FunctionExamples = // lists of functions, and more let add6 = [add1; add2; add3] |> List.reduce (>>) let d = add6 7 - printfn "1+2+3+7 = %i" d + printfn "1 + 2 + 3 + 7 = %i" d // ================================================ // Lists and collection @@ -168,12 +168,12 @@ module FunctionExamples = module ListExamples = // lists use square brackets - let list1 = ["a";"b"] + let list1 = ["a"; "b"] let list2 = "c" :: list1 // :: is prepending let list3 = list1 @ list2 // @ is concat // list comprehensions (aka generators) - let squares = [for i in 1..10 do yield i*i] + let squares = [for i in 1..10 do yield i * i] // prime number generator let rec sieve = function @@ -190,8 +190,8 @@ module ListExamples = | [first; second] -> printfn "list is %A and %A" first second | _ -> printfn "the list has more than two elements" - listMatcher [1;2;3;4] - listMatcher [1;2] + listMatcher [1; 2; 3; 4] + listMatcher [1; 2] listMatcher [1] listMatcher [] @@ -219,7 +219,7 @@ module ListExamples = module ArrayExamples = // arrays use square brackets with bar - let array1 = [| "a";"b" |] + let array1 = [| "a"; "b" |] let first = array1.[0] // indexed access using dot // pattern matching for arrays is same as for lists @@ -230,13 +230,13 @@ module ArrayExamples = | [| first; second |] -> printfn "array is %A and %A" first second | _ -> printfn "the array has more than two elements" - arrayMatcher [| 1;2;3;4 |] + arrayMatcher [| 1; 2; 3; 4 |] // Standard library functions just as for List [| 1..10 |] - |> Array.map (fun i -> i+3) - |> Array.filter (fun i -> i%2 = 0) + |> Array.map (fun i -> i + 3) + |> Array.filter (fun i -> i % 2 = 0) |> Array.iter (printfn "value is %i. ") @@ -255,7 +255,7 @@ module SequenceExamples = yield! [5..10] yield! seq { for i in 1..10 do - if i%2 = 0 then yield i }} + if i % 2 = 0 then yield i }} // test strange |> Seq.toList @@ -280,11 +280,11 @@ module DataTypeExamples = // Tuples are quick 'n easy anonymous types // -- Use a comma to create a tuple - let twoTuple = 1,2 - let threeTuple = "a",2,true + let twoTuple = 1, 2 + let threeTuple = "a", 2, true // Pattern match to unpack - let x,y = twoTuple //sets x=1 y=2 + let x, y = twoTuple // sets x = 1, y = 2 // ------------------------------------ // Record types have named fields @@ -297,7 +297,7 @@ module DataTypeExamples = let person1 = {First="John"; Last="Doe"} // Pattern match to unpack - let {First=first} = person1 //sets first="John" + let {First = first} = person1 // sets first="John" // ------------------------------------ // Union types (aka variants) have a set of choices @@ -331,7 +331,7 @@ module DataTypeExamples = | Worker of Person | Manager of Employee list - let jdoe = {First="John";Last="Doe"} + let jdoe = {First="John"; Last="Doe"} let worker = Worker jdoe // ------------------------------------ @@ -383,8 +383,8 @@ module DataTypeExamples = type Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace - let hand = [ Club,Ace; Heart,Three; Heart,Ace; - Spade,Jack; Diamond,Two; Diamond,Ace ] + let hand = [ Club, Ace; Heart, Three; Heart, Ace; + Spade, Jack; Diamond, Two; Diamond, Ace ] // sorting List.sort hand |> printfn "sorted hand is (low to high) %A" @@ -419,7 +419,7 @@ module ActivePatternExamples = | _ -> printfn "%c is something else" ch // print a list - ['a';'b';'1';' ';'-';'c'] |> List.iter printChar + ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar // ----------------------------------- // FizzBuzz using active patterns @@ -479,7 +479,7 @@ module AlgorithmExamples = List.concat [smallerElements; [firstElem]; largerElements] // test - sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A" + sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A" // ================================================ // Asynchronous Code @@ -536,7 +536,7 @@ module NetCompatibilityExamples = // ------- work with existing library functions ------- - let (i1success,i1) = System.Int32.TryParse("123"); + let (i1success, i1) = System.Int32.TryParse("123"); if i1success then printfn "parsed as %i" i1 else printfn "parse failed" // ------- Implement interfaces on the fly! ------- @@ -570,12 +570,12 @@ module NetCompatibilityExamples = // abstract base class with virtual methods [<AbstractClass>] type Shape() = - //readonly properties + // readonly properties abstract member Width : int with get abstract member Height : int with get - //non-virtual method + // non-virtual method member this.BoundingArea = this.Height * this.Width - //virtual method with base implementation + // virtual method with base implementation abstract member Print : unit -> unit default this.Print () = printfn "I'm a shape" @@ -586,19 +586,19 @@ module NetCompatibilityExamples = override this.Height = y override this.Print () = printfn "I'm a Rectangle" - //test - let r = Rectangle(2,3) + // test + let r = Rectangle(2, 3) printfn "The width is %i" r.Width printfn "The area is %i" r.BoundingArea r.Print() // ------- extension methods ------- - //Just as in C#, F# can extend existing classes with extension methods. + // Just as in C#, F# can extend existing classes with extension methods. type System.String with member this.StartsWithA = this.StartsWith "A" - //test + // test let s = "Alice" printfn "'%s' starts with an 'A' = %A" s s.StartsWithA -- cgit v1.2.3 From 34c7c6acb22c934f879a353f3ba92b38b602f7fc Mon Sep 17 00:00:00 2001 From: Andy <andrewgallasch@gmail.com> Date: Sat, 31 Oct 2015 16:57:22 +1030 Subject: Fixed typo at BigInteger assignment --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 1813f81c..901e2dad 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -128,7 +128,7 @@ public class LearnJava { // // BigInteger can be initialized using an array of bytes or a string. - BigInteger fooBigInteger = new BigDecimal(fooByteArray); + BigInteger fooBigInteger = new BigInteger(fooByteArray); // BigDecimal - Immutable, arbitrary-precision signed decimal number -- cgit v1.2.3 From 5bda926dcc79dea4e936cc752fd1ff00e29d71bb Mon Sep 17 00:00:00 2001 From: Elijah Karari <eljhkrr@gmail.com> Date: Sat, 31 Oct 2015 09:47:55 +0300 Subject: Minor correction calling li.index(2) with li as [1, 2, 3, 4, 5, 6] will return 1 not 3 --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 541bd36d..80cef828 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -238,7 +238,7 @@ li.remove(2) # Raises a ValueError as 2 is not in the list li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again # Get the index of the first item found -li.index(2) # => 3 +li.index(2) # => 1 li.index(7) # Raises a ValueError as 7 is not in the list # Check for existence in a list with "in" -- cgit v1.2.3 From ab1acb1bb265577ea4f189d203ac35726f02970a Mon Sep 17 00:00:00 2001 From: Elijah Karari <eljhkrr@gmail.com> Date: Sat, 31 Oct 2015 09:56:06 +0300 Subject: Updated tuple examples for clarity --- python.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 541bd36d..b0add668 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -261,8 +261,9 @@ tup[:2] # => (1, 2) # You can unpack tuples (or lists) into variables a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +d, e, f = 4, 5, 6 # you can leave out the parentheses # Tuples are created by default if you leave out the parentheses -d, e, f = 4, 5, 6 +g = 4, 5, 6 # => (4, 5, 6) # Now look how easy it is to swap two values e, d = d, e # d is now 5 and e is now 4 -- cgit v1.2.3 From f7af2da9dbb504377c2ff7c2f29a55b9f363a4c1 Mon Sep 17 00:00:00 2001 From: Andy <andrewgallasch@gmail.com> Date: Sat, 31 Oct 2015 18:31:51 +1030 Subject: Added BigDecimal float constructor caveat --- java.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 1813f81c..d7d0199b 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -144,7 +144,12 @@ public class LearnJava { // or by initializing the unscaled value (BigInteger) and scale (int). BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); - + + // Be wary of the constructor that takes a float or double as + // the inaccuracy of the float/double will be copied in BigDecimal. + // Prefer the String constructor when you need an exact value. + + BigDecimal tenCents = new BigDecimal("0.1"); // Strings -- cgit v1.2.3 From a38705757b95eb500d51e0dd0c5294b7aa76cada Mon Sep 17 00:00:00 2001 From: Abdul Alim <alim@iflix.com> Date: Sat, 31 Oct 2015 16:36:30 +0800 Subject: Added Bahasa Malaysia translation of the JavaScript file --- ms-my/javascript-my.html.markdown | 588 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 588 insertions(+) create mode 100644 ms-my/javascript-my.html.markdown diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown new file mode 100644 index 00000000..90e37133 --- /dev/null +++ b/ms-my/javascript-my.html.markdown @@ -0,0 +1,588 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ms.js +translators: + - ["abdalim", "https://github.com/abdalim"] +lang: ms-my +--- + +Javascript dicipta oleh Brendan Eich dari Netscape pada 1995. Pada awalnya, ia +dicipta sebagai bahasa skrip yang ringkas untuk laman web, melengkapi penggunaan +Java untuk aplikasi web yang lebih rumit, namun begitu, integrasi rapat pada +halaman web dan sokongan tersedia dalam pelayar web telah menyebabkan ia menjadi +lebih kerap digunakan berbanding Java pada bahagian hadapan laman web. + +Namun begitu, Javascript tidak terhad pada pelayar web; Node.js, sebuah projek +yang menyediakan 'runtime' berdiri sendiri untuk enjin V8 Google Chrome sedang +kian mendapat sambutan yang hangat. + +```js +// Komentar adalah seperti dalam C. Komentar sebaris bermula dengan dua sengkang +/* dan komentar banyak baris bermula dengan sengkang-bintang + dan berakhir dengan bintang-sengkang */ + +// Pernyataan boleh ditamatkan dengan ';' +doStuff(); + +// ... tetapi ia tidak wajib, kerana koma bertitik secara automatik akan +// dimasukkan dimana tempat yang ada baris baru, kecuali dalam kes - kes +// tertentu. +doStuff() + +// Disebabkan kes - kes itu boleh menyebabkan hasil yang tidak diduga, kami +// akan sentiasa menggunakan koma bertitik dalam panduan ini. + +/////////////////////////////////// +// 1. Nombor, String dan Operator + +// Javascript mempunyai satu jenis nombor (iaitu 64-bit IEEE 754 double). +// Double mempunyai 52-bit mantissa, iaitu ia cukup untuk menyimpan integer +// sehingga 9✕10¹⁵ secara tepatnya. +3; // = 3 +1.5; // = 1.5 + +// Sebahagian aritmetic asas berfungsi seperti yang anda jangkakan. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Termasuk pembahagian tidak rata. +5 / 2; // = 2.5 + +// Dan pembahagian modulo. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + +// Operasi bitwise juga boleh digunakan; bila anda melakukan operasi bitwise, +// float anda akan ditukarkan kepada int bertanda *sehingga* 32 bit. +1 << 2; // = 4 + +// Keutamaan ditekankan menggunakan kurungan. +(1 + 3) * 2; // = 8 + +// Terdapat tiga nilai nombor-tidak-nyata istimewa +Infinity; // hasil operasi seperti 1/0 +-Infinity; // hasil operasi seperti -1/0 +NaN; // hasil operasi seperti 0/0, bermaksud 'Bukan Sebuah Nombor' + +// Terdapat juga jenis boolean +true; +false; + +// Talian dicipta dengan ' atau ''. +'abc'; +"Hello, world"; + +// Penafian menggunakan simbol ! +!true; // = tidak benar +!false; // = benar + +// Sama ialah === +1 === 1; // = benar +2 === 1; // = tidak benar + +// Tidak sama ialah !== +1 !== 1; // = tidak benar +2 !== 1; // = benar + +// Lagi perbandingan +1 < 10; // = benar +1 > 10; // = tidak benar +2 <= 2; // = benar +2 >= 2; // = benar + +// Talian disambungkan dengan + +"Hello " + "world!"; // = "Hello world!" + +// dan dibandingkan dengan < dan > +"a" < "b"; // = benar + +// Paksaan jenis dilakukan untuk perbandingan menggunakan dua sama dengan... +"5" == 5; // = benar +null == undefined; // = benar + +// ...melainkan anda menggunakan === +"5" === 5; // = tidak benar +null === undefined; // = tidak benar + +// ...yang boleh menghasilkan keputusan yang pelik... +13 + !0; // 14 +"13" + !0; // '13true' + +// Anda boleh akses huruf dalam perkataan dengan `charAt` +"This is a string".charAt(0); // = 'T' + +// ...atau menggunakan `substring` untuk mendapatkan bahagian yang lebih besar. +"Hello world".substring(0, 5); // = "Hello" + +// `length` adalah ciri, maka jangan gunakan (). +"Hello".length; // = 5 + +// Selain itu, terdapat juga `null` dan `undefined`. +null; // digunakan untuk menandakan bukan-nilai yang disengajakan +undefined; // digunakan untuk menandakan nilai yang tidak wujud pada waktu ini (walaupun `undefined` adalah nilai juga) + +// false, null, undefined, NaN, 0 dan "" adalah tidak benar; semua selain itu adalah benar. +// Peringatan, 0 adalah tidak benar dan "0" adalah benar, walaupun 0 == "0". + +/////////////////////////////////// +// 2. Pembolehubah, Array dan Objek + +// Pembolehubah digunakan dengan kata kunci 'var'. Javascript ialah sebuah +// bahasa aturcara yang jenisnya dinamik, maka anda tidak perlu spesifikasikan +// jenis pembolehubah. Penetapan menggunakan satu '=' karakter. +var someVar = 5; + +// jika anda tinggalkan kata kunci var, anda tidak akan dapat ralat... +someOtherVar = 10; + +// ...tetapi pembolehubah anda akan dicipta di dalam skop global, bukan di +// dalam skop anda menciptanya. + +// Pembolehubah yang dideklarasikan tanpa ditetapkan sebarang nilai akan +// ditetapkan kepada undefined. +var someThirdVar; // = undefined + +// jika anda ingin mendeklarasikan beberapa pembolehubah, maka anda boleh +// menggunakan koma sebagai pembahagi +var someFourthVar = 2, someFifthVar = 4; + +// Terdapat cara mudah untuk melakukan operasi - operasi matematik pada +// pembolehubah: +someVar += 5; // bersamaan dengan someVar = someVar +5; someVar sama dengan 10 sekarang +someVar *= 10; // sekarang someVar bernilai 100 + +// dan cara lebih mudah untuk penambahan atau penolakan 1 +someVar++; // sekarang someVar ialah 101 +someVar--; // kembali kepada 100 + +// Array adalah senarai nilai yang tersusun, yang boleh terdiri daripada +// pembolehubah pelbagai jenis. +var myArray = ["Hello", 45, true]; + +// Setiap ahli array boleh diakses menggunakan syntax kurungan-petak. +// Indeks array bermula pada sifar. +myArray[1]; // = 45 + +// Array boleh diubah dan mempunyai panjang yang tidak tetap dan boleh ubah. +myArray.push("World"); +myArray.length; // = 4 + +// Tambah/Ubah di index yang spesifik +myArray[3] = "Hello"; + +// Objek javascript adalah sama dengan "dictionaries" atau "maps" dalam bahasa +// aturcara yang lain: koleksi pasangan kunci-nilai yang tidak mempunyai +// sebarang susunan. +var myObj = {key1: "Hello", key2: "World"}; + +// Kunci adalah string, tetapi 'quote' tidak diperlukan jika ia adalah pengecam +// javascript yang sah. Nilai boleh mempunyai sebarang jenis. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Ciri - ciri objek boleh juga diakses menggunakan syntax subskrip (kurungan- +// petak), +myObj["my other key"]; // = 4 + +// ... atau menggunakan syntax titik, selagi kuncinya adalah pengecam yang sah. +myObj.myKey; // = "myValue" + +// Objek adalah boleh diubah; nilai boleh diubah dan kunci baru boleh ditambah. +myObj.myThirdKey = true; + +// Jika anda cuba untuk akses nilai yang belum ditetapkan, anda akan mendapat +// undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logik dan Struktur Kawalan + +// Syntax untuk bahagian ini adalah hampir sama dengan Java. + +// Struktur `if` berfungsi seperti yang anda jangkakan. +var count = 1; +if (count == 3){ + // dinilai jika count ialah 3 +} else if (count == 4){ + // dinilai jika count ialah 4 +} else { + // dinilai jika count bukan 3 atau 4 +} + +// Sama juga dengan `while`. +while (true){ + // Sebuah ulangan yang tidak terhingga! + // An infinite loop! +} + +// Ulangan do-while adalah sama dengan ulangan while, kecuali ia akan diulang +// sekurang-kurangnya sekali. +var input; +do { + input = getInput(); +} while (!isValid(input)) + +// Ulangan `for` adalah sama dengan C dan Java: +// Persiapan; kondisi untuk bersambung; pengulangan. +for (var i = 0; i < 5; i++){ + // akan berulang selama 5 kali +} + +// Pernyataan ulangan For/In akan mengulang setiap ciri seluruh jaringan +// 'prototype' +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} + +// Jika anda cuma mahu mengambil kira ciri - ciri yang ditambah pada objek it +// sendiri dan bukan 'prototype'nya, sila gunakan semakan hasOwnProperty() +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + if (person.hasOwnProperty(x)){ + description += person[x] + " "; + } +} + +// for/in tidak sepatutnya digunakan untuk mengulang sebuah Array di mana +// indeks susunan adalah penting. +// Tiada sebarang jaminan bahawa for/in akan mengembalikan indeks dalam +// mana - mana susunan + +// && adalah logikal dan, || adalah logikal atau +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // warna adalah sama ada 'red' atau 'blue' +} + +// && dan || adalah "lintar pintas", di mana ia berguna untuk menetapkan +// nilai asal. +var name = otherName || "default"; + + +// Pernyataan `switch` menyemak persamaan menggunakan `===`. +// gunakan pernyataan `break` selepas setiap kes +// atau tidak, kes - kes selepas kes yang betul akan dijalankan juga. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Skop dan Closures + +// Function javascript dideklarasikan dengan kata kunci `function`. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Perhatikan yang nilai yang dikembalikan mesti bermula pada baris yang sama +// dengan kata kunci `return`, jika tidak, anda akan sentiasa mengembalikan +// `undefined` disebabkan kemasukan 'semicolon' secara automatik. Sila berjaga - +// jaga dengan hal ini apabila menggunakan Allman style. +function myFunction(){ + return // <- semicolon dimasukkan secara automatik di sini + {thisIsAn: 'object literal'} +} +myFunction(); // = undefined + +// Function javascript adalah objek kelas pertama, maka ia boleh diberikan +// nama pembolehubah yang lain dan diberikan kepada function yang lain sebagai +// input - sebagai contoh, apabila membekalkan pengendali event: +function myFunction(){ + // kod ini akan dijalankan selepas 5 saat +} +setTimeout(myFunction, 5000); +// Nota: setTimeout bukan sebahagian daripada bahasa JS, tetapi ia disediakan +// oleh pelayar web dan Node.js. + +// Satu lagi function yang disediakan oleh pelayar web adalah setInterval +function myFunction(){ + // kod ini akan dijalankan setiap 5 saat +} +setInterval(myFunction, 5000); + +// Objek function tidak perlu dideklarasikan dengan nama - anda boleh menulis +// function yang tidak bernama didalam input sebuah function lain. +setTimeout(function(){ + // kod ini akan dijalankan dalam 5 saat +}, 5000); + +// Javascript mempunyai skop function; function mempunyai skop mereka +// tersendiri tetapi blok tidak. +if (true){ + var i = 5; +} +i; // = 5 - bukan undefined seperti yang anda jangkakan di dalam bahasa blok-skop + +// Ini telah menyebabkan corak biasa iaitu "immediately-executing anonymous +// functions", yang mengelakkan pembolehubah sementara daripada bocor ke +// skop global. +(function(){ + var temporary = 5; + // Kita boleh akses skop global dengan menetapkan nilai ke "objek global", + // iaitu dalam pelayar web selalunya adalah `window`. Objek global mungkin + // mempunyai nama yang berlainan dalam alam bukan pelayar web seperti Node.js. + window.permanent = 10; +})(); +temporary; // akan menghasilkan ralat ReferenceError +permanent; // = 10 + +// Salah satu ciri terhebat Javascript ialah closure. Jika sebuah function +// didefinisikan di dalam sebuah function lain, function yang di dalam akan +// mempunyai akses kepada semua pembolehubah function yang di luar, mahupun +// selepas function yang di luar tersebut selesai. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Function dalam diletakkan di dalam skop lokal secara asal, seperti + // ia dideklarasikan dengan `var`. + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout adalah tak segerak atau asinkroni, maka function sayHelloInFiveSeconds akan selesai serta merta, dan setTimeout akan memanggil + // inner selepas itu. Walaubagaimanapun, disebabkan inner terletak didalam + // sayHelloInFiveSeconds, inner tetap mempunyai akses kepada pembolehubah + // `prompt` apabila ia dipanggil. +} +sayHelloInFiveSeconds("Adam"); // akan membuka sebuah popup dengan "Hello, Adam!" selepas 5s + +/////////////////////////////////// +// 5. Lagi tentang Objek, Constructor dan Prototype + +// Objek boleh mengandungi function. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Apabila function sesebuah object dipanggil, ia boleh mengakses objek asalnya +// dengan menggunakan kata kunci `this`. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Nilai sebenar yang ditetapkan kepada this akan ditentukan oleh bagaimana +// sesebuah function itu dipanggil, bukan dimana ia didefinisikan. Oleh it, +// sesebuah function tidak akan berfungsi jika ia dipanggil bukan pada konteks +// objeknya. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Sebaliknya, sebuah function boleh ditetapkan kepada objek dan mendapat akses +// kepada objek itu melalui `this`, walaupun ia tidak ditetapkan semasa ia +// didefinisikan. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// Kita juga boleh menentukan konteks untuk sebuah function dijalankan apabila +// ia dipanggil menggunakan `call` atau `apply`. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// Function `apply` adalah hampir sama, tetapi ia mengambil sebuah array +// sebagai senarai input. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// Ini sangat berguna apabila menggunakan sebuah function yang menerima senarai +// input dan anda mahu menggunakan sebuah array sebagai input. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Tetapi, `call` dan `apply` adalah hanya sementara, sebagaimana hidup ini. +// Apabila kita mahu ia kekal, kita boleh menggunakan `bind`. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// `bind` boleh juga digunakan untuk menggunakan sebuah function tidak +// sepenuhnya (curry). + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Apabila anda memanggil sebuah function dengan kata kunci `new`, sebuah +// objek baru akan dicipta dan dijadikan tersedia kepada function itu melalui +// kata kunci `this`. Function yang direka bentuk untuk dipanggil sebegitu rupa +// dikenali sebagai constructors. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Setiap objek JavaScript mempunyai `prototype`. Apabila anda akses sesuatu +// ciri sebuah objek yang tidak wujud dalam objek sebenar itu, interpreter akan +// mencari ciri itu didalam `prototype`nya. + +// Sebahagian implementasi JS membenarkan anda untuk akses prototype sebuah +// objek pada ciri istimewa `__proto__`. Walaupun ini membantu dalam menerangkan +// mengenai prototypes, ia bukan sebahagian dari piawai; kita akan melihat +// cara - cara piawai untuk menggunakan prototypes nanti. +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Ini berfungsi untuk function juga. +myObj.myFunc(); // = "hello world!" + +// Sudah pasti, jika ciri anda bukan pada prototype anda, prototype kepada +// prototype anda akan disemak, dan seterusnya. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Tiada penyalinan terlibat disini; setiap objek menyimpan rujukan kepada +// prototypenya sendiri. Ini bermaksud, kita boleh mengubah prototypenya dan +// pengubahsuaian itu akan dilihat dan berkesan dimana sahaja. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Kami menyatakan yang `__proto__` adalah bukan piawai, dan tiada cara rasmi +// untuk mengubah prototype sesebuah objek. Walaubagaimanapun, terdapat dua +// cara untuk mencipta objek baru dengan sesebuah prototype. + +// Yang pertama ialah Object.create, yang merupakan tambahan terbaru pada JS, +// dan oleh itu tiada dalam semua implementasi buat masa ini. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Cara kedua, yang boleh digunakan dimana sahaja, adalah berkaitan dengan +// constructor. Constructors mempunyai sebuah ciri yang dipanggil prototype. +// Ini *bukan* prototype constructor terbabit; tetapi, ia adalah prototype yang +// diberikan kepada objek baru apabila ia dicipta menggunakan constructor dan +// kata kunci new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Jenis yang terbina sedia seperti string dan nombor juga mempunyai constructor +// yang mencipta objek pembalut yang serupa. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Kecuali, mereka sebenarnya tak sama sepenuhnya. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // Kod ini tidak akan dilaksanakan, kerana 0 adalah tidak benar. +} + +// Walaubagaimanapun, pembalut objek dan jenis terbina yang biasa berkongsi +// prototype, maka sebagai contoh, anda sebenarnya boleh menambah fungsi +// kepada string. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Fakta ini selalu digunakan dalam "polyfilling", iaitu melaksanakan fungsi +// baru JavaScript didalam subset JavaScript yang lama, supaya ia boleh +// digunakan di dalam persekitaran yang lama seperti pelayar web yang lama. + +// Sebagai contoh, kami menyatakan yang Object.create belum lagi tersedia +// di semua implementasi, tetapi kita masih boleh menggunakannya dengan polyfill: +if (Object.create === undefined){ // jangan ganti jika ia sudah wujud + Object.create = function(proto){ + // buat satu constructor sementara dengan prototype yang betul + var Constructor = function(){}; + Constructor.prototype = proto; + // kemudian gunakannya untuk mencipta objek baru yang diberikan + // prototype yang betul + return new Constructor(); + } +} +``` +## Bacaan Lanjut + +[Mozilla Developer Network][1] menyediakan dokumentasi yang sangat baik untuk +JavaScript kerana ia digunakan di dalam pelayar - pelayar web. Tambahan pula, +ia adalah sebuah wiki, maka, sambil anda belajar lebih banyak lagi, anda boleh +membantu orang lain dengan berkongsi pengetahuan anda. + +[A re-introduction to JavaScript][2] oleh MDN meliputi semua konsep yang +diterangkan di sini dengan lebih terperinci. Panduan ini menerangkan bahasa +aturcara JavaScript dengan agak mudah; jika anda mahu belajar lebih lanjut +tentang menggunakan JavaScript didalam laman web, mulakan dengan mempelajari +tentang [Document Object Model][3]. + +[Learn Javascript by Example and with Challenges][4] adalah variasi panduan ini +dengan cabaran yang tersedia pakai. + +[JavaScript Garden][5] pula adalah panduan yang lebih terperinci mengenai +semua bahagian bahasa aturcara ini yang bertentangan dengan naluri atau +kebiasaan. + +[JavaScript: The Definitive Guide][6] adalah panduan klasik dan buku rujukan. + +Selain daripada penyumbang terus kepada artikel ini, sebahagian kandungannya +adalah adaptasi daripada tutorial Python Louie Dinh di dalam laman web ini, +dan [JS Tutorial][7] di Mozilla Developer Network. + + +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript -- cgit v1.2.3 From 4593c65543eec73688acf999c4bab002116909b0 Mon Sep 17 00:00:00 2001 From: Andy <andrewgallasch@gmail.com> Date: Sat, 31 Oct 2015 19:39:26 +1030 Subject: Improved int division comment and code --- java.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 1813f81c..966aee15 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -207,8 +207,8 @@ public class LearnJava { System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) - System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 // Modulo System.out.println("11%3 = "+(11 % 3)); // => 2 -- cgit v1.2.3 From 231b60b7c0c21e2f76a3dfc0939abe1b7efbfad3 Mon Sep 17 00:00:00 2001 From: Andy <andrewgallasch@gmail.com> Date: Sat, 31 Oct 2015 20:05:05 +1030 Subject: Added missing new in HashSet instantiation --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 966aee15..2836f601 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -416,7 +416,7 @@ public class LearnJava { // easier way, by using something that is called Double Brace // Initialization. - private static final Set<String> COUNTRIES = HashSet<String>() {{ + private static final Set<String> COUNTRIES = new HashSet<String>() {{ add("DENMARK"); add("SWEDEN"); add("FINLAND"); -- cgit v1.2.3 From b5cb14703ac99e70ecd6c1ec2abd9a2b5dbde54d Mon Sep 17 00:00:00 2001 From: Niko Weh <niko.weh@gmail.com> Date: Sat, 31 Oct 2015 19:44:04 +1000 Subject: Haskell: Fix !! operator - Use a finite list, as infinite lists are not introduced yet - Use a list starting from 1 instead of 0, to make it obvious that the element returned comes from the list (and is not the second argument to !!). --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 08611e63..936744a0 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -81,7 +81,7 @@ not False -- True [5,4..1] -- [5, 4, 3, 2, 1] -- indexing into a list -[0..] !! 5 -- 5 +[1..10] !! 3 -- 4 -- You can also have infinite lists in Haskell! [1..] -- a list of all the natural numbers -- cgit v1.2.3 From deb62f41467fc94513b9adbef3a2cbb1e03cb220 Mon Sep 17 00:00:00 2001 From: Niko Weh <niko.weh@gmail.com> Date: Sat, 31 Oct 2015 20:20:01 +1000 Subject: [haskell/de] Synchronized with english version Added changes from a7b8858 to HEAD (b5cb14703) to the german version, where appropiate. --- de-de/haskell-de.html.markdown | 63 +++++++++++++++++++++++++++--------------- 1 file changed, 40 insertions(+), 23 deletions(-) diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index 2c548961..41b80d95 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Henrik Jürges", "https://github.com/santifa"] + - ["Nikolai Weh", "http://weh.hamburg"] filename: haskell-de.hs --- @@ -64,6 +65,7 @@ not False -- True "Hello " ++ "world!" -- "Hello world!" -- Ein String ist eine Liste von Zeichen. +['H', 'a', 'l', 'l', 'o', '!'] -- "Hallo!" "Das ist eine String" !! 0 -- 'D' @@ -76,6 +78,18 @@ not False -- True [1, 2, 3, 4, 5] [1..5] +-- Die zweite Variante nennt sich die "range"-Syntax. +-- Ranges sind recht flexibel: +['A'..'F'] -- "ABCDEF" + +-- Es ist möglich eine Schrittweite anzugeben: +[0,2..10] -- [0,2,4,6,8,10] +[5..1] -- [], da Haskell standardmässig inkrementiert. +[5,4..1] -- [5,4,3,2,1] + +-- Der "!!"-Operator extrahiert das Element an einem bestimmten Index: +[1..10] !! 3 -- 4 + -- Haskell unterstuetzt unendliche Listen! [1..] -- Die Liste aller natuerlichen Zahlen @@ -95,9 +109,6 @@ not False -- True -- Ein Element als Head hinzufuegen 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- Gibt den 5. Index zurueck -[0..] !! 5 -- 5 - -- Weitere Listenoperationen head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] @@ -114,7 +125,8 @@ last [1..5] -- 5 -- Ein Tupel: ("haskell", 1) --- Auf Elemente eines Tupels zugreifen: +-- Ein Paar (Pair) ist ein Tupel mit 2 Elementen, auf die man wie folgt +-- zugreifen kann: fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 @@ -142,7 +154,7 @@ add 1 2 -- 3 -- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen. fib x - | x < 2 = x + | x < 2 = 1 | otherwise = fib (x - 1) + fib (x - 2) -- Pattern Matching funktioniert ähnlich. @@ -190,23 +202,28 @@ foo 5 -- 15 -- Funktionskomposition -- Die (.) Funktion verkettet Funktionen. -- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und --- multipliziert dieses Ergebnis mit 5. -foo = (*5) . (+10) +-- multipliziert dieses Ergebnis mit 4. +foo = (*4) . (+10) + +-- (5 + 10) * 4 = 60 +foo 5 -- 60 --- (5 + 10) * 5 = 75 -foo 5 -- 75 +-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchfuehrt. +-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist +-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator +-- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt, +-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die +-- Funktion auf der linken Seite verwendet wird. +-- Mit `.` und `$` kann man sich so viele Klammern ersparen. --- Haskell hat eine Funktion `$`. Diese ändert den Vorrang, --- so dass alles links von ihr zuerst berechnet wird und --- und dann an die rechte Seite weitergegeben wird. --- Mit `.` und `$` kann man sich viele Klammern ersparen. +(even (fib 7)) -- false --- Vorher -(even (fib 7)) -- true +-- Äquivalent: +even $ fib 7 -- false --- Danach -even . fib $ 7 -- true +-- Funktionskomposition: +even . fib $ 7 -- false ---------------------------------------------------- -- 5. Typensystem @@ -233,19 +250,19 @@ double :: Integer -> Integer double x = x * 2 ---------------------------------------------------- --- 6. If-Anweisung und Kontrollstrukturen +-- 6. If-Ausdrücke und Kontrollstrukturen ---------------------------------------------------- --- If-Anweisung: +-- If-Ausdruck: haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" --- If-Anweisungen können auch ueber mehrere Zeilen verteilt sein. --- Das Einruecken ist dabei äußerst wichtig. +-- If-Ausdrücke können auch über mehrere Zeilen verteilt sein. +-- Die Einrückung ist dabei wichtig. haskell = if 1 == 1 then "awesome" else "awful" --- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen. +-- Case-Ausdruck: Am Beispiel vom Parsen von "commandline"-Argumenten. case args of "help" -> printHelp "start" -> startProgram @@ -276,7 +293,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- die Abarbeitung sieht so aus: -(2 * 3 + (2 * 2 + (2 * 1 + 4))) +(2 * 1 + (2 * 2 + (2 * 3 + 4))) ---------------------------------------------------- -- 7. Datentypen -- cgit v1.2.3 From 093c3e656242e84682da7910e8d56db62c08ca10 Mon Sep 17 00:00:00 2001 From: Andy <andrewgallasch@gmail.com> Date: Sat, 31 Oct 2015 20:52:07 +1030 Subject: Formatted enum comments --- java.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index e1efc375..84978ecc 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -706,10 +706,12 @@ public abstract class Mammal() // Enum Type // -// An enum type is a special data type that enables for a variable to be a set of predefined constants. The // variable must be equal to one of the values that have been predefined for it. -// Because they are constants, the names of an enum type's fields are in uppercase letters. -// In the Java programming language, you define an enum type by using the enum keyword. For example, you would -// specify a days-of-the-week enum type as: +// An enum type is a special data type that enables for a variable to be a set +// of predefined constants. The variable must be equal to one of the values that +// have been predefined for it. Because they are constants, the names of an enum +// type's fields are in uppercase letters. In the Java programming language, you +// define an enum type by using the enum keyword. For example, you would specify +// a days-of-the-week enum type as: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, -- cgit v1.2.3 From 4545257ce36075b7dfeb12244fd38c1614895ae6 Mon Sep 17 00:00:00 2001 From: Elie Moreau <moreau.ejw@gmail.com> Date: Sat, 31 Oct 2015 21:23:35 +1100 Subject: Closed a comment that was not properly closed --- css.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/css.html.markdown b/css.html.markdown index d8f30ca3..e824914c 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -29,7 +29,7 @@ The main focus of this article is on the syntax and some general tips. #################### */ /* the selector is used to target an element on a page. -selector { property: value; /* more properties...*/ } +selector { property: value; /* more properties...*/ } */ /* Here is an example element: -- cgit v1.2.3 From fb5365ec8fcc898cba845b2194ab51fec57e84bb Mon Sep 17 00:00:00 2001 From: Adam Bard <github@adambard.com> Date: Sat, 31 Oct 2015 18:26:19 +0800 Subject: Revert "Closed a comment that was not properly closed" --- css.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/css.html.markdown b/css.html.markdown index e824914c..d8f30ca3 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -29,7 +29,7 @@ The main focus of this article is on the syntax and some general tips. #################### */ /* the selector is used to target an element on a page. -selector { property: value; /* more properties...*/ } */ +selector { property: value; /* more properties...*/ } /* Here is an example element: -- cgit v1.2.3 From db632ee03ca837fcdc4ca45e428ad7efb9c8135f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= <mario@geekytheory.com> Date: Sat, 31 Oct 2015 11:27:29 +0100 Subject: Create file for PHP translation es-ES --- es-es/php-es.html.markdown | 823 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 823 insertions(+) create mode 100644 es-es/php-es.html.markdown diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown new file mode 100644 index 00000000..a8276e53 --- /dev/null +++ b/es-es/php-es.html.markdown @@ -0,0 +1,823 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Mario Pérez", "https://github.com/MarioPerezEsteso"] +lang: es-es +filename: learnphp-es.php +--- + +This document describes PHP 5+. + +```php +<?php // PHP code must be enclosed with <?php tags + +// If your php file only contains PHP code, it is best practice +// to omit the php closing tag to prevent accidental output. + +// Two forward slashes start a one-line comment. + +# So will a hash (aka pound symbol) but // is more common + +/* + Surrounding text in slash-asterisk and asterisk-slash + makes it a multi-line comment. +*/ + +// Use "echo" or "print" to print output +print('Hello '); // Prints "Hello " with no line break + +// () are optional for print and echo +echo "World\n"; // Prints "World" with a line break +// (all statements must end with a semicolon) + +// Anything outside <?php tags is echoed automatically +?> +Hello World Again! +<?php + + +/************************************ + * Types & Variables + */ + +// Variables begin with the $ symbol. +// A valid variable name starts with a letter or underscore, +// followed by any number of letters, numbers, or underscores. + +// Boolean values are case-insensitive +$boolean = true; // or TRUE or True +$boolean = false; // or FALSE or False + +// Integers +$int1 = 12; // => 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (a leading 0 denotes an octal number) +$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) + +// Floats (aka doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Delete variable +unset($int1); + +// Arithmetic +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// Shorthand arithmetic +$number = 0; +$number += 1; // Increment $number by 1 +echo $number++; // Prints 1 (increments after evaluation) +echo ++$number; // Prints 3 (increments before evaluation) +$number /= $float; // Divide and assign the quotient to $number + +// Strings should be enclosed in single quotes; +$sgl_quotes = '$String'; // => '$String' + +// Avoid using double quotes except to embed other variables +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Special characters are only escaped in double quotes +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// Enclose a variable in curly braces if needed +$money = "I have $${number} in the bank."; + +// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredocs will do string interpolation +$heredoc = <<<END +Multi line +$sgl_quotes +END; + +// String concatenation is done with . +echo 'This string ' . 'is concatenated'; + +// Strings can be passed in as parameters to echo +echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' + + +/******************************** + * Constants + */ + +// A constant is defined by using define() +// and can never be changed during runtime! + +// a valid constant name starts with a letter or underscore, +// followed by any number of letters, numbers, or underscores. +define("FOO", "something"); + +// access to a constant is possible by calling the choosen name without a $ +echo FOO; // Returns 'something' +echo 'This outputs '.FOO; // Returns 'This ouputs something' + + + +/******************************** + * Arrays + */ + +// All arrays in PHP are associative arrays (hashmaps), + +// Associative arrays, known as hashmaps in some languages. + +// Works with all PHP versions +$associative = array('One' => 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 introduced a new syntax +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // prints 1 + +// List literals implicitly assign integer keys +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Add an element to the end of an array +$array[] = 'Four'; +// or +array_push($array, 'Five'); + +// Remove element from array +unset($array[3]); + +/******************************** + * Output + */ + +echo('Hello World!'); +// Prints Hello World! to stdout. +// Stdout is the web page if running in a browser. + +print('Hello World!'); // The same as echo + +// echo and print are language constructs too, so you can drop the parentheses +echo 'Hello World!'; +print 'Hello World!'; + +$paragraph = 'paragraph'; + +echo 100; // Echo scalar variables directly +echo $paragraph; // or variables + +// If short open tags are configured, or your PHP version is +// 5.4.0 or greater, you can use the short echo syntax +?> +<p><?= $paragraph ?></p> +<?php + +$x = 1; +$y = 2; +$x = $y; // $x now contains the same value as $y +$z = &$y; +// $z now contains a reference to $y. Changing the value of +// $z will change the value of $y also, and vice-versa. +// $x will remain unchanged as the original value of $y + +echo $x; // => 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Dumps type and value of variable to stdout +var_dump($z); // prints int(0) + +// Prints variable to stdout in human-readable format +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logic + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert throws a warning if its argument is not true + +// These comparisons will always be true, even if the types aren't the same. +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// The following will only be true if the values match and are the same type. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// 'Spaceship' operator (since PHP 7) +// Returns 0 if values on either side are equal +// Returns 1 if value on the left is greater +// Returns -1 if the value on the right is greater + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 since they are equal +echo $a <=> $b; // -1 since $a < $b +echo $b <=> $a; // 1 since $b > $a + +// Variables can be converted between types, depending on their usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (strings are coerced to integers) + +$string = 'one'; +echo $string + $string; // => 0 +// Outputs 0 because the + operator cannot cast the string 'one' to a number + +// Type casting can be used to treat a variable as another type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// There are also dedicated functions for casting most types +$integer = 5; +$string = strval($integer); + +$var = null; // Null value + + +/******************************** + * Control Structures + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// ternary operator +print (false ? 'Does not get printed' : 'Does'); + +// ternary shortcut operator since PHP 5.3 +// equivalent of "$x ? $x : 'Does'"" +$x = false; +print($x ?: 'Does'); + +// null coalesce operator since php 7 +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// This alternative syntax is useful for templates: +?> + +<?php if ($x): ?> +This is displayed if the test is truthy. +<?php else: ?> +This is displayed otherwise. +<?php endif; ?> + +<?php + +// Use switch to save some logic. +switch ($x) { + case '0': + print 'Switch does type coercion'; + break; // You must include a break, or you will fall through + // to cases 'two' and 'three' + case 'two': + case 'three': + // Do something if $variable is either 'two' or 'three' + break; + default: + // Do something by default +} + +// While, do...while and for loops are probably familiar +$i = 0; +while ($i < 5) { + echo $i++; +}; // Prints "01234" + +echo "\n"; + +$i = 0; +do { + echo $i++; +} while ($i < 5); // Prints "01234" + +echo "\n"; + +for ($x = 0; $x < 10; $x++) { + echo $x; +} // Prints "0123456789" + +echo "\n"; + +$wheels = ['bicycle' => 2, 'car' => 4]; + +// Foreach loops can iterate over arrays +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// You can iterate over the keys as well as the values +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * Functions + */ + +// Define a function with "function": +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// A valid function name starts with a letter or underscore, followed by any +// number of letters, numbers, or underscores. + +function add ($x, $y = 1) { // $y is optional and defaults to 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result is not accessible outside the function +// print $result; // Gives a warning. + +// Since PHP 5.3 you can declare anonymous functions; +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Functions can return functions +function bar ($x, $y) { + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// You can call named functions using strings +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Useful for programatically determining which function to run. +// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +// Since PHP 5.6 you can get a variable number of arguments +function variable($word, ...$list) { + echo $word . " || "; + foreach ($list as $item) { + echo $item . ' | '; + } +} + +variable("Separate", "Hello", "World") // Separate || Hello | World | + +/******************************** + * Includes + */ + +<?php +// PHP within included files must also begin with a PHP open tag. + +include 'my-file.php'; +// The code in my-file.php is now available in the current scope. +// If the file cannot be included (e.g. file not found), a warning is emitted. + +include_once 'my-file.php'; +// If the code in my-file.php has been included elsewhere, it will +// not be included again. This prevents multiple class declaration errors + +require 'my-file.php'; +require_once 'my-file.php'; +// Same as include(), except require() will cause a fatal error if the +// file cannot be included. + +// Contents of my-include.php: +<?php + +return 'Anything you like.'; +// End file + +// Includes and requires may also return a value. +$value = include 'my-include.php'; + +// Files are included based on the file path given or, if none is given, +// the include_path configuration directive. If the file isn't found in +// the include_path, include will finally check in the calling script's +// own directory and the current working directory before failing. +/* */ + +/******************************** + * Classes + */ + +// Classes are defined with the class keyword + +class MyClass +{ + const MY_CONST = 'value'; // A constant + + static $staticVar = 'static'; + + // Static variables and their visibility + public static $publicStaticVar = 'publicStatic'; + // Accessible within the class only + private static $privateStaticVar = 'privateStatic'; + // Accessible from the class and subclasses + protected static $protectedStaticVar = 'protectedStatic'; + + // Properties must declare their visibility + public $property = 'public'; + public $instanceProp; + protected $prot = 'protected'; // Accessible from the class and subclasses + private $priv = 'private'; // Accessible within the class only + + // Create a constructor with __construct + public function __construct($instanceProp) { + // Access instance variables with $this + $this->instanceProp = $instanceProp; + } + + // Methods are declared as functions inside a class + public function myMethod() + { + print 'MyClass'; + } + + //final keyword would make a function unoverridable + final function youCannotOverrideMe() + { + } + +/* + * Declaring class properties or methods as static makes them accessible without + * needing an instantiation of the class. A property declared as static can not + * be accessed with an instantiated class object (though a static method can). + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Class constants can always be accessed statically +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; + +// Instantiate classes using new +$my_class = new MyClass('An instance property'); +// The parentheses are optional if not passing in an argument. + +// Access class members using -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + +<?php + +// By default, classes exist in the global namespace, and can +// be explicitly called with a backslash. + +$cls = new \MyClass(); + + + +// Set the namespace for a file +namespace My\Namespace; + +class MyClass +{ +} + +// (from another file) +$cls = new My\Namespace\MyClass; + +//Or from within another namespace. +namespace My\Other\Namespace; + +use My\Namespace\MyClass; + +$cls = new MyClass(); + +// Or you can alias the namespace; + +namespace My\Other\Namespace; + +use My\Namespace as SomeOtherNamespace; + +$cls = new SomeOtherNamespace\MyClass(); + + +/********************** +* Late Static Binding +* +*/ + +class ParentClass { + public static function who() { + echo "I'm a " . __CLASS__ . "\n"; + } + public static function test() { + // self references the class the method is defined within + self::who(); + // static references the class the method was invoked on + static::who(); + } +} + +ParentClass::test(); +/* +I'm a ParentClass +I'm a ParentClass +*/ + +class ChildClass extends ParentClass { + public static function who() { + echo "But I'm " . __CLASS__ . "\n"; + } +} + +ChildClass::test(); +/* +I'm a ParentClass +But I'm ChildClass +*/ + + +/********************** +* Error Handling +* +*/ + +// Simple error handling can be done with try catch block + +try { + // Do something +} catch (Exception $e) { + // Handle exception +} + +// When using try catch blocks in a namespaced enviroment use the following + +try { + // Do something +} catch (\Exception $e) { + // Handle exception +} + +// Custom exceptions + +class MyException extends Exception {} + +try { + + $condition = true; + + if ($condition) { + throw new MyException('Something just happend'); + } + +} catch (MyException $e) { + // Handle my exception +} + +``` + +## More Information + +Visit the [official PHP documentation](http://www.php.net/manual/) for reference +and community input. + +If you're interested in up-to-date best practices, visit +[PHP The Right Way](http://www.phptherightway.com/). + +If you're coming from a language with good package management, check out +[Composer](http://getcomposer.org/). + +For common standards, visit the PHP Framework Interoperability Group's +[PSR standards](https://github.com/php-fig/fig-standards). -- cgit v1.2.3 From 0156044d6f4f0630e1f82989b905a9f2a625e1a7 Mon Sep 17 00:00:00 2001 From: Kristy Vuong <kristyvuong@gmail.com> Date: Sat, 31 Oct 2015 21:29:46 +1100 Subject: Added fullstops at the end of most lines --- markdown.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 2333110f..b3284e71 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -11,7 +11,7 @@ Give me as much feedback as you want! / Feel free to fork and pull request! ```markdown -<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that +<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown. This means we can use HTML elements in Markdown, such as the comment element, and they won't be affected by a markdown parser. However, if you create an HTML element in your markdown file, you cannot use markdown syntax within that @@ -23,7 +23,7 @@ specific to a certain parser. --> <!-- Headers --> <!-- You can create HTML elements <h1> through <h6> easily by prepending the -text you want to be in that element by a number of hashes (#) --> +text you want to be in that element by a number of hashes (#). --> # This is an <h1> ## This is an <h2> ### This is an <h3> @@ -31,7 +31,7 @@ text you want to be in that element by a number of hashes (#) --> ##### This is an <h5> ###### This is an <h6> -<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 --> +<!-- Markdown also provides us with two alternative ways of indicating h1 and h2. --> This is an h1 ============= @@ -39,7 +39,7 @@ This is an h2 ------------- <!-- Simple text styles --> -<!-- Text can be easily styled as italic or bold using markdown --> +<!-- Text can be easily styled as italic or bold using markdown. --> *This text is in italics.* _And so is this text._ @@ -85,7 +85,7 @@ There's a <br /> above me! > How neat is that? <!-- Lists --> -<!-- Unordered lists can be made using asterisks, pluses, or hyphens --> +<!-- Unordered lists can be made using asterisks, pluses, or hyphens. --> * Item * Item @@ -103,21 +103,21 @@ or - Item - One last item -<!-- Ordered lists are done with a number followed by a period --> +<!-- Ordered lists are done with a number followed by a period. --> 1. Item one 2. Item two 3. Item three <!-- You don't even have to label the items correctly and markdown will still -render the numbers in order, but this may not be a good idea --> +render the numbers in order, but this may not be a good idea. --> 1. Item one 1. Item two 1. Item three <!-- (This renders the same as the above example) --> -<!-- You can also use sublists --> +<!-- You can also use sublists. --> 1. Item one 2. Item two @@ -136,13 +136,13 @@ This checkbox below will be a checked HTML checkbox. <!-- Code blocks --> <!-- You can indicate a code block (which uses the <code> element) by indenting -a line with four spaces or a tab --> +a line with four spaces or a tab. --> This is code So is this <!-- You can also re-tab (or add an additional four spaces) for indentation -inside your code --> +inside your code. --> my_array.each do |item| puts item @@ -152,7 +152,7 @@ inside your code --> John didn't even know what the `go_to()` function did! -<!-- In Github Flavored Markdown, you can use a special syntax for code --> +<!-- In Github Flavored Markdown, you can use a special syntax for code. --> \`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! --> def foobar @@ -174,11 +174,11 @@ with or without spaces. --> <!-- Links --> <!-- One of the best things about markdown is how easy it is to make links. Put -the text to display in hard brackets [] followed by the url in parentheses () --> +the text to display in hard brackets [] followed by the url in parentheses (). --> [Click me!](http://test.com/) -<!-- You can also add a link title using quotes inside the parentheses --> +<!-- You can also add a link title using quotes inside the parentheses. --> [Click me!](http://test.com/ "Link to Test.com") @@ -186,7 +186,7 @@ the text to display in hard brackets [] followed by the url in parentheses () -- [Go to music](/music/). -<!-- Markdown also supports reference style links --> +<!-- Markdown also supports reference style links. --> [Click this link][link1] for more info about it! [Also check out this link][foobar] if you want to. @@ -198,7 +198,7 @@ the text to display in hard brackets [] followed by the url in parentheses () -- entirely. The references can be anywhere in your document and the reference IDs can be anything so long as they are unique. --> -<!-- There is also "implicit naming" which lets you use the link text as the id --> +<!-- There is also "implicit naming" which lets you use the link text as the id. --> [This][] is a link. @@ -211,7 +211,7 @@ can be anything so long as they are unique. --> ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") -<!-- And reference style works as expected --> +<!-- And reference style works as expected. --> ![This is the alt-attribute.][myimage] @@ -233,7 +233,7 @@ I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. <!-- Keyboard keys --> -<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys --> +<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys. --> Your computer crashed? Try sending a <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> -- cgit v1.2.3 From fd16cf95ae0a96424f1cd78ffb3ac99138eda4ff Mon Sep 17 00:00:00 2001 From: Niko Weh <niko.weh@gmail.com> Date: Sat, 31 Oct 2015 20:57:30 +1000 Subject: [haskell/de] [yaml/de] Fix umlauts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaced ae/oe/ue with ä/ö/ü where appropriate. I did a "grep" in the de-de directory, i've only found problems in haskell and yaml files. --- de-de/haskell-de.html.markdown | 40 ++++++++++++++++++++-------------------- de-de/yaml-de.html.markdown | 4 ++-- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index 41b80d95..d1a0008e 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -59,7 +59,7 @@ not False -- True -- Strings und Zeichen "Das ist ein String." 'a' -- Zeichen -'Einfache Anfuehrungszeichen gehen nicht.' -- error! +'Einfache Anführungszeichen gehen nicht.' -- error! -- Strings können konkateniert werden. "Hello " ++ "world!" -- "Hello world!" @@ -90,11 +90,11 @@ not False -- True -- Der "!!"-Operator extrahiert das Element an einem bestimmten Index: [1..10] !! 3 -- 4 --- Haskell unterstuetzt unendliche Listen! -[1..] -- Die Liste aller natuerlichen Zahlen +-- Haskell unterstützt unendliche Listen! +[1..] -- Die Liste aller natürlichen Zahlen -- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation" --- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird. +-- unterstützt. Haskell evaluiert erst etwas, wenn es benötigt wird. -- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir: [1..] !! 999 -- 1000 @@ -106,7 +106,7 @@ not False -- True -- Zwei Listen konkatenieren [1..5] ++ [6..10] --- Ein Element als Head hinzufuegen +-- Ein Element als Head hinzufügen 0:[1..5] -- [0, 1, 2, 3, 4, 5] -- Weitere Listenoperationen @@ -152,7 +152,7 @@ add 1 2 -- 3 (//) a b = a `div` b 35 // 4 -- 8 --- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen. +-- Guards sind eine einfache Möglichkeit für Fallunterscheidungen. fib x | x < 2 = 1 | otherwise = fib (x - 1) + fib (x - 2) @@ -186,7 +186,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 -- 4. Mehr Funktionen ---------------------------------------------------- --- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt, +-- currying: Wenn man nicht alle Argumente an eine Funktion übergibt, -- so wird sie eine neue Funktion gebildet ("curried"). -- Es findet eine partielle Applikation statt und die neue Funktion -- nimmt die fehlenden Argumente auf. @@ -209,7 +209,7 @@ foo = (*4) . (+10) foo 5 -- 60 --- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchfuehrt. +-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt. -- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist -- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator -- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt, @@ -238,14 +238,14 @@ even . fib $ 7 -- false True :: Bool -- Funktionen haben genauso Typen. --- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt: +-- `not` ist Funktion die ein Bool annimmt und ein Bool zurückgibt: -- not :: Bool -> Bool -- Eine Funktion die zwei Integer Argumente annimmt: -- add :: Integer -> Integer -> Integer -- Es ist guter Stil zu jeder Funktionsdefinition eine --- Typdefinition darueber zu schreiben: +-- Typdefinition darüber zu schreiben: double :: Integer -> Integer double x = x * 2 @@ -317,7 +317,7 @@ data Maybe a = Nothing | Just a -- Diese sind alle vom Typ Maybe: Just "hello" -- vom Typ `Maybe String` Just 1 -- vom Typ `Maybe Int` -Nothing -- vom Typ `Maybe a` fuer jedes `a` +Nothing -- vom Typ `Maybe a` für jedes `a` ---------------------------------------------------- -- 8. Haskell IO @@ -326,8 +326,8 @@ Nothing -- vom Typ `Maybe a` fuer jedes `a` -- IO kann nicht völlig erklärt werden ohne Monaden zu erklären, -- aber man kann die grundlegenden Dinge erklären. --- Wenn eine Haskell Programm ausgefuehrt wird, so wird `main` aufgerufen. --- Diese muss etwas vom Typ `IO ()` zurueckgeben. Zum Beispiel: +-- Wenn eine Haskell Programm ausgeführt wird, so wird `main` aufgerufen. +-- Diese muss etwas vom Typ `IO ()` zurückgeben. Zum Beispiel: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) @@ -355,10 +355,10 @@ sayHello = do -- an die Variable "name" gebunden putStrLn $ "Hello, " ++ name --- Uebung: Schreibe deine eigene Version von `interact`, +-- Übung: Schreibe deine eigene Version von `interact`, -- die nur eine Zeile einliest. --- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt. +-- `sayHello` wird niemals ausgeführt, nur `main` wird ausgeführt. -- Um `sayHello` laufen zulassen kommentiere die Definition von `main` -- aus und ersetze sie mit: -- main = sayHello @@ -376,7 +376,7 @@ action = do input1 <- getLine input2 <- getLine -- Der Typ von `do` ergibt sich aus der letzten Zeile. - -- `return` ist eine Funktion und keine Schluesselwort + -- `return` ist eine Funktion und keine Schlüsselwort return (input1 ++ "\n" ++ input2) -- return :: String -> IO String -- Nun können wir `action` wie `getLine` benutzen: @@ -387,7 +387,7 @@ main'' = do putStrLn result putStrLn "This was all, folks!" --- Der Typ `IO` ist ein Beispiel fuer eine Monade. +-- Der Typ `IO` ist ein Beispiel für eine Monade. -- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit -- eine rein funktional Sprache zu sein. -- Jede Funktion die mit der Außenwelt interagiert (z.B. IO) @@ -404,7 +404,7 @@ main'' = do -- Starte die REPL mit dem Befehl `ghci` -- Nun kann man Haskell Code eingeben. --- Alle neuen Werte muessen mit `let` gebunden werden: +-- Alle neuen Werte müssen mit `let` gebunden werden: let foo = 5 @@ -413,7 +413,7 @@ let foo = 5 >:t foo foo :: Integer --- Auch jede `IO ()` Funktion kann ausgefuehrt werden. +-- Auch jede `IO ()` Funktion kann ausgeführt werden. > sayHello What is your name? @@ -437,6 +437,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater Haskell ist sehr einfach zu installieren. Hohl es dir von [hier](http://www.haskell.org/platform/). -Eine sehr viele langsamere Einfuehrung findest du unter: +Eine sehr viele langsamere Einführung findest du unter: [Learn you a Haskell](http://learnyouahaskell.com/) oder [Real World Haskell](http://book.realworldhaskell.org/). diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index 19ea9e87..a46c30f6 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -30,7 +30,7 @@ null_Wert: null Schlüssel mit Leerzeichen: value # Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber: jedoch: "Ein String in Anführungzeichen" -"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schluessel haben willst." +"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schlüssel haben willst." # Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text) # oder ein 'folded block' (> gefolgt vom text). @@ -64,7 +64,7 @@ eine_verschachtelte_map: hallo: hallo # Schlüssel müssen nicht immer String sein. -0.25: ein Float-Wert als Schluessel +0.25: ein Float-Wert als Schlüssel # Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels ? | -- cgit v1.2.3 From c23fa3613874bc22b65e5506c374c8f8bf2691d8 Mon Sep 17 00:00:00 2001 From: Adam <adam@adambard.com> Date: Sat, 31 Oct 2015 19:34:51 +0800 Subject: Revert "[php/en]" This reverts commit 5afca01bdfb7dab2e6086a63bb80444aae9831cb. --- php.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 7b0cf61c..0504ced2 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -3,7 +3,6 @@ language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] - - [ Liam Demafelix , https://liamdemafelix.com/] filename: learnphp.php --- @@ -157,13 +156,14 @@ unset($array[3]); * Output */ -echo 'Hello World!'; +echo('Hello World!'); // Prints Hello World! to stdout. // Stdout is the web page if running in a browser. print('Hello World!'); // The same as echo -// print is a language construct too, so you can drop the parentheses +// echo and print are language constructs too, so you can drop the parentheses +echo 'Hello World!'; print 'Hello World!'; $paragraph = 'paragraph'; @@ -335,7 +335,7 @@ switch ($x) { $i = 0; while ($i < 5) { echo $i++; -} // Prints "01234" +}; // Prints "01234" echo "\n"; -- cgit v1.2.3 From b307b65e8df4e27991c8cf7ade1e3d7faa1e87fd Mon Sep 17 00:00:00 2001 From: Anton Ivanov <sendmailn@gmail.com> Date: Sat, 31 Oct 2015 14:37:12 +0300 Subject: Add binary number example. --- php.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 7b0cf61c..d03b89fe 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -54,6 +54,8 @@ $int1 = 12; // => 12 $int2 = -12; // => -12 $int3 = 012; // => 10 (a leading 0 denotes an octal number) $int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +// Binary integer literals are available since PHP 5.4.0. +$int5 = 0b11111111; // 255 (a leading 0b denotes a binary number) // Floats (aka doubles) $float = 1.234; @@ -117,11 +119,11 @@ echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' // a valid constant name starts with a letter or underscore, // followed by any number of letters, numbers, or underscores. -define("FOO", "something"); +define("FOO", "something"); // access to a constant is possible by calling the choosen name without a $ echo FOO; // Returns 'something' -echo 'This outputs '.FOO; // Returns 'This ouputs something' +echo 'This outputs ' . FOO; // Returns 'This ouputs something' -- cgit v1.2.3 From c990b720e4416fd5c516af906ba548d0b2b12f0f Mon Sep 17 00:00:00 2001 From: Reinoud Kruithof <reinoud.kruithof@gmail.com> Date: Sat, 31 Oct 2015 12:37:39 +0100 Subject: Added Dutch translation of AMD. --- nl-nl/amd-nl.html.markdown | 235 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 nl-nl/amd-nl.html.markdown diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown new file mode 100644 index 00000000..d5e0022a --- /dev/null +++ b/nl-nl/amd-nl.html.markdown @@ -0,0 +1,235 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +translators: + - ["Reinoud Kruithof", "https://github.com/reinoudk"] +filename: learnamd-nl.js +lang: nl-nl +--- + +## Aan de slag met AMD + +De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript + modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon + geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het + synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid, + debugging en cross-domain toegangsproblemen. + +### Basis concept +```javascript +// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require` +// and gaat vooral over de definitie en gebruik van modules: +// `define(id?, dependencies?, factory)` definieert een module +// `require(dependencies, callback)` importeert een set van dependencies en +// gebruikt ze in de gegeven callback + +// Laten we starten met het gebruiken van define om een nieuwe module (met naam) +// te creeren, welke geen dependencies heeft. Dit doen we door een naam +// en een zogeheten factory functie door te geven aan define: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // De return waarde van een module's factory functie is + // wat andere modules of require calls ontvangen wanneer + // ze onze `awesomeAMD` module requiren. + // De gexporteerde waarde kan van alles zijn: (constructor) functies, + // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft). + return isAMDAwesome; +}); + + +// We gaan nu een andere module defineren die afhankelijk is van onze +// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument +// is die de dependencies van onze module defineert: +define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){ + // dependencies worden naar de factory's functieargumenten + // gestuurd in de volgorde waarin ze gespecificeert zijn + var vertelIedereen = function(){ + if (awesomeAMD()){ + alert('Dit is zOoOo cool!'); + } else { + alert('Vrij saai, niet?'); + } + }; + return vertelIedereen; +}); + +// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken +// om ons programma mee te starten. De vorm van `require` is +// `(arrayVanDependencies, callback)`. +require(['schreeuwlelijk'], function(schreewlelijk){ + schreeuwlelijk(); +}); + +// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic +// (niet-asynchrone) versie van AMD implementeren: +function define(naam, deps, factory){ + // merk op hoe modules zonder dependencies worden afgehandeld + define[naam] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // we halen eerst alle dependecies op die nodig zijn + // om require aan te roepen + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // voldoe aan alle dependencies van de callback + return callback.apply(null, args); +} +// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/ +``` + +### require.js in de echte wereld + +In contrast met het voorbeeld uit de introductie, implementeert `require.js` + (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk + om je modules en hun dependencies asynchroon in the laden via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // de callback word uitgesteld tot de dependency geladen is + var things = new SomeClass(); +}); +console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd +``` + +De afspraak is dat je over het algemeen n module in n bestand opslaat. +`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie, +dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen + door hun locatie te gebruiken. +In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map, + relatief ten opzichte van de `baseUrl` uit je configuratie. + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren: + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // definitie van de module gebeurt, natuurlijk, ook asynchroon + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` +Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping + aan te passen in je `main.js`: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // je kan ook modules uit andere locatie inladen + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibUitBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){ + // een `main` bestand moet require minstens eenmaal aanroepen, + // anders zal er geen code uitgevoerd worden + coolLib.doFancyDingenMet(helpers.transform($('#foo'))); +}); +``` +Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`) + welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut. +Deze zal automisch geladen en uitgevoerd worden als de pagina laadt: + +```html +<!DOCTYPE html> +<html> +<head> + <title>Honder script tags? Nooi meer! + + + + + +``` + +### Een heel project optimaliseren met r.js + +Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de + ontwikkelfase om code op een gezonde manier te organiseren maar + willen nog steeds een enkel scriptbestand gebruiken in productie in + plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt. + +`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk +uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de +dependency book van je project analyseert en een enkel bestand bouwt met daarin +al je module (juist genaamd), geminificeerd en klaar voor productie. + +Instaleren met `npm`: +```shell +$ npm install requirejs -g +``` + +Nu kun je het een configuratiebestand voeden: +```shell +$ r.js -o app.build.js +``` + +Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien: +```javascript +/* file : app.build.js */ +({ + name : 'main', // naam van het beginpunt + out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt + baseUrl : 'app', + paths : { + // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN, + // gebruik makend van de locatie gespecificeert in `main.js` + jquery : 'empty:', + coolLibUitBower : '../bower_components/cool-lib/coollib' + } +}) +``` +Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie: +```html + +``` + +Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is +beschikbar in de GitHub repo (Engels). + +Hieronder vind je nog meer informatie over AMD (Engels). + +### Onderwerpen die niet aan bod zijn gekomen +* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) +* [Advanced configuration](http://requirejs.org/docs/api.html#config) +* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) +* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Using almond.js for builds](https://github.com/jrburke/almond) + +### Verder lezen: + +* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Why AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementaties: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) -- cgit v1.2.3 From 1bd371bcda266c594ab4a4be9868db32a157c296 Mon Sep 17 00:00:00 2001 From: Tom Anderson Date: Sat, 31 Oct 2015 22:43:43 +1030 Subject: Add section heading info Give information about using comments for code sections --- matlab.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/matlab.html.markdown b/matlab.html.markdown index 9d78978e..25f762bb 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -15,6 +15,7 @@ If you have any feedback please feel free to reach me at [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). ```matlab +%% Code sections start with two percent signs. Section titles go on the same line. % Comments start with a percent sign. %{ -- cgit v1.2.3 From 608615360c7f49cb33c9e7eb3957e031b9b8a89c Mon Sep 17 00:00:00 2001 From: Niko Weh Date: Sat, 31 Oct 2015 22:37:13 +1000 Subject: [haskell/en] Extended section on GHCi - Added the :i command, as i feel that it is as useful as :t. - Added another example for :t, hopefully showcasing it's flexibility - For consistency, changed the name of (.) from function to operator (as is already the case with ($)), and added a short remark in the GHCi section that (most) operators are also functions. --- haskell.html.markdown | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 936744a0..940cf4c7 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -193,7 +193,7 @@ foo = (+10) foo 5 -- 15 -- function composition --- the (.) function chains functions together. +-- the operator `.` chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, -- multiplies the result of that by 4, and then returns the final value. foo = (*4) . (+10) @@ -401,11 +401,26 @@ main'' = do let foo = 5 --- You can see the type of any value with `:t`: +-- You can see the type of any value or expression with `:t`: ->:t foo +> :t foo foo :: Integer +-- Operators, such as `+`, `:` and `$`, are functions. +-- Their type can be inspected by putting the operator in parentheses: + +> :t (:) +(:) :: a -> [a] -> [a] + +-- You can get additional information on any `name` using `:i`: + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + -- You can also run any action of type `IO ()` > sayHello -- cgit v1.2.3 From bda1e01ae0260e5ebbc7f93972b57bbad39c2ab4 Mon Sep 17 00:00:00 2001 From: IvanEh Date: Sat, 31 Oct 2015 14:46:06 +0200 Subject: Add Ukrainian translation for JSON --- ua-ua/json-ua.html.markdown | 67 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 ua-ua/json-ua.html.markdown diff --git a/ua-ua/json-ua.html.markdown b/ua-ua/json-ua.html.markdown new file mode 100644 index 00000000..6281ea56 --- /dev/null +++ b/ua-ua/json-ua.html.markdown @@ -0,0 +1,67 @@ +--- +language: json +filename: learnjson-ru.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Ehreshi Ivan", "https://github.com/IvanEh"] +lang: ua-ua +--- + +JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом +"Learn X in Y Minutes". + +В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють +використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього +поля, але все-таки краще такого уникати для кращої сумісності + +```json +{ + "ключ": "значеннь", + + "ключі": "завжди мають бути обгорнуті в подвійні лапки", + "числа": 0, + "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".", + "логічний тип": true, + "нічого": null, + + "велике число": 1.2e+100, + + "об’єкти": { + "коментар": "Більшість ваших структур будуть складатися з об’єктів", + + "масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5], + + "інший об’єкт": { + "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно." + } + }, + + "безглуздя": [ + { + "джерело калія": ["банани"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "нео"], + [0, 0, 0, 1] + ] + ], + + "альтернативнтй стиль": { + "коментар": "Гляньте!" + , "позиція коми": "неважлива, поки вона знаходиться до наступного поля" + , "інший коментар": "класно" + }, + + "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON." +} + +Одиничний масив значень теж є правильним JSON + +[1, 2, 3, "text", true] + + +``` -- cgit v1.2.3 From b336e810865a1a2ce54c53b467bcd1545455a679 Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:12:18 +0300 Subject: removed controversial performance info, fixed recursion info and typos --- scala.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..13e8d9d8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -231,7 +231,7 @@ r foreach println (5 to 1 by -1) foreach (println) -// A while loops +// A while loop var i = 0 while (i < 10) { println("i " + i); i += 1 } @@ -239,17 +239,18 @@ while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very - // fast, faster that Java loops, but using the combinators and - // comprehensions above is easier to understand and parallelize + // fast, but using the combinators and comprehensions above is easier + // to understand and parallelize -// A do while loop +// A do-while loop i = 0 do { println("i is still less than 10") i += 1 } while (i < 10) -// Tail recursion is an idiomatic way of doing recurring things in Scala. +// Recursion is the idiomatic way of repeating an action in Scala (as in most +// other functional languages). // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. def showNumbersInRange(a: Int, b: Int): Unit = { @@ -267,7 +268,7 @@ val x = 10 if (x == 1) println("yeah") if (x == 10) println("yeah") if (x == 11) println("yeah") -if (x == 11) println ("yeah") else println("nay") +if (x == 11) println("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -- cgit v1.2.3 From 3dbcf1c2c6092b0287bae150eec2271446f95927 Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:22:59 +0300 Subject: added docs for multi-variable tuple assignment --- scala.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..4ba9a31b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -321,9 +321,15 @@ divideInts(10, 3) // (Int, Int) = (3,1) val d = divideInts(10, 3) // (Int, Int) = (3,1) d._1 // Int = 3 - d._2 // Int = 1 +// Alternatively you can do multiple-variable assignment to tuple, which is more +// convenient and readable in many cases +val (div, mod) = divideInts(10, 3) + +div // Int = 3 +mod // Int = 1 + ///////////////////////////////////////////////// // 5. Object Oriented Programming -- cgit v1.2.3 From a5182d8021920760fc863c0c80581e4210590b8f Mon Sep 17 00:00:00 2001 From: Anton Ivanov Date: Sat, 31 Oct 2015 16:30:09 +0300 Subject: Fix and update russian translation for PHP. --- ru-ru/php-ru.html.markdown | 55 ++++++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index dc254bf8..f6daa946 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -32,7 +32,7 @@ print('Hello '); // Напечатать "Hello " без перевода стр // () необязательно применять для print и echo echo "World\n"; // Напечатать "World" и перейти на новую строку. -// (все утверждения должны заканчиваться ;) +// (все утверждения должны заканчиваться точкой с запятой) // Любые символы за пределами закрывающего тега выводятся автоматически: ?> @@ -45,8 +45,8 @@ Hello World Again! */ // Переменные начинаются с символа $. -// Правильное имя переменной начинается с буквы или знака подчеркивания, -// и может содержать любые цифры, буквы, или знаки подчеркивания. +// Правильное имя переменной начинается с буквы или символа подчеркивания, +// за которым следует любое количество букв, цифр или символов подчеркивания. // Не рекомендуется использовать кириллические символы в именах (прим. пер.) // Логические значения нечувствительны к регистру @@ -55,7 +55,7 @@ $boolean = false; // или FALSE или False // Целые числа $int1 = 12; // => 12 -$int2 = -12; // => -12- +$int2 = -12; // => -12 $int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число) $int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число) @@ -87,7 +87,7 @@ $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; -// Заключайте переменные в фигурные скобки если это необходимо +// Заключайте переменные в фигурные скобки, если это необходимо $money = "I have $${number} in the bank."; // Начиная с PHP 5.3, синтаксис nowdocs может использоваться для @@ -106,6 +106,9 @@ END; // Строки соединяются при помощи . echo 'This string ' . 'is concatenated'; +// echo можно передавать строки как параметры +echo 'Multiple', 'Parameters', 'Valid'; // печатает 'MultipleParametersValid' + /******************************** * Константы @@ -114,18 +117,19 @@ echo 'This string ' . 'is concatenated'; // Константа определяется при помощи define() // и никогда не может быть изменена во время выполнения программы! -// Правильное имя константы начинается с буквы или символа подчеркивания, -// и содержит любое колличество букв, цифр и знаков подчеркивания. +// Правильное имя константы начинается с буквы или символа подчеркивания +// и содержит любое колличество букв, цифр или символов подчеркивания. define("FOO", "something"); -// Доступ к константе возможен через прямое указание её имени -echo 'This outputs '.FOO; +// Доступ к константе возможен через прямое указание её имени без знака $ +echo FOO; // печатает 'something' +echo 'This outputs ' . FOO; // печатает 'This ouputs something' /******************************** * Массивы */ -// Все массивы в PHP - это ассоциативные массивы или хеши, +// Все массивы в PHP - это ассоциативные массивы // Ассоциативные массивы, известные в других языках как HashMap. @@ -189,7 +193,7 @@ $b = '0'; $c = '1'; $d = '1'; -// Утверждение (assert) выдает предупреждение если аргумент не true +// Утверждение (assert) выдает предупреждение, если его аргумент не true // Эти сравнения всегда будут истинными, даже если типы будут различаться assert($a == $b); // "равно" @@ -284,35 +288,35 @@ This is displayed otherwise. // Использование switch. switch ($x) { case '0': - print 'Switch does type coercion'; - break; // You must include a break, or you will fall through - // to cases 'two' and 'three' + print 'Switch использует неточное сравнение'; + break; // вы должны использовать break, иначе PHP будет продолжать + // исполнять команды следующих секций case 'two' и 'three' case 'two': case 'three': - // Do something if $variable is either 'two' or 'three' + // делаем что-то, если $x == 'two' или $x == 'three' break; default: - // Do something by default + // делаем что-то по умолчанию } // Циклы: while, do...while и for $i = 0; while ($i < 5) { echo $i++; -}; // Prints "01234" +}; // печатает "01234" echo "\n"; $i = 0; do { echo $i++; -} while ($i < 5); // Prints "01234" +} while ($i < 5); // печатает "01234" echo "\n"; for ($x = 0; $x < 10; $x++) { echo $x; -} // Напечатает "0123456789" +} // печатает "0123456789" echo "\n"; @@ -335,17 +339,17 @@ echo "\n"; $i = 0; while ($i < 5) { if ($i === 3) { - break; // Exit out of the while loop + break; // выйти из цикла while } echo $i++; } // Напечатает "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { - continue; // Skip this iteration of the loop + continue; // пропустить текущую итерацию цикла } echo $i; -} // Напечатает "0124" +} // печатает "0124" /******************************** @@ -360,7 +364,7 @@ function my_function () { echo my_function(); // => "Hello" // Правильное имя функции начинается с буквы или символа подчеркивания -// и состоит из букв, цифр или знаков подчеркивания. +// и состоит из букв, цифр или символов подчеркивания. function add ($x, $y = 1) { // $y по умолчанию равно 1 $result = $x + $y; @@ -656,7 +660,10 @@ $cls = new SomeOtherNamespace\MyClass(); ``` ## Смотрите также: -Посетите страницу [официальной документации PHP](http://www.php.net/manual/) для справки. +Посетите страницу [официальной документации PHP](http://www.php.net/manual/) для справки. + Если вас интересуют полезные приемы использования PHP посетите [PHP The Right Way](http://www.phptherightway.com/). + Если вы раньше пользовались языком с хорошей организацией пакетов, посмотрите [Composer](http://getcomposer.org/). + Для изучения стандартов использования языка посетите PHP Framework Interoperability Group's [PSR standards](https://github.com/php-fig/fig-standards). -- cgit v1.2.3 From bc087b50370a3c32c35ef026047c2fa9db9944d8 Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:39:47 +0300 Subject: usage of named parameters --- scala.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..bc8cd422 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -169,6 +169,12 @@ def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y // Syntax for calling functions is familiar: sumOfSquares(3, 4) // => 25 +// You can use parameters names to specify them in different order +def subtract(x: Int, y: Int): Int = x - y + +subtract(10, 3) // => 7 +subtract(y=10, x=3) // => -7 + // In most cases (with recursive functions the most notable exception), function // return type can be omitted, and the same type inference we saw with variables // will work with function return values: -- cgit v1.2.3 From d47f06345b37cecf4072523c1c79f63f37846d8c Mon Sep 17 00:00:00 2001 From: Pavel Kazlou Date: Sat, 31 Oct 2015 16:50:40 +0300 Subject: added docs for default case in pattern matching --- scala.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scala.html.markdown b/scala.html.markdown index 192e03d7..131bd71c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -454,6 +454,9 @@ def matchEverything(obj: Any): String = obj match { // You can nest patterns: case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" + + // Match any case (default) if all previous haven't matched + case _ => "Got unknown object" } // In fact, you can pattern match any object with an "unapply" method. This -- cgit v1.2.3 From a11e01b82162ad43db9b4f751ead0fdd09ad3fb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= Date: Sat, 31 Oct 2015 15:32:24 +0100 Subject: Translate learn PHP to es-es --- es-es/php-es.html.markdown | 714 +++++++++++++++++++++++---------------------- 1 file changed, 358 insertions(+), 356 deletions(-) diff --git a/es-es/php-es.html.markdown b/es-es/php-es.html.markdown index a8276e53..fa52353c 100644 --- a/es-es/php-es.html.markdown +++ b/es-es/php-es.html.markdown @@ -9,121 +9,121 @@ lang: es-es filename: learnphp-es.php --- -This document describes PHP 5+. +Este documento explica el funcionamiento de PHP 5+. ```php - -Hello World Again! +¡Hola Mundo de nuevo! 12 $int2 = -12; // => -12 -$int3 = 012; // => 10 (a leading 0 denotes an octal number) -$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +$int3 = 012; // => 10 (un 0 al comienzo declara un número octal) +$int4 = 0x0F; // => 15 (un 0x al comienzo declara un hexadecimal) -// Floats (aka doubles) +// Floats (también conocidos como doubles) $float = 1.234; $float = 1.2e3; $float = 7E-10; -// Delete variable +// Eliminar variable unset($int1); -// Arithmetic -$sum = 1 + 1; // 2 -$difference = 2 - 1; // 1 -$product = 2 * 2; // 4 -$quotient = 2 / 1; // 2 +// Operaciones aritméticas +$suma = 1 + 1; // 2 +$diferencia = 2 - 1; // 1 +$producto = 2 * 2; // 4 +$cociente = 2 / 1; // 2 -// Shorthand arithmetic -$number = 0; -$number += 1; // Increment $number by 1 -echo $number++; // Prints 1 (increments after evaluation) -echo ++$number; // Prints 3 (increments before evaluation) -$number /= $float; // Divide and assign the quotient to $number +// Operaciones aritméticas de escritura rápida +$numero = 0; +$numero += 1; // Incrementa $numero en 1 +echo $numero++; // Imprime 1 (incremento después la evaluación) +echo ++$numero; // Imprime 3 (incremento antes de la evaluación) +$numero /= $float; // Divide y asigna el cociente a $numero -// Strings should be enclosed in single quotes; +// Las cadenas de caracteres deben declararse entre comillas simples $sgl_quotes = '$String'; // => '$String' -// Avoid using double quotes except to embed other variables +// Evita utilizar comillas dobles excepto para embeber otras variables $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' -// Special characters are only escaped in double quotes -$escaped = "This contains a \t tab character."; -$unescaped = 'This just contains a slash and a t: \t'; +// Los caracteres especiales solo son válidos entre comillas dobles +$escaped = "Esto contiene \t un caracter tabulador."; +$unescaped = 'Esto solo contiene una barra y una t: \t'; -// Enclose a variable in curly braces if needed -$money = "I have $${number} in the bank."; +// Rodea una variable entre corchetes si es necesario +$dinero = "Tengo $${numero} en el banco."; -// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +// Desde PHP 5.3, los nowdocs pueden ser utilizados para multilíneas no interpoladas $nowdoc = <<<'END' Multi line string END; -// Heredocs will do string interpolation +// Heredocs interpola cadenas de caracteres $heredoc = << 1, 'Two' => 2, 'Three' => 3); +// Funciona con todas las versiones de php +$asociativo = array('Uno' => 1, 'Dos' => 2, 'Tres' => 3); -// PHP 5.4 introduced a new syntax -$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; +// PHP 5.4 introdujo una nueva sintaxis +$asociativo = ['Uno' => 1, 'Dos' => 2, 'Tres' => 3]; -echo $associative['One']; // prints 1 +echo $asociativo['Uno']; // imprime 1 -// List literals implicitly assign integer keys -$array = ['One', 'Two', 'Three']; -echo $array[0]; // => "One" +// Lista literales implícitamente asignados con claves enteras +$array = ['Uno', 'Dos', 'Tres']; +echo $array[0]; // => "Uno" -// Add an element to the end of an array -$array[] = 'Four'; -// or -array_push($array, 'Five'); +// Añadir un elemento al final de un array +$array[] = 'Cuatro'; +// o +array_push($array, 'Cinco'); -// Remove element from array +// Eliminar un elemento de un array unset($array[3]); /******************************** - * Output + * Salidas por pantalla */ -echo('Hello World!'); -// Prints Hello World! to stdout. -// Stdout is the web page if running in a browser. +echo('¡Hola Mundo!'); +// Imprime ¡Hola Mundo! en stdout. +// Stdout es la página web si se está ejecutando en un navegador. -print('Hello World!'); // The same as echo +print('!Hola Mundo!'); // Es lo mismo que echo -// echo and print are language constructs too, so you can drop the parentheses -echo 'Hello World!'; -print 'Hello World!'; +// No es necesario el paréntesis en echo y print +echo '¡Hola Mundo!'; +print '¡Hola Mundo!'; -$paragraph = 'paragraph'; +$parrafo = 'parrafo'; -echo 100; // Echo scalar variables directly -echo $paragraph; // or variables +echo 100; // Haz echo de escalares directamente +echo $parrafo; // o de variables -// If short open tags are configured, or your PHP version is -// 5.4.0 or greater, you can use the short echo syntax +// Si las etiquetas cortas estás configuradas y tu versión de PHP es +// la 5.4.0 o superior, puede utilizar la sintaxis abreviada de echo ?> -

+

2 echo $z; // => 2 @@ -194,179 +194,178 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 -// Dumps type and value of variable to stdout -var_dump($z); // prints int(0) +// Dump muestra el tipo y valor de una variable en stdout +var_dump($z); // imprime int(0) -// Prints variable to stdout in human-readable format -print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) +// Para mostrar el valor de una variable en un formato legible para humanos +print_r($array); // imprime: Array ( [0] => Uno [1] => Dos [2] => Tres ) /******************************** - * Logic + * Lógica */ $a = 0; $b = '0'; $c = '1'; $d = '1'; -// assert throws a warning if its argument is not true +// assert lanza una advertencia si su argumento no es verdadero -// These comparisons will always be true, even if the types aren't the same. -assert($a == $b); // equality -assert($c != $a); // inequality -assert($c <> $a); // alternative inequality +// Estas comparaciones siempre serán verdaderas, incluso si los tipos no son los mismos. +assert($a == $b); // igualdad +assert($c != $a); // desigualdad +assert($c <> $a); // desigualdad alternativa assert($a < $c); assert($c > $b); assert($a <= $b); assert($c >= $d); -// The following will only be true if the values match and are the same type. +// Los siguiente solo será verdadero si los valores coinciden y son del mismo tipo. assert($c === $d); assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); -// 'Spaceship' operator (since PHP 7) -// Returns 0 if values on either side are equal -// Returns 1 if value on the left is greater -// Returns -1 if the value on the right is greater +// Operador 'Spaceship' (desde PHP 7) +// Devuelve 0 si ambos valores son iguales +// Devuelve 1 si el valor de la izquierda es mayor +// Devuelve -1 si el valor de la derecha es mayor $a = 100; $b = 1000; -echo $a <=> $a; // 0 since they are equal -echo $a <=> $b; // -1 since $a < $b -echo $b <=> $a; // 1 since $b > $a +echo $a <=> $a; // 0 porque son iguales +echo $a <=> $b; // -1 porque $a < $b +echo $b <=> $a; // 1 porque $b > $a -// Variables can be converted between types, depending on their usage. +// Las variables pueden ser convertidas entre tipos, dependiendo de su uso. -$integer = 1; -echo $integer + $integer; // => 2 +$entero = 1; +echo $entero + $entero; // => 2 $string = '1'; -echo $string + $string; // => 2 (strings are coerced to integers) +echo $string + $string; // => 2 (los strings son convertidos a enteros) -$string = 'one'; +$string = 'uno'; echo $string + $string; // => 0 -// Outputs 0 because the + operator cannot cast the string 'one' to a number +// Muestra un 0 porque el operador + no puede convertir la cadena de caracteres 'uno' a un número -// Type casting can be used to treat a variable as another type +// La conversión de tipos puede ser utilizada para tratar a una variable como otro tipo $boolean = (boolean) 1; // => true -$zero = 0; -$boolean = (boolean) $zero; // => false +$cero = 0; +$boolean = (boolean) $cero; // => false -// There are also dedicated functions for casting most types -$integer = 5; -$string = strval($integer); +// También hay funciones dedicadas a la conversión de tipos +$entero = 5; +$string = strval($entero); -$var = null; // Null value +$var = null; // Valor nulo /******************************** - * Control Structures + * Estructuras de control */ if (true) { - print 'I get printed'; + print 'He sido imprimido'; } if (false) { - print 'I don\'t'; + print 'Yo no'; } else { - print 'I get printed'; + print 'He sido imprimido'; } if (false) { - print 'Does not get printed'; + print 'No se imprime'; } elseif(true) { - print 'Does'; + print 'Sí se imprime'; } -// ternary operator -print (false ? 'Does not get printed' : 'Does'); +// operador ternario +print (false ? 'No se imprime' : 'Sí se imprime'); -// ternary shortcut operator since PHP 5.3 -// equivalent of "$x ? $x : 'Does'"" +// atajo para el operador ternario desde PHP 5.3 +// equivalente de "$x ? $x : 'Sí'"" $x = false; -print($x ?: 'Does'); +print($x ?: 'Sí'); -// null coalesce operator since php 7 +// operador 'no definido' desde php 7 $a = null; -$b = 'Does print'; -echo $a ?? 'a is not set'; // prints 'a is not set' -echo $b ?? 'b is not set'; // prints 'Does print' +$b = 'Imprime'; +echo $a ?? 'a no está definido'; // imprime 'a no está definido' +echo $b ?? 'b no está definido'; // imprime 'Imprime' $x = 0; if ($x === '0') { - print 'Does not print'; + print 'No imprime'; } elseif($x == '1') { - print 'Does not print'; + print 'No imprime'; } else { - print 'Does print'; + print 'Imprime'; } -// This alternative syntax is useful for templates: +// Esta sintaxis alternativa se utiliza para plantillas: ?> -This is displayed if the test is truthy. +Esto se muestra si la evaluación es verdadera. -This is displayed otherwise. +En otro caso, se muestra esto. 2, 'car' => 4]; +$ruedas = ['bicicleta' => 2, 'coche' => 4]; -// Foreach loops can iterate over arrays -foreach ($wheels as $wheel_count) { - echo $wheel_count; -} // Prints "24" +// Los bucles foreach pueden iterar por arrays +foreach ($ruedas as $numero_ruedas) { + echo $numero_ruedas; +} // Imprime "24" echo "\n"; -// You can iterate over the keys as well as the values -foreach ($wheels as $vehicle => $wheel_count) { - echo "A $vehicle has $wheel_count wheels"; +// También se puede iterar sobre las claves, así como sobre los valores +foreach ($ruedas as $vehiculo => $numero_ruedas) { + echo "Un $vehiculo tiene $numero_ruedas ruedas"; } echo "\n"; @@ -374,45 +373,45 @@ echo "\n"; $i = 0; while ($i < 5) { if ($i === 3) { - break; // Exit out of the while loop + break; // Sale fuera del bucle while } echo $i++; -} // Prints "012" +} // Imprime "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { - continue; // Skip this iteration of the loop + continue; // Se salta esta iteración del bucle } echo $i; -} // Prints "0124" +} // Imprime "0124" /******************************** - * Functions + * Funciones */ -// Define a function with "function": -function my_function () { - return 'Hello'; +// Define una función con "function": +function mi_funcion () { + return 'Hola'; } -echo my_function(); // => "Hello" +echo mi_funcion(); // => "Hola" -// A valid function name starts with a letter or underscore, followed by any -// number of letters, numbers, or underscores. +// Un nombre válido de función comienza con una letra o guión bajo, seguido de cualquier +// número de letras, números o guiones bajos. -function add ($x, $y = 1) { // $y is optional and defaults to 1 - $result = $x + $y; - return $result; +function anadir ($x, $y = 1) { // $y es opcional y por defecto es 1 + $resultado = $x + $y; + return $resultado; } -echo add(4); // => 5 -echo add(4, 2); // => 6 +echo anadir(4); // => 5 +echo anadir(4, 2); // => 6 -// $result is not accessible outside the function -// print $result; // Gives a warning. +// $resultado no es accesible fuera de la función +// print $resultado; // Devuelve una advertencia. -// Since PHP 5.3 you can declare anonymous functions; +// Desde PHP 5.3 se pueden declarar funciones anónimas $inc = function ($x) { return $x + 1; }; @@ -423,28 +422,28 @@ function foo ($x, $y, $z) { echo "$x - $y - $z"; } -// Functions can return functions +// Las funciones pueden devolver funciones function bar ($x, $y) { - // Use 'use' to bring in outside variables + // Utiliza 'use' para meter variables de fuera de la función return function ($z) use ($x, $y) { foo($x, $y, $z); }; } $bar = bar('A', 'B'); -$bar('C'); // Prints "A - B - C" +$bar('C'); // Imprime "A - B - C" -// You can call named functions using strings -$function_name = 'add'; -echo $function_name(1, 2); // => 3 -// Useful for programatically determining which function to run. -// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); +// Puedes llamar a funciones utilizando cadenas de caracteres +$nombre_funcion = 'add'; +echo $nombre_funcion(1, 2); // => 3 +// Es útil para determinarl qué función ejecutar. +// O, utiliza call_user_func(callable $callback [, $parameter [, ... ]]); -// You can get the all the parameters passed to a function -function parameters() { - $numargs = func_num_args(); - if ($numargs > 0) { +// Puedes obtener todos los parámetros pasados a una función +function parametros() { + $numero_argumentos = func_num_args(); + if ($numero_argumentos > 0) { echo func_get_arg(0) . ' | '; } $args_array = func_get_args(); @@ -453,151 +452,153 @@ function parameters() { } } -parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | +parametros('Hola', 'Mundo'); // Hola | 0 - Hola | 1 - Mundo | -// Since PHP 5.6 you can get a variable number of arguments -function variable($word, ...$list) { - echo $word . " || "; - foreach ($list as $item) { +// Desde PHP 5.6 se puede obtener un número variable de argumentos +function variable($palabra, ...$lista) { + echo $palabra . " || "; + foreach ($lista as $item) { echo $item . ' | '; } } -variable("Separate", "Hello", "World") // Separate || Hello | World | +variable("Separa", "Hola", "Mundo") // Separa || Hola | Mundo | /******************************** * Includes */ instanceProp = $instanceProp; } - // Methods are declared as functions inside a class - public function myMethod() + // Los métodos son declarados como funciones dentro de una clase + public function miMetodo() { - print 'MyClass'; + print 'MiClase'; } - //final keyword would make a function unoverridable - final function youCannotOverrideMe() + // la palabra clave final hará una función no sobreescribible + final function noMePuedesSobreEscribir() { } /* - * Declaring class properties or methods as static makes them accessible without - * needing an instantiation of the class. A property declared as static can not - * be accessed with an instantiated class object (though a static method can). + * Declarar propiedades de clase o métodos como estáticos los hace accesibles sin + * necesidad de instanciar la clase. Una propiedad declarada como estática no + * puede ser accedida mediante una instancia de la clase, pero sí mediante un + * método estático. */ - public static function myStaticMethod() + public static function miMetodoEstatico() { - print 'I am static'; + print 'Soy estático'; } } -// Class constants can always be accessed statically -echo MyClass::MY_CONST; // Outputs 'value'; +// Las constantes de una clase siempre pueden ser accedidas estáticamente +echo MiClase::MI_CONSTANTE; // Muestra 'valor'; -echo MyClass::$staticVar; // Outputs 'static'; -MyClass::myStaticMethod(); // Outputs 'I am static'; +echo MiClase::$staticVar; // Muestra 'static'; +MiClase::miMetodoEstatico(); // Muestra 'Soy estático'; -// Instantiate classes using new -$my_class = new MyClass('An instance property'); -// The parentheses are optional if not passing in an argument. +// Instancia una clase usando new +$mi_clase = new MiClase('Una instancia'); +// Los paréntesis son opcionales si no se pasa ningún argumento. -// Access class members using -> -echo $my_class->property; // => "public" -echo $my_class->instanceProp; // => "An instance property" -$my_class->myMethod(); // => "MyClass" +// Accede a los miembros de una clase utilizando -> +echo $mi_clase->propiedad; // => "public" +echo $mi_clase->instanceProp; // => "Una instancia" +$mi_clase->miMetodo(); // => "MiClase" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Extender clases utilizando "extends" +class MiOtraClase extends MiClase { - function printProtectedProperty() + function imprimePropiedadProtegida() { echo $this->prot; } - // Override a method - function myMethod() + // Sobreescribe un método + function miMetodo() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::miMetodo(); + print ' > MiOtraClase'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$mi_otra_clase = new MiOtraClase('Propiedad de instancia'); +$mi_otra_clase->imprimePropiedadProtegida(); // => Imprime "protected" +$mi_otra_clase->miMetodo(); // Imprime "MiClase > MiOtraClase" -final class YouCannotExtendMe +final class NoMePuedesExtender { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Puedes utilizar "métodos mágicos" para crear los getters y setters +class MiClaseMapeada { - private $property; + private $propiedad; public function __get($key) { @@ -610,60 +611,60 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new MiClaseMapeada(); +echo $x->propiedad; // Utilizará el método __get() +$x->propiedad = 'Algo'; // Utilizará el método __set() -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Las clases pueden ser abstractas (utilizando la palabra clave abstract) o +// implementando interfaces (utilizando la palabra clave implements). +// Una interfaz puede ser declarada con la palabra clave interface. -interface InterfaceOne +interface InterfazUno { - public function doSomething(); + public function hazAlgo(); } -interface InterfaceTwo +interface InterfazDos { - public function doSomethingElse(); + public function hazOtraCosa(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// las interfaces pueden ser extendidas +interface InterfazTres extends InterfazDos { - public function doAnotherContract(); + public function hazCualquierOtraCosa(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class MiClaseAbstracta implements InterfazUno { - public $x = 'doSomething'; + public $x = 'hazAlgo'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class MiOtraClase extends MiClaseAbstracta implements InterfazDos { - public function doSomething() + public function hazAlgo() { echo $x; } - public function doSomethingElse() + public function hazOtraCosa() { - echo 'doSomethingElse'; + echo 'hazOtraCosa'; } } -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Las clases pueden implementar más de una interfaz +class CualquierOtraClase implements InterfazUno, InterfazDos { - public function doSomething() + public function hazAlgo() { - echo 'doSomething'; + echo 'hazAlgo'; } - public function doSomethingElse() + public function hazOtraCosa() { - echo 'doSomethingElse'; + echo 'hazOtraCosa'; } } @@ -672,65 +673,65 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Traits */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Los traits están disponibles desde PHP 5.4.0 y son declarados utilizando "trait" -trait MyTrait +trait MiTrait { - public function myTraitMethod() + public function miMetodoTrait() { - print 'I have MyTrait'; + print 'Tengo trait'; } } -class MyTraitfulClass +class MiClaseTrait { - use MyTrait; + use MiTrait; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$cls = new MiClaseTrait(); +$cls->miMetodoTrait(); // Imprime "Tengo trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Esta sección está separada porque una declaración de namespace debe +// ser la primera sentencia en un archivo. Vamos a suponer que no es el caso Date: Sat, 31 Oct 2015 15:39:50 +0100 Subject: Improvements to the german LaTeX document. Fix a sentence, added a command to be able to define multiline comment blocks. Additionally, make use of the \LaTeX command to correctly show the LaTeX logo. --- de-de/latex-de.html.markdown | 91 +++++++++++++++++++++++++------------------- 1 file changed, 51 insertions(+), 40 deletions(-) diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown index 2c18b8fd..ee9c6e3e 100644 --- a/de-de/latex-de.html.markdown +++ b/de-de/latex-de.html.markdown @@ -6,19 +6,19 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] translators: - ["Moritz Kammerer", "https://github.com/phxql"] + - ["Jerome Meinke", "https://github.com/jmeinke"] lang: de-de filename: latex-de.tex --- ``` -% Alle Kommentare starten fangen mit % an -% Es gibt keine Kommentare über mehrere Zeilen +% Alle Kommentare starten mit einem Prozentzeichen % -% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% LaTeX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. % MS Word oder OpenOffice Writer -% Jedes LateX-Kommando startet mit einem Backslash (\) +% Jedes LaTeX-Kommando startet mit einem Backslash (\) -% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% LaTeX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen % Weitere Dokumententypen sind z.B. book, report, presentations, etc. % Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall % wollen wir einen 12 Punkte-Font verwenden. @@ -26,7 +26,7 @@ filename: latex-de.tex % Als nächstes definieren wir die Pakete, die wir verwenden wollen. % Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, -% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% musst du die Fähigkeiten von LaTeX durch Hinzufügen von Paketen erweitern. % Wir verwenden die Pakete float und caption für Bilder. \usepackage{caption} \usepackage{float} @@ -34,30 +34,41 @@ filename: latex-de.tex % Mit diesem Paket können leichter Umlaute getippt werden \usepackage[utf8]{inputenc} +% Es gibt eigentlich keine Kommentare über mehrere Zeilen, solche kann man +% aber selbst durch die Angabe eigener Kommandos definieren. +% Dieses Kommando kann man später benutzen. +\newcommand{\comment}[1]{} + % Es können durchaus noch weitere Optione für das Dokument gesetzt werden! \author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} \date{\today} -\title{Learn LaTeX in Y Minutes!} +\title{Learn \LaTeX\ in Y Minutes!} % Nun kann's losgehen mit unserem Dokument. % Alles vor dieser Zeile wird die Preamble genannt. -\begin{document} +\begin{document} + +\comment{ + Dies ist unser selbst-definierter Befehl + für mehrzeilige Kommentare. +} + % Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann -% LateX für uns eine Titelseite generieren +% LaTeX für uns eine Titelseite generieren \maketitle -% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigen Befehl an. % Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem % Inhalt erscheinen. % Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. \begin{abstract} - LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! + \LaTeX -Documentation geschrieben in \LaTeX ! Wie ungewöhnlich und garantiert nicht meine Idee! \end{abstract} % Section Befehle sind intuitiv. % Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. \section{Einleitung} -Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! +Hi, mein Name ist Moritz und zusammen werden wir \LaTeX\ erforschen! \section{Noch eine section} Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. @@ -71,16 +82,16 @@ So ist's schon viel besser. % Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. % Das funktioniert auch bei anderen Befehlen. -\section*{Das ist eine unnummerierte section} -Es müssen nicht alle sections nummeriert sein! +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle Sections nummeriert sein! \section{Ein paar Notizen} -LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +\LaTeX\ ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge \textbackslash\textbackslash in den Code ein.\\ \section{Listen} -Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +Listen sind eine der einfachsten Dinge in \LaTeX. Ich muss morgen einkaufen gehen, also lass uns eine Einkaufsliste schreiben: \begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. % \item bringt enumerate dazu, eins weiterzuzählen. @@ -96,7 +107,7 @@ also lass uns eine Einkaufsliste schreiben: \section{Mathe} -Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Einer der Haupteinsatzzwecke von \LaTeX\ ist das Schreiben von akademischen Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle Symbole zu unserem Paper hinzuzufügen! \\ @@ -106,18 +117,18 @@ Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstabe um nur ein paar zu nennen.\\ Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen -Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ +Papern. So schreibt man in \LaTeX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ -% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LaTeX schreiben, % geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings % nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und % ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. -Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den \LaTeX nicht kennt! Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: -Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), Logarithmus und Exponenten ($\log$, $\exp$), Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. Lass uns eine Gleichung schreiben: \\ @@ -127,7 +138,7 @@ $\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ Brüche (Zähler / Nenner) können so geschrieben werden: % 10 / 7 -$^{10}/_{7}$ +$^{10}/_{7}$ % Komplexere Brüche können so geschrieben werden: % \frac{Zähler}{Nenner} @@ -142,19 +153,19 @@ Wir können Gleichungen auch in einer equation Umgebung verwenden. \end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen Wir können nun unsere Gleichung referenzieren! -Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: Grafiken, Gleichungen, Sections, etc. Summen und Integrale können mit den sum und int Befehlen dargestellt werden: -% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen -\begin{equation} +% Manche LaTeX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} +\end{equation} +\begin{equation} \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} +\end{equation} \section{Grafiken} @@ -164,7 +175,7 @@ Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. \begin{figure}[H] % H ist die Platzierungsoption \centering % Zentriert die Grafik auf der Seite % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} + %\includegraphics[width=0.8\linewidth]{right-triangle.png} % Auskommentiert, damit es nicht im Dokument auftaucht. \caption{Dreieck mit den Seiten $a$, $b$, $c$} \label{fig:right-triangle} @@ -177,7 +188,7 @@ Wir können Tabellen genauso wie Grafiken einfügen. \caption{Überschrift der Tabelle.} % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. - \begin{tabular}{c|cc} + \begin{tabular}{c|cc} Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt \hline % Eine horizontale Linie 1 & Biggus & Dickus \\ @@ -187,36 +198,36 @@ Wir können Tabellen genauso wie Grafiken einfügen. % \section{Links} % Kommen bald! -\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} -Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll -in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +\section{Verhindern, dass \LaTeX\ etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem \LaTeX-Dokument. \LaTeX\ soll +in diesem Fall nicht den Quelltext als \LaTeX-Kommandos interpretieren, sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden wir eine verbatim Umgebung. % Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) % aber verbatim ist das simpelste. -\begin{verbatim} +\begin{verbatim} print("Hello World!") a%b; % Schau dir das an! Wir können % im verbatim verwenden! random = 4; #decided by fair random dice roll \end{verbatim} -\section{Kompilieren} +\section{Kompilieren} Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ Dafür musst du folgende Schritte durchführen: \begin{enumerate} - \item Schreibe das Dokument. (den LateX-Quelltext). - \item Kompiliere den Quelltext in ein PDF. + \item Schreibe das Dokument. (den \LaTeX -Quelltext). + \item Kompiliere den Quelltext in ein PDF. Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf \end{verbatim} \end{enumerate} -Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +Manche \LaTeX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt 2 wird unsichtbar im Hintergrund ausgeführt. Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet -- cgit v1.2.3 From c0b2ccdb43ab8b49cfdab277c8cc266abf532bd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mario=20P=C3=A9rez?= Date: Sat, 31 Oct 2015 15:45:36 +0100 Subject: Create latex es-es file --- es-es/latex-es.html.markdown | 239 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 es-es/latex-es.html.markdown diff --git a/es-es/latex-es.html.markdown b/es-es/latex-es.html.markdown new file mode 100644 index 00000000..11bac4fc --- /dev/null +++ b/es-es/latex-es.html.markdown @@ -0,0 +1,239 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Mario Pérez", "https://github.com/MarioPerezEsteso"] +filename: learn-latex-es.tex +--- + +```tex +% All comment lines start with % +% There are no multi-line comments + +% LaTeX is NOT a "What You See Is What You Get" word processing software like +% MS Word, or OpenOffice Writer + +% Every LaTeX command starts with a backslash (\) + +% LaTeX documents start with a defining the type of document it's compiling +% Other document types include book, report, presentations, etc. +% The options for the document appear in the [] brackets. In this case +% it specifies we want to use 12pt font. +\documentclass[12pt]{article} + +% Next we define the packages the document uses. +% If you want to include graphics, colored text, or +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% I'm going to include the float and caption packages for figures. +\usepackage{caption} +\usepackage{float} + +% We can define some other document properties too! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Now we're ready to begin the document +% Everything before this line is called "The Preamble" +\begin{document} +% if we set the author, date, title fields, we can have LaTeX +% create a title page for us. +\maketitle + +% Most research papers have abstract, you can use the predefined commands for this. +% This should appear in its logical order, therefore, after the top matter, +% but before the main sections of the body. +% This command is available in the document classes article and report. +\begin{abstract} + LaTeX documentation written as LaTeX! How novel and totally not my idea! +\end{abstract} + +% Section commands are intuitive. +% All the titles of the sections are added automatically to the table of contents. +\section{Introduction} +Hello, my name is Colton and together we're going to explore LaTeX! + +\section{Another section} +This is the text for another section. I think it needs a subsection. + +\subsection{This is a subsection} % Subsections are also intuitive. +I think we need another one + +\subsubsection{Pythagoras} +Much better now. +\label{subsec:pythagoras} + +% By using the asterisk we can suppress LaTeX's inbuilt numbering. +% This works for other LaTeX commands as well. +\section*{This is an unnumbered section} +However not all sections have to be numbered! + +\section{Some Text notes} +LaTeX is generally pretty good about placing text where it should go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to +the source code. \\ + +\section{Lists} +Lists are one of the easiest things to create in LaTeX! I need to go shopping +tomorrow, so let's make a grocery list. +\begin{enumerate} % This creates an "enumerate" environment. + % \item tells the enumerate to increment + \item Salad. + \item 27 watermelon. + \item A single jackrabbit. + % we can even override the item number by using [] + \item[how many?] Medium sized squirt guns. + + Not a list item, but still part of the enumerate. + +\end{enumerate} % All environments must have an end. + +\section{Math} + +One of the primary uses for LaTeX is to produce academic articles or +technical papers. Usually in the realm of math and science. As such, +we need to be able to add special symbols to our paper! \\ + +Math has many symbols, far beyond what you can find on a keyboard; +Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ + +Sets and relations play a vital role in many mathematical research papers. +Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. +% We can enter math-mode from text mode with the $ signs. +% The opposite also holds true. Variable can also be rendered in math-mode. +% We can also enter math mode with \[\] + +\[a^2 + b^2 = c^2 \] + +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +I haven't found a Greek letter that yet that LaTeX doesn't know about! + +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. +Let's write an equation to see how it's done: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fractions(Numerator-denominators) can be written in these forms: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatively complex fractions can be written as +% \frac{numerator}{denominator} +$\frac{n!}{k!(n - k)!}$ \\ + +We can also insert equations in an "equation environment". + +% Display math with the equation 'environment' +\begin{equation} % enters math-mode + c^2 = a^2 + b^2. + \label{eq:pythagoras} % for referencing +\end{equation} % all \begin statements must have an end statement + +We can then reference our new equation! +Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +figures, equations, sections, etc. + +Summations and Integrals are written with sum and int commands: + +% Some LaTeX compilers will complain if there are blank lines +% In an equation environment. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figures} + +Let's insert a Figure. Figure placement can get a little tricky. +I definitely have to lookup the placement options each time. + +\begin{figure}[H] % H here denoted the placement option. + \centering % centers the figure on the page + % Inserts a figure scaled to 0.8 the width of the page. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Commented out for compilation purposes. Please use your imagination. + \caption{Right triangle with sides $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Table} +We can also insert Tables in the same way as figures. + +\begin{table}[H] + \caption{Caption for the Table.} + % the {} arguments below describe how each row of the table is drawn. + % Again, I have to look these up. Each. And. Every. Time. + \begin{tabular}{c|cc} + Number & Last Name & First Name \\ % Column rows are separated by $ + \hline % a horizontal line + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Coming soon + +\section{Getting LaTeX to not compile something (i.e. Source Code)} +Let's say we want to include some code into our LaTeX document, +we would then need LaTeX to not try and interpret that text and +instead just print it to the document. We do this we a verbatim +environment. + +% There are other packages that exist (i.e. minty, lstlisting, etc.) +% but verbatim is the bare-bones basic one. +\begin{verbatim} + print("Hello World!") + a%b; % look! We can use % signs in verbatim. + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Compiling} + +By now you're probably wondering how to compile this fabulous document +and look at the glorious glory that is a LaTeX pdf. +(yes, this document actually does compiles). \\ +Getting to the final document using LaTeX consists of the following steps: + \begin{enumerate} + \item Write the document in plain text (the "source code"). + \item Compile source code to produce a pdf. + The compilation step looks something like this (in Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of +software. So, you get to see Step 1, but not Step 2 completely. +Step 2 is still happening behind the scenes. + +You write all your formatting information in plain text in Step 1. +The compilation part in Step 2 takes care of producing the document in the +format you defined in Step 1. + +\section{End} + +That's all for now! + +% end the document +\end{document} +``` + +## Más información sobre LaTeX + +* El wikilibro LaTeX: [https://es.wikibooks.org/wiki/Manual_de_LaTeX](https://es.wikibooks.org/wiki/Manual_de_LaTeX) +* Un tutorial real: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) -- cgit v1.2.3 From bbdfc9502f3476d637107ceec71dc2adf0186f67 Mon Sep 17 00:00:00 2001 From: Anton Ivanov Date: Sat, 31 Oct 2015 17:35:51 +0300 Subject: Update russian translation for Java. --- ru-ru/java-ru.html.markdown | 46 ++++++++++++++++++++++++++++++++++----------- 1 file changed, 35 insertions(+), 11 deletions(-) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index b24ad555..a1a5cdfc 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -9,7 +9,7 @@ filename: LearnJavaRu.java lang: ru-ru --- -Java - это объектно ориентированный язык программирования общего назначения, +Java - это объектно-ориентированный язык программирования общего назначения, основанный на классах и поддерживающий параллельное программирование. [Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html) @@ -43,17 +43,41 @@ public class LearnJavaRu { " Double: " + 3.14 + " Boolean: " + true); - // Чтобы напечатать что-либо не заканчивая переводом строки - // используется System.out.print. + // Чтобы печатать что-либо, не заканчивая переводом строки, + // используйте System.out.print. System.out.print("Hello "); System.out.print("World"); + // Используйте System.out.printf() для печати с форматированием + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 /////////////////////////////////////// - // Типы и Переменные + // Переменные /////////////////////////////////////// + /* + * Объявление переменных + */ // Переменные объявляются с использованием <тип> <имя> + int fooInt; + // Одновременное объявление нескольких переменных одного типа + // , , + int fooInt1, fooInt2, fooInt3; + + /* + * Инициализация переменных + */ + + // объявление и инициализация переменной = + int fooInt = 1; + int fooInt1, fooInt2, fooInt3; + // инициализация нескольких переменных одного типа + // , , = + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Типы переменных + */ // Byte - 8-битное целое число. // (-128 <= byte <= 127) byte fooByte = 100; @@ -247,7 +271,7 @@ public class LearnJavaRu { // Switch Case // switch работает с типами byte, short, char и int. // Также он работает с перечислениями, - // классом String и с некоторыми классами-обертками над + // классом String (с Java 7) и с некоторыми классами-обертками над // примитивными типами: Character, Byte, Short и Integer. int month = 3; String monthString; @@ -319,7 +343,7 @@ public class LearnJavaRu { System.out.println("trek info: " + trek.toString()); } // Конец метода main. -} // Конец класса LearnJava. +} // Конец класса LearnJavaRu. // Вы можете включать другие, не публичные классы в .java файл. @@ -362,7 +386,7 @@ class Bicycle { // Классы в Java часто реализуют сеттеры и геттеры для своих полей. // Синтаксис определения метода: - // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>) + // <модификатор доступа> <тип возвращаемого значения> <имя метода>(<аргументы>) public int getCadence() { return cadence; } @@ -424,10 +448,10 @@ class PennyFarthing extends Bicycle { // Интерфейсы // Синтаксис определения интерфейса: -// <модификатор доступа> interface <имя> extends <базовый интерфейс> { -// // Константы -// // Определение методов. -//} +// <модификатор доступа> interface <имя интерфейса> extends <базовый интерфейс> { +// // Константы +// // Определение методов +// } // Пример - Еда: public interface Edible { -- cgit v1.2.3 From 23b35d9da0b3c1de5ff6a0b262b08020f0f56c4f Mon Sep 17 00:00:00 2001 From: roymiloh Date: Sat, 31 Oct 2015 17:20:03 +0200 Subject: [C#/en] Fix to "extension methods" over using "extension functions", it's more accurate. --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index dfdd98de..d6c503ae 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -630,7 +630,7 @@ on a new line! ""Wow!"", the masses cried"; public static class Extensions { - // EXTENSION FUNCTIONS + // EXTENSION METHODS public static void Print(this object obj) { Console.WriteLine(obj.ToString()); -- cgit v1.2.3 From 09cbaa6536e13dc2e4e20d8222423968cd989492 Mon Sep 17 00:00:00 2001 From: Abdul Alim Date: Sat, 31 Oct 2015 23:28:39 +0800 Subject: [JSON/ms-my] Added Malay (Malaysia) translation for JSON --- ms-my/json-my.html.markdown | 102 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 ms-my/json-my.html.markdown diff --git a/ms-my/json-my.html.markdown b/ms-my/json-my.html.markdown new file mode 100644 index 00000000..2d2da519 --- /dev/null +++ b/ms-my/json-my.html.markdown @@ -0,0 +1,102 @@ +--- +language: json +filename: learnjson-ms.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] +translators: + - ["abdalim", "https://github.com/abdalim"] +lang: ms-my +--- + +Disebabkan JSON adalah format pertukaran-data yang sangat ringkas, panduan ini +kemungkinan besar adalah Learn X in Y Minutes yang paling mudah. + +JSON dalam bentuk paling aslinya sebenarnya tidak mempunyai sebarang komentar, +tetapi kebanyakan pembaca menerima komen dalam bentuk C (`\\`,`/* */`). Beberapa +pembaca juga bertoleransi terhadap koma terakhir (iaitu koma selepas elemen +terakhir di dalam array atau selepas ciri terakhir sesuatu objek), tetapi semua +ini harus dielakkan dan dijauhkan untuk keserasian yang lebih baik. + +Untuk tujuan ini bagaimanapun, semua di dalam panduan ini adalah 100% JSON yang +sah. Luckily, it kind of speaks for itself. + +Sebuah nilai JSON harus terdiri dari salah satu, iaitu, nombor, string, array, +objek atau salah satu dari nama literal berikut: true, false, null. + +Pelayar web yang menyokong adalah: Firefox 3.5+, Internet Explorer 8.0+, Chrome +1.0+, Opera 10.0+, dan Safari 4.0+. + +Sambungan fail untuk fail - fail JSON adalah ".json" dan jenis MIME untuk teks +JSON adalah "application/json". + +Banyak bahasa aturcara mempunyai fungsi untuk menyirikan (mengekod) dan +menyah-sirikan (men-dekod) data JSON kepada struktur data asal. Javascript +mempunyai sokongon tersirat untuk memanipulasi teks JSON sebagai data. + +Maklumat lebih lanjut boleh dijumpai di http://www.json.org/ + +JSON dibina pada dua struktur: +* Sebuah koleksi pasangan nama/nilai. Di dalam pelbagai bahasa aturcara, ini +direalisasikan sebagai objek, rekod, "struct", "dictionary", "hash table", +senarai berkunci, atau "associative array". +* Sebuah senarai nilai yang tersusun. Dalam kebanyakan bahasa aturcara, ini +direalisasikan sebagai array, vektor, senarai atau urutan. + +Sebuah objek dengan pelbagai pasangan nama/nilai. + +```json +{ + "kunci": "nilai", + + "kekunci": "harus sentiasa dibalut dengan 'double quotes'", + "nombor": 0, + "strings": "Hellø, wørld. Semua unicode dibenarkan, bersama \"escaping\".", + "ada bools?": true, + "tiada apa - apa": null, + + "nombor besar": 1.2e+100, + + "objek": { + "komen": "Sebahagian besar struktur akan terdiri daripada objek.", + + "array": [0, 1, 2, 3, "Array boleh mempunyai sebarang jenis data di dalamnya.", 5], + + "objek lain": { + "komen": "Objek boleh dibina dengan pelbagai lapisan, sangat berguna." + } + }, + + "kebendulan": [ + { + "punca potassium": ["pisang"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "stail alternatif": { + "komen": "cuba lihat ini!" + , "posisi koma": "tidak mengapa - selagi ia adalah sebelum nama atau kunci seterusnya, maka ia sah" + , "komen lain": "sungguh bagus" + } +} +``` + +Sebuah array sahaja yang mengandungi nilai - nilai juga adalah JSON yang sah. + +```json +[1, 2, 3, "text", true] +``` + +Objek - objek boleh menjadi sebahagian dari array juga. + +```json +[{"nama": "Abe", "umur": 25}, {"nama": "Jemah", "umur": 29}, {"name": "Yob", "umur": 31}] +``` -- cgit v1.2.3 From 24f4a4fdab76111889d356c25cd31e2d21e2fbcc Mon Sep 17 00:00:00 2001 From: Anton Ivanov Date: Sat, 31 Oct 2015 18:42:42 +0300 Subject: Update Markdown russian translation. --- ru-ru/markdown-ru.html.markdown | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index eb8e4881..c4c25ef2 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -61,7 +61,7 @@ __И этот тоже.__ **_И тут!_** *__И даже здесь!__* - ~~Зачёркнутый текст.~~ @@ -139,6 +139,14 @@ __И этот тоже.__ * Сложные 4. Заключение + + +Для отметки включенного чекбокса используйте 'x' +- [ ] Первая задача +- [ ] Вторая задача +Этот чекбокс ниже будет отмечен +- [x] Задача была завершена + @@ -252,6 +260,12 @@ end \*текст, заключённый в звёздочки!\* + + + +Ваш компьютер завис? Попробуйте нажать +Ctrl+Alt+Del + + + + + + +# Tämä on

+## Tämä on

+### Tämä on

+#### Tämä on

+##### Tämä on

+###### Tämä on
+ + +Tämä on h1 +============= + +Tämä on h2 +------------- + + + + +*Tämä teksti on kursivoitua.* +_Kuten on myös tämä teksti._ + +**Tämä teksti on lihavoitua.** +__Kuten on tämäkin teksti.__ + +***Tämä teksti on molempia.*** +**_Kuten tämäkin!_** +*__Kuten tämäkin!__* + + + +~~Tämä teksti on yliviivattua.~~ + + + +Tämä on kappala. Kirjoittelen kappaleeseen, eikö tämä olekin hauskaa? + +Nyt olen kappaleessa 2. +Olen edelleen toisessa kappaleessa! + + +Olen kolmannessa kappaleessa! + + + +Päätän tämän kahteen välilyöntiin (maalaa minut nähdäksesi ne). + +There's a
above me! + + + +> Tämä on lainaus. Voit joko +> manuaalisesti rivittää tekstisi ja laittaa >-merkin jokaisen rivin eteen tai antaa jäsentimen rivittää pitkät tekstirivit. +> Sillä ei ole merkitystä kunhan rivit alkavat >-merkillä. + +> Voit myös käyttää useampaa +>> sisennystasoa +> Kuinka hienoa se on? + + + + +* Kohta +* Kohta +* Kolmas kohta + +tai + ++ Kohta ++ Kohta ++ Kolmas kohta + +tai + +- Kohta +- Kohta +- Kolmas kohta + + + +1. Kohta yksi +2. Kohta kaksi +3. Kohta kolme + + + +1. Kohta yksi +1. Kohta kaksi +1. Kohta kolme + + + + +1. Kohta yksi +2. Kohta kaksi +3. Kohta kolme + * Alakohta + * Alakohta +4. Kohta neljä + + + +Alla olevat ruudut ilman x-merkkiä ovat merkitsemättömiä HTML-valintaruutuja. +- [ ] Ensimmäinen suoritettava tehtävä. +- [ ] Toinen tehtävä joka täytyy tehdä +Tämä alla oleva ruutu on merkitty HTML-valintaruutu. +- [x] Tämä tehtävä on suoritettu + + + + + Tämä on koodia + Kuten tämäkin + + + + my_array.each do |item| + puts item + end + + + +John ei tiennyt edes mitä `go_to()` -funktio teki! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Klikkaa tästä!](http://example.com/) + + + +[Klikkaa tästä!](http://example.com/ "Linkki Example.com:iin") + + + +[Musiikkia](/musiikki/). + + + +[Klikkaa tätä linkkiä][link1] saadaksesi lisätietoja! +[Katso myös tämä linkki][foobar] jos haluat. + +[link1]: http://example.com/ "Siistii!" +[foobar]: http://foobar.biz/ "Selkis!" + + + + + +[This][] is a link. + +[this]: http://tämäonlinkki.com/ + + + + + + +![Kuvan alt-attribuutti](http://imgur.com/munkuva.jpg "Vaihtoehtoinen otsikko") + + + +![Tämä on se alt-attribuutti][munkuva] + +[munkuva]: suhteellinen/polku/siitii/kuva.jpg "otsikko tähän tarvittaessa" + + + + + on sama kuin +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en halua +sen kursivoituvan, joten teen näin: \*tämän tekstin ympärillä on asteriskit\*. + + + + +Tietokoneesi kaatui? Kokeile painaa +Ctrl+Alt+Del + + + + +| Kolumni1 | Kolumni2 | Kolumni3 | +| :----------- | :------: | ------------: | +| Vasemmalle | Keskelle | Oikealle | +| blaa | blaa | blaa | + + + +Kolumni 1 | Kolumni 2 | Kolumni 3 +:-- | :-: | --: +Hyi tämä on ruma | saa se | loppumaan + + + +``` + +Lisää tietoa löydät John Gruberin [virallisesta julkaisusta](http://daringfireball.net/projects/markdown/syntax) +ja Adam Pritchardin loistavasta [lunttilapusta](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 99fbb1398edae2523411614578f2e96613743104 Mon Sep 17 00:00:00 2001 From: ComSecNinja Date: Sat, 31 Oct 2015 23:55:17 +0200 Subject: Revert "Translate markdown/en to Finnish" This reverts commit d59c326fe0d90e01f31ff10d89d7fe37a2f654e6. --- fi-fi/markdown-fi.html.markdown | 259 ---------------------------------------- 1 file changed, 259 deletions(-) delete mode 100644 fi-fi/markdown-fi.html.markdown diff --git a/fi-fi/markdown-fi.html.markdown b/fi-fi/markdown-fi.html.markdown deleted file mode 100644 index 14b0f1d9..00000000 --- a/fi-fi/markdown-fi.html.markdown +++ /dev/null @@ -1,259 +0,0 @@ ---- -language: markdown -filename: markdown-fi.md -contributors: - - ["Dan Turkel", "http://danturkel.com/"] -translators: - - ["Timo Virkkunen", "https://github.com/ComSecNinja"] -lang: fi-fi ---- - -John Gruber loi Markdownin vuona 2004. Sen tarkoitus on olla helposti luettava ja kirjoitettava syntaksi joka muuntuu helposti HTML:ksi (ja nyt myös moneksi muuksi formaatiksi). - -```markdown - - - - - - -# Tämä on

-## Tämä on

-### Tämä on

-#### Tämä on

-##### Tämä on

-###### Tämä on
- - -Tämä on h1 -============= - -Tämä on h2 -------------- - - - - -*Tämä teksti on kursivoitua.* -_Kuten on myös tämä teksti._ - -**Tämä teksti on lihavoitua.** -__Kuten on tämäkin teksti.__ - -***Tämä teksti on molempia.*** -**_Kuten tämäkin!_** -*__Kuten tämäkin!__* - - - -~~Tämä teksti on yliviivattua.~~ - - - -Tämä on kappala. Kirjoittelen kappaleeseen, eikö tämä olekin hauskaa? - -Nyt olen kappaleessa 2. -Olen edelleen toisessa kappaleessa! - - -Olen kolmannessa kappaleessa! - - - -Päätän tämän kahteen välilyöntiin (maalaa minut nähdäksesi ne). - -There's a
above me! - - - -> Tämä on lainaus. Voit joko -> manuaalisesti rivittää tekstisi ja laittaa >-merkin jokaisen rivin eteen tai antaa jäsentimen rivittää pitkät tekstirivit. -> Sillä ei ole merkitystä kunhan rivit alkavat >-merkillä. - -> Voit myös käyttää useampaa ->> sisennystasoa -> Kuinka hienoa se on? - - - - -* Kohta -* Kohta -* Kolmas kohta - -tai - -+ Kohta -+ Kohta -+ Kolmas kohta - -tai - -- Kohta -- Kohta -- Kolmas kohta - - - -1. Kohta yksi -2. Kohta kaksi -3. Kohta kolme - - - -1. Kohta yksi -1. Kohta kaksi -1. Kohta kolme - - - - -1. Kohta yksi -2. Kohta kaksi -3. Kohta kolme - * Alakohta - * Alakohta -4. Kohta neljä - - - -Alla olevat ruudut ilman x-merkkiä ovat merkitsemättömiä HTML-valintaruutuja. -- [ ] Ensimmäinen suoritettava tehtävä. -- [ ] Toinen tehtävä joka täytyy tehdä -Tämä alla oleva ruutu on merkitty HTML-valintaruutu. -- [x] Tämä tehtävä on suoritettu - - - - - Tämä on koodia - Kuten tämäkin - - - - my_array.each do |item| - puts item - end - - - -John ei tiennyt edes mitä `go_to()` -funktio teki! - - - -\`\`\`ruby -def foobar - puts "Hello world!" -end -\`\`\` - - - - - - -*** ---- -- - - -**************** - - - - -[Klikkaa tästä!](http://example.com/) - - - -[Klikkaa tästä!](http://example.com/ "Linkki Example.com:iin") - - - -[Musiikkia](/musiikki/). - - - -[Klikkaa tätä linkkiä][link1] saadaksesi lisätietoja! -[Katso myös tämä linkki][foobar] jos haluat. - -[link1]: http://example.com/ "Siistii!" -[foobar]: http://foobar.biz/ "Selkis!" - - - - - -[This][] is a link. - -[this]: http://tämäonlinkki.com/ - - - - - - -![Kuvan alt-attribuutti](http://imgur.com/munkuva.jpg "Vaihtoehtoinen otsikko") - - - -![Tämä on se alt-attribuutti][munkuva] - -[munkuva]: suhteellinen/polku/siitii/kuva.jpg "otsikko tähän tarvittaessa" - - - - - on sama kuin -[http://testwebsite.com/](http://testwebsite.com/) - - - - - - - -haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en halua -sen kursivoituvan, joten teen näin: \*tämän tekstin ympärillä on asteriskit\*. - - - - -Tietokoneesi kaatui? Kokeile painaa -Ctrl+Alt+Del - - - - -| Kolumni1 | Kolumni2 | Kolumni3 | -| :----------- | :------: | ------------: | -| Vasemmalle | Keskelle | Oikealle | -| blaa | blaa | blaa | - - - -Kolumni 1 | Kolumni 2 | Kolumni 3 -:-- | :-: | --: -Hyi tämä on ruma | saa se | loppumaan - - - -``` - -Lisää tietoa löydät John Gruberin [virallisesta julkaisusta](http://daringfireball.net/projects/markdown/syntax) -ja Adam Pritchardin loistavasta [lunttilapusta](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From c3e769e4ac50d4475a530969663e073f4ff002ca Mon Sep 17 00:00:00 2001 From: Brook Zhou Date: Sat, 31 Oct 2015 16:17:58 -0700 Subject: [cpp/en] comparator function for std containers --- c++.html.markdown | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index d03092e5..6b452b1b 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -801,6 +801,24 @@ void doSomethingWithAFile(const std::string& filename) // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock +// containers with object keys of non-primitive values (custom classes) require +// compare function in the object itself or as a function pointer. Primitives +// have default comparators, but you can override it. +class Foo { +public: + int j; + Foo(int a) : j(a) {} +}; +struct compareFunction { + bool operator()(const Foo& a, const Foo& b) const { + return a.j < b.j; + } +}; +//this isn't allowed (although it can vary depending on compiler) +//std::map fooMap; +std::map fooMap; +fooMap[Foo(1)] = 1; +fooMap.find(Foo(1)); //true ///////////////////// // Fun stuff -- cgit v1.2.3 From 6e9e1f4af018dc0e277c968d9b5fe011e0a1ce97 Mon Sep 17 00:00:00 2001 From: Ryan Date: Sat, 31 Oct 2015 16:49:57 -0700 Subject: Added new resource to javascript --- javascript.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index e285ca4e..98261334 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -561,7 +561,9 @@ of the language. [Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal -[Javascript: The Right Way][9] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. +[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples. + +[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. In addition to direct contributors to this article, some content is adapted from @@ -577,4 +579,5 @@ Mozilla Developer Network. [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [8]: http://eloquentjavascript.net/ -[9]: http://jstherightway.org/ +[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version +[10]: http://jstherightway.org/ -- cgit v1.2.3 From f10292ed98674521cc80a0ab66d8508c74e7a627 Mon Sep 17 00:00:00 2001 From: Ryan Date: Sat, 31 Oct 2015 16:55:25 -0700 Subject: Added new ruby resource --- ruby.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 8720fec6..1118e2dd 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -588,6 +588,7 @@ Something.new.qux # => 'qux' ## Additional resources - [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials. - [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) - [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. -- cgit v1.2.3 From dbe6184519860e526432c4987a6f67d6c0acf38e Mon Sep 17 00:00:00 2001 From: Fernando Valverde Arredondo Date: Sun, 1 Nov 2015 01:48:44 +0100 Subject: Update contributor list --- objective-c.html.markdown | 13 ++++++------- swift.html.markdown | 5 +++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 1fa731e3..097cb846 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -1,13 +1,12 @@ --- - language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Clayton Walker", "https://github.com/cwalk"] + - ["Fernando Valverde", "http://visualcosita.xyz"] filename: LearnObjectiveC.m - --- Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. @@ -152,13 +151,13 @@ int main (int argc, const char * argv[]) [mutableDictionary setObject:@"value1" forKey:@"key1"]; [mutableDictionary setObject:@"value2" forKey:@"key2"]; [mutableDictionary removeObjectForKey:@"key1"]; - + // Change types from Mutable To Immutable //In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy]; NSDictionary *mutableDictionaryChanged = [mutableDictionary copy]; - - + + // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) @@ -605,7 +604,7 @@ int main (int argc, const char * argv[]) { // Starting in Xcode 7.0, you can create Generic classes, // allowing you to provide greater type safety and clarity -// without writing excessive boilerplate. +// without writing excessive boilerplate. @interface Result<__covariant A> : NSObject - (void)handleSuccess:(void(^)(A))success @@ -633,7 +632,7 @@ Result *result; @property (nonatomic) NSNumber * object; @end -// It should be obvious, however, that writing one +// It should be obvious, however, that writing one // Class to solve a problem is always preferable to writing two // Note that Clang will not accept generic types in @implementations, diff --git a/swift.html.markdown b/swift.html.markdown index 1ca81bc2..f3746613 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] - ["Clayton Walker", "https://github.com/cwalk"] + - ["Fernando Valverde", "http://visualcosita.xyz"] filename: learnswift.swift --- @@ -25,7 +26,7 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark -// MARK: - Section mark with a separator line +// MARK: - Section mark with a separator line // TODO: Do something soon // FIXME: Fix this code @@ -83,7 +84,7 @@ if someOptionalString != nil { someOptionalString = nil /* - Trying to use ! to access a non-existent optional value triggers a runtime + 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. */ -- cgit v1.2.3 From 0e1a77c065076993a170bc2874987a6289856a9f Mon Sep 17 00:00:00 2001 From: Willie Zhu Date: Sat, 31 Oct 2015 22:31:27 -0400 Subject: [whip/en] Fix typos --- whip.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/whip.html.markdown b/whip.html.markdown index 61c301a5..e7e5e427 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -9,7 +9,7 @@ filename: whip.lisp --- Whip is a LISP-dialect made for scripting and simplified concepts. -It has also borrowed a lot of functions and syntax from Haskell(a non-related language). +It has also borrowed a lot of functions and syntax from Haskell (a non-related language). These docs were written by the creator of the language himself. So is this line. @@ -172,12 +172,12 @@ undefined ; user to indicate a value that hasn't been set ; Comprehensions ; `range` or `..` generates a list of numbers for -; each number between it's two args. +; each number between its two args. (range 1 5) ; => (1 2 3 4 5) (.. 0 2) ; => (0 1 2) -; `map` applies it's first arg(which should be a lambda/function) -; to each item in the following arg(which should be a list) +; `map` applies its first arg (which should be a lambda/function) +; to each item in the following arg (which should be a list) (map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) ; Reduce -- cgit v1.2.3 From 84a1ae46c7bd98906b90e1ae0e8089382e95777f Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sat, 31 Oct 2015 21:02:18 -0600 Subject: Made the rendered text more readable. I formatted the document so that the rendered page is more easily readable. (plus it also serves as even more of an example of how to use Markdown.) #meta --- markdown.html.markdown | 217 +++++++++++++++++++++++++++++-------------------- 1 file changed, 130 insertions(+), 87 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index b956a5f2..f17c2b75 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -2,45 +2,53 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] + - ["Jacob Ward", "http://github.com/JacobCWard/"] filename: markdown.md --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). - -Give me as much feedback as you want! / Feel free to fork and pull request! +Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -```markdown - +element's contents. - +specific to a certain parser. + +- [Headings](#headings) +- [Simple Text Styles](#simple-text-styles) + +## Headings - - +You can create HTML elements `

` through `

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

## This is an

### This is an

#### This is an

##### This is an

###### This is an
+``` +Markdown also provides us with two alternative ways of indicating h1 and h2. - +```markdown This is an h1 ============= This is an h2 ------------- +``` +## Simple text styles - - +Text can be easily styled as italic or bold using markdown. +```markdown *This text is in italics.* _And so is this text._ @@ -50,15 +58,20 @@ __And so is this text.__ ***This text is in both.*** **_As is this!_** *__And this!__* +``` - +In Github Flavored Markdown, which is used to render markdown files on +Github, we also have strikethrough: +```markdown ~~This text is rendered with strikethrough.~~ +``` +## Paragraphs - +Paragraphs are a one or multiple adjacent lines of text separated by one or +multiple blank lines. +```markdown This is a paragraph. I'm typing in a paragraph isn't this fun? Now I'm in paragraph 2. @@ -66,16 +79,20 @@ I'm still in paragraph 2 too! I'm in paragraph three! +``` - +Should you ever want to insert an HTML
tag, you can end a paragraph +with two or more spaces and then begin a new paragraph. +```markdown I end with two spaces (highlight me to see them). There's a
above me! +``` - +Block quotes are easy and done with the > character. +```markdown > This is a block quote. You can either > manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. > It doesn't make a difference so long as they start with a `>`. @@ -84,9 +101,12 @@ There's a
above me! >> of indentation? > How neat is that? - - +``` + +## Lists +Unordered lists can be made using asterisks, pluses, or hyphens. +```markdown * Item * Item * Another item @@ -102,159 +122,182 @@ or - Item - Item - One last item +``` +Ordered lists are done with a number followed by a period. - - +```markdown 1. Item one 2. Item two 3. Item three +``` - +You don't even have to label the items correctly and markdown will still +render the numbers in order, but this may not be a good idea. +```markdown 1. Item one 1. Item two 1. Item three - - - +``` +(This renders the same as the above example) +You can also use sublists +```markdown 1. Item one 2. Item two 3. Item three * Sub-item * Sub-item 4. Item four +``` - +There are even task lists. This creates HTML checkboxes. +```markdown Boxes below without the 'x' are unchecked HTML checkboxes. - [ ] First task to complete. - [ ] Second task that needs done This checkbox below will be a checked HTML checkbox. - [x] This task has been completed +``` + +## Code blocks - - +You can indicate a code block (which uses the `` element) by indenting +a line with four spaces or a tab. +```markdown This is code So is this +``` - +You can also re-tab (or add an additional four spaces) for indentation +inside your code +```markdown my_array.each do |item| puts item end +``` - +Inline code can be created using the backtick character ` +```markdown John didn't even know what the `go_to()` function did! +``` - - +In Github Flavored Markdown, you can use a special syntax for code +```markdown \`\`\`ruby def foobar puts "Hello world!" end \`\`\` +``` - +The above text doesn't require indenting, plus Github will use syntax +highlighting of the language you specify after the \`\`\` - - +## Horizontal rule (`
`) +Horizontal rules are easily added with three or more asterisks or hyphens, +with or without spaces. +```markdown *** --- - - - **************** +``` - - +## Links -[Click me!](http://test.com/) - - +One of the best things about markdown is how easy it is to make links. Put +the text to display in hard brackets [] followed by the url in parentheses () +```markdown +[Click me!](http://test.com/) +``` +You can also add a link title using quotes inside the parentheses. +```markdown [Click me!](http://test.com/ "Link to Test.com") - - - +``` +Relative paths work too. +```markdown [Go to music](/music/). - - - +``` +Markdown also supports reference style links. +```markdown [Click this link][link1] for more info about it! [Also check out this link][foobar] if you want to. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" - - - - +There is also "implicit naming" which lets you use the link text as the id. +```markdown [This][] is a link. [this]: http://thisisalink.com/ +``` +But it's not that commonly used. - - - - - +## Images +Images are done the same way as links but with an exclamation point in front! +```markdown ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") - - - +``` +And reference style works as expected. +```markdown ![This is the alt-attribute.][myimage] [myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" +``` - - - +## Miscellany +### Auto-links +```markdown is equivalent to [http://testwebsite.com/](http://testwebsite.com/) +``` - - +### Auto-links for emails +```markdown +``` - - +### Escaping characters +```markdown I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. +``` - - +### Keyboard keys +In Github Flavored Markdown, you can use a tag to represent keyboard keys. +```markdown Your computer crashed? Try sending a Ctrl+Alt+Del +``` +### Tables - - - +Tables are only available in Github Flavored Markdown and are slightly +cumbersome, but if you really want it: +```markdown | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Left-aligned | Centered | Right-aligned | | blah | blah | blah | +``` +or, for the same results - - +```markdown Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop - - - ``` - +--- For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From cf9c94934533dbd3c96ac35d94bc88e50154c7ac Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sat, 31 Oct 2015 21:09:58 -0600 Subject: in-page navigational links added links to the various sections of the document --- markdown.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index f17c2b75..7be37f81 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -21,6 +21,13 @@ specific to a certain parser. - [Headings](#headings) - [Simple Text Styles](#simple-text-styles) +- [Paragraphs](#paragraphs) +- [Lists](#lists) +- [Code blocks](#code-blocks) +- [Horizontal rule](#horizontal-rule) +- [Links](#links) +- [Images](#images) +- [Miscellany](#miscellany) ## Headings @@ -198,9 +205,9 @@ end The above text doesn't require indenting, plus Github will use syntax highlighting of the language you specify after the \`\`\` -## Horizontal rule (`
`) +## Horizontal rule -Horizontal rules are easily added with three or more asterisks or hyphens, +Horizontal rules (`
`) are easily added with three or more asterisks or hyphens, with or without spaces. ```markdown *** -- cgit v1.2.3 From 06c6c0fe2c03f6479c5906a807a88842b780cce9 Mon Sep 17 00:00:00 2001 From: poetienshul Date: Sat, 31 Oct 2015 23:20:00 -0400 Subject: visualbasic Commenting spacing inconsistency --- visualbasic.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index accdbf56..dfb89307 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -9,13 +9,13 @@ filename: learnvisualbasic.vb Module Module1 Sub Main() - ' A Quick Overview of Visual Basic Console Applications before we dive - ' in to the deep end. - ' Apostrophe starts comments. - ' To Navigate this tutorial within the Visual Basic Complier, I've put - ' together a navigation system. - ' This navigation system is explained however as we go deeper into this - ' tutorial, you'll understand what it all means. + 'A Quick Overview of Visual Basic Console Applications before we dive + 'in to the deep end. + 'Apostrophe starts comments. + 'To Navigate this tutorial within the Visual Basic Complier, I've put + 'together a navigation system. + 'This navigation system is explained however as we go deeper into this + 'tutorial, you'll understand what it all means. Console.Title = ("Learn X in Y Minutes") Console.WriteLine("NAVIGATION") 'Display Console.WriteLine("") @@ -32,9 +32,9 @@ Module Module1 Console.WriteLine("50. About") Console.WriteLine("Please Choose A Number From The Above List") Dim selection As String = Console.ReadLine - ' The "Case" in the Select statement is optional. - ' For example, "Select selection" instead of "Select Case selection" - ' will also work. + 'The "Case" in the Select statement is optional. + 'For example, "Select selection" instead of "Select Case selection" + 'will also work. Select Case selection Case "1" 'HelloWorld Output Console.Clear() 'Clears the application and opens the private sub @@ -91,12 +91,12 @@ Module Module1 'Two Private Sub HelloWorldInput() Console.Title = "Hello World YourName | Learn X in Y Minutes" - ' Variables - ' Data entered by a user needs to be stored. - ' Variables also start with a Dim and end with an As VariableType. + 'Variables + 'Data entered by a user needs to be stored. + 'Variables also start with a Dim and end with an As VariableType. - ' In this tutorial, we want to know what your name, and make the program - ' respond to what is said. + 'In this tutorial, we want to know what your name, and make the program + 'respond to what is said. Dim username As String 'We use string as string is a text based variable. Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. -- cgit v1.2.3 From 244c649f46cad2d3955c97db26772720307647d1 Mon Sep 17 00:00:00 2001 From: ingmrb Date: Sun, 1 Nov 2015 01:40:07 -0300 Subject: [gites] fixed typos --- es-es/git-es.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 18b544b4..4e1e68ba 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -18,11 +18,11 @@ versionar y administrar nuestro código fuente. ## Versionamiento, conceptos. -### Qué es el control de versiones? +### ¿Qué es el control de versiones? El control de versiones es un sistema que guarda todos los cambios realizados en uno o varios archivos, a lo largo del tiempo. -### Versionamiento centralizado vs Versionamiento Distribuido. +### Versionamiento centralizado vs versionamiento distribuido. + El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar archivos. @@ -33,9 +33,9 @@ uno o varios archivos, a lo largo del tiempo. [Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones) -### Por qué usar Git? +### ¿Por qué usar Git? -* Se puede trabajar sin conexion. +* Se puede trabajar sin conexión. * ¡Colaborar con otros es sencillo!. * Derivar, crear ramas del proyecto (aka: Branching) es fácil. * Combinar (aka: Merging) @@ -47,7 +47,7 @@ uno o varios archivos, a lo largo del tiempo. ### Repositorio Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka: -comits), y encabezados (aka: heads). Imagina que un repositorio es una clase, +commits), y encabezados (aka: heads). Imagina que un repositorio es una clase, y que sus atributos otorgan acceso al historial del elemento, además de otras cosas. @@ -62,12 +62,12 @@ y mas. ### Directorio de trabajo (componentes del repositorio) -Es basicamente los directorios y archivos dentro del repositorio. La mayoría de +Es básicamente los directorios y archivos dentro del repositorio. La mayoría de las veces se le llama "directorio de trabajo". ### Índice (componentes del directorio .git) -El índice es el área de inicio en git. Es basicamente la capa que separa el +El índice es el área de inicio en git. Es básicamente la capa que separa el directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores más poder sobre lo que se envía y se recibe del repositorio. -- cgit v1.2.3 -- cgit v1.2.3 From db482790ec142138118a8d71a1a7b17a99cd1491 Mon Sep 17 00:00:00 2001 From: ingmrb Date: Sun, 1 Nov 2015 02:14:51 -0300 Subject: [json/es] fixed typos --- es-es/json-es.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown index fff678eb..c98049f9 100644 --- a/es-es/json-es.html.markdown +++ b/es-es/json-es.html.markdown @@ -21,22 +21,22 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead "llaves": "siempre debe estar entre comillas (ya sean dobles o simples)", "numeros": 0, "strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".", - "soporta booleanos?": true, - "vacios": null, + "¿soporta booleanos?": true, + "vacíos": null, "numero grande": 1.2e+100, "objetos": { - "comentario": "La mayoria de tu estructura vendra de objetos.", + "comentario": "La mayoría de tu estructura vendrá de objetos.", "arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5], "otro objeto": { - "comentario": "Estas cosas pueden estar anidadas, muy util." + "comentario": "Estas cosas pueden estar anidadas, muy útil." } }, - "tonteria": [ + "tontería": [ { "fuentes de potasio": ["bananas"] }, @@ -50,10 +50,10 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead "estilo alternativo": { "comentario": "Mira esto!" - , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido" - , "otro comentario": "que lindo" + , "posición de la coma": "no importa - mientras este antes del valor, entonces sera válido" + , "otro comentario": "qué lindo" }, - "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer." + "eso fue rapido": "Y, estás listo. Ahora sabes todo lo que JSON tiene para ofrecer." } ``` -- cgit v1.2.3 From 471c4b129bceb74c5c38758cebd9851d9f838064 Mon Sep 17 00:00:00 2001 From: ingmrb Date: Sun, 1 Nov 2015 02:16:35 -0300 Subject: [javascript/es] fixed typos --- es-es/javascript-es.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index d475cf42..c5419a21 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -30,7 +30,7 @@ Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto // Cada sentencia puede ser terminada con punto y coma ; hazAlgo(); -// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente +// ... aunque no es necesario, ya que el punto y coma se agrega automáticamente // cada que se detecta una nueva línea, a excepción de algunos casos. hazAlgo() @@ -109,7 +109,7 @@ null == undefined; // = true null === undefined; // false // Los Strings funcionan como arreglos de caracteres -// Puedes accesar a cada caracter con la función charAt() +// Puedes acceder a cada caracter con la función charAt() "Este es un String".charAt(0); // = 'E' // ...o puedes usar la función substring() para acceder a pedazos más grandes @@ -301,7 +301,7 @@ i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, per //inmediatamente", que preveé variables temporales de fugarse al ámbito global (function(){ var temporal = 5; - // Podemos accesar al ámbito global asignando al 'objeto global', el cual + // Podemos acceder al ámbito global asignando al 'objeto global', el cual // en un navegador siempre es 'window'. El objeto global puede tener // un nombre diferente en ambientes distintos, por ejemplo Node.js . window.permanente = 10; @@ -321,7 +321,7 @@ function decirHolaCadaCincoSegundos(nombre){ alert(texto); } setTimeout(interna, 5000); - // setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos + // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos // terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos // Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene // acceso a la variable 'texto' cuando es llamada. @@ -339,7 +339,7 @@ var miObjeto = { }; miObjeto.miFuncion(); // = "¡Hola Mundo!" -// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables +// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables // del objeto con la palabra clave 'this'. miObjeto = { miString: "¡Hola Mundo!", @@ -401,11 +401,11 @@ var MiConstructor = function(){ miNuevoObjeto = new MiConstructor(); // = {miNumero: 5} miNuevoObjeto.miNumero; // = 5 -// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una +// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a acceder a una // propiedad en un objeto que no existe en el objeto el intérprete buscará en // el prototipo. -// Algunas implementaciones de JavaScript te permiten accesar al prototipo de +// Algunas implementaciones de JavaScript te permiten acceder al prototipo de // un objeto con la propiedad __proto__. Mientras que esto es útil para explicar // prototipos, no es parte del estándar; veremos formas estándar de usar prototipos // más adelante. @@ -440,7 +440,7 @@ miPrototipo.sentidoDeLaVida = 43; miObjeto.sentidoDeLaVida; // = 43 // Mencionabamos anteriormente que __proto__ no está estandarizado, y que no -// existe una forma estándar de accesar al prototipo de un objeto. De todas formas. +// existe una forma estándar de acceder al prototipo de un objeto. De todas formas. // hay dos formas de crear un nuevo objeto con un prototipo dado. // El primer método es Object.create, el cual es una adición reciente a JavaScript, -- cgit v1.2.3 From 5b58fae6a3770341207e810a466c0be863d80782 Mon Sep 17 00:00:00 2001 From: ingmrb Date: Sun, 1 Nov 2015 02:19:50 -0300 Subject: [javascript /es] fixed typos. --- es-es/javascript-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index c5419a21..3273f7ad 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -186,7 +186,7 @@ miObjeto.miLlave; // = "miValor" // agregar nuevas llaves. miObjeto.miTerceraLlave = true; -// Si intentas accesar con una llave que aún no está asignada tendrás undefined. +// Si intentas acceder con una llave que aún no está asignada tendrás undefined. miObjeto.miCuartaLlave; // = undefined /////////////////////////////////// -- cgit v1.2.3 From a3b69a2275c343d4e5b4e58d6eb4010517e0eef9 Mon Sep 17 00:00:00 2001 From: ingmrb Date: Sun, 1 Nov 2015 02:24:00 -0300 Subject: [javascript /es] typo --- es-es/javascript-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 3273f7ad..9ef0c63e 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -476,7 +476,7 @@ typeof miNumero; // = 'number' typeof miNumeroObjeto; // = 'object' miNumero === miNumeroObjeyo; // = false if (0){ - // Este código no se ejecutara porque 0 es false. + // Este código no se ejecutará porque 0 es false. } // Aún así, los objetos que envuelven y los prototipos por defecto comparten -- cgit v1.2.3 From 09c3177531eacd476ec4e822ddc485439e22c4b8 Mon Sep 17 00:00:00 2001 From: Saravanan Ganesh Date: Sat, 31 Oct 2015 22:55:11 -0700 Subject: [less/en] Add Less tutorial, similar to sass --- less.html.markdown | 379 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 379 insertions(+) create mode 100644 less.html.markdown diff --git a/less.html.markdown b/less.html.markdown new file mode 100644 index 00000000..41d66a54 --- /dev/null +++ b/less.html.markdown @@ -0,0 +1,379 @@ +--- +language: less +filename: learnless.less +contributors: + - ["Saravanan Ganesh", "http://srrvnn.me"] +--- + +Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. +Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code. + +```less + + +//Single line comments are removed when Less is compiled to CSS. + +/*Multi line comments are preserved. */ + + +/*Variables +==============================*/ + + + +/* You can store a CSS value (such as a color) in a variable. +Use the '@' symbol to create a variable. */ + +@primary-color: #A3A4FF; +@secondary-color: #51527F; +@body-font: 'Roboto', sans-serif; + +/* You can use the variables throughout your stylesheet. +Now if you want to change a color, you only have to make the change once.*/ + +body { + background-color: @primary-color; + color: @secondary-color; + font-family: @body-font; +} + +/* This would compile to: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* This is much more maintainable than having to change the color +each time it appears throughout your stylesheet. */ + + +/*Mixins +==============================*/ + + + +/* If you find you are writing the same code for more than one +element, you might want to reuse that easily.*/ + +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* You can use the mixin by simply adding the selector as a style */ + +div { + .center; + background-color: @primary-color; +} + +/*Which would compile to: */ +.center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + +/* You can omit the mixin code from being compiled by adding paranthesis + after the selector */ + +.center() { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +div { + .center; + background-color: @primary-color; +} + +/*Which would compile to: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/*Functions +==============================*/ + + + +/* Less provides functions that can be used to accomplish a variety of + tasks. Consider the following */ + +/* Functions can be invoked by using their name and passing in the + required arguments */ +body { + width: round(10.25px); +} + +.footer { + background-color: fadeout(#000000, 0.25) +} + +/* Compiles to: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* You may also define your own functions. Functions are very similar to + mixins. When trying to choose between a function or a mixin, remember + that mixins are best for generating CSS while functions are better for + logic that might be used throughout your Less code. The examples in + the Math Operators' section are ideal candidates for becoming a reusable + function. */ + +/* This function will take a target size and the parent size and calculate + and return the percentage */ + +.average(@x, @y) { + @average_result: ((@x + @y) / 2); +} + +div { + .average(16px, 50px); // "call" the mixin + padding: @average_result; // use its "return" value +} + +/* Compiles to: */ + +div { + padding: 33px; +} + +/*Extend (Inheritance) +==============================*/ + + + +/*Extend is a way to share the properties of one selector with another. */ + +.display { + height: 50px; +} + +.display-success { + &:extend(.display); + border-color: #22df56; +} + +/* Compiles to: */ +.display, +.display-success { + height: 50px; +} +.display-success { + border-color: #22df56; +} + +/* Extending a CSS statement is preferable to creating a mixin + because of the way it groups together the classes that all share + the same base styling. If this was done with a mixin, the properties + would be duplicated for each statement that + called the mixin. While it won't affect your workflow, it will + add unnecessary bloat to the files created by the Less compiler. */ + + + +/*Nesting +==============================*/ + + + +/*Less allows you to nest selectors within selectors */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' will be replaced by the parent selector. */ +/* You can also nest pseudo-classes. */ +/* Keep in mind that over-nesting will make your code less maintainable. +Best practices recommend going no more than 3 levels deep when nesting. +For example: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compiles to: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/*Partials and Imports +==============================*/ + + + +/* Less allows you to create partial files. This can help keep your Less + code modularized. Partial files conventionally begin with an '_', + e.g. _reset.less. and are imported into a main less file that gets + compiled into CSS */ + +/* Consider the following CSS which we'll put in a file called _reset.less */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Less offers @import which can be used to import partials into a file. + This differs from the traditional CSS @import statement which makes + another HTTP request to fetch the imported file. Less takes the + imported file and combines it with the compiled code. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compiles to: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + +/*Math Operations +==============================*/ + + + +/* Less provides the following operators: +, -, *, /, and %. These can + be useful for calculating values directly in your Less files instead + of using values that you've already calculated by hand. Below is an example + of a setting up a simple two column design. */ + +@content-area: 960px; +@main-content: 600px; +@sidebar-content: 300px; + +@main-size: @main-content / @content-area * 100%; +@sidebar-size: @sidebar-content / @content-area * 100%; +@gutter: 100% - (@main-size + @sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: @main-size; +} + +.sidebar { + width: @sidebar-size; +} + +.gutter { + width: @gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + +## Practice Less + +If you want to play with Less in your browser, check out [LESS2CSS](http://lesscss.org/less-preview/). + +## Compatibility + +Less can be used in any project as long as you have a program to compile it +into CSS. You'll want to verify that the CSS you're using is compatible +with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility. + +## Further reading +* [Official Documentation](http://lesscss.org/features/) -- cgit v1.2.3 From ecdd217522a1f1b70dd1abca720e36f24622db6d Mon Sep 17 00:00:00 2001 From: Ramanan Balakrishnan Date: Sat, 31 Oct 2015 23:35:20 -0700 Subject: [latex/en] Explain how to setup a bibliography section --- latex.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/latex.html.markdown b/latex.html.markdown index 31231a70..e89d7e3b 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -227,6 +227,15 @@ format you defined in Step 1. That's all for now! +% Most often, you would want to have a references section in your document. +% The easiest way to set this up would be by using the bibliography section +\begin{thebibliography}{1} + % similar to other lists, the \bibitem command can be used to list items + % each entry can then be cited directly in the body of the text + \bibitem{latexwiki} The amazing LaTeX wikibook: {\em https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} An actual tutorial: {\em http://www.latex-tutorial.com} +\end{thebibliography} + % end the document \end{document} ``` -- cgit v1.2.3 From 96f0b3b3903c6f619b4a964a98e1cb0a463c47e6 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 00:03:58 +0800 Subject: Transated Python 2 to zh-tw. Line 01 .. 143 --- zh-tw/python-tw.html.markdown | 731 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 731 insertions(+) create mode 100644 zh-tw/python-tw.html.markdown diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown new file mode 100644 index 00000000..8381f325 --- /dev/null +++ b/zh-tw/python-tw.html.markdown @@ -0,0 +1,731 @@ +--- +language: python +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] +translators: + - ["Michael Yeh", "https://github.com/hinet60613"] +filename: learnpython.py +--- + +Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 + +非常歡迎各位給我們任何回饋! 你可以在[@louiedinh](http://twitter.com/louiedinh) 或 louiedinh [at] [google's email service]聯絡到我。 + +註: 本篇文章適用的版本為Python 2.7,但大部分的Python 2.X版本應該都適用。 Python 2.7將會在2020年停止維護,因此建議您可以從Python 3開始學Python。 +Python 3.X可以看這篇[Python 3 教學 (英文)](http://learnxinyminutes.com/docs/python3/). + +讓程式碼同時支援Python 2.7和3.X是可以做到的,只要引入 + [`__future__` imports](https://docs.python.org/2/library/__future__.html) 模組. + `__future__` 模組允許你撰寫可以在Python 2上執行的Python 3程式碼,詳細訊息請參考Python 3 教學。 + +```python + +# 單行註解從井字號開始 + +""" 多行字串可以用三個雙引號 + 包住,不過通常這種寫法會 + 被拿來當作多行註解 +""" + +#################################################### +## 1. 原始型別與運算元 +#################################################### + +# 你可以使用數字 +3 # => 3 + +# 還有四則運算 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# 除法比較麻煩,除以整數時會自動捨去小數位。 +5 / 2 # => 2 + +# 要做精確的除法,我們需要浮點數 +2.0 # 浮點數 +11.0 / 4.0 # => 2.75 精確多了! + +# 整數除法的無條件捨去對正數或負數都適用 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # 浮點數的整數也適用 +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# 我們可以用除法模組(參考第六節:模組),讓 +# 單一斜線代表普通除法,而非無條件捨去 +from __future__ import division +11/4 # => 2.75 ...普通除法 +11//4 # => 2 ...無條件捨去 + +# 取餘數 +7 % 3 # => 1 + +# 指數 (x的y次方) +2**4 # => 16 + +# 括號即先乘除後加減 +(1 + 3) * 2 # => 8 + +# 布林運算 +# 注意 "and" 和 "or" 的大小寫 +True and False #=> False +False or True #=> True + +# 用整數與布林值做運算 +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# 用not取反向 +not True # => False +not False # => True + +# 等於判斷是用 == +1 == 1 # => True +2 == 1 # => False + +# 不等於判斷是用 != +1 != 1 # => False +2 != 1 # => True + +# 更多比較 +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# 比較是可以串接的 +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# 字串用單引號 ' 或雙引號 " 建立 +"This is a string." +'This is also a string.' + +# 字串相加會被串接再一起 +"Hello " + "world!" # => "Hello world!" +# 不用加號也可以做字串相加 +"Hello " "world!" # => "Hello world!" + +# ... 也可以做相乘 +"Hello" * 3 # => "HelloHelloHello" + +# 字串可以被視為字元的陣列 +"This is a string"[0] # => 'T' + +# 字串的格式化可以用百分之符號 % +# 儘管在Python 3.1後這個功能被廢棄了,並且在 +# 之後的版本會被移除,但還是可以了解一下 +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y) + +# 新的格式化方式是使用format函式 +# 這個方式也是較為推薦的 +"{} is a {}".format("This", "placeholder") +"{0} can be {1}".format("strings", "formatted") +# 你也可以用關鍵字,如果你不想數你是要用第幾個變數的話 +"{name} wants to eat {food}".format(name="Bob", food="lasagna") + +# 無(None) 是一個物件 +None # => None + +# 不要用等於符號 "==" 對 無(None)做比較 +# 用 "is" +"etc" is None # => False +None is None # => True + +# The 'is' operator tests for object identity. This isn't +# very useful when dealing with primitive values, but is +# very useful when dealing with objects. + +# Any object can be used in a Boolean context. +# The following values are considered falsey: +# - None +# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) +# - empty sequences (e.g., '', (), []) +# - empty containers (e.g., {}, set()) +# - instances of user-defined classes meeting certain conditions +# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# All other values are truthy (using the bool() function on them returns True). +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Variables and Collections +#################################################### + +# Python has a print statement +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Simple way to get input data from console +input_string_var = raw_input("Enter some data: ") # Returns the data as a string +input_var = input("Enter some data: ") # Evaluates the data as python code +# Warning: Caution is recommended for input() method usage +# Note: In python 3, input() is deprecated and raw_input() is renamed to input() + +# No need to declare variables before assigning to them. +some_var = 5 # Convention is to use lower_case_with_underscores +some_var # => 5 + +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_other_var # Raises a name error + +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Lists store sequences +li = [] +# You can start with a prefilled list +other_li = [4, 5, 6] + +# Add stuff to the end of a list with append +li.append(1) # li is now [1] +li.append(2) # li is now [1, 2] +li.append(4) # li is now [1, 2, 4] +li.append(3) # li is now [1, 2, 4, 3] +# Remove from the end with pop +li.pop() # => 3 and li is now [1, 2, 4] +# Let's put it back +li.append(3) # li is now [1, 2, 4, 3] again. + +# Access a list like you would any array +li[0] # => 1 +# Assign new values to indexes that have already been initialized with = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Note: setting it back to the original value +# Look at the last element +li[-1] # => 3 + +# Looking out of bounds is an IndexError +li[4] # Raises an IndexError + +# You can look at ranges with slice syntax. +# (It's a closed/open range for you mathy types.) +li[1:3] # => [2, 4] +# Omit the beginning +li[2:] # => [4, 3] +# Omit the end +li[:3] # => [1, 2, 4] +# Select every second entry +li[::2] # =>[1, 4] +# Reverse a copy of the list +li[::-1] # => [3, 4, 2, 1] +# Use any combination of these to make advanced slices +# li[start:end:step] + +# Remove arbitrary elements from a list with "del" +del li[2] # li is now [1, 2, 3] + +# You can add lists +li + other_li # => [1, 2, 3, 4, 5, 6] +# Note: values for li and for other_li are not modified. + +# Concatenate lists with "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3, 4, 5, 6] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again + +# Get the index of the first item found +li.index(2) # => 1 +li.index(7) # Raises a ValueError as 7 is not in the list + +# Check for existence in a list with "in" +1 in li # => True + +# Examine the length with "len()" +len(li) # => 6 + + +# Tuples are like lists but are immutable. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Raises a TypeError + +# You can do all those list thingies on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# You can unpack tuples (or lists) into variables +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +d, e, f = 4, 5, 6 # you can leave out the parentheses +# Tuples are created by default if you leave out the parentheses +g = 4, 5, 6 # => (4, 5, 6) +# Now look how easy it is to swap two values +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = {} +# Here is a prefilled dictionary +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys as a list with "keys()" +filled_dict.keys() # => ["three", "two", "one"] +# Note - Dictionary key ordering is not guaranteed. +# Your results might not match this exactly. + +# Get all values as a list with "values()" +filled_dict.values() # => [3, 2, 1] +# Note - Same as above regarding key ordering. + +# Check for existence of keys in a dictionary with "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError + +# Use "get()" method to avoid the KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# The get method supports a default argument when the value is missing +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# note that filled_dict.get("four") is still => None +# (get doesn't set the value in the dictionary) + +# set the value of a key with a syntax similar to lists +filled_dict["four"] = 4 # now, filled_dict["four"] => 4 + +# "setdefault()" inserts into a dictionary only if the given key isn't present +filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 + + +# Sets store ... well sets (which are like lists but can contain no duplicates) +empty_set = set() +# Initialize a "set()" with a bunch of values +some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) + +# order is not guaranteed, even though it may sometimes look sorted +another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) + +# Since Python 2.7, {} can be used to declare a set +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Add more items to a set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} + +# Do set intersection with & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Do set union with | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Do set difference with - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + +# Check for existence in a set with in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Control Flow +#################################################### + +# Let's just make a variable +some_var = 5 + +# Here is an if statement. Indentation is significant in python! +# prints "some_var is smaller than 10" +if some_var > 10: + print "some_var is totally bigger than 10." +elif some_var < 10: # This elif clause is optional. + print "some_var is smaller than 10." +else: # This is optional too. + print "some_var is indeed 10." + + +""" +For loops iterate over lists +prints: + dog is a mammal + cat is a mammal + mouse is a mammal +""" +for animal in ["dog", "cat", "mouse"]: + # You can use {0} to interpolate formatted strings. (See above.) + print "{0} is a mammal".format(animal) + +""" +"range(number)" returns a list of numbers +from zero to the given number +prints: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(lower, upper)" returns a list of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +While loops go until a condition is no longer met. +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Shorthand for x = x + 1 + +# Handle exceptions with a try/except block + +# Works on Python 2.6 and up: +try: + # Use "raise" to raise an error + raise IndexError("This is an index error") +except IndexError as e: + pass # Pass is just a no-op. Usually you would do recovery here. +except (TypeError, NameError): + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks + print "All good!" # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print "We can clean up resources here" + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print line + +#################################################### +## 4. Functions +#################################################### + +# Use "def" to create new functions +def add(x, y): + print "x is {0} and y is {1}".format(x, y) + return x + y # Return values with a return statement + +# Calling functions with parameters +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 + +# Another way to call functions is with keyword arguments +add(y=6, x=5) # Keyword arguments can arrive in any order. + + +# You can define functions that take a variable number of +# positional args, which will be interpreted as a tuple if you do not use the * +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# You can define functions that take a variable number of +# keyword args, as well, which will be interpreted as a dict if you do not use ** +def keyword_args(**kwargs): + return kwargs + +# Let's call it to see what happens +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# You can do both at once, if you like +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) prints: + (1, 2) + {"a": 3, "b": 4} +""" + +# When calling functions, you can do the opposite of args/kwargs! +# Use * to expand positional args and use ** to expand keyword args. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) + +# you can pass args and kwargs along to other functions that take args/kwargs +# by expanding them with * and ** respectively +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Function Scope +x = 5 + +def set_x(num): + # Local var x not the same as global variable x + x = num # => 43 + print x # => 43 + +def set_global_x(num): + global x + print x # => 5 + x = num # global var x is now set to 6 + print x # => 6 + +set_x(43) +set_global_x(6) + +# Python has first class functions +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# There are also anonymous functions +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# There are built-in higher order functions +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nice maps and filters +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. Classes +#################################################### + +# We subclass from object to get a class. +class Human(object): + + # A class attribute. It is shared by all instances of this class + species = "H. sapiens" + + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. You should not invent such names on your own. + def __init__(self, name): + # Assign the argument to the instance's name attribute + self.name = name + + # Initialize property + self.age = 0 + + + # An instance method. All methods take "self" as the first argument + def say(self, msg): + return "{0}: {1}".format(self.name, msg) + + # A class method is shared among all instances + # They are called with the calling class as the first argument + @classmethod + def get_species(cls): + return cls.species + + # A static method is called without a class or instance reference + @staticmethod + def grunt(): + return "*grunt*" + + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + + +# Instantiate a class +i = Human(name="Ian") +print i.say("hi") # prints out "Ian: hi" + +j = Human("Joel") +print j.say("hello") # prints out "Joel: hello" + +# Call our class method +i.get_species() # => "H. sapiens" + +# Change the shared attribute +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Call the static method +Human.grunt() # => "*grunt*" + +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + + +#################################################### +## 6. Modules +#################################################### + +# You can import modules +import math +print math.sqrt(16) # => 4 + +# You can get specific functions from a module +from math import ceil, floor +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# you can also test that the functions are equivalent +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + + +#################################################### +## 7. Advanced +#################################################### + +# Generators help you make lazy code +def double_numbers(iterable): + for i in iterable: + yield i + i + +# A generator creates values on the fly. +# Instead of generating and returning all values at once it creates one in each +# iteration. This means values bigger than 15 wont be processed in +# double_numbers. +# Note xrange is a generator that does the same thing range does. +# Creating a list 1-900000000 would take lot of time and space to be made. +# xrange creates an xrange generator object instead of creating the entire list +# like range does. +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +xrange_ = xrange(1, 900000000) + +# will double all numbers until a result >=30 found +for i in double_numbers(xrange_): + print i + if i >= 30: + break + + +# Decorators +# in this example beg wraps say +# Beg will call say. If say_please is True then it will change the returned +# message +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( +``` + +## Ready For More? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 09cd1ab461ad8b560824f687cc818d7708aea427 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 00:40:41 +0800 Subject: Add lang of translation. Translate to Line 255 --- zh-tw/python-tw.html.markdown | 129 +++++++++++++++++++++--------------------- 1 file changed, 65 insertions(+), 64 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 8381f325..8e9ca79a 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -8,6 +8,7 @@ contributors: translators: - ["Michael Yeh", "https://github.com/hinet60613"] filename: learnpython.py +lang: zh-tw --- Python是在1990年代早期由Guido Van Rossum創建的。它是現在最流行的程式語言之一。我愛上Python是因為他極為清晰的語法,甚至可以說它就是可執行的虛擬碼。 @@ -142,115 +143,115 @@ None # => None "etc" is None # => False None is None # => True -# The 'is' operator tests for object identity. This isn't -# very useful when dealing with primitive values, but is -# very useful when dealing with objects. - -# Any object can be used in a Boolean context. -# The following values are considered falsey: -# - None -# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) -# - empty sequences (e.g., '', (), []) -# - empty containers (e.g., {}, set()) -# - instances of user-defined classes meeting certain conditions -# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# 'is' 運算元是用來識別物件的。對原始型別來說或許沒什麼用, +# 但對物件來說是很有用的。 + +# 任何物件都可以被當作布林值使用 +# 以下的值會被視為是False : +# - 無(None) +# - 任何型別的零 (例如: 0, 0L, 0.0, 0j) +# - 空序列 (例如: '', (), []) +# - 空容器 (例如: {}, set()) +# - 自定義型別的實體,且滿足某些條件 +# 請參考文件: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ # -# All other values are truthy (using the bool() function on them returns True). +# 其餘的值都會被視為True (用bool()函式讓他們回傳布林值). bool(0) # => False bool("") # => False #################################################### -## 2. Variables and Collections +## 2. 變數與集合 #################################################### -# Python has a print statement +# Python的輸出很方便 print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! -# Simple way to get input data from console -input_string_var = raw_input("Enter some data: ") # Returns the data as a string -input_var = input("Enter some data: ") # Evaluates the data as python code -# Warning: Caution is recommended for input() method usage -# Note: In python 3, input() is deprecated and raw_input() is renamed to input() +# 從命令列獲得值也很方便 +input_string_var = raw_input("Enter some data: ") # 資料會被視為字串存進變數 +input_var = input("Enter some data: ") # 輸入的資料會被當作Python程式碼執行 +# 注意: 請謹慎使用input()函式 +# 註: 在Python 3中,input()已被棄用,raw_input()已被更名為input() -# No need to declare variables before assigning to them. -some_var = 5 # Convention is to use lower_case_with_underscores +# 使用變數前不需要先宣告 +some_var = 5 # 方便好用 +lower_case_with_underscores some_var # => 5 -# Accessing a previously unassigned variable is an exception. -# See Control Flow to learn more about exception handling. -some_other_var # Raises a name error +# 存取沒有被賦值的變數會造成例外 +# 請參考錯誤流程部分做例外處理 +some_other_var # 造成 NameError -# if can be used as an expression -# Equivalent of C's '?:' ternary operator +# if可以當判斷式使用 +# 相當於C語言中的二元判斷式 "yahoo!" if 3 > 2 else 2 # => "yahoo!" -# Lists store sequences +# 串列型態可以儲存集合 li = [] -# You can start with a prefilled list +# 你可以預先填好串列內容 other_li = [4, 5, 6] -# Add stuff to the end of a list with append -li.append(1) # li is now [1] -li.append(2) # li is now [1, 2] -li.append(4) # li is now [1, 2, 4] -li.append(3) # li is now [1, 2, 4, 3] -# Remove from the end with pop +# 用append()在串列後新增東西 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 and li is now [1, 2, 4] -# Let's put it back +# 然後再塞回去 li.append(3) # li is now [1, 2, 4, 3] again. -# Access a list like you would any array +# 你可以像存取陣列一樣的存取串列 li[0] # => 1 -# Assign new values to indexes that have already been initialized with = +# 用等號 = 給串列中特定索引的元素賦值 li[0] = 42 li[0] # => 42 -li[0] = 1 # Note: setting it back to the original value -# Look at the last element +li[0] = 1 # 註: 將其設定回原本的值 +# 用 -1 索引值查看串列最後一個元素 li[-1] # => 3 -# Looking out of bounds is an IndexError +# 存取超過範圍會產生IndexError li[4] # Raises an IndexError -# You can look at ranges with slice syntax. -# (It's a closed/open range for you mathy types.) +# 你可以用切片語法來存取特定範圍的值 +# (相當於數學中的左閉右開區間,即包含最左邊界,但不包含右邊界) li[1:3] # => [2, 4] -# Omit the beginning +# 略過開頭元素 li[2:] # => [4, 3] -# Omit the end +# 略過結尾元素 li[:3] # => [1, 2, 4] -# Select every second entry +# 每隔兩個元素取值 li[::2] # =>[1, 4] -# Reverse a copy of the list +# 串列反轉 li[::-1] # => [3, 4, 2, 1] -# Use any combination of these to make advanced slices -# li[start:end:step] +# 你可以任意組合來達到你想要的效果 +# li[開始索引:結束索引:間隔] -# Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] +# 用 "del" 從串列中移除任意元素 +del li[2] # 現在 li 內容為 [1, 2, 3] -# You can add lists +# 你可以做串列相加 li + other_li # => [1, 2, 3, 4, 5, 6] -# Note: values for li and for other_li are not modified. +# 註: li 及 other_li 沒有被更動 -# Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +# 用 "extend()" 做串列串接 +li.extend(other_li) # 現在 li 內容為 [1, 2, 3, 4, 5, 6] -# Remove first occurrence of a value -li.remove(2) # li is now [1, 3, 4, 5, 6] -li.remove(2) # Raises a ValueError as 2 is not in the list +# 移除特定值的第一次出現 +li.remove(2) # 現在 li 內容為 [1, 3, 4, 5, 6] +li.remove(2) # 2 不在串列中,造成 ValueError -# Insert an element at a specific index -li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again +# 在特定位置插入值 +li.insert(1, 2) # 現在 li 內容再次回復為 [1, 2, 3, 4, 5, 6] -# Get the index of the first item found +# 取得特定值在串列中第一次出現的位置 li.index(2) # => 1 -li.index(7) # Raises a ValueError as 7 is not in the list +li.index(7) # 7 不在串列中,造成 ValueError -# Check for existence in a list with "in" +# 用 "in" 檢查特定值是否出現在串列中 1 in li # => True -# Examine the length with "len()" +# 用 "len()" 取得串列長度 len(li) # => 6 -- cgit v1.2.3 From 6c9bf0dc5bccf644439346763f36b047a898a694 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:06:40 +0800 Subject: Translate to Sec. 4 finished. --- zh-tw/python-tw.html.markdown | 197 +++++++++++++++++++++--------------------- 1 file changed, 100 insertions(+), 97 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 8e9ca79a..073c5e91 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Andre Polykanine", "https://github.com/Oire"] - ["evuez", "http://github.com/evuez"] translators: - - ["Michael Yeh", "https://github.com/hinet60613"] + - ["Michael Yeh", "https://hinet60613.github.io/"] filename: learnpython.py lang: zh-tw --- @@ -255,137 +255,139 @@ li.index(7) # 7 不在串列中,造成 ValueError len(li) # => 6 -# Tuples are like lists but are immutable. +# 元組(Tuple,以下仍用原文)類似於串列,但是它是不可改變的 tup = (1, 2, 3) tup[0] # => 1 -tup[0] = 3 # Raises a TypeError +tup[0] = 3 # 產生TypeError -# You can do all those list thingies on tuples too +# 能對串列做的東西都可以對tuple做 len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True -# You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 -d, e, f = 4, 5, 6 # you can leave out the parentheses -# Tuples are created by default if you leave out the parentheses +# 你可以把tuple拆開並分別將值存入不同變數 +a, b, c = (1, 2, 3) # a 現在是 1, b 現在是 2, c 現在是 3 +d, e, f = 4, 5, 6 # 也可以不寫括號 +# 如果不加括號,預設會產生tuple g = 4, 5, 6 # => (4, 5, 6) -# Now look how easy it is to swap two values +# 你看,交換兩個值很簡單吧 e, d = d, e # d is now 5 and e is now 4 -# Dictionaries store mappings +# 字典(Dictionary)用來儲存映射關係 empty_dict = {} -# Here is a prefilled dictionary +# 你可以對字典做初始化 filled_dict = {"one": 1, "two": 2, "three": 3} -# Look up values with [] +# 用 [] 取值 filled_dict["one"] # => 1 -# Get all keys as a list with "keys()" +# 用 "keys()" 將所有的Key輸出到一個List中 filled_dict.keys() # => ["three", "two", "one"] -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. +# 註: 字典裡key的排序是不固定的 +# 你的執行結果可能與上面不同 +# 譯註: 只能保證所有的key都有出現,但不保證順序 -# Get all values as a list with "values()" +# 用 "valuess()" 將所有的Value輸出到一個List中 filled_dict.values() # => [3, 2, 1] -# Note - Same as above regarding key ordering. +# 註: 同上,不保證順序 -# Check for existence of keys in a dictionary with "in" +# 用 "in" 來檢查指定的Key是否在字典中 "one" in filled_dict # => True 1 in filled_dict # => False -# Looking up a non-existing key is a KeyError +# 查詢不存在的Key會造成KeyError filled_dict["four"] # KeyError -# Use "get()" method to avoid the KeyError +# 用 "get()" 來避免KeyError +# 若指定的Key不存在的話會得到None filled_dict.get("one") # => 1 filled_dict.get("four") # => None -# The get method supports a default argument when the value is missing +# "get()" 函式支援預設值,當找不到指定的值時,會回傳指定的預設值 filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 -# note that filled_dict.get("four") is still => None -# (get doesn't set the value in the dictionary) +# 注意此時 filled_dict.get("four") 仍然為 None +# (get()此時並沒有產生出任何的值) -# set the value of a key with a syntax similar to lists -filled_dict["four"] = 4 # now, filled_dict["four"] => 4 +# 像操作list一樣,對指定的Key賦值 +filled_dict["four"] = 4 # 此時 filled_dict["four"] => 4 -# "setdefault()" inserts into a dictionary only if the given key isn't present -filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 -filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 +# "setdefault()" 只在指定的Key不存在時才會將值插入dictionary +filled_dict.setdefault("five", 5) # filled_dict["five"] 被指定為 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] 仍保持 5 -# Sets store ... well sets (which are like lists but can contain no duplicates) +# 集合(Set)被用來儲存...集合。 +# 跟串列(List)有點像,但集合內不會有重複的元素 empty_set = set() -# Initialize a "set()" with a bunch of values -some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) +# 初始化 "set()" 並給定一些值 +some_set = set([1, 2, 2, 3, 4]) # 現在 some_set 為 set([1, 2, 3, 4]),注意重複的元素只有一個會被存入 -# order is not guaranteed, even though it may sometimes look sorted -another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) +# 一樣,不保證順序,就算真的有照順序排也只是你運氣好 +another_set = set([4, 3, 2, 2, 1]) # another_set 現在為 set([1, 2, 3, 4]) -# Since Python 2.7, {} can be used to declare a set +# 從 Python 2.7 開始,可以使用大括號 {} 來宣告Set filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} -# Add more items to a set +# 加入更多元素進入Set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} -# Do set intersection with & +# 用 & 來對兩個集合取交集 other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} -# Do set union with | +# 用 | 來對兩個集合取聯集 filled_set | other_set # => {1, 2, 3, 4, 5, 6} -# Do set difference with - +# 用 - 來將第二個集合內有的元素移出第一個集合 {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} -# Do set symmetric difference with ^ +# 用 ^ 來對兩個集合取差集 {1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} -# Check if set on the left is a superset of set on the right +# 檢查左邊是否為右邊的母集 {1, 2} >= {1, 2, 3} # => False -# Check if set on the left is a subset of set on the right +# 檢查左邊是否為右邊的子集 {1, 2} <= {1, 2, 3} # => True -# Check for existence in a set with in +# 用 in 來檢查某元素是否存在於集合內 2 in filled_set # => True 10 in filled_set # => False #################################################### -## 3. Control Flow +## 3. 控制流程 #################################################### -# Let's just make a variable +# 首先,先宣告一個變數 some_var = 5 -# Here is an if statement. Indentation is significant in python! -# prints "some_var is smaller than 10" +# 這邊是 if 判斷式。注意,縮排對Python是很重要的。 +# 下面應該會印出 "some_var is smaller than 10" if some_var > 10: print "some_var is totally bigger than 10." -elif some_var < 10: # This elif clause is optional. +elif some_var < 10: # elif 可有可無 print "some_var is smaller than 10." -else: # This is optional too. +else: # else 也可有可無 print "some_var is indeed 10." """ -For loops iterate over lists -prints: +For 迴圈會遞迴整的List +下面的程式碼會輸出: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: - # You can use {0} to interpolate formatted strings. (See above.) + # 你可以用{0}來組合0出格式化字串 (見上面.) print "{0} is a mammal".format(animal) """ -"range(number)" returns a list of numbers -from zero to the given number -prints: +"range(number)" 回傳一個包含從0到給定值的數字List, +下面的程式碼會輸出: 0 1 2 @@ -395,9 +397,9 @@ for i in range(4): print i """ -"range(lower, upper)" returns a list of numbers -from the lower number to the upper number -prints: +"range(lower, upper)" 回傳一個包含從給定的下限 +到給定的上限的數字List +下面的程式碼會輸出: 4 5 6 @@ -407,8 +409,8 @@ for i in range(4, 8): print i """ -While loops go until a condition is no longer met. -prints: +While迴圈會執行到條件不成立為止 +下面的程式碼會輸出: 0 1 2 @@ -417,62 +419,62 @@ prints: x = 0 while x < 4: print x - x += 1 # Shorthand for x = x + 1 + x += 1 # x = x + 1 的簡寫 -# Handle exceptions with a try/except block +# 用try/except處理例外 -# Works on Python 2.6 and up: +# 適用Python 2.6及以上版本 try: - # Use "raise" to raise an error + # 用 "raise" 來發起例外 raise IndexError("This is an index error") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # 毫無反應,就只是個什麼都沒做的pass。通常這邊會讓你做對例外的處理 except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks - print "All good!" # Runs only if the code in try raises no exceptions -finally: # Execute under all circumstances + pass # 有需要的話,多種例外可以一起處理 +else: # else 可有可無,但必須寫在所有的except後 + print "All good!" # 只有在try的時候沒有產生任何except才會被執行 +finally: # 不管什麼情況下一定會被執行 print "We can clean up resources here" -# Instead of try/finally to cleanup resources you can use a with statement +# 除了try/finally以外,你可以用 with 來簡單的處理清理動作 with open("myfile.txt") as f: for line in f: print line #################################################### -## 4. Functions +## 4. 函式 #################################################### -# Use "def" to create new functions +# 用 "def" 來建立新函式 def add(x, y): print "x is {0} and y is {1}".format(x, y) - return x + y # Return values with a return statement + return x + y # 用 "return" 來回傳值 -# Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +# 用參數來呼叫韓式 +add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 -# Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +# 你也可以寫上參數名稱來呼叫函式 +add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 -# You can define functions that take a variable number of -# positional args, which will be interpreted as a tuple if you do not use the * +# 你可以定義接受多個變數的函式,這些變數是按照順序排序的 +# 如果不加*的話會被解讀為tuple def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) -# You can define functions that take a variable number of -# keyword args, as well, which will be interpreted as a dict if you do not use ** +# 你可以定義接受多個變數的函式,這些變數是按照keyword排序的 +# 如果不加**的話會被解讀為dictionary def keyword_args(**kwargs): return kwargs -# Let's call it to see what happens +# 呼叫看看會發生什麼事吧 keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} -# You can do both at once, if you like +# 如果你想要,你也可以兩個同時用 def all_the_args(*args, **kwargs): print args print kwargs @@ -482,39 +484,40 @@ all_the_args(1, 2, a=3, b=4) prints: {"a": 3, "b": 4} """ -# When calling functions, you can do the opposite of args/kwargs! -# Use * to expand positional args and use ** to expand keyword args. +# 呼叫函式時,你可以做反向的操作 +# 用 * 將變數展開為順序排序的變數 +# 用 ** 將變數展開為Keyword排序的變數 args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # 等同於 foo(1, 2, 3, 4) +all_the_args(**kwargs) # 等同於 foo(a=3, b=4) +all_the_args(*args, **kwargs) # 等同於 foo(1, 2, 3, 4, a=3, b=4) -# you can pass args and kwargs along to other functions that take args/kwargs -# by expanding them with * and ** respectively +# 你可以把args跟kwargs傳到下一個函式內 +# 分別用 * 跟 ** 將它展開就可以了 def pass_all_the_args(*args, **kwargs): all_the_args(*args, **kwargs) print varargs(*args) print keyword_args(**kwargs) -# Function Scope +# 函式範圍 x = 5 def set_x(num): - # Local var x not the same as global variable x + # 區域變數 x 和全域變數 x 不是同一個東西 x = num # => 43 print x # => 43 def set_global_x(num): global x print x # => 5 - x = num # global var x is now set to 6 + x = num # 全域變數 x 在set_global_x(6)被設定為 6 print x # => 6 set_x(43) set_global_x(6) -# Python has first class functions +# Python有一級函式 def create_adder(x): def adder(y): return x + y @@ -523,23 +526,23 @@ def create_adder(x): add_10 = create_adder(10) add_10(3) # => 13 -# There are also anonymous functions +# 也有匿名函式 (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 -# There are built-in higher order functions +# 還有內建的高階函式 map(add_10, [1, 2, 3]) # => [11, 12, 13] map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# We can use list comprehensions for nice maps and filters +# 我們可以用List列表的方式對map和filter等高階函式做更有趣的應用 [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### -## 5. Classes +## 5. 類別 #################################################### # We subclass from object to get a class. -- cgit v1.2.3 From e2b93f579cbcbb58612081b46f4460cd0255edb3 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:18:21 +0800 Subject: Finish translation of Sec. 6 --- zh-tw/python-tw.html.markdown | 44 +++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 073c5e91..d113f90c 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -545,25 +545,25 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] ## 5. 類別 #################################################### -# We subclass from object to get a class. +# 我們可以由object繼承出一個新的類別 class Human(object): - # A class attribute. It is shared by all instances of this class + # 類別的參數,被所有這個類別的實體所共用 species = "H. sapiens" - # Basic initializer, this is called when this class is instantiated. - # Note that the double leading and trailing underscores denote objects - # or attributes that are used by python but that live in user-controlled - # namespaces. You should not invent such names on your own. + # 基礎建構函式,當class被實體化的時候會被呼叫 + # 注意前後的雙底線代表物件 + # 還有被python用,但實際上是在使用者控制的命名 + # 空間內的參數。你不應該自己宣告這樣的名稱。 def __init__(self, name): - # Assign the argument to the instance's name attribute + # 將函式引入的參數 name 指定給實體的 name 參數 self.name = name - # Initialize property + # 初始化屬性 self.age = 0 - # An instance method. All methods take "self" as the first argument + # 一個實體的方法(method)。 所有的method都以self為第一個參數 def say(self, msg): return "{0}: {1}".format(self.name, msg) @@ -626,41 +626,41 @@ i.age # => raises an AttributeError #################################################### -## 6. Modules +## 6. 模組 #################################################### -# You can import modules +# 你可以引入模組來做使用 import math print math.sqrt(16) # => 4 + # math.sqrt()為取根號 -# You can get specific functions from a module +# 你可以只從模組取出特定幾個函式 from math import ceil, floor print ceil(3.7) # => 4.0 print floor(3.7) # => 3.0 -# You can import all functions from a module. -# Warning: this is not recommended +# 你可以將所有的函式從模組中引入 +# 注意:不建議這麼做 from math import * -# You can shorten module names +# 你可以用 as 簡寫模組名稱 import math as m math.sqrt(16) == m.sqrt(16) # => True -# you can also test that the functions are equivalent +# 你也可以測試函示是否相等 from math import sqrt math.sqrt == m.sqrt == sqrt # => True -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. +# Python的模組就只是一般的Python檔。 +# 你可以自己的模組自己寫、自己的模組自己引入 +# 模組的名稱和檔案名稱一樣 -# You can find out which functions and attributes -# defines a module. +# 你可以用dir()來查看有哪些可用函式和屬性 import math dir(math) #################################################### -## 7. Advanced +## 7. 進階 #################################################### # Generators help you make lazy code -- cgit v1.2.3 From 3544a43d117d7b63de2c3443250270d92d00dce9 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:27:42 +0800 Subject: Finish Sec. 7 translation. --- zh-tw/python-tw.html.markdown | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index d113f90c..797fc6ed 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -663,34 +663,30 @@ dir(math) ## 7. 進階 #################################################### -# Generators help you make lazy code +# 產生器(Generator)可以讓你寫更懶惰的程式碼 def double_numbers(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note xrange is a generator that does the same thing range does. -# Creating a list 1-900000000 would take lot of time and space to be made. -# xrange creates an xrange generator object instead of creating the entire list -# like range does. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword +# 產生器可以讓你即時的產生值 +# 不是全部產生完之後再一次回傳,產生器會在每一個遞迴時 +# 產生值。 這也意味著大於15的值不會在double_numbers中產生。 +# 這邊,xrange()做的事情和range()一樣 +# 建立一個 1-900000000 的List會消耗很多時間和記憶體空間 +# xrange() 建立一個產生器物件,而不是如range()建立整個List +# 我們用底線來避免可能和python的關鍵字重複的名稱 xrange_ = xrange(1, 900000000) -# will double all numbers until a result >=30 found +# 下面的程式碼會把所有的值乘以兩倍,直到出現大於30的值 for i in double_numbers(xrange_): print i if i >= 30: break -# Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# 裝飾子 +# 在這個範例中,beg會綁在say上 +# Beg會呼叫say。 如果say_please為True的話,它會更改回傳的訊息 from functools import wraps @@ -715,9 +711,9 @@ print say() # Can you buy me a beer? print say(say_please=True) # Can you buy me a beer? Please! I am poor :( ``` -## Ready For More? +## 準備好學更多了嗎? -### Free Online +### 線上免費資源 * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) @@ -728,7 +724,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) -### Dead Tree +### 或買本書? * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 2ecf370ce4e8b6644863e92652f9b63717ab3e6e Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Mon, 2 Nov 2015 02:32:25 +0800 Subject: Sec. 6 translated. All sections translated. Hooray. --- zh-tw/python-tw.html.markdown | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 797fc6ed..10b4669c 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -567,60 +567,59 @@ class Human(object): def say(self, msg): return "{0}: {1}".format(self.name, msg) - # A class method is shared among all instances - # They are called with the calling class as the first argument + # 一個類別方法會被所有的實體所共用 + # 他們會以類別為第一參數的方式被呼叫 @classmethod def get_species(cls): return cls.species - # A static method is called without a class or instance reference + # 靜態方法 @staticmethod def grunt(): return "*grunt*" - # A property is just like a getter. - # It turns the method age() into an read-only attribute - # of the same name. + # 屬性就像是用getter取值一樣 + # 它將方法 age() 轉為同名的、只能讀取的屬性 @property def age(self): return self._age - # This allows the property to be set + # 這樣寫的話可以讓屬性被寫入新的值 @age.setter def age(self, age): self._age = age - # This allows the property to be deleted + # 這樣寫的話允許屬性被刪除 @age.deleter def age(self): del self._age -# Instantiate a class +# 將類別實體化 i = Human(name="Ian") print i.say("hi") # prints out "Ian: hi" j = Human("Joel") print j.say("hello") # prints out "Joel: hello" -# Call our class method +# 呼叫類別方法 i.get_species() # => "H. sapiens" -# Change the shared attribute +# 更改共用的屬性 Human.species = "H. neanderthalensis" i.get_species() # => "H. neanderthalensis" j.get_species() # => "H. neanderthalensis" -# Call the static method +# 呼叫靜態方法 Human.grunt() # => "*grunt*" -# Update the property +# 更新屬性 i.age = 42 -# Get the property +# 取得屬性 i.age # => 42 -# Delete the property +# 移除屬性 del i.age i.age # => raises an AttributeError -- cgit v1.2.3 From 8d879735365461d817ccd75d0cae1be9d361197b Mon Sep 17 00:00:00 2001 From: CY Lim Date: Mon, 2 Nov 2015 11:23:59 +1100 Subject: println() depreciated in swift2.0 --- zh-cn/swift-cn.html.markdown | 99 ++++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 50 deletions(-) diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index 28001e3f..81efbb3e 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -19,7 +19,7 @@ Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.co // 导入外部模块 import UIKit -// +// // MARK: 基础 // @@ -28,12 +28,12 @@ import UIKit // TODO: TODO 标记 // FIXME: FIXME 标记 -println("Hello, world") +print("Hello, world") // 变量 (var) 的值设置后可以随意改变 // 常量 (let) 的值设置后不能改变 var myVariable = 42 -let øπΩ = "value" // 可以支持 unicode 变量名 +let øπΩ = "value" // 可以支持 unicode 变量名 let π = 3.1415926 let myConstant = 3.1415926 let explicitDouble: Double = 70 // 明确指定变量类型为 Double ,否则编译器将自动推断变量类型 @@ -46,16 +46,16 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // 格式化字符串 // 条件编译 // 使用 -D 定义编译开关 #if false - println("Not printed") + print("Not printed") let buildValue = 3 #else let buildValue = 7 #endif -println("Build value: \(buildValue)") // Build value: 7 +print("Build value: \(buildValue)") // Build value: 7 /* Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None - + Swift 要求所有的 Optinal 属性都必须有明确的值,如果为空,则必须明确设定为 nil Optional 是个枚举类型 @@ -67,9 +67,9 @@ var someOptionalString2: Optional = "optional" if someOptionalString != nil { // 变量不为空 if someOptionalString!.hasPrefix("opt") { - println("has the prefix") + print("has the prefix") } - + let empty = someOptionalString?.isEmpty } someOptionalString = nil @@ -94,7 +94,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible." /* 这里是注释 - + /* 支持嵌套的注释 */ @@ -136,21 +136,21 @@ var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量 let myArray = [1, 1, 2, 3, 5] for value in myArray { if value == 1 { - println("One!") + print("One!") } else { - println("Not one!") + print("Not one!") } } // 字典的 for 循环 var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + print("\(key): \(value)") } // 区间的 loop 循环:其中 `...` 表示闭环区间,即[-1, 3];`..<` 表示半开闭区间,即[-1,3) for i in -1...shoppingList.count { - println(i) + print(i) } shoppingList[1...2] = ["steak", "peacons"] // 可以使用 `..<` 来去掉最后一个元素 @@ -163,7 +163,7 @@ while i < 1000 { // do-while 循环 do { - println("hello") + print("hello") } while 1 == 2 // Switch 语句 @@ -177,7 +177,7 @@ case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let localScopeValue where localScopeValue.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(localScopeValue)?" -default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句 +default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句 let vegetableComment = "Everything tastes good in soup." } @@ -219,8 +219,8 @@ let pricesTuple = getGasPrices() let price = pricesTuple.2 // 3.79 // 通过下划线 (_) 来忽略不关心的值 let (_, price1, _) = pricesTuple // price1 == 3.69 -println(price1 == pricesTuple.1) // true -println("Gas price: \(price)") +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") // 可变参数 func setup(numbers: Int...) { @@ -248,7 +248,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { var someIntA = 7 var someIntB = 3 swapTwoInts(&someIntA, &someIntB) -println(someIntB) // 7 +print(someIntB) // 7 // @@ -296,7 +296,7 @@ print(numbers) // [3, 6, 18] struct NamesTable { let names = [String]() - + // 自定义下标运算符 subscript(index: Int) -> String { return names[index] @@ -306,7 +306,7 @@ struct NamesTable { // 结构体有一个自动生成的隐含的命名构造函数 let namesTable = NamesTable(names: ["Me", "Them"]) let name = namesTable[1] -println("Name is \(name)") // Name is Them +print("Name is \(name)") // Name is Them // // MARK: 类 @@ -329,7 +329,7 @@ public class Shape { internal class Rect: Shape { // 值属性 (Stored properties) var sideLength: Int = 1 - + // 计算属性 (Computed properties) private var perimeter: Int { get { @@ -340,11 +340,11 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - + // 延时加载的属性,只有这个属性第一次被引用时才进行初始化,而不是定义时就初始化 // subShape 值为 nil ,直到 subShape 第一次被引用时才初始化为一个 Rect 实例 lazy var subShape = Rect(sideLength: 4) - + // 监控属性值的变化。 // 当我们需要在属性值改变时做一些事情,可以使用 `willSet` 和 `didSet` 来设置监控函数 // `willSet`: 值改变之前被调用 @@ -352,14 +352,14 @@ internal class Rect: Shape { var identifier: String = "defaultID" { // `willSet` 的参数是即将设置的新值,参数名可以指定,如果没有指定,就是 `newValue` willSet(someIdentifier) { - println(someIdentifier) + print(someIdentifier) } // `didSet` 的参数是已经被覆盖掉的旧的值,参数名也可以指定,如果没有指定,就是 `oldValue` didSet { - println(oldValue) + print(oldValue) } } - + // 命名构造函数 (designated inits),它必须初始化所有的成员变量, // 然后调用父类的命名构造函数继续初始化父类的所有变量。 init(sideLength: Int) { @@ -367,13 +367,13 @@ internal class Rect: Shape { // 必须显式地在构造函数最后调用父类的构造函数 super.init super.init() } - + func shrink() { if sideLength > 0 { --sideLength } } - + // 函数重载使用 override 关键字 override func getArea() -> Int { return sideLength * sideLength @@ -394,16 +394,16 @@ class Square: Rect { } var mySquare = Square() -println(mySquare.getArea()) // 25 +print(mySquare.getArea()) // 25 mySquare.shrink() -println(mySquare.sideLength) // 4 +print(mySquare.sideLength) // 4 // 类型转换 let aShape = mySquare as Shape // 使用三个等号来比较是不是同一个实例 if mySquare === aShape { - println("Yep, it's mySquare") + print("Yep, it's mySquare") } class Circle: Shape { @@ -411,12 +411,12 @@ class Circle: Shape { override func getArea() -> Int { return 3 * radius * radius } - + // optional 构造函数,可能会返回 nil init?(radius: Int) { self.radius = radius super.init() - + if radius <= 0 { return nil } @@ -425,13 +425,13 @@ class Circle: Shape { // 根据 Swift 类型推断,myCircle 是 Optional 类型的变量 var myCircle = Circle(radius: 1) -println(myCircle?.getArea()) // Optional(3) -println(myCircle!.getArea()) // 3 +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 var myEmptyCircle = Circle(radius: -1) -println(myEmptyCircle?.getArea()) // "nil" +print(myEmptyCircle?.getArea()) // "nil" if let circle = myEmptyCircle { // 此语句不会输出,因为 myEmptyCircle 变量值为 nil - println("circle is not nil") + print("circle is not nil") } @@ -461,7 +461,7 @@ enum BookName: String { case John = "John" case Luke = "Luke" } -println("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.John.rawValue)") // 与特定数据类型关联的枚举 enum Furniture { @@ -469,7 +469,7 @@ enum Furniture { case Desk(height: Int) // 和 String, Int 关联的枚举记录 case Chair(brand: String, height: Int) - + func description() -> String { switch self { case .Desk(let height): @@ -481,9 +481,9 @@ enum Furniture { } var desk: Furniture = .Desk(height: 80) -println(desk.description()) // "Desk with 80 cm" +print(desk.description()) // "Desk with 80 cm" var chair = Furniture.Chair(brand: "Foo", height: 40) -println(chair.description()) // "Chair of Foo with 40 cm" +print(chair.description()) // "Chair of Foo with 40 cm" // @@ -512,7 +512,7 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 @@ -539,21 +539,21 @@ extension Square: Printable { } } -println("Square: \(mySquare)") // Area: 16 - ID: defaultID +print("Square: \(mySquare)") // Area: 16 - ID: defaultID // 也可以给系统内置类型添加功能支持 extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } } -println(7.customProperty) // "This is 7" -println(14.multiplyBy(3)) // 42 +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 // 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。 // 如果只有一个类型限制,可以省略 `where` 关键字 @@ -566,7 +566,7 @@ func findIndex(array: [T], valueToFind: T) -> Int? { return nil } let foundAtIndex = findIndex([1, 2, 3, 4], 3) -println(foundAtIndex == 2) // true +print(foundAtIndex == 2) // true // 自定义运算符: // 自定义运算符可以以下面的字符打头: @@ -581,11 +581,10 @@ prefix func !!! (inout shape: Square) -> Square { } // 当前值 -println(mySquare.sideLength) // 4 +print(mySquare.sideLength) // 4 // 使用自定义的 !!! 运算符来把矩形边长放大三倍 !!!mySquare -println(mySquare.sideLength) // 12 +print(mySquare.sideLength) // 12 ``` - -- cgit v1.2.3 From 9b0242fbe95517db45347a0416b53e9ed6769bdd Mon Sep 17 00:00:00 2001 From: CY Lim Date: Mon, 2 Nov 2015 12:17:23 +1100 Subject: add in update from English version --- zh-cn/swift-cn.html.markdown | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index 81efbb3e..78e97c2f 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -5,7 +5,8 @@ contributors: - ["Grant Timmerman", "http://github.com/grant"] translators: - ["Xavier Yao", "http://github.com/xavieryao"] - - ["Joey Huang", "http://github.com/kamidox"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["CY Lim", "http://github.com/cylim"] lang: zh-cn --- @@ -28,7 +29,9 @@ import UIKit // TODO: TODO 标记 // FIXME: FIXME 标记 -print("Hello, world") +// Swift2.0 println() 及 print() 已经整合成 print()。 +print("Hello, world") // 这是原本的 println(),会自动进入下一行 +print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false // 变量 (var) 的值设置后可以随意改变 // 常量 (let) 的值设置后不能改变 @@ -54,7 +57,8 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // 格式化字符串 print("Build value: \(buildValue)") // Build value: 7 /* - Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None + Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None 。 + 可在值名称后加个问号 (?) 来表示这个值是 Optional。 Swift 要求所有的 Optinal 属性都必须有明确的值,如果为空,则必须明确设定为 nil @@ -74,6 +78,10 @@ if someOptionalString != nil { } someOptionalString = nil +/* + 使用 (!) 可以解决无法访问optional值的运行错误。若要使用 (!)来强制解析,一定要确保 Optional 里不是 nil参数。 +*/ + // 显式解包 optional 变量 var unwrappedString: String! = "Value is expected." // 下面语句和上面完全等价,感叹号 (!) 是个后缀运算符,这也是个语法糖 @@ -116,6 +124,7 @@ shoppingList[1] = "bottle of water" let emptyArray = [String]() // 使用 let 定义常量,此时 emptyArray 数组不能添加或删除内容 let emptyArray2 = Array() // 与上一语句等价,上一语句更常用 var emptyMutableArray = [String]() // 使用 var 定义变量,可以向 emptyMutableArray 添加数组元素 +var explicitEmptyMutableStringArray: [String] = [] // 与上一语句等价 // 字典 var occupations = [ @@ -126,6 +135,7 @@ occupations["Jayne"] = "Public Relations" // 修改字典,如果 key 不存 let emptyDictionary = [String: Float]() // 使用 let 定义字典常量,字典常量不能修改里面的值 let emptyDictionary2 = Dictionary() // 与上一语句类型等价,上一语句更常用 var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量 +var explicitEmptyMutableDictionary: [String: Float] = [:] // 与上一语句类型等价 // @@ -256,7 +266,7 @@ print(someIntB) // 7 // var numbers = [1, 2, 6] -// 函数是闭包的一个特例 +// 函数是闭包的一个特例 ({}) // 闭包实例 // `->` 分隔了闭包的参数和返回值 @@ -587,4 +597,18 @@ print(mySquare.sideLength) // 4 !!!mySquare print(mySquare.sideLength) // 12 +// 运算符也可以是泛型 +infix operator <-> {} +func <-> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" + ``` -- cgit v1.2.3 From a4ed1aee75d13c237b4747b5560d209bce65f62b Mon Sep 17 00:00:00 2001 From: CY Lim Date: Mon, 2 Nov 2015 12:18:04 +1100 Subject: fixed Getting Start Guide link --- zh-cn/swift-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index 78e97c2f..3efe4941 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -14,7 +14,7 @@ Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于20 Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载. -亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) ——一个完整的Swift 教程 +亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程 ```swift // 导入外部模块 -- cgit v1.2.3 From c32a8b2ca157c1be2d3fa67fe429a5e2e92241b6 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sun, 1 Nov 2015 19:38:55 -0700 Subject: Removed extraneous characters. --- markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 7be37f81..e148213c 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -242,7 +242,7 @@ Markdown also supports reference style links. ``` The title can also be in single quotes or in parentheses, or omitted entirely. The references can be anywhere in your document and the reference IDs -can be anything so long as they are unique. --> +can be anything so long as they are unique. There is also "implicit naming" which lets you use the link text as the id. ```markdown -- cgit v1.2.3 From 9444609b7d44a7f16cbd6c920374eb5e26f10725 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sun, 1 Nov 2015 20:32:41 -0700 Subject: Fixed grammar --- markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index e148213c..d38bfe33 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -9,7 +9,7 @@ filename: markdown.md Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -Markdown is a superset of HTML, so any HTML file is valid Markdown, that +Markdown is a superset of HTML, so any HTML file is valid Markdown. This means we can use HTML elements in Markdown, such as the comment element, and they won't be affected by a markdown parser. However, if you create an HTML element in your markdown file, you cannot use markdown syntax within that -- cgit v1.2.3 From c64f9231a9e9eb797519a582a73dbca452f00672 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sun, 1 Nov 2015 20:56:59 -0700 Subject: fix kbd tag --- markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index d38bfe33..64f5f351 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -284,7 +284,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. ### Keyboard keys -In Github Flavored Markdown, you can use a tag to represent keyboard keys. +In Github Flavored Markdown, you can use a `` tag to represent keyboard keys. ```markdown Your computer crashed? Try sending a Ctrl+Alt+Del -- cgit v1.2.3 From a4a7b2dd8308a8d67722d8c93e4c1a8c052f7f6a Mon Sep 17 00:00:00 2001 From: EL Date: Mon, 2 Nov 2015 16:30:15 +0300 Subject: fixed unintended opposite meaning --- python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 2b43c5fc..f8f712d3 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -458,7 +458,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of -# positional args, which will be interpreted as a tuple if you do not use the * +# positional args, which will be interpreted as a tuple by using * def varargs(*args): return args @@ -466,7 +466,7 @@ varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of -# keyword args, as well, which will be interpreted as a dict if you do not use ** +# keyword args, as well, which will be interpreted as a dict by using ** def keyword_args(**kwargs): return kwargs -- cgit v1.2.3 From b13bb0ce47386d0426342c0470ddc4a52720c56d Mon Sep 17 00:00:00 2001 From: Jake Faris Date: Mon, 2 Nov 2015 10:06:01 -0500 Subject: adds JF to authors --- ruby.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 782ffc4c..243f788b 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -14,6 +14,7 @@ contributors: - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gabriel Halley", "https://github.com/ghalley"] - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] --- ```ruby -- cgit v1.2.3 From db4e212602121c5d84fc987d47054dbbbe21b1b0 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Mon, 2 Nov 2015 08:11:50 -0700 Subject: Demonstrate html comments --- markdown.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/markdown.html.markdown b/markdown.html.markdown index 64f5f351..5f8d31c8 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -19,6 +19,7 @@ Markdown also varies in implementation from one parser to a next. This guide will attempt to clarify when features are universal or when they are specific to a certain parser. +- [HTML Elements](#html-elements) - [Headings](#headings) - [Simple Text Styles](#simple-text-styles) - [Paragraphs](#paragraphs) @@ -29,6 +30,12 @@ specific to a certain parser. - [Images](#images) - [Miscellany](#miscellany) +## HTML Elements +Markdown is a superset of HTML, so any HTML file is valid Markdown. +```markdown + +``` + ## Headings You can create HTML elements `

` through `

` easily by prepending the -- cgit v1.2.3 From 6d705f17b6295be0525ff98a94dd4703912e3654 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Mon, 2 Nov 2015 08:17:40 -0700 Subject: fix demonstrate html elements/comments --- markdown.html.markdown | 6 ------ 1 file changed, 6 deletions(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index 5f8d31c8..fdc59067 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -9,12 +9,6 @@ filename: markdown.md Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). -Markdown is a superset of HTML, so any HTML file is valid Markdown. This -means we can use HTML elements in Markdown, such as the comment element, and -they won't be affected by a markdown parser. However, if you create an HTML -element in your markdown file, you cannot use markdown syntax within that -element's contents. - Markdown also varies in implementation from one parser to a next. This guide will attempt to clarify when features are universal or when they are specific to a certain parser. -- cgit v1.2.3 From 2469dd6f445bee0758c621a99e24fea8adc97c59 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Mon, 2 Nov 2015 08:29:25 -0700 Subject: fix line breaks --- markdown.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/markdown.html.markdown b/markdown.html.markdown index fdc59067..8961c995 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -27,7 +27,9 @@ specific to a certain parser. ## HTML Elements Markdown is a superset of HTML, so any HTML file is valid Markdown. ```markdown - + ``` ## Headings -- cgit v1.2.3 From 37f6f848a6393a998d75e7b587f605422952f38b Mon Sep 17 00:00:00 2001 From: Serg Date: Mon, 2 Nov 2015 21:26:21 +0200 Subject: Rename ua-ua/javascript-ua.html.markdown to uk-ua/javascript-ua.html.markdown Please, change lang to uk-ua. --- ua-ua/javascript-ua.html.markdown | 501 -------------------------------------- uk-ua/javascript-ua.html.markdown | 501 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 501 insertions(+), 501 deletions(-) delete mode 100644 ua-ua/javascript-ua.html.markdown create mode 100644 uk-ua/javascript-ua.html.markdown diff --git a/ua-ua/javascript-ua.html.markdown b/ua-ua/javascript-ua.html.markdown deleted file mode 100644 index fedbf5ac..00000000 --- a/ua-ua/javascript-ua.html.markdown +++ /dev/null @@ -1,501 +0,0 @@ ---- -language: javascript -contributors: - - ["Adam Brenecki", "http://adam.brenecki.id.au"] - - ["Ariel Krakowski", "http://www.learneroo.com"] -filename: javascript-ru.js -translators: - - ["Alexey Gonchar", "http://github.com/finico"] - - ["Andre Polykanine", "https://github.com/Oire"] -lang: ru-ru ---- - -JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape. -Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java -для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і -вбудована підтримка браузерами призвела до того, що JavaScript став популярніший -за власне Java. - -Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js, -програмна платформа, що дозволяє виконувати JavaScript код з використанням -рушія V8 від браузера Google Chrome, стає все більш і більш популярною. - -```js -// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш) -/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і - закінчуються символами зірочка-слеш */ - -Інструкції можуть закінчуватися крапкою з комою ; -doStuff(); - -// ... але не обов’язково, тому що крапка з комою автоматично вставляється на -// місці символу нового рядка, крім деяких випадків. -doStuff() - -// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці -// винятки можуть призвести до неочікуваних результатів - -/////////////////////////////////// -// 1. Числа, Рядки і Оператори - -// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double) -// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з -// точністю до 9✕10¹⁵. -3; // = 3 -1.5; // = 1.5 - -// Деякі прості арифметичні операції працють так, як ми очікуємо. -1 + 1; // = 2 -0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні) -8 - 1; // = 7 -10 * 2; // = 20 -35 / 5; // = 7 - -// В тому числі ділення з остачою -5 / 2; // = 2.5 - -// В JavaScript є побітові операції; коли ви виконуєте таку операцію, -// число з плаваючою точкою переводиться в ціле зі знаком -// довжиною *до* 32 розрядів. -1 << 2; // = 4 - -// Пріоритет у виразах можна задати явно круглими дужками -(1 + 3) * 2; // = 8 - -// Є три спеціальні значення, які не є реальними числами: -Infinity; // "нескінченність", наприклад, як результат ділення на 0 --Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0 -NaN; // "не число", наприклад, ділення 0/0 - -// Логічні типи -true; -false; - -// Рядки створюються за допомогою подвійних та одинарних лапок -'абв'; -"Hello, world!"; - -// Для логічного заперечення використовується знак оклику. -!true; // = false -!false; // = true - -// Строга рівність === -1 === 1; // = true -2 === 1; // = false - -// Строга нерівність !== -1 !== 1; // = false -2 !== 1; // = true - -// Інші оператори порівняння -1 < 10; // = true -1 > 10; // = false -2 <= 2; // = true -2 >= 2; // = true - -// Рядки об’єднуються за допомогою оператор + -"hello, " + "world!"; // = "hello, world!" - -// І порівнюються за допомогою > і < -"a" < "b"; // = true - -// Перевірка на рівність з приведнням типів здійснюється оператором == -"5" == 5; // = true -null == undefined; // = true - -// ... але приведення не виконується при === -"5" === 5; // = false -null === undefined; // = false - -// ... приведення типів може призвести до дивних результатів -13 + !0; // 14 -"13" + !0; // '13true' - -// Можна отримати доступ до будь-якого символа рядка за допомгою charAt -"Это строка".charAt(0); // = 'Э' - -// ... або використати метод substring, щоб отримати більший кусок -"Hello, world".substring(0, 5); // = "Hello" - -// length - це не метод, а поле -"Hello".length; // = 5 - -// Типи null и undefined -null; // навмисна відсутність результату -undefined; // використовується для позначення відсутності присвоєного значення - -// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина. -// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що: -// 0 == "0". - -/////////////////////////////////// -// 2. Змінні, Масиви, Об’єкти - -// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з -// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння -// значення змінної використовується символ = -var someVar = 5; - -// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ... -someOtherVar = 10; - -// ... але ваша змінна буде створення в глобальному контексті, а не там, де -// ви її оголосили - -// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined -var someThirdVar; // = undefined - -// У математичних операцій є скорочені форми: -someVar += 5; // як someVar = someVar + 5; -someVar *= 10; // тепер someVar = 100 - -// Інкремент і декремент -someVar++; // тепер someVar дорівнює 101 -someVar--; // а зараз 100 - -// Масиви — це нумеровані списку, які зберігають значення будь-якого типу. -var myArray = ["Hello", 45, true]; - -// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками -// Індексація починається з нуля -myArray[1]; // = 45 - -// Массивы можно изменять, как и их длину, -myArray.push("Мир"); -myArray.length; // = 4 - -// додавання і редагування елементів -myArray[3] = "Hello"; - -// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах -var myObj = {key1: "Hello", key2: "World"}; - -// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє -// правилам формування назв змінних. Значення можуть бути будь-яких типів. -var myObj = {myKey: "myValue", "my other key": 4}; - -// Атрибути можна отримати використовуючи квадратні дужки -myObj["my other key"]; // = 4 - -// Або через точку, якщо ключ є правильним ідентифікатором -myObj.myKey; // = "myValue" - -// Об’єкти можна динамічно змінювати й додавати нові поля -myObj.myThirdKey = true; - -// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined -myObj.myFourthKey; // = undefined - -/////////////////////////////////// -// 3. Управляючі конструкції - -// Синтаксис для цього розділу майже такий самий, як у Java - -// Умовна конструкція -var count = 1; -if (count == 3) { - // виконується, якщо count дорівнює 3 -} else if (count == 4) { - // .. -} else { - // ... -} - -// ... цикл while. -while (true){ - // Нескінченний цикл! -} - -// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз. -var input -do { - input = getInput(); -} while (!isValid(input)) - -// цикл for такий самий, кяк в C і Java: -// ініціалізація; умова; крок. -for (var i = 0; i < 5; i++) { - // виконається 5 разів -} - -// && — логічне І, || — логічне АБО -if (house.size == "big" && house.color == "blue") { - house.contains = "bear"; -} -if (color == "red" || color == "blue") { - // колір червоний або синій -} - -// && і || використовують скорочене обчислення -// тому їх можна використовувати для задання значень за замовчуванням. -var name = otherName || "default"; - -// Оператор switch виконує перевірку на рівність за допомогою === -// використовуйте break, щоб призупити виконання наступного case, -grade = 4; -switch (grade) { - case 5: - console.log("Відмінно"); - break; - case 4: - console.log("Добре"); - break; - case 3: - console.log("Можна краще"); - break; - default: - console.log("Погано!"); - break; -} - - -/////////////////////////////////// -// 4. Функції, область видимості і замикання - -// Функції в JavaScript оголошуються за допомогою ключового слова function. -function myFunction(thing) { - return thing.toUpperCase(); -} -myFunction("foo"); // = "FOO" - -// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж -// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined -// із-за автоматичної вставки крапки з комою -function myFunction() -{ - return // <- крапка з комою вставляється автоматично - { - thisIsAn: 'object literal' - } -} -myFunction(); // = undefined - -// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися -// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник -// події. -function myFunction() { - // код буде виконано через 5 сек. -} -setTimeout(myFunction, 5000); -// setTimeout не є частиною мови, але реалізований в браузерах і Node.js - -// Функции не обязательно должны иметь имя при объявлении — вы можете написать -// анонимное определение функции непосредственно в аргументе другой функции. -// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати -// анонімну функцію прямо в якості аргумента іншої функції -setTimeout(function() { - // Цей код буде виконано через п’ять секунд -}, 5000); - -// В JavaScript реалізована концепція області видимості; функції мають свою -// область видимости, а інші блоки не мають -if (true) { - var i = 5; -} -i; // = 5, а не undefined, як це звичайно буває в інших мова - -// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе" -// що дозволяє уникнути проникнення змінних в глобальну область видимості -(function() { - var temporary = 5; - // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати - // змінні до глобальної області - window.permanent = 10; -})(); -temporary; // повідомлення про помилку ReferenceError -permanent; // = 10 - -// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция -// определена внутри другой функции, то внутренняя функция имеет доступ к -// переменным внешней функции даже после того, как контекст выполнения выйдет из -// внешней функции. -// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена -// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої -// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції -function sayHelloInFiveSeconds(name) { - var prompt = "Hello, " + name + "!"; - // Внутрішня функція зберігається в локальній області так, - // ніби функція була оголошена за допомогою ключового слова var - function inner() { - alert(prompt); - } - setTimeout(inner, 5000); - // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться, - // після чого setTimeout викличе функцію inner. Але функція inner - // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt -} -sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!» - -/////////////////////////////////// -// 5. Об’єкти: конструктори і прототипи - -// Об’єкти можуть містити функції -var myObj = { - myFunc: function() { - return "Hello, world!"; - } -}; -myObj.myFunc(); // = "Hello, world!" - -// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за -// допомогою ключового слова this. -myObj = { - myString: "Hello, world!", - myFunc: function() { - return this.myString; - } -}; -myObj.myFunc(); // = "Hello, world!" - -// Значення this залежить від того, як функція викликається -// а не від того, де вона визначена. Таким чином наша функція не працює, якщо -// вона викликана не в контексті об’єкта -var myFunc = myObj.myFunc; -myFunc(); // = undefined - -// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до -// цього об’єкта через this -var myOtherFunc = function() { -} -myObj.myOtherFunc = myOtherFunc; -myObj.myOtherFunc(); // = "HELLO, WORLD!" - -// Контекст виконання функції можна задати за допомогою сall або apply -var anotherFunc = function(s) { - return this.myString + s; -} -anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!" - -// Функцiя apply приймає в якості аргументу масив -anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!" - -// apply можна використати, коли функція працює послідовністю аргументів, а -// ви хочете передати масив -Math.min(42, 6, 27); // = 6 -Math.min([42, 6, 27]); // = NaN (Ой-ой!) -Math.min.apply(Math, [42, 6, 27]); // = 6 - -// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт -// використовують bind -var boundFunc = anotherFunc.bind(myObj); -boundFunc(" Hello!"); // = "Hello world, Hello!" - -// Bind можна використати для задання аргументів -var product = function(a, b) { return a * b; } -var doubler = product.bind(this, 2); -doubler(8); // = 16 - -// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт, -// доступний функції за допомогою this. Такі функції називають конструкторами. -var MyConstructor = function() { - this.myNumber = 5; -} -myNewObj = new MyConstructor(); // = {myNumber: 5} -myNewObj.myNumber; // = 5 - -// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому -// об’єктів, інтерпретатор буде шукати поле в прототипі - -// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через -// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують -// стандартні способи використання прототипів, які ми побачимо пізніше -var myObj = { - myString: "Hello, world!" -}; -var myPrototype = { - meaningOfLife: 42, - myFunc: function() { - return this.myString.toLowerCase() - } -}; - -myObj.__proto__ = myPrototype; -myObj.meaningOfLife; // = 42 - -// Аналогічно для функцій -myObj.myFunc(); // = "Hello, world!" - -// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук -// в прототипі прототипа і так далі -myPrototype.__proto__ = { - myBoolean: true -}; -myObj.myBoolean; // = true - -// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити -// наш прототип, і наші зміни будуть всюди відображені. -myPrototype.meaningOfLife = 43; -myObj.meaningOfLife; // = 43 - -// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу -// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим -// прототипом - -// Перший спосіб — це Object.create, який з’явився JavaScript недавно, -// а тому в деяких реалізаціях може бути не доступним. -var myObj = Object.create(myPrototype); -myObj.meaningOfLife; // = 43 - -// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не* -// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені -// цим конструктором і ключового слова new. -MyConstructor.prototype = { - myNumber: 5, - getMyNumber: function() { - return this.myNumber; - } -}; -var myNewObj2 = new MyConstructor(); -myNewObj2.getMyNumber(); // = 5 -myNewObj2.myNumber = 6 -myNewObj2.getMyNumber(); // = 6 - -// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні -// об’єкти-обгортки -var myNumber = 12; -var myNumberObj = new Number(12); -myNumber == myNumberObj; // = true - -// Але вони не ідентичні -typeof myNumber; // = 'number' -typeof myNumberObj; // = 'object' -myNumber === myNumberObj; // = false -if (0) { - // Этот код не выполнится, потому что 0 - это ложь. -} - -// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому -// ви можете розширити функціонал рядків: -String.prototype.firstCharacter = function() { - return this.charAt(0); -} -"abc".firstCharacter(); // = "a" - -// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості -// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих -// середовищах - -// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо -// використати функції за допомогою наступного поліфіла: -if (Object.create === undefined) { // не перезаписываем метод, если он существует - Object.create = function(proto) { - // Створюємо правильний конструктор з правильним прототипом - var Constructor = function(){}; - Constructor.prototype = proto; - - return new Constructor(); - } -} -``` - -## Що почитати - -[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript -[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript -[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core -[4]: http://www.learneroo.com/modules/64/nodes/350 -[5]: http://bonsaiden.github.io/JavaScript-Garden/ -[6]: http://www.amazon.com/gp/product/0596805527/ -[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript -[8]: http://eloquentjavascript.net/ -[9]: http://jstherightway.org/ diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown new file mode 100644 index 00000000..fedbf5ac --- /dev/null +++ b/uk-ua/javascript-ua.html.markdown @@ -0,0 +1,501 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ru.js +translators: + - ["Alexey Gonchar", "http://github.com/finico"] + - ["Andre Polykanine", "https://github.com/Oire"] +lang: ru-ru +--- + +JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape. +Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java +для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і +вбудована підтримка браузерами призвела до того, що JavaScript став популярніший +за власне Java. + +Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js, +програмна платформа, що дозволяє виконувати JavaScript код з використанням +рушія V8 від браузера Google Chrome, стає все більш і більш популярною. + +```js +// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш) +/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і + закінчуються символами зірочка-слеш */ + +Інструкції можуть закінчуватися крапкою з комою ; +doStuff(); + +// ... але не обов’язково, тому що крапка з комою автоматично вставляється на +// місці символу нового рядка, крім деяких випадків. +doStuff() + +// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці +// винятки можуть призвести до неочікуваних результатів + +/////////////////////////////////// +// 1. Числа, Рядки і Оператори + +// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double) +// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з +// точністю до 9✕10¹⁵. +3; // = 3 +1.5; // = 1.5 + +// Деякі прості арифметичні операції працють так, як ми очікуємо. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні) +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// В тому числі ділення з остачою +5 / 2; // = 2.5 + +// В JavaScript є побітові операції; коли ви виконуєте таку операцію, +// число з плаваючою точкою переводиться в ціле зі знаком +// довжиною *до* 32 розрядів. +1 << 2; // = 4 + +// Пріоритет у виразах можна задати явно круглими дужками +(1 + 3) * 2; // = 8 + +// Є три спеціальні значення, які не є реальними числами: +Infinity; // "нескінченність", наприклад, як результат ділення на 0 +-Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0 +NaN; // "не число", наприклад, ділення 0/0 + +// Логічні типи +true; +false; + +// Рядки створюються за допомогою подвійних та одинарних лапок +'абв'; +"Hello, world!"; + +// Для логічного заперечення використовується знак оклику. +!true; // = false +!false; // = true + +// Строга рівність === +1 === 1; // = true +2 === 1; // = false + +// Строга нерівність !== +1 !== 1; // = false +2 !== 1; // = true + +// Інші оператори порівняння +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Рядки об’єднуються за допомогою оператор + +"hello, " + "world!"; // = "hello, world!" + +// І порівнюються за допомогою > і < +"a" < "b"; // = true + +// Перевірка на рівність з приведнням типів здійснюється оператором == +"5" == 5; // = true +null == undefined; // = true + +// ... але приведення не виконується при === +"5" === 5; // = false +null === undefined; // = false + +// ... приведення типів може призвести до дивних результатів +13 + !0; // 14 +"13" + !0; // '13true' + +// Можна отримати доступ до будь-якого символа рядка за допомгою charAt +"Это строка".charAt(0); // = 'Э' + +// ... або використати метод substring, щоб отримати більший кусок +"Hello, world".substring(0, 5); // = "Hello" + +// length - це не метод, а поле +"Hello".length; // = 5 + +// Типи null и undefined +null; // навмисна відсутність результату +undefined; // використовується для позначення відсутності присвоєного значення + +// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина. +// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що: +// 0 == "0". + +/////////////////////////////////// +// 2. Змінні, Масиви, Об’єкти + +// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з +// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння +// значення змінної використовується символ = +var someVar = 5; + +// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ... +someOtherVar = 10; + +// ... але ваша змінна буде створення в глобальному контексті, а не там, де +// ви її оголосили + +// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined +var someThirdVar; // = undefined + +// У математичних операцій є скорочені форми: +someVar += 5; // як someVar = someVar + 5; +someVar *= 10; // тепер someVar = 100 + +// Інкремент і декремент +someVar++; // тепер someVar дорівнює 101 +someVar--; // а зараз 100 + +// Масиви — це нумеровані списку, які зберігають значення будь-якого типу. +var myArray = ["Hello", 45, true]; + +// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками +// Індексація починається з нуля +myArray[1]; // = 45 + +// Массивы можно изменять, как и их длину, +myArray.push("Мир"); +myArray.length; // = 4 + +// додавання і редагування елементів +myArray[3] = "Hello"; + +// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах +var myObj = {key1: "Hello", key2: "World"}; + +// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє +// правилам формування назв змінних. Значення можуть бути будь-яких типів. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Атрибути можна отримати використовуючи квадратні дужки +myObj["my other key"]; // = 4 + +// Або через точку, якщо ключ є правильним ідентифікатором +myObj.myKey; // = "myValue" + +// Об’єкти можна динамічно змінювати й додавати нові поля +myObj.myThirdKey = true; + +// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Управляючі конструкції + +// Синтаксис для цього розділу майже такий самий, як у Java + +// Умовна конструкція +var count = 1; +if (count == 3) { + // виконується, якщо count дорівнює 3 +} else if (count == 4) { + // .. +} else { + // ... +} + +// ... цикл while. +while (true){ + // Нескінченний цикл! +} + +// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// цикл for такий самий, кяк в C і Java: +// ініціалізація; умова; крок. +for (var i = 0; i < 5; i++) { + // виконається 5 разів +} + +// && — логічне І, || — логічне АБО +if (house.size == "big" && house.color == "blue") { + house.contains = "bear"; +} +if (color == "red" || color == "blue") { + // колір червоний або синій +} + +// && і || використовують скорочене обчислення +// тому їх можна використовувати для задання значень за замовчуванням. +var name = otherName || "default"; + +// Оператор switch виконує перевірку на рівність за допомогою === +// використовуйте break, щоб призупити виконання наступного case, +grade = 4; +switch (grade) { + case 5: + console.log("Відмінно"); + break; + case 4: + console.log("Добре"); + break; + case 3: + console.log("Можна краще"); + break; + default: + console.log("Погано!"); + break; +} + + +/////////////////////////////////// +// 4. Функції, область видимості і замикання + +// Функції в JavaScript оголошуються за допомогою ключового слова function. +function myFunction(thing) { + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж +// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined +// із-за автоматичної вставки крапки з комою +function myFunction() +{ + return // <- крапка з комою вставляється автоматично + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися +// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник +// події. +function myFunction() { + // код буде виконано через 5 сек. +} +setTimeout(myFunction, 5000); +// setTimeout не є частиною мови, але реалізований в браузерах і Node.js + +// Функции не обязательно должны иметь имя при объявлении — вы можете написать +// анонимное определение функции непосредственно в аргументе другой функции. +// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати +// анонімну функцію прямо в якості аргумента іншої функції +setTimeout(function() { + // Цей код буде виконано через п’ять секунд +}, 5000); + +// В JavaScript реалізована концепція області видимості; функції мають свою +// область видимости, а інші блоки не мають +if (true) { + var i = 5; +} +i; // = 5, а не undefined, як це звичайно буває в інших мова + +// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе" +// що дозволяє уникнути проникнення змінних в глобальну область видимості +(function() { + var temporary = 5; + // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати + // змінні до глобальної області + window.permanent = 10; +})(); +temporary; // повідомлення про помилку ReferenceError +permanent; // = 10 + +// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция +// определена внутри другой функции, то внутренняя функция имеет доступ к +// переменным внешней функции даже после того, как контекст выполнения выйдет из +// внешней функции. +// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена +// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої +// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції +function sayHelloInFiveSeconds(name) { + var prompt = "Hello, " + name + "!"; + // Внутрішня функція зберігається в локальній області так, + // ніби функція була оголошена за допомогою ключового слова var + function inner() { + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться, + // після чого setTimeout викличе функцію inner. Але функція inner + // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt +} +sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!» + +/////////////////////////////////// +// 5. Об’єкти: конструктори і прототипи + +// Об’єкти можуть містити функції +var myObj = { + myFunc: function() { + return "Hello, world!"; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за +// допомогою ключового слова this. +myObj = { + myString: "Hello, world!", + myFunc: function() { + return this.myString; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Значення this залежить від того, як функція викликається +// а не від того, де вона визначена. Таким чином наша функція не працює, якщо +// вона викликана не в контексті об’єкта +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до +// цього об’єкта через this +var myOtherFunc = function() { +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO, WORLD!" + +// Контекст виконання функції можна задати за допомогою сall або apply +var anotherFunc = function(s) { + return this.myString + s; +} +anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!" + +// Функцiя apply приймає в якості аргументу масив +anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!" + +// apply можна використати, коли функція працює послідовністю аргументів, а +// ви хочете передати масив +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (Ой-ой!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт +// використовують bind +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" Hello!"); // = "Hello world, Hello!" + +// Bind можна використати для задання аргументів +var product = function(a, b) { return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт, +// доступний функції за допомогою this. Такі функції називають конструкторами. +var MyConstructor = function() { + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому +// об’єктів, інтерпретатор буде шукати поле в прототипі + +// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через +// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують +// стандартні способи використання прототипів, які ми побачимо пізніше +var myObj = { + myString: "Hello, world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function() { + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Аналогічно для функцій +myObj.myFunc(); // = "Hello, world!" + +// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук +// в прототипі прототипа і так далі +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити +// наш прототип, і наші зміни будуть всюди відображені. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу +// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим +// прототипом + +// Перший спосіб — це Object.create, який з’явився JavaScript недавно, +// а тому в деяких реалізаціях може бути не доступним. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не* +// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені +// цим конструктором і ключового слова new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function() { + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні +// об’єкти-обгортки +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Але вони не ідентичні +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0) { + // Этот код не выполнится, потому что 0 - это ложь. +} + +// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому +// ви можете розширити функціонал рядків: +String.prototype.firstCharacter = function() { + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості +// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих +// середовищах + +// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо +// використати функції за допомогою наступного поліфіла: +if (Object.create === undefined) { // не перезаписываем метод, если он существует + Object.create = function(proto) { + // Створюємо правильний конструктор з правильним прототипом + var Constructor = function(){}; + Constructor.prototype = proto; + + return new Constructor(); + } +} +``` + +## Що почитати + +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: http://eloquentjavascript.net/ +[9]: http://jstherightway.org/ -- cgit v1.2.3 From a25d4db0bcfb9325f69f68a2532df6fd88f4e78d Mon Sep 17 00:00:00 2001 From: rainjay Date: Tue, 3 Nov 2015 11:09:19 +0800 Subject: fix typo --- zh-tw/python-tw.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 10b4669c..c4706c43 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -450,7 +450,7 @@ def add(x, y): print "x is {0} and y is {1}".format(x, y) return x + y # 用 "return" 來回傳值 -# 用參數來呼叫韓式 +# 用參數來呼叫函式 add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 # 你也可以寫上參數名稱來呼叫函式 -- cgit v1.2.3 From ae26df01957eb870401494b2f0a993920c7da665 Mon Sep 17 00:00:00 2001 From: WinChris Date: Tue, 3 Nov 2015 09:42:26 +0100 Subject: Create HTML-fr.html.markdown --- fr-fr/HTML-fr.html.markdown | 115 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 fr-fr/HTML-fr.html.markdown diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown new file mode 100644 index 00000000..fdde9107 --- /dev/null +++ b/fr-fr/HTML-fr.html.markdown @@ -0,0 +1,115 @@ +--- +language: html +filename: learnhtml-fr.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +lang: fr-fr +--- +HTML signifie HyperText Markup Language. +C'est un langage (format de fichiers) qui permet d'écrire des pages internet. +C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). +Les fichiers HTML sont en réalité de simple fichier texte. +Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. +Ce balisage sert à donner une signification au texte ainsi entouré. +Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. + +**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. +Cet article porte principalement sur la syntaxe et quelques astuces. + + +```HTML + + + + + + + + + + + Mon Site + + +

Hello, world!

+ Venez voir ce que ça donne +

Ceci est un paragraphe

+

Ceci est un autre paragraphe

+
    +
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • +
  • Ceci est un autre item
  • +
  • Et ceci est le dernier item de la liste
  • +
+ + + + + + + + + + + + + + + + + + + + Mon Site + + + + + + + +

Hello, world!

+ + Venez voir ce que ça donne +

Ceci est un paragraphe

+

Ceci est un autre paragraphe

+
    + +
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • +
  • Ceci est un autre item
  • +
  • Et ceci est le dernier item de la liste
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
First Header Second Header
Première ligne, première cellule Première ligne, deuxième cellule
Deuxième ligne, première celluleDeuxième ligne, deuxième cellule
+ +## Utilisation + +Le HTML s'écrit dans des fichiers `.html`. + +## En savoir plus + +* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 05dac0dd3536dcf98c453198e6ebab5c122848a8 Mon Sep 17 00:00:00 2001 From: ioab Date: Wed, 4 Nov 2015 00:07:37 +0300 Subject: [vb/en] typos correction --- visualbasic.html.markdown | 64 +++++++++++++++++++++++------------------------ 1 file changed, 32 insertions(+), 32 deletions(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index dfb89307..4f696262 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -45,10 +45,10 @@ Module Module1 Case "3" 'Calculating Whole Numbers Console.Clear() CalculatingWholeNumbers() - Case "4" 'Calculting Decimal Numbers + Case "4" 'Calculating Decimal Numbers Console.Clear() CalculatingDecimalNumbers() - Case "5" 'Working Calcculator + Case "5" 'Working Calculator Console.Clear() WorkingCalculator() Case "6" 'Using Do While Loops @@ -77,10 +77,10 @@ Module Module1 'One - I'm using numbers to help with the above navigation when I come back 'later to build it. - 'We use private subs to seperate different sections of the program. + 'We use private subs to separate different sections of the program. Private Sub HelloWorldOutput() 'Title of Console Application - Console.Title = "Hello World Ouput | Learn X in Y Minutes" + Console.Title = "Hello World Output | Learn X in Y Minutes" 'Use Console.Write("") or Console.WriteLine("") to print outputs. 'Followed by Console.Read() alternatively Console.Readline() 'Console.ReadLine() prints the output to the console. @@ -102,7 +102,7 @@ Module Module1 Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. username = Console.ReadLine() 'Stores the users name. Console.WriteLine("Hello " + username) 'Output is Hello 'Their name' - Console.ReadLine() 'Outsputs the above. + Console.ReadLine() 'Outputs the above. 'The above will ask you a question followed by printing your answer. 'Other variables include Integer and we use Integer for whole numbers. End Sub @@ -110,7 +110,7 @@ Module Module1 'Three Private Sub CalculatingWholeNumbers() Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes" - Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect + Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104, etc Dim a As Integer = Console.ReadLine() Console.Write("Second number: ") 'Enter second whole number. Dim b As Integer = Console.ReadLine() @@ -126,7 +126,7 @@ Module Module1 'Of course we would like to be able to add up decimals. 'Therefore we could change the above from Integer to Double. - 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect + 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 etc Console.Write("First number: ") Dim a As Double = Console.ReadLine Console.Write("Second number: ") 'Enter second whole number. @@ -153,7 +153,7 @@ Module Module1 Dim f As Integer = a / b 'By adding the below lines we are able to calculate the subtract, - 'multply as well as divide the a and b values + 'multiply as well as divide the a and b values Console.Write(a.ToString() + " + " + b.ToString()) 'We want to pad the answers to the left by 3 spaces. Console.WriteLine(" = " + c.ToString.PadLeft(3)) @@ -199,7 +199,7 @@ Module Module1 Console.Write("Would you like to continue? (yes / no)") 'The program grabs the variable and prints and starts again. answer = Console.ReadLine - 'The command for the variable to work would be in this case "yes" + 'The command for the variable to work would be in this case "yes" Loop While answer = "yes" End Sub @@ -211,7 +211,7 @@ Module Module1 Console.Title = "Using For Loops | Learn X in Y Minutes" 'Declare Variable and what number it should count down in Step -1, - 'Step -2, Step -3 ect. + 'Step -2, Step -3 etc. For i As Integer = 10 To 0 Step -1 Console.WriteLine(i.ToString) 'Print the value of the counter Next i 'Calculate new value @@ -238,36 +238,36 @@ Module Module1 'Nine Private Sub IfElseStatement() - Console.Title = "If / Else Statement | Learn X in Y Minutes" + Console.Title = "If / Else Statement | Learn X in Y Minutes" 'Sometimes it is important to consider more than two alternatives. 'Sometimes there are a good few others. 'When this is the case, more than one if statement would be required. 'An if statement is great for vending machines. Where the user enters a code. - 'A1, A2, A3, ect to select an item. + 'A1, A2, A3, etc to select an item. 'All choices can be combined into a single if statement. Dim selection As String = Console.ReadLine 'Value for selection - Console.WriteLine("A1. for 7Up") - Console.WriteLine("A2. for Fanta") - Console.WriteLine("A3. for Dr. Pepper") - Console.WriteLine("A4. for Diet Coke") + Console.WriteLine("A1. for 7Up") + Console.WriteLine("A2. for Fanta") + Console.WriteLine("A3. for Dr. Pepper") + Console.WriteLine("A4. for Diet Coke") + Console.ReadLine() + If selection = "A1" Then + Console.WriteLine("7up") Console.ReadLine() - If selection = "A1" Then - Console.WriteLine("7up") - Console.ReadLine() - ElseIf selection = "A2" Then - Console.WriteLine("fanta") - Console.ReadLine() - ElseIf selection = "A3" Then - Console.WriteLine("dr. pepper") - Console.ReadLine() - ElseIf selection = "A4" Then - Console.WriteLine("diet coke") - Console.ReadLine() - Else - Console.WriteLine("Please select a product") - Console.ReadLine() - End If + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + Console.ReadLine() + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + Console.ReadLine() + ElseIf selection = "A4" Then + Console.WriteLine("diet coke") + Console.ReadLine() + Else + Console.WriteLine("Please select a product") + Console.ReadLine() + End If End Sub -- cgit v1.2.3 From d92db6ea39723c7778b225de0f27d977bdee0b99 Mon Sep 17 00:00:00 2001 From: ioab Date: Wed, 4 Nov 2015 00:24:43 +0300 Subject: [vb/en] fix type inconsistencies for calculator subs --- visualbasic.html.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index 4f696262..d6d1759d 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -126,10 +126,10 @@ Module Module1 'Of course we would like to be able to add up decimals. 'Therefore we could change the above from Integer to Double. - 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 etc + 'Enter a floating-point number, 1.2, 2.4, 50.1, 104.9 etc Console.Write("First number: ") Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. + Console.Write("Second number: ") 'Enter second floating-point number. Dim b As Double = Console.ReadLine Dim c As Double = a + b Console.WriteLine(c) @@ -145,12 +145,12 @@ Module Module1 'Copy and paste the above again. Console.Write("First number: ") Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b + Console.Write("Second number: ") 'Enter second floating-point number. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Dim d As Double = a * b + Dim e As Double = a - b + Dim f As Double = a / b 'By adding the below lines we are able to calculate the subtract, 'multiply as well as divide the a and b values @@ -179,11 +179,11 @@ Module Module1 Console.Write("First number: ") Dim a As Double = Console.ReadLine Console.Write("Second number: ") - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Dim d As Double = a * b + Dim e As Double = a - b + Dim f As Double = a / b Console.Write(a.ToString() + " + " + b.ToString()) Console.WriteLine(" = " + c.ToString.PadLeft(3)) @@ -196,7 +196,7 @@ Module Module1 Console.ReadLine() 'Ask the question, does the user wish to continue? Unfortunately it 'is case sensitive. - Console.Write("Would you like to continue? (yes / no)") + Console.Write("Would you like to continue? (yes / no) ") 'The program grabs the variable and prints and starts again. answer = Console.ReadLine 'The command for the variable to work would be in this case "yes" -- cgit v1.2.3 From 4552c56f03754ac6349c96ab73f794ecf1861254 Mon Sep 17 00:00:00 2001 From: ioab Date: Wed, 4 Nov 2015 00:49:44 +0300 Subject: [vb/en] remove unnecessary lines. Improve conditions (8 and 9) subs. --- visualbasic.html.markdown | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index d6d1759d..30d03f77 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -222,7 +222,7 @@ Module Module1 'Eight Private Sub ConditionalStatement() Console.Title = "Conditional Statements | Learn X in Y Minutes" - Dim userName As String = Console.ReadLine + Dim userName As String Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. userName = Console.ReadLine() 'Stores the users name. If userName = "Adam" Then @@ -244,30 +244,28 @@ Module Module1 'When this is the case, more than one if statement would be required. 'An if statement is great for vending machines. Where the user enters a code. 'A1, A2, A3, etc to select an item. - 'All choices can be combined into a single if statement. + 'All choices can be combined into a single if block. - Dim selection As String = Console.ReadLine 'Value for selection + Dim selection As String 'Declare a variable for selection + Console.WriteLine("Please select a product form our lovely vending machine.") Console.WriteLine("A1. for 7Up") Console.WriteLine("A2. for Fanta") Console.WriteLine("A3. for Dr. Pepper") Console.WriteLine("A4. for Diet Coke") - Console.ReadLine() + + selection = Console.ReadLine() 'Store a selection from the user If selection = "A1" Then Console.WriteLine("7up") - Console.ReadLine() ElseIf selection = "A2" Then Console.WriteLine("fanta") - Console.ReadLine() ElseIf selection = "A3" Then Console.WriteLine("dr. pepper") - Console.ReadLine() ElseIf selection = "A4" Then Console.WriteLine("diet coke") - Console.ReadLine() Else - Console.WriteLine("Please select a product") - Console.ReadLine() + Console.WriteLine("Sorry, I don't have any " + selection) End If + Console.ReadLine() End Sub -- cgit v1.2.3 From 7cbb4ec3ca21102f49e20f864223b084928db378 Mon Sep 17 00:00:00 2001 From: Deivuh Date: Tue, 3 Nov 2015 20:49:40 -0600 Subject: Correcciones de ortografia y de usos de palabras --- es-es/swift-es.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown index dcc3a607..c04ab02b 100644 --- a/es-es/swift-es.html.markdown +++ b/es-es/swift-es.html.markdown @@ -16,7 +16,7 @@ por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia de desarrolladores de Apple. -Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), el cual tiene un completo tutorial de Swift. +Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), el cual tiene un completo tutorial de Swift. ```swift @@ -56,7 +56,7 @@ let largeIntValue = 77_000 // 77000 let label = "some text " + String(myVariable) // Conversión (casting) let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string -// Valos específicos de la construcción (build) +// Valores específicos de la compilación (build) // utiliza la configuración -D #if false print("No impreso") @@ -185,8 +185,7 @@ do { } while 1 == 2 // Switch -// Muy potente, se puede pensar como declaraciones `if` -// Very powerful, think `if` statements with con azúcar sintáctico +// Muy potente, se puede pensar como declaraciones `if` con _azúcar sintáctico_ // Soportan String, instancias de objetos, y primitivos (Int, Double, etc) let vegetable = "red pepper" switch vegetable { @@ -196,7 +195,7 @@ case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let localScopeValue where localScopeValue.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(localScopeValue)?" -default: // required (in order to cover all possible input) +default: // obligatorio (se debe cumplir con todos los posibles valores de entrada) let vegetableComment = "Everything tastes good in soup." } @@ -273,7 +272,7 @@ print(someIntB) // 7 // -// MARK: Closures +// MARK: Closures (Clausuras) // var numbers = [1, 2, 6] @@ -288,7 +287,7 @@ numbers.map({ return result }) -// Cuando se conoce el tipo, cono en lo anterior, se puede hacer esto +// Cuando se conoce el tipo, como en lo anterior, se puede hacer esto numbers = numbers.map({ number in 3 * number }) // o esto //numbers = numbers.map({ $0 * 3 }) -- cgit v1.2.3 From d5e0a9fbf87e80427850e06511f768c19ebf74d7 Mon Sep 17 00:00:00 2001 From: Suhas Date: Wed, 4 Nov 2015 20:14:45 +0530 Subject: Add more complex key examples, and an example of inheritance --- yaml.html.markdown | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index 6e3e2c94..62f08fb9 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -3,6 +3,7 @@ language: yaml filename: learnyaml.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Suhas SG", "https://github.com/jargnar"] --- YAML is a data serialisation language designed to be directly writable and @@ -66,14 +67,19 @@ a_nested_map: # Maps don't have to have string keys. 0.25: a float key -# Keys can also be multi-line objects, using ? to indicate the start of a key. +# Keys can also be complex, like multi-line objects +# We use ? followed by a space to indicate the start of a complex key. ? | This is a key that has multiple lines : and this is its value -# YAML also allows collection types in keys, but many programming languages -# will complain. +# YAML also allows mapping between sequences with the complex key syntax +# Some language parsers might complain +# An example +? - Manchester United + - Real Madrid +: [ 2001-01-01, 2002-02-02 ] # Sequences (equivalent to lists or arrays) look like this: a_sequence: @@ -101,12 +107,31 @@ json_seq: [3, 2, 1, "takeoff"] anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name +# Anchors can be used to duplicate/inherit properties +base: &base + name: Everyone has same name + +foo: &foo + <<: *base + age: 10 + +bar: &bar + <<: *base + age: 20 + +# foo and bar would also have name: Everyone has same name + # YAML also has tags, which you can use to explicitly declare types. explicit_string: !!str 0.5 # Some parsers implement language specific tags, like this one for Python's # complex number type. python_complex_number: !!python/complex 1+2j +# We can also use yaml complex keys with language specific tags +? !!python/tuple [5, 7] +: Fifty Seven +# Would be {(5, 7): 'Fifty Seven'} in python + #################### # EXTRA YAML TYPES # #################### -- cgit v1.2.3 From 20f8f41ad5631f6638d42aca88ad2e0590abbccb Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Wed, 4 Nov 2015 22:15:59 +0530 Subject: Add description that strings can be lexicographically compared with comparison operators --- julia.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/julia.html.markdown b/julia.html.markdown index cba7cd45..2fedcfd8 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -102,6 +102,11 @@ false # Printing is easy println("I'm Julia. Nice to meet you!") +# String can be compared lexicographically compared +"good" > "bye" # => true +"good" == "good" # => true +"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true + #################################################### ## 2. Variables and Collections #################################################### -- cgit v1.2.3 From a6927f543ce6aee3ed409d7c88fc3695163c6609 Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Wed, 4 Nov 2015 23:04:42 +0530 Subject: Add description about compact assignment of functions --- julia.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/julia.html.markdown b/julia.html.markdown index 2fedcfd8..a9eed2da 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -395,6 +395,10 @@ end add(5, 6) # => 11 after printing out "x is 5 and y is 6" +# Compact assignment of functions +f_add(x, y) = x + y # => "f (generic function with 1 method)" +f_add(3, 4) # => 7 + # You can define functions that take a variable number of # positional arguments function varargs(args...) -- cgit v1.2.3 From a00cc7127170fe47203900d1ab1aac998501e6ec Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Wed, 4 Nov 2015 23:05:47 +0530 Subject: Add description about multiple return values --- julia.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/julia.html.markdown b/julia.html.markdown index a9eed2da..1a698834 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -399,6 +399,10 @@ add(5, 6) # => 11 after printing out "x is 5 and y is 6" f_add(x, y) = x + y # => "f (generic function with 1 method)" f_add(3, 4) # => 7 +# Function can also return multiple values as tuple +f(x, y) = x + y, x - y +f(3, 4) # => (7, -1) + # You can define functions that take a variable number of # positional arguments function varargs(args...) -- cgit v1.2.3 From 33628dca5cb4367cbbad1e4f48ddab0630b03330 Mon Sep 17 00:00:00 2001 From: Chris Martin Date: Wed, 4 Nov 2015 23:28:26 -0500 Subject: elixir: add eval results to try-rescue examples --- elixir.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/elixir.html.markdown b/elixir.html.markdown index eedeb227..720e080c 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -343,6 +343,7 @@ rescue RuntimeError -> "rescued a runtime error" _error -> "this will rescue any error" end +#=> "rescued a runtime error" # All exceptions have a message try do @@ -351,6 +352,7 @@ rescue x in [RuntimeError] -> x.message end +#=> "some error" ## --------------------------- ## -- Concurrency -- cgit v1.2.3 From 646eb2a2a19c4cecc20f680c959dd42da1a2961f Mon Sep 17 00:00:00 2001 From: Leslie Zhang Date: Sat, 7 Nov 2015 16:57:44 +0800 Subject: Correct math.sqrt(16) math.sqrt(16) returns 4.0 instead of 4 --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 2398e7ac..1f9d0e42 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -689,7 +689,7 @@ i.age # => raises an AttributeError # You can import modules import math -print(math.sqrt(16)) # => 4 +print(math.sqrt(16)) # => 4.0 # You can get specific functions from a module from math import ceil, floor -- cgit v1.2.3 From 3c1311a298211e099bb1d199947e88c2e09fddd4 Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sat, 7 Nov 2015 18:12:21 +0100 Subject: [markdown/fr] Corrects the filename --- fr-fr/markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index e5e7c73a..66f0efbe 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -2,7 +2,7 @@ language: markdown contributors: - ["Andrei Curelaru", "http://www.infinidad.fr"] -filename: markdown.md +filename: markdown-fr.md lang: fr-fr --- -- cgit v1.2.3 From fdf5b334392a7cadba2c89b2f5f05cb0290e5025 Mon Sep 17 00:00:00 2001 From: zygimantus Date: Sat, 7 Nov 2015 21:10:35 +0200 Subject: lithuanian translation of json --- lt-lt/json.html.markdown | 80 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 lt-lt/json.html.markdown diff --git a/lt-lt/json.html.markdown b/lt-lt/json.html.markdown new file mode 100644 index 00000000..70d7c714 --- /dev/null +++ b/lt-lt/json.html.markdown @@ -0,0 +1,80 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Zygimantus", "https://github.com/zygimantus"] +--- + +JSON („džeisonas“) yra itin paprastas duomenų mainų formatas, todėl tai bus pati lengviausia „Learn X in Y Minutes“ pamoka. + +JSON savo gryniausioje formoje neturi jokių komentarų, tačiau dauguma analizatorių priimtų C stiliaus komentarus (`//`, `/* */`). Kai kurie analizatoriai taip pat toleruoja gale esantį kablelį, pvz., kablelis po kiekvieno masyvo paskutinio elemento arba po paskutinio objekto lauko, tačiau jų reikėtų vengti dėl geresnio suderinamumo. + +JSON reikšmė privalo būti skaičius, eilutė, masyvas, objektas arba viena reikšmė iš šių: true, false, null. + +Palaikančios naršyklės yra: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+. + +Failo plėtinys JSON failams yra „.json“, o MIME tipas yra „application/json“. + +Dauguma programavimo kalbų palaiko JSON duomenų serializaciją (kodavimą) ir deserializaciją (dekodavimą) į natyviasias duomenų struktūras. Javascript turi visišką JSON teksto kaip duomenų manipuliavimo palaikymą. + +Daugiau informacijos galima rasti http://www.json.org/ + +JSON yra pastatytas iš dviejų struktūrų: +* Vardų/reikšmių porų rinkinys. Daugomoje kalbų, tai yra realizuojama kaip objektas, įrašas, struktūra, žodynas, hash lentelė, sąrašas su raktais arba asociatyvusis masyvas. +* Rūšiuotas reikšmių sąrašas. Daugumoje kalbų, toks sąrašas yra realizuojama kaip masyvas, vektorius, sąrašas arba seka. + +Objektas su įvairiomis vardo/reikšmės poromis. + +```json +{ + "raktas": "reikšmė", + + "raktai": "privalo visada būti uždaryti dvigubomis kabutėmis", + "skaičiai": 0, + "eilutės": "Labas, pasauli. Visas unikodas yra leidžiamas, kartu su \"vengimu\".", + "turi logiką?": true, + "niekas": null, + + "didelis skaičius": 1.2e+100, + + "objektai": { + "komentaras": "Dauguma tavo struktūrų ateis iš objektų.", + + "masyvas": [0, 1, 2, 3, "Masyvas gali turėti bet ką savyje.", 5], + + "kitas objektas": { + "komentaras": "Šie dalykai gali būti įdedami naudingai." + } + }, + + "kvailumas": [ + { + "kalio šaltiniai": ["bananai"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternativus stilius": { + "komentaras": "tik pažiūrėk!" + , "kablelio padėti": "nesvarbi - kol jis prieš kitą raktą, tada teisingas" + , "kitas komentaras": "kaip gražu" + } +} +``` + +Paprastas reikšmių masyvas pats savaime yra galiojantis JSON. + +```json +[1, 2, 3, "tekstas", true] +``` + +Objektai taip pat gali būti masyvų dalis. + +```json +[{"vardas": "Jonas", "amžius": 25}, {"vardas": "Eglė", "amžius": 29}, {"vardas": "Petras", "amžius": 31}] +``` -- cgit v1.2.3 From d50fc51aa615267ab78d18e046e94ec68529fdeb Mon Sep 17 00:00:00 2001 From: ioab Date: Sun, 8 Nov 2015 23:46:41 +0300 Subject: correction --- visualbasic.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index 30d03f77..0371e6f6 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -126,7 +126,7 @@ Module Module1 'Of course we would like to be able to add up decimals. 'Therefore we could change the above from Integer to Double. - 'Enter a floating-point number, 1.2, 2.4, 50.1, 104.9 etc + 'Enter a floating-point number, 1.2, 2.4, 50.1, 104.9, etc Console.Write("First number: ") Dim a As Double = Console.ReadLine Console.Write("Second number: ") 'Enter second floating-point number. @@ -211,7 +211,7 @@ Module Module1 Console.Title = "Using For Loops | Learn X in Y Minutes" 'Declare Variable and what number it should count down in Step -1, - 'Step -2, Step -3 etc. + 'Step -2, Step -3, etc. For i As Integer = 10 To 0 Step -1 Console.WriteLine(i.ToString) 'Print the value of the counter Next i 'Calculate new value -- cgit v1.2.3 From 341066bb8668a71e455f735ab34638c3533d2bdd Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 8 Nov 2015 22:04:44 +0100 Subject: Address #1390 @Zoffixnet, awaiting your review --- perl6.html.markdown | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 45b15f05..3eec19f3 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1,10 +1,9 @@ --- -name: perl6 category: language language: perl6 filename: learnperl6.pl contributors: - - ["Nami-Doc", "http://github.com/Nami-Doc"] + - ["vendethiel", "http://github.com/vendethiel"] --- Perl 6 is a highly capable, feature-rich programming language made for at @@ -374,6 +373,8 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return say join(' ', @array[15..*]); #=> 15 16 17 18 19 # which is equivalent to: say join(' ', @array[-> $n { 15..$n }]); +# Note: if you try to do either of those with an infinite loop, +# you'll trigger an infinite loop (your program won't finish) # You can use that in most places you'd expect, even assigning to an array my @numbers = ^20; @@ -763,8 +764,9 @@ try { # and `enum`) are actually packages. (Packages are the lowest common denominator) # Packages are important - especially as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. -# You usually don't use packages directly: you use `class Package::Name::Here;`, -# or if you only want to export variables/subs, you can use `module`: +# You're not supposed to use the package keyword, usually: +# you use `class Package::Name::Here;` to declare a class, +# or if you only want to export variables/subs, you can use `module`: module Hello::World { # Bracketed form # If `Hello` doesn't exist yet, it'll just be a "stub", # that can be redeclared as something else later. @@ -774,11 +776,6 @@ unit module Parse::Text; # file-scoped form grammar Parse::Text::Grammar { # A grammar is a package, which you could `use` } -# NOTE for Perl 5 users: even though the `package` keyword exists, -# the braceless form is invalid (to catch a "perl5ism"). This will error out: -# package Foo; # because Perl 6 will think the entire file is Perl 5 -# Just use `module` or the brace version of `package`. - # You can use a module (bring its declarations into scope) with `use` use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module say from-json('[1]').perl; #=> [1] @@ -870,8 +867,16 @@ LEAVE { say "Runs everytime you leave a block, even when an exception PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" } +# exemple: +for 0..2 { + PRE { $_ > 1 } # This is going to blow up with "Precondition failed" +} + POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" } +for 0..2 { + POST { $_ < 2 } # This is going to blow up with "Postcondition failed" +} ## * Block/exceptions phasers sub { @@ -1239,14 +1244,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left # Group: you can group parts of your regexp with `[]`. # These groups are *not* captured (like PCRE's `(?:)`). so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing -so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; +so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /; # The previous line returns `True`. -# We match the "ABC" 1 or more time (the `+` was applied to the group). +# We match the "012" 1 or more time (the `+` was applied to the group). # But this does not go far enough, because we can't actually get back what # we matched. # Capture: We can actually *capture* the results of the regexp, using parentheses. -so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below) +so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below) # So, starting with the grouping explanations. # As we said before, our `Match` object is available as `$/`: -- cgit v1.2.3 From eee0aba489080a13cdca80af46c3128997d792b3 Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Mon, 9 Nov 2015 10:33:22 +0530 Subject: Remove the extra 'compared' in julia.html.markdown --- julia.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/julia.html.markdown b/julia.html.markdown index 1a698834..fcfa7e30 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -102,7 +102,7 @@ false # Printing is easy println("I'm Julia. Nice to meet you!") -# String can be compared lexicographically compared +# String can be compared lexicographically "good" > "bye" # => true "good" == "good" # => true "1 + 2 = 3" == "1 + 2 = $(1+2)" # => true -- cgit v1.2.3 From afc5ea14654e0e9cd11c7ef1b672639d12418bad Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Mon, 9 Nov 2015 17:54:05 -0600 Subject: - update examples - add examples for labeled tuples and computed properties --- swift.html.markdown | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 0d1d2df4..5e6b76e6 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -211,7 +211,7 @@ greet("Bob", "Tuesday") func greet2(#requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } -greet2(requiredName:"John", externalParamName: "Sunday") +greet2(requiredName: "John", externalParamName: "Sunday") // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { @@ -224,6 +224,16 @@ let (_, price1, _) = pricesTuple // price1 == 3.69 println(price1 == pricesTuple.1) // true println("Gas price: \(price)") +// Named tuple params +func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) { + return (1.77, 37.70, 7.37) +} +let pricesTuple2 = getGasPrices2() +let price2 = pricesTuple2.lowestPrice +let (_, price3, _) = pricesTuple2 +println(pricesTuple2.highestPrice == pricesTuple2.1) // true +println("Highest gas price: \(pricesTuple2.highestPrice)") + // Variadic Args func setup(numbers: Int...) { // its an array @@ -337,6 +347,11 @@ internal class Rect: Shape { } } + // 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) -- cgit v1.2.3 From 618f8f5badfded04ee1edb7c24ccf24ea61a947b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Mon, 9 Nov 2015 18:09:48 -0600 Subject: - update Swift examples - update to upgrade to Swift 2.1 - code cleanup --- swift.html.markdown | 81 +++++++++++++++++++++++++---------------------------- 1 file changed, 38 insertions(+), 43 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index f2e9d04c..a39bc1d6 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -32,7 +32,7 @@ import UIKit // In Swift 2, println and print were combined into one print method. Print automatically appends a new line. print("Hello, world") // println is now print -print("Hello, world", appendNewLine: false) // printing without appending a newline +print("Hello, world", terminator: "") // printing without appending a newline // variables (var) value can change after being set // constants (let) value can NOT be changed after being set @@ -60,14 +60,14 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation print("Build value: \(buildValue)") // Build value: 7 /* - Optionals are a Swift language feature that either contains a value, - or contains nil (no value) to indicate that a value is missing. - A question mark (?) after the type marks the value as optional. +Optionals are a Swift language feature that either contains a value, +or contains nil (no value) to indicate that a value is missing. +A question mark (?) after the type marks the value as optional. - Because Swift requires every property to have a value, even nil must be - explicitly stored as an Optional value. +Because Swift requires every property to have a value, even nil must be +explicitly stored as an Optional value. - Optional is an enum. +Optional is an enum. */ var someOptionalString: String? = "optional" // Can be nil // same as above, but ? is a postfix operator (syntax candy) @@ -84,9 +84,9 @@ if someOptionalString != nil { someOptionalString = nil /* - 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. +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. */ // implicitly unwrapped optional @@ -120,8 +120,8 @@ anyObjectVar = "Changed value to a string, not good practice, but possible." // /* - Array and Dictionary types are structs. So `let` and `var` also indicate - that they are mutable (var) or immutable (let) when declaring these types. +Array and Dictionary types are structs. So `let` and `var` also indicate +that they are mutable (var) or immutable (let) when declaring these types. */ // Array @@ -178,8 +178,8 @@ while i < 1000 { i *= 2 } -// do-while loop -do { +// repeat-while loop +repeat { print("hello") } while 1 == 2 @@ -209,22 +209,22 @@ default: // required (in order to cover all possible input) // Function with Swift header docs (format as reStructedText) /** - A greet operation +A greet operation - - A bullet in docs - - Another bullet in the docs +- A bullet in docs +- Another bullet in the docs - :param: name A name - :param: day A day - :returns: A string containing the name and day value. +:param: name A name +:param: day A day +:returns: A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } -greet("Bob", "Tuesday") +greet("Bob", day: "Tuesday") // similar to above except for the function parameter behaviors -func greet2(#requiredName: String, externalParamName localParamName: String) -> String { +func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } greet2(requiredName: "John", externalParamName: "Sunday") @@ -247,14 +247,14 @@ func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Do let pricesTuple2 = getGasPrices2() let price2 = pricesTuple2.lowestPrice let (_, price3, _) = pricesTuple2 -println(pricesTuple2.highestPrice == pricesTuple2.1) // true -println("Highest gas price: \(pricesTuple2.highestPrice)") +print(pricesTuple2.highestPrice == pricesTuple2.1) // true +print("Highest gas price: \(pricesTuple2.highestPrice)") // Variadic Args func setup(numbers: Int...) { // its an array - let number = numbers[0] - let argCount = numbers.count + let _ = numbers[0] + let _ = numbers.count } // Passing and returning functions @@ -275,7 +275,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { } var someIntA = 7 var someIntB = 3 -swapTwoInts(&someIntA, &someIntB) +swapTwoInts(&someIntA, b: &someIntB) print(someIntB) // 7 @@ -303,23 +303,17 @@ numbers = numbers.map({ number in 3 * number }) print(numbers) // [3, 6, 18] // Trailing closure -numbers = sorted(numbers) { $0 > $1 } +numbers = numbers.sort { $0 > $1 } print(numbers) // [18, 6, 3] -// Super shorthand, since the < operator infers the types - -numbers = sorted(numbers, < ) - -print(numbers) // [3, 6, 18] - // // MARK: Structures // // Structures and classes have very similar capabilities struct NamesTable { - let names = [String]() + let names: [String] // Custom subscript subscript(index: Int) -> String { @@ -472,9 +466,10 @@ enum Suit { // when the variable is explicitly declared var suitValue: Suit = .Hearts -// Non-Integer enums require direct raw value assignments +// String enums can have direct raw value assignments +// or their raw values will be derived from the Enum field enum BookName: String { - case John = "John" + case John case Luke = "Luke" } print("Name: \(BookName.John.rawValue)") @@ -518,7 +513,7 @@ protocol ShapeGenerator { // Protocols declared with @objc allow optional functions, // which allow you to check for conformance @objc protocol TransformShape { - optional func reshaped() + optional func reshape() optional func canReshape() -> Bool } @@ -531,9 +526,9 @@ class MyShape: Rect { // Place a question mark after an optional property, method, or // subscript to gracefully ignore a nil value and return nil // instead of throwing a runtime error ("optional chaining"). - if let allow = self.delegate?.canReshape?() { + if let reshape = self.delegate?.canReshape?() where reshape { // test for delegate then for method - self.delegate?.reshaped?() + self.delegate?.reshape?() } } } @@ -546,7 +541,7 @@ class MyShape: Rect { // `extension`s: Add extra functionality to an already existing type // Square now "conforms" to the `Printable` protocol -extension Square: Printable { +extension Square: CustomStringConvertible { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" } @@ -571,8 +566,8 @@ print(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. -func findIndex(array: [T], valueToFind: T) -> Int? { - for (index, value) in enumerate(array) { +func findIndex(array: [T], _ valueToFind: T) -> Int? { + for (index, value) in array.enumerate() { if value == valueToFind { return index } -- cgit v1.2.3 From 70b3fa5bb6410b1c50e549a76807fd509119dd85 Mon Sep 17 00:00:00 2001 From: Ramanan Balakrishnan Date: Mon, 9 Nov 2015 18:15:18 -0800 Subject: add output of latex file --- latex.pdf | Bin 0 -> 145946 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100755 latex.pdf diff --git a/latex.pdf b/latex.pdf new file mode 100755 index 00000000..6cf5f378 Binary files /dev/null and b/latex.pdf differ -- cgit v1.2.3 From 99b2c3db3705b5231ca360c9fa69c8319caab69b Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Tue, 10 Nov 2015 17:03:40 -0600 Subject: - add where and guard examples --- swift.html.markdown | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index a39bc1d6..df9c5092 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -149,6 +149,14 @@ var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above // MARK: Control Flow // +// Condition statements support "where" clauses, which can be used +// to help provide conditions on optional values. +// Both the assignment and the "where" clause must pass. +let someNumber = Optional(7) +if let num = someNumber where num > 3 { + print("num is greater than 3") +} + // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { @@ -198,7 +206,6 @@ default: // required (in order to cover all possible input) let vegetableComment = "Everything tastes good in soup." } - // // MARK: Functions // @@ -240,7 +247,7 @@ let (_, price1, _) = pricesTuple // price1 == 3.69 print(price1 == pricesTuple.1) // true print("Gas price: \(price)") -// Named tuple params +// Labeled/named tuple params func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) { return (1.77, 37.70, 7.37) } @@ -250,6 +257,18 @@ let (_, price3, _) = pricesTuple2 print(pricesTuple2.highestPrice == pricesTuple2.1) // true print("Highest gas price: \(pricesTuple2.highestPrice)") +// guard statements +func testGuard() { + // guards provide early exits or breaks, placing the error handler code near the conditions. + // it places variables it declares in the same scope as the guard statement. + guard let aNumber = Optional(7) else { + return + } + + print("number is \(aNumber)") +} +testGuard() + // Variadic Args func setup(numbers: Int...) { // its an array -- cgit v1.2.3 From f48bfca185bff1e8d69f29039f8e796db8ca6f68 Mon Sep 17 00:00:00 2001 From: Ramanan Balakrishnan Date: Tue, 10 Nov 2015 22:26:17 -0800 Subject: [latex/en] Cleanup of pdf file after previous commit --- latex.html.markdown | 1 + latex.pdf | Bin 145946 -> 0 bytes 2 files changed, 1 insertion(+) delete mode 100755 latex.pdf diff --git a/latex.html.markdown b/latex.html.markdown index e89d7e3b..2492f226 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Chaitanya Krishna Ande", "http://icymist.github.io"] - ["Colton Kohnke", "http://github.com/voltnor"] - ["Sricharan Chiruvolu", "http://sricharan.xyz"] + - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] filename: learn-latex.tex --- diff --git a/latex.pdf b/latex.pdf deleted file mode 100755 index 6cf5f378..00000000 Binary files a/latex.pdf and /dev/null differ -- cgit v1.2.3 From 4077facd3c880c96f8044fc99ca656af8d1427b3 Mon Sep 17 00:00:00 2001 From: Serg Date: Wed, 11 Nov 2015 08:58:13 +0200 Subject: Update javascript-ua.html.markdown Fixed translation and heading. --- uk-ua/javascript-ua.html.markdown | 88 ++++++++++++++++++--------------------- 1 file changed, 41 insertions(+), 47 deletions(-) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index fedbf5ac..dae27d32 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -3,11 +3,11 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] -filename: javascript-ru.js +filename: javascript-ua.js translators: - - ["Alexey Gonchar", "http://github.com/finico"] - - ["Andre Polykanine", "https://github.com/Oire"] -lang: ru-ru + - ["Ivan Neznayu", "https://github.com/IvanEh"] + - ["Serhii Maksymchuk", "https://maximchuk.tk"] +lang: uk-ua --- JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape. @@ -25,7 +25,7 @@ JavaScript було створено в 1995 році Бренданом Айк /* а багаторядкові коментарі починаються з послідовності слеша та зірочки і закінчуються символами зірочка-слеш */ -Інструкції можуть закінчуватися крапкою з комою ; +//Інструкції можуть закінчуватися крапкою з комою ; doStuff(); // ... але не обов’язково, тому що крапка з комою автоматично вставляється на @@ -51,7 +51,7 @@ doStuff() 10 * 2; // = 20 35 / 5; // = 7 -// В тому числі ділення з остачою +// В тому числі ділення з остачею 5 / 2; // = 2.5 // В JavaScript є побітові операції; коли ви виконуєте таку операцію, @@ -73,7 +73,7 @@ false; // Рядки створюються за допомогою подвійних та одинарних лапок 'абв'; -"Hello, world!"; +"Світ, привіт!"; // Для логічного заперечення використовується знак оклику. !true; // = false @@ -93,10 +93,10 @@ false; 2 <= 2; // = true 2 >= 2; // = true -// Рядки об’єднуються за допомогою оператор + +// Рядки об’єднуються за допомогою оператора + "hello, " + "world!"; // = "hello, world!" -// І порівнюються за допомогою > і < +// І порівнюються за допомогою > та < "a" < "b"; // = true // Перевірка на рівність з приведнням типів здійснюється оператором == @@ -112,7 +112,7 @@ null === undefined; // = false "13" + !0; // '13true' // Можна отримати доступ до будь-якого символа рядка за допомгою charAt -"Это строка".charAt(0); // = 'Э' +"Це рядок".charAt(0); // = 'Ц' // ... або використати метод substring, щоб отримати більший кусок "Hello, world".substring(0, 5); // = "Hello" @@ -124,8 +124,8 @@ null === undefined; // = false null; // навмисна відсутність результату undefined; // використовується для позначення відсутності присвоєного значення -// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина. -// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що: +// false, null, undefined, NaN, 0 та "" — хиба; все інше - істина. +// Потрібно відмітити, що 0 — це хиба, а "0" — істина, не зважаючи на те що: // 0 == "0". /////////////////////////////////// @@ -139,7 +139,7 @@ var someVar = 5; // якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ... someOtherVar = 10; -// ... але ваша змінна буде створення в глобальному контексті, а не там, де +// ... але ваша змінна буде створена в глобальному контексті, а не там, де // ви її оголосили // Змінні, які оголошені без присвоєння, автоматично приймають значення undefined @@ -153,21 +153,21 @@ someVar *= 10; // тепер someVar = 100 someVar++; // тепер someVar дорівнює 101 someVar--; // а зараз 100 -// Масиви — це нумеровані списку, які зберігають значення будь-якого типу. -var myArray = ["Hello", 45, true]; +// Масиви — це нумеровані списки, які зберігають значення будь-якого типу. +var myArray = ["Привіт", 45, true]; // Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками // Індексація починається з нуля myArray[1]; // = 45 -// Массивы можно изменять, как и их длину, -myArray.push("Мир"); +// Масиви можна змінювати, як і їх довжину +myArray.push("Привіт"); myArray.length; // = 4 -// додавання і редагування елементів -myArray[3] = "Hello"; +// Додавання і редагування елементів +myArray[3] = "світ"; -// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах +// Об’єкти в JavaScript схожі на словники або асоціативні масиви в інших мовах var myObj = {key1: "Hello", key2: "World"}; // Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє @@ -183,11 +183,11 @@ myObj.myKey; // = "myValue" // Об’єкти можна динамічно змінювати й додавати нові поля myObj.myThirdKey = true; -// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined +// Коли ви звертаєтесь до поля, що не існує, ви отримуєте значення undefined myObj.myFourthKey; // = undefined /////////////////////////////////// -// 3. Управляючі конструкції +// 3. Керуючі конструкції // Синтаксис для цього розділу майже такий самий, як у Java @@ -212,7 +212,7 @@ do { input = getInput(); } while (!isValid(input)) -// цикл for такий самий, кяк в C і Java: +// цикл for такий самий, як в C і Java: // ініціалізація; умова; крок. for (var i = 0; i < 5; i++) { // виконається 5 разів @@ -226,7 +226,7 @@ if (color == "red" || color == "blue") { // колір червоний або синій } -// && і || використовують скорочене обчислення +// && та || використовують скорочене обчислення // тому їх можна використовувати для задання значень за замовчуванням. var name = otherName || "default"; @@ -260,7 +260,7 @@ myFunction("foo"); // = "FOO" // Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж // рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined -// із-за автоматичної вставки крапки з комою +// через автоматичну вставку крапки з комою function myFunction() { return // <- крапка з комою вставляється автоматично @@ -279,8 +279,6 @@ function myFunction() { setTimeout(myFunction, 5000); // setTimeout не є частиною мови, але реалізований в браузерах і Node.js -// Функции не обязательно должны иметь имя при объявлении — вы можете написать -// анонимное определение функции непосредственно в аргументе другой функции. // Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати // анонімну функцію прямо в якості аргумента іншої функції setTimeout(function() { @@ -288,11 +286,11 @@ setTimeout(function() { }, 5000); // В JavaScript реалізована концепція області видимості; функції мають свою -// область видимости, а інші блоки не мають +// область видимості, а інші блоки не мають if (true) { var i = 5; } -i; // = 5, а не undefined, як це звичайно буває в інших мова +i; // = 5, а не undefined, як це звичайно буває в інших мовах // Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе" // що дозволяє уникнути проникнення змінних в глобальну область видимості @@ -305,26 +303,22 @@ i; // = 5, а не undefined, як це звичайно буває в інши temporary; // повідомлення про помилку ReferenceError permanent; // = 10 -// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция -// определена внутри другой функции, то внутренняя функция имеет доступ к -// переменным внешней функции даже после того, как контекст выполнения выйдет из -// внешней функции. -// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена +// Замикання - один з найпотужніших інтрументів JavaScript. Якщо функція визначена // всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої // функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції function sayHelloInFiveSeconds(name) { - var prompt = "Hello, " + name + "!"; + var prompt = "Привіт, " + name + "!"; // Внутрішня функція зберігається в локальній області так, // ніби функція була оголошена за допомогою ключового слова var function inner() { alert(prompt); } setTimeout(inner, 5000); - // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться, + // setTimeout асинхронна, тому функція sayHelloInFiveSeconds одразу завершиться, // після чого setTimeout викличе функцію inner. Але функція inner // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt } -sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!» +sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Привіт, Адам!» /////////////////////////////////// // 5. Об’єкти: конструктори і прототипи @@ -394,7 +388,7 @@ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 // У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому -// об’єктів, інтерпретатор буде шукати поле в прототипі +// об’єкті, інтерпретатор буде шукати поле в прототипі // Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через // "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують @@ -415,24 +409,24 @@ myObj.meaningOfLife; // = 42 // Аналогічно для функцій myObj.myFunc(); // = "Hello, world!" -// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук +// Якщо інтерпретатор не знайде властивість в прототипі, то він продовжить пошук // в прототипі прототипа і так далі myPrototype.__proto__ = { myBoolean: true }; myObj.myBoolean; // = true -// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити +// Кожен об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити // наш прототип, і наші зміни будуть всюди відображені. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу -// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим +// Ми сказали, що властивість __proto__ нестандартна, і нема ніякого стандартного способу +// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт із заданим // прототипом -// Перший спосіб — це Object.create, який з’явився JavaScript недавно, -// а тому в деяких реалізаціях може бути не доступним. +// Перший спосіб — це Object.create, який з’явився в JavaScript недавно, +// а тому в деяких реалізаціях може бути недоступним. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 @@ -461,7 +455,7 @@ typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0) { - // Этот код не выполнится, потому что 0 - это ложь. + // Цей код не виконається, тому що 0 - це хиба. } // Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому @@ -475,9 +469,9 @@ String.prototype.firstCharacter = function() { // JavaScript в старій реалізації мови, так що вони можуть бути використані в старих // середовищах -// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо +// Наприклад, Object.create доступний не у всіх реалізаціях, але ми можемо // використати функції за допомогою наступного поліфіла: -if (Object.create === undefined) { // не перезаписываем метод, если он существует +if (Object.create === undefined) { // не перезаписуємо метод, якщо він існує Object.create = function(proto) { // Створюємо правильний конструктор з правильним прототипом var Constructor = function(){}; -- cgit v1.2.3 From 1391eed837546e442eeaa48bfae9504b999b8c58 Mon Sep 17 00:00:00 2001 From: Dan Ellis Date: Tue, 10 Nov 2015 23:31:16 -0800 Subject: Fix variable name typo in dlang examples. --- d.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 6f3710ab..9ebba385 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -53,15 +53,15 @@ void main() { // For and while are nice, but in D-land we prefer 'foreach' loops. // The '..' creates a continuous range, including the first value // but excluding the last. - foreach(i; 1..1_000_000) { + foreach(n; 1..1_000_000) { if(n % 2 == 0) - writeln(i); + writeln(n); } // There's also 'foreach_reverse' when you want to loop backwards. - foreach_reverse(i; 1..int.max) { + foreach_reverse(n; 1..int.max) { if(n % 2 == 1) { - writeln(i); + writeln(n); } else { writeln("No!"); } -- cgit v1.2.3 From b97027263a7247110597bc6cbe6b46a78cb5e86f Mon Sep 17 00:00:00 2001 From: Zygimantus Date: Wed, 11 Nov 2015 10:22:03 +0200 Subject: -lt to filename added --- lt-lt/json-lt.html.markdown | 80 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 lt-lt/json-lt.html.markdown diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown new file mode 100644 index 00000000..70d7c714 --- /dev/null +++ b/lt-lt/json-lt.html.markdown @@ -0,0 +1,80 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Zygimantus", "https://github.com/zygimantus"] +--- + +JSON („džeisonas“) yra itin paprastas duomenų mainų formatas, todėl tai bus pati lengviausia „Learn X in Y Minutes“ pamoka. + +JSON savo gryniausioje formoje neturi jokių komentarų, tačiau dauguma analizatorių priimtų C stiliaus komentarus (`//`, `/* */`). Kai kurie analizatoriai taip pat toleruoja gale esantį kablelį, pvz., kablelis po kiekvieno masyvo paskutinio elemento arba po paskutinio objekto lauko, tačiau jų reikėtų vengti dėl geresnio suderinamumo. + +JSON reikšmė privalo būti skaičius, eilutė, masyvas, objektas arba viena reikšmė iš šių: true, false, null. + +Palaikančios naršyklės yra: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+. + +Failo plėtinys JSON failams yra „.json“, o MIME tipas yra „application/json“. + +Dauguma programavimo kalbų palaiko JSON duomenų serializaciją (kodavimą) ir deserializaciją (dekodavimą) į natyviasias duomenų struktūras. Javascript turi visišką JSON teksto kaip duomenų manipuliavimo palaikymą. + +Daugiau informacijos galima rasti http://www.json.org/ + +JSON yra pastatytas iš dviejų struktūrų: +* Vardų/reikšmių porų rinkinys. Daugomoje kalbų, tai yra realizuojama kaip objektas, įrašas, struktūra, žodynas, hash lentelė, sąrašas su raktais arba asociatyvusis masyvas. +* Rūšiuotas reikšmių sąrašas. Daugumoje kalbų, toks sąrašas yra realizuojama kaip masyvas, vektorius, sąrašas arba seka. + +Objektas su įvairiomis vardo/reikšmės poromis. + +```json +{ + "raktas": "reikšmė", + + "raktai": "privalo visada būti uždaryti dvigubomis kabutėmis", + "skaičiai": 0, + "eilutės": "Labas, pasauli. Visas unikodas yra leidžiamas, kartu su \"vengimu\".", + "turi logiką?": true, + "niekas": null, + + "didelis skaičius": 1.2e+100, + + "objektai": { + "komentaras": "Dauguma tavo struktūrų ateis iš objektų.", + + "masyvas": [0, 1, 2, 3, "Masyvas gali turėti bet ką savyje.", 5], + + "kitas objektas": { + "komentaras": "Šie dalykai gali būti įdedami naudingai." + } + }, + + "kvailumas": [ + { + "kalio šaltiniai": ["bananai"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternativus stilius": { + "komentaras": "tik pažiūrėk!" + , "kablelio padėti": "nesvarbi - kol jis prieš kitą raktą, tada teisingas" + , "kitas komentaras": "kaip gražu" + } +} +``` + +Paprastas reikšmių masyvas pats savaime yra galiojantis JSON. + +```json +[1, 2, 3, "tekstas", true] +``` + +Objektai taip pat gali būti masyvų dalis. + +```json +[{"vardas": "Jonas", "amžius": 25}, {"vardas": "Eglė", "amžius": 29}, {"vardas": "Petras", "amžius": 31}] +``` -- cgit v1.2.3 From cbbb4cb49f658e5ce1c3404365796af3c7aa2520 Mon Sep 17 00:00:00 2001 From: Zygimantus Date: Wed, 11 Nov 2015 13:47:21 +0200 Subject: lang added --- lt-lt/json-lt.html.markdown | 1 + lt-lt/json.html.markdown | 80 --------------------------------------------- 2 files changed, 1 insertion(+), 80 deletions(-) delete mode 100644 lt-lt/json.html.markdown diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown index 70d7c714..bfe00709 100644 --- a/lt-lt/json-lt.html.markdown +++ b/lt-lt/json-lt.html.markdown @@ -1,6 +1,7 @@ --- language: json filename: learnjson.json +lang: lt contributors: - ["Zygimantus", "https://github.com/zygimantus"] --- diff --git a/lt-lt/json.html.markdown b/lt-lt/json.html.markdown deleted file mode 100644 index 70d7c714..00000000 --- a/lt-lt/json.html.markdown +++ /dev/null @@ -1,80 +0,0 @@ ---- -language: json -filename: learnjson.json -contributors: - - ["Zygimantus", "https://github.com/zygimantus"] ---- - -JSON („džeisonas“) yra itin paprastas duomenų mainų formatas, todėl tai bus pati lengviausia „Learn X in Y Minutes“ pamoka. - -JSON savo gryniausioje formoje neturi jokių komentarų, tačiau dauguma analizatorių priimtų C stiliaus komentarus (`//`, `/* */`). Kai kurie analizatoriai taip pat toleruoja gale esantį kablelį, pvz., kablelis po kiekvieno masyvo paskutinio elemento arba po paskutinio objekto lauko, tačiau jų reikėtų vengti dėl geresnio suderinamumo. - -JSON reikšmė privalo būti skaičius, eilutė, masyvas, objektas arba viena reikšmė iš šių: true, false, null. - -Palaikančios naršyklės yra: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+. - -Failo plėtinys JSON failams yra „.json“, o MIME tipas yra „application/json“. - -Dauguma programavimo kalbų palaiko JSON duomenų serializaciją (kodavimą) ir deserializaciją (dekodavimą) į natyviasias duomenų struktūras. Javascript turi visišką JSON teksto kaip duomenų manipuliavimo palaikymą. - -Daugiau informacijos galima rasti http://www.json.org/ - -JSON yra pastatytas iš dviejų struktūrų: -* Vardų/reikšmių porų rinkinys. Daugomoje kalbų, tai yra realizuojama kaip objektas, įrašas, struktūra, žodynas, hash lentelė, sąrašas su raktais arba asociatyvusis masyvas. -* Rūšiuotas reikšmių sąrašas. Daugumoje kalbų, toks sąrašas yra realizuojama kaip masyvas, vektorius, sąrašas arba seka. - -Objektas su įvairiomis vardo/reikšmės poromis. - -```json -{ - "raktas": "reikšmė", - - "raktai": "privalo visada būti uždaryti dvigubomis kabutėmis", - "skaičiai": 0, - "eilutės": "Labas, pasauli. Visas unikodas yra leidžiamas, kartu su \"vengimu\".", - "turi logiką?": true, - "niekas": null, - - "didelis skaičius": 1.2e+100, - - "objektai": { - "komentaras": "Dauguma tavo struktūrų ateis iš objektų.", - - "masyvas": [0, 1, 2, 3, "Masyvas gali turėti bet ką savyje.", 5], - - "kitas objektas": { - "komentaras": "Šie dalykai gali būti įdedami naudingai." - } - }, - - "kvailumas": [ - { - "kalio šaltiniai": ["bananai"] - }, - [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, "neo"], - [0, 0, 0, 1] - ] - ], - - "alternativus stilius": { - "komentaras": "tik pažiūrėk!" - , "kablelio padėti": "nesvarbi - kol jis prieš kitą raktą, tada teisingas" - , "kitas komentaras": "kaip gražu" - } -} -``` - -Paprastas reikšmių masyvas pats savaime yra galiojantis JSON. - -```json -[1, 2, 3, "tekstas", true] -``` - -Objektai taip pat gali būti masyvų dalis. - -```json -[{"vardas": "Jonas", "amžius": 25}, {"vardas": "Eglė", "amžius": 29}, {"vardas": "Petras", "amžius": 31}] -``` -- cgit v1.2.3 From 3598a6f3304fb1fd297af3e6df54d0f849e2a35d Mon Sep 17 00:00:00 2001 From: Zygimantus Date: Wed, 11 Nov 2015 15:21:56 +0200 Subject: small fix --- lt-lt/json-lt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown index bfe00709..8c97e598 100644 --- a/lt-lt/json-lt.html.markdown +++ b/lt-lt/json-lt.html.markdown @@ -1,7 +1,7 @@ --- language: json filename: learnjson.json -lang: lt +lang: lt-lt contributors: - ["Zygimantus", "https://github.com/zygimantus"] --- -- cgit v1.2.3 From 62a380dddf47d70e31f308c2120c9fa8a169e9af Mon Sep 17 00:00:00 2001 From: ComSecNinja Date: Wed, 11 Nov 2015 15:39:16 +0200 Subject: Translate en/Markdown to Finnish --- fi-fi/markdown-fi.html.markdown | 259 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 fi-fi/markdown-fi.html.markdown diff --git a/fi-fi/markdown-fi.html.markdown b/fi-fi/markdown-fi.html.markdown new file mode 100644 index 00000000..14b0f1d9 --- /dev/null +++ b/fi-fi/markdown-fi.html.markdown @@ -0,0 +1,259 @@ +--- +language: markdown +filename: markdown-fi.md +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Timo Virkkunen", "https://github.com/ComSecNinja"] +lang: fi-fi +--- + +John Gruber loi Markdownin vuona 2004. Sen tarkoitus on olla helposti luettava ja kirjoitettava syntaksi joka muuntuu helposti HTML:ksi (ja nyt myös moneksi muuksi formaatiksi). + +```markdown + + + + + + +# Tämä on

+## Tämä on

+### Tämä on

+#### Tämä on

+##### Tämä on

+###### Tämä on
+ + +Tämä on h1 +============= + +Tämä on h2 +------------- + + + + +*Tämä teksti on kursivoitua.* +_Kuten on myös tämä teksti._ + +**Tämä teksti on lihavoitua.** +__Kuten on tämäkin teksti.__ + +***Tämä teksti on molempia.*** +**_Kuten tämäkin!_** +*__Kuten tämäkin!__* + + + +~~Tämä teksti on yliviivattua.~~ + + + +Tämä on kappala. Kirjoittelen kappaleeseen, eikö tämä olekin hauskaa? + +Nyt olen kappaleessa 2. +Olen edelleen toisessa kappaleessa! + + +Olen kolmannessa kappaleessa! + + + +Päätän tämän kahteen välilyöntiin (maalaa minut nähdäksesi ne). + +There's a
above me! + + + +> Tämä on lainaus. Voit joko +> manuaalisesti rivittää tekstisi ja laittaa >-merkin jokaisen rivin eteen tai antaa jäsentimen rivittää pitkät tekstirivit. +> Sillä ei ole merkitystä kunhan rivit alkavat >-merkillä. + +> Voit myös käyttää useampaa +>> sisennystasoa +> Kuinka hienoa se on? + + + + +* Kohta +* Kohta +* Kolmas kohta + +tai + ++ Kohta ++ Kohta ++ Kolmas kohta + +tai + +- Kohta +- Kohta +- Kolmas kohta + + + +1. Kohta yksi +2. Kohta kaksi +3. Kohta kolme + + + +1. Kohta yksi +1. Kohta kaksi +1. Kohta kolme + + + + +1. Kohta yksi +2. Kohta kaksi +3. Kohta kolme + * Alakohta + * Alakohta +4. Kohta neljä + + + +Alla olevat ruudut ilman x-merkkiä ovat merkitsemättömiä HTML-valintaruutuja. +- [ ] Ensimmäinen suoritettava tehtävä. +- [ ] Toinen tehtävä joka täytyy tehdä +Tämä alla oleva ruutu on merkitty HTML-valintaruutu. +- [x] Tämä tehtävä on suoritettu + + + + + Tämä on koodia + Kuten tämäkin + + + + my_array.each do |item| + puts item + end + + + +John ei tiennyt edes mitä `go_to()` -funktio teki! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Klikkaa tästä!](http://example.com/) + + + +[Klikkaa tästä!](http://example.com/ "Linkki Example.com:iin") + + + +[Musiikkia](/musiikki/). + + + +[Klikkaa tätä linkkiä][link1] saadaksesi lisätietoja! +[Katso myös tämä linkki][foobar] jos haluat. + +[link1]: http://example.com/ "Siistii!" +[foobar]: http://foobar.biz/ "Selkis!" + + + + + +[This][] is a link. + +[this]: http://tämäonlinkki.com/ + + + + + + +![Kuvan alt-attribuutti](http://imgur.com/munkuva.jpg "Vaihtoehtoinen otsikko") + + + +![Tämä on se alt-attribuutti][munkuva] + +[munkuva]: suhteellinen/polku/siitii/kuva.jpg "otsikko tähän tarvittaessa" + + + + + on sama kuin +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en halua +sen kursivoituvan, joten teen näin: \*tämän tekstin ympärillä on asteriskit\*. + + + + +Tietokoneesi kaatui? Kokeile painaa +Ctrl+Alt+Del + + + + +| Kolumni1 | Kolumni2 | Kolumni3 | +| :----------- | :------: | ------------: | +| Vasemmalle | Keskelle | Oikealle | +| blaa | blaa | blaa | + + + +Kolumni 1 | Kolumni 2 | Kolumni 3 +:-- | :-: | --: +Hyi tämä on ruma | saa se | loppumaan + + + +``` + +Lisää tietoa löydät John Gruberin [virallisesta julkaisusta](http://daringfireball.net/projects/markdown/syntax) +ja Adam Pritchardin loistavasta [lunttilapusta](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From ce0c0a2853dee805350a0423dae070bff0098eb4 Mon Sep 17 00:00:00 2001 From: Hughes Perreault Date: Wed, 11 Nov 2015 22:50:15 -0500 Subject: [hy/fr] A translation of Hy in french. --- fr-fr/hy-fr.html.markdown | 180 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 fr-fr/hy-fr.html.markdown diff --git a/fr-fr/hy-fr.html.markdown b/fr-fr/hy-fr.html.markdown new file mode 100644 index 00000000..ccd397cf --- /dev/null +++ b/fr-fr/hy-fr.html.markdown @@ -0,0 +1,180 @@ +--- +language: hy +filename: learnhy.hy +contributors: + - ["Abhishek L", "http://twitter.com/abhishekl"] +translators: + - ["Hughes Perreault", "https://github.com/hperreault"] +lang: fr-fr +--- + +Hy est un dialecte du lisp bâti par dessus python. Il fonctionne en +convertissant le code hy en un arbre de syntaxe abstraite de python (ast). +Ceci permet à hy d'appeler du code python et à python d'appeler du code hy. + +Ce tutoriel fonctionne pour hy > 0.9.12 + +```clojure +;; Ceci est une introduction facile à hy, pour un tutoriel rapide aller à +;; http://try-hy.appspot.com +;; +; Les commentaires se font avec des points-virgules, comme les autres LISPS + +;; les s-expression de bases +; Les programmes Lisp sont fait d'expressions symboliques ou sexps qui +; ressemble à +(some-function args) +; maintenant le quintessentiel hello world +(print "hello world") + +;; les types de données simples +; Tous les types de données simples sont exactement similaires à leurs +; homologues de python +42 ; => 42 +3.14 ; => 3.14 +True ; => True +4+10j ; => (4+10j) un nombre complexe + +; Commençons par un peu d'arithmétique très simple +(+ 4 1) ;=> 5 +; l'opérateur est appliqué à tous les arguments, comme les autres lisps +(+ 4 1 2 3) ;=> 10 +(- 2 1) ;=> 1 +(* 4 2) ;=> 8 +(/ 4 1) ;=> 4 +(% 4 2) ;=> 0 l'opérateur modulo +; l'opérateur d'élévation à la puissance est représenté par ** comme en python +(** 3 2) ;=> 9 +; les expressions imbriquées vont se comporter comme on s'y attend +(+ 2 (* 4 2)) ;=> 10 +; aussi, les opérateurs logiques and or not et equal to etc. vont se comporter +; comme on s'y attend +(= 5 4) ;=> False +(not (= 5 4)) ;=> True + +;; variables +; les variables sont déclarées en utilisant setv, les noms de variables +; peuvent utiliser UTF-8 à l'exception de ()[]{}",'`;#| +(setv a 42) +(setv π 3.14159) +(def *foo* 42) +;; d'autres types de données conteneur +; les chaînes, les listes, les tuples et dicts +; ce sont exactement les mêmes que les types de conteneurs de python +"hello world" ;=> "hello world" +; les opérations sur les chaînes fonctionnent comme en python +(+ "hello " "world") ;=> "hello world" +; les listes sont créés en utilisant [], l'indexation commence à 0 +(setv mylist [1 2 3 4]) +; les tuples sont des structures de données immuables +(setv mytuple (, 1 2)) +; les dictionnaires sont des paires clé-valeur +(setv dict1 {"key1" 42 "key2" 21}) +; :nam peut être utilisé pour définir des mots clés dans hy qui peuvent être +; utilisées comme clés +(setv dict2 {:key1 41 :key2 20}) +; utilisez `get' pour obtenir l'élément à l'index / clé +(get mylist 1) ;=> 2 +(get dict1 "key1") ;=> 42 +; Alternativement, si des mots clés ont été utilisés, l'élément peut être +; obtenu directement +(:key1 dict2) ;=> 41 + +;; fonctions et autres constructions de programme +; les fonctions sont définies en utilisant defn, la dernière sexp est renvoyé par défaut +(defn greet [name] + "A simple greeting" ; une docstring optionnelle + (print "hello " name)) + +(greet "bilbo") ;=> "hello bilbo" + +; les fonctions peuvent prendre des arguments optionnels ainsi que des +; arguments sous forme de mots clés +(defn foolists [arg1 &optional [arg2 2]] + [arg1 arg2]) + +(foolists 3) ;=> [3 2] +(foolists 10 3) ;=> [10 3] + +; les fonctions anonymes sont créés en utilisant `fn' ou `lambda' +; qui sont semblable à `defn ' +(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] + +;; Opérations sur les séquences +; hy a des utilitaires pré-construit pour les opérations sur les séquences etc. +; récupérez le premier élément en utilisant `first' ou `car' +(setv mylist [1 2 3 4]) +(setv mydict {"a" 1 "b" 2}) +(first mylist) ;=> 1 + +; découpez les listes en utilisant slice +(slice mylist 1 3) ;=> [2 3] + +; obtenez les éléments d'une liste ou dict en utilisant `get' +(get mylist 1) ;=> 2 +(get mydict "b") ;=> 2 +; l'indexation des listes commence à 0 comme en python +; assoc peut définir les éléments à clés/index +(assoc mylist 2 10) ; makes mylist [1 2 10 4] +(assoc mydict "c" 3) ; makes mydict {"a" 1 "b" 2 "c" 3} +; il ya tout un tas d'autres fonctions de base qui rend le travail avec +; les séquences amusant + +;; les importations fonctionnent comme en pyhtonn +(import datetime) +(import [functools [partial reduce]]) ; importe fun1 et fun2 de module1 +(import [matplotlib.pyplot :as plt]) ; faire une importation foo comme bar +; toutes les méthodes pré-construites de python sont accessibles à partir de hy +; a.foo(arg) est appelé (.foo un arg) +(.split (.strip "hello world ")) ;=> ["hello" "world"] + +;; Conditionelles +; (if condition (body-if-true) (body-if-false) +(if (= passcode "moria") + (print "welcome") + (print "Speak friend, and Enter!")) + +; imbriquez plusieurs if else if avec le mot clé cond +(cond + [(= someval 42) + (print "Life, universe and everything else!")] + [(> someval 42) + (print "val too large")] + [(< someval 42) + (print "val too small")]) + +; groupez les expressions avec do, ceux-ci seront executé séquentiellemnt +; les expressions comme defn ont un do implicite +(do + (setv someval 10) + (print "someval is set to " someval)) ;=> 10 + +; créer une liaison lexicale avec `let', toutes les variables déclarées +; comme cela ont une portée locale +(let [[nemesis {"superman" "lex luther" + "sherlock" "moriarty" + "seinfeld" "newman"}]] + (for [(, h v) (.items nemesis)] + (print (.format "{0}'s nemesis was {1}" h v)))) + +;; classes +; les classes sont définies comme ceci +(defclass Wizard [object] + [[--init-- (fn [self spell] + (setv self.spell spell) ; init the spell attr + None)] + [get-spell (fn [self] + self.spell)]]) + +;; allez voir hylang.org +``` + +### Lectures complémentaires + +Ce tutoriel est juste une simple introduction à hy/lisp/python. + +La documentation de HY: [http://hy.readthedocs.org](http://hy.readthedocs.org) + +Le repo GitHub de HY: [http://github.com/hylang/hy](http://github.com/hylang/hy) + +Sur freenode irc #hy, twitter hashtag #hylang -- cgit v1.2.3 From 5aceaa8c3469998b43642fc7e5f5251466376eda Mon Sep 17 00:00:00 2001 From: Hughes Perreault Date: Thu, 12 Nov 2015 12:11:40 -0500 Subject: Add "-fr" before filename extansion, Replace "facile" with "simple" --- fr-fr/hy-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/hy-fr.html.markdown b/fr-fr/hy-fr.html.markdown index ccd397cf..07007061 100644 --- a/fr-fr/hy-fr.html.markdown +++ b/fr-fr/hy-fr.html.markdown @@ -1,6 +1,6 @@ --- language: hy -filename: learnhy.hy +filename: learnhy-fr.hy contributors: - ["Abhishek L", "http://twitter.com/abhishekl"] translators: @@ -15,7 +15,7 @@ Ceci permet à hy d'appeler du code python et à python d'appeler du code hy. Ce tutoriel fonctionne pour hy > 0.9.12 ```clojure -;; Ceci est une introduction facile à hy, pour un tutoriel rapide aller à +;; Ceci est une introduction simple à hy, pour un tutoriel rapide aller à ;; http://try-hy.appspot.com ;; ; Les commentaires se font avec des points-virgules, comme les autres LISPS -- cgit v1.2.3 From cf53a882c69a40dbe1eb56506ab266042c2bb668 Mon Sep 17 00:00:00 2001 From: Marcin Klocek Date: Thu, 12 Nov 2015 20:17:55 +0100 Subject: Create Polish translations for Ruby --- pl-pl/ruby-pl.html.markdown | 593 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 593 insertions(+) create mode 100644 pl-pl/ruby-pl.html.markdown diff --git a/pl-pl/ruby-pl.html.markdown b/pl-pl/ruby-pl.html.markdown new file mode 100644 index 00000000..36f9a9bf --- /dev/null +++ b/pl-pl/ruby-pl.html.markdown @@ -0,0 +1,593 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] +translators: + - ["Marcin Klocek", "https://github.com/mklocek"] +lang: pl-pl +--- + +```ruby +# To jest komentarz + +=begin +To jest wielolinijkowy komentarz +Nikt ich nie używa +Ty też nie powinieneś +=end + +# Przede wszystkim: Wszystko jest obiektem. + +# Liczby są obiektami + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Trochę podstawowej arytmetyki +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 +5 ^ 6 #=> 3 + +# Arytmetyka jest zastąpeniem składni +# metod wywoływanych na obiektach +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Wartości specjalne są obiektami +nil # To na prawdę jest niczym +true # prawda +false # fałsz + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Równość +1 == 1 #=> true +2 == 1 #=> false + +# Nierówność +1 != 1 #=> false +2 != 1 #=> true + +# jedyną 'fałszywą' wartością poza false, jest nil + +!nil #=> true +!false #=> true +!0 #=> false + +# Więcej porównań +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Operatory logiczne +true && false #=> false +true || false #=> true +!true #=> false + +# Istnieją alternatywne wersje operatorów logicznych ze znacznie mniejszym +# pierwszeństwem. Używane są by kontrolować wyrażenia w łańcuchach wyrażeń +# aż jedno z nich wróci true lub false. + +# `zrob_cos_innego` wywołaj tylko wtedy gdy `zrob_cos` zakończy się sukcesem. +zrob_cos_innego() and zrob_cos() +# `log_error` wywołaj tylko wtedy gdy `zrob_cos` nie zakończy się sukcesem. +zrob_cos() or log_error() + + +# Stringi są obiektami + +'Jestem stringiem.'.class #=> String +"Ja również jestem stringiem.".class #=> String + +wypelnienie = 'użyć interpolacji stringa' +"Potrafię #{wypelnienie} używając podwójnych cudzysłowów." +#=> "Potrafię użyć interpolacji stringa używając podwójnych cudzysłowów." + +# Staraj się zapisywać stringi za pomocą apostrof, zamiast cudzysłowów tam, gdzie to możliwe +# Cudzysłowy wykonują dodatkowe wewnętrzne operacje + + +# Łączenie stringów, ale nie liczb +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Łączenie stringów i operatorów +'hello ' * 3 #=> "hello hello hello " + +# Dodawanie do stringa +'hello' << ' world' #=> "hello world" + +# wydrukowanie wartości wraz z nową linią na końcu +puts "Drukuję!" +#=> Drukuję! +#=> nil + +# wydrukowanie wartości bez nowej linii na końcu +print "Drukuję!" +#=> Drukuję! => nill + +# Zmienne +x = 25 #=> 25 +x #=> 25 + +# Zauważ, że przypisanie zwraca przypisywaną wartość +# To znaczy, że możesz wykonać wielokrotne przypisanie: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Zwyczajowo, używaj notacji snake_case dla nazw zmiennych +snake_case = true + +# Używaj opisowych nazw zmiennych +sciezka_do_projektu = '/dobra/nazwa/' +sciezka = '/zla/nazwa/' + +# Symbole (są obiektami) +# Symbole są niezmiennymi, wielokrotnie używanymi stałymi reprezentowanymi wewnętrznie jako +# liczby całkowite. Często używane są zamiast stringów w celu wydajniejszego przekazywania danych + +:oczekujacy.class #=> Symbol + +status = :oczekujacy + +status == :oczekujacy #=> true + +status == 'oczekujacy' #=> false + +status == :zatwierdzony #=> false + +# Tablice + +# To jest tablica +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Tablice mogą zwierać różne typy danych + +[1, 'hello', false] #=> [1, "hello", false] + +# Tablice mogę być indeksowane +# Od początku +tablica[0] #=> 1 +tablica.first #=> 1 +tablica[12] #=> nil + +# Podobnie jak przy arytmetyce, dostę poprzez [zmienna] +# jest tylko czytelniejszą składnią +# dla wywoływania metody [] na obiekcie +tablica.[] 0 #=> 1 +tablica.[] 12 #=> nil + +# Od końca +tablica[-1] #=> 5 +tablica.last #=> 5 + +# Z początkowym indeksem i długością +tablica[2, 3] #=> [3, 4, 5] + +# Odwrotność tablicy +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Lub zakres +array[1..3] #=> [2, 3, 4] + +# Dodawanie do tablicy w taki sposób +tablica << 6 #=> [1, 2, 3, 4, 5, 6] +# Lub taki +tablica.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Sprawdzanie, czy tablica zawiera element +tablica.include?(1) #=> true + +# Hasze są Ruby'owymi podstawowymi słownikami z parami klucz/wartość. +# Hasze są zapisywane za pomocą nawiasów klamrowych +hasz = { 'kolor' => 'zielony', 'numer' => 5 } + +hasz.keys #=> ['kolor', 'numer'] + +# Można szybko sprawdzić zawartość hasza za pomocą kluczy: +hasz['kolor'] #=> 'zielony' +hasz['numer'] #=> 5 + +# Sprawdzenie wartośći dla nieistniejącego klucza zwraca nil: +hasz['nic tutaj nie ma'] #=> nil + +# Od wersji 1.9, Ruby posiada specjalną składnię, gdy używamy symboli jako kluczy: + +nowy_hasz = { stan: 3, akcja: true } + +nowy_hasz.keys #=> [:stan, :akcja] + +# Sprawdzenie istnienia kluczy i wartości w haszu +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + +# Wskazówka: Zarówno tablice, jak i hasze, są policzalne +# Współdzielą wiele metod takich jak each, map, count, i inne + +# Instrukcje warunkowe + +if true + 'wyrażenie if' +elsif false + 'wyrażenie if, opcjonalne' +else + 'wyrażenie else, również opcjonalne' +end + +for licznik in 1..5 + puts "powtórzenie #{licznik}" +end +#=> powtórzenie 1 +#=> powtórzenie 2 +#=> powtórzenie 3 +#=> powtórzenie 4 +#=> powtórzenie 5 + +# JEDNAKŻE, Nikt nie używa pętli for. +# Zamiast tego, powinno się używać metody "each" i podawać jej blok. +# Blok jest kawałkiem kodu, który możesz podać metodzie podobnej do "each". +# Jest analogiczny do wyrażeń lambda, funkcji anonimowych lub zamknięć w innych +# językach programowania. +# +# Metoda "each" danego zakresu, wykonuje blok dla każdego elementu w zakresie. +# Do bloku zostaje przekazany licznik jako parametr. +# Wykonanie metody "each" z przekazaniem bloku wygląda następująco: + +(1..5).each do |licznik| + puts "powtórzenie #{licznik}" +end +#=> powtórzenie 1 +#=> powtórzenie 2 +#=> powtórzenie 3 +#=> powtórzenie 4 +#=> powtórzenie 5 + +# Możesz również otoczyć blok nawiasami klamrowymi: +(1..5).each { |licznik| puts "powtórzenie #{licznik}" } + +# Zawartość struktur danych również może być powtarzana używając each. +tablica.each do |element| + puts "#{element} jest częścią tablicy" +end +hasz.each do |klucz, wartosc| + puts "#{klucz} jest #{wartosc}" +end + +# Jeśli nadal potrzebujesz indeksum, możesz użyć "each_with_index" i zdefiniować +# zmienną odpowiadającą indeksowi +tablica.each_with_index do |element, indeks| + puts "#{element} jest numerem #{indeks} w tablicy" +end + +licznik = 1 +while licznik <= 5 do + puts "powtórzenie #{licznik}" + licznik += 1 +end +#=> powtórzenie 1 +#=> powtórzenie 2 +#=> powtórzenie 3 +#=> powtórzenie 4 +#=> powtórzenie 5 + +# W Ruby istnieje dużo pomocnych funkcji wykonujących pętle, +# na przykład "map", "reduce", "inject" i wiele innych. Map, +# w każdym wywołaniu, pobiera tablicę, na której wykonuję pętlę, +# wykonuje kod zapisany za pomocą bloku i zwraca całkowicie nową tablicę. +tablica = [1,2,3,4,5] +podwojone = tablica.map do |element| + element * 2 +end +puts podwojona +#=> [2,4,6,8,10] +puts tablica +#=> [1,2,3,4,5] + +ocena = 2 + +case ocena +when 1 + puts 'Dobra robota, masz wolne' +when 2 + puts 'Następnym razem będziesz miał więcej szczęścia' +when 3 + puts 'Możesz to zrobić lepiej' +when 4 + puts 'Przebrnąłeś' +when 5 + puts 'Oblałeś!' +else + puts 'Inny system oceniania?' +end +#=> "Następnym razem będziesz miał więcej szczęścia" + +# case może również użwać zakresów +ocena = 82 +case ocena +when 90..100 + puts 'Hurra!' +when 80...90 + puts 'Dobra robota' +else + puts 'Oblałeś!' +end +#=> "Dobra robota" + +# obsługa błędów: +begin + # kod, który może wywołać wyjątek + raise NoMemoryError, 'Zabrakło pamięci.' +rescue NoMemoryError => zmienna_wyjatku + puts 'Został wywołany NoMemoryError', zmienna_wyjatku +rescue RuntimeError => inna_zmienna_wyjatku + puts 'Teraz został wywołany RuntimeError' +else + puts 'To zostanie uruchomione, jeśli nie wystąpi żaden wyjątek' +ensure + puts 'Ten kod wykona się zawsze' +end + +# Funkcje + +def podwojenie(x) + x * 2 +end + +# Funkcje (i wszystkie bloki) zawsze zwracają wartość ostatniego wyrażenia +podwojenie(2) #=> 4 + +# Okrągłe nawiady są opcjonalne, gdy wynik jest jednoznaczny +podwojenie 3 #=> 6 + +podwojenie podwojenie 3 #=> 12 + +def suma(x, y) + x + y +end + +# Argumenty metod są oddzielone przecinkami +suma 3, 4 #=> 7 + +suma suma(3, 4), 5 #=> 12 + +# yield +# Wszystkie metody mają ukryty, opcjonalny parametr bloku, +# który może być wykonany używając słowa kluczowego 'yield' + +def otoczenie + puts '{' + yield + puts '}' +end + +otoczenie { puts 'hello world' } + +# { +# hello world +# } + + +# Możesz przekazać blok do funkcji +# "&" oznacza referencję to przekazanego bloku +def goscie(&blok) + blok.call 'jakis_argument' +end + +# Możesz przekazać listę argumentów, które będę przekonwertowane na tablicę +# Do tego służy operator ("*") +def goscie(*tablica) + tablica.each { |gosc| puts gosc } +end + +# Definiowanie klas używając słowa kluczowego class +class Czlowiek + + # Zmienna klasowa. Jest współdzielona przez wszystkie instancje tej klasy. + @@gatunek = 'H. sapiens' + + # Podstawowe inicjalizowanie + def initialize(imie, wiek = 0) + # Przypisanie argumentu do zmiennej danej instancji o nazwie "imie" + @imie = imie + # Jeśli nie podano wieku, zostanie użyta domyślna wartość z listy argumentów. + @wiek = wiek + end + + # Podstawowa metoda przypisująca wartość + def imie=(imie) + @imie = imie + end + + # Podstawowa metoda pobierająca wartość + def imie + @imie + end + + # Powyższa funkcjonalność może być zastąpiona używając metody attr_accessor w taki sposób + attr_accessor :imie + + # Metody przypisujące/pobierające mogą być stworzone indywidualnie + attr_reader :imie + attr_writer :imie + + # Metody klasowe używają self aby odróżnić się od metody instancji. + # To może być wywołane na klasie, nie na instancji. + def self.powiedz(wiadomosc) + puts wiadomosc + end + + def gatunek + @@gatunek + end +end + + +# Tworzenie instancji klasy +jim = Czlowiek.new('Jim Halpert') + +dwight = Czlowiek.new('Dwight K. Schrute') + +# Wywołajmy parę metod +jim.gatunek #=> "H. sapiens" +jim.imie #=> "Jim Halpert" +jim.imie = "Jim Halpert II" #=> "Jim Halpert II" +jim.imie #=> "Jim Halpert II" +dwight.gatunek #=> "H. sapiens" +dwight.imie #=> "Dwight K. Schrute" + +# Wywołanie metody klasowej +Czlowiek.powiedz('Cześć') #=> "Cześć" + +# Zasięg zmiennej jest definiowany poprzez jej nazwę. +# Zmienne, które zaczynają się na $ mają zasięg globalny +$zmienna = "Jestem zmienną globalną" +defined? $zmienna #=> "global-variable" + +# Zmienne zczynające się na @ mają zasięg danej instancji +@zmienna = "Jestem zmienną instancji" +defined? @zmienna #=> "instance-variable" + +# Zmienne, które zaczynają się na @@ mają zasięg danej klasy +@@zmienna = "Jestem zmienną klasową" +defined? @@zmienna #=> "class variable" + +# Zmienne, które zaczynają się na dużą literę, są stałymi +Zmienna = "Jestem stałą" +defined? Zmienna #=> "constant" + +# Klasa jest również obiektem w ruby. Może więc mieć zmienne instancji. +# Zmienna klasowa może być współdzielona między klasą i jej potomstwem. + +# podstawowa klasa +class Czlowiek + @@cokolwiek = 0 + + def self.cokolwiek + @@cokolwiek + end + + def self.cokolwiek=(wartosc) + @@cokolwiek = wartosc + end +end + +# klasa pochodna +class Pracownik < Czlowiek +end + +Czlowiek.cokolwiek # 0 +Pracownik.cokolwiek # 0 + +Czlowiek.cokolwiek = 2 # 2 +Pracownik.cokolwiek # 2 + +# Zmienna instancji danej klasy nie jest współdzielona przez jej potomstwo. + +class Czlowiek + @cos = 0 + + def self.cos + @cos + end + + def self.cos=(wartosc) + @cos = wartosc + end +end + +class Doktor < Czlowiek +end + +Czlowiek.cos # 0 +Doktor.cos # nil + +module PrzykladowyModul + def cokolwiek + 'cokolwiek' + end +end + +# Włączanie modułów łączy ich metody z metodami instancji klasy +# Rozszerzanie modułów łączy ich metody z metodami klasy + +class Osoba + include PrzykladowyModul +end + +class Ksiazka + extend PrzykladowyModul +end + +Osoba.cokolwiek # => NoMethodError: undefined method `cokolwiek' for Osoba:Class +Osoba.new.cokolwiek # => 'cokolwiek' +Ksiazka.cokolwiek # => 'cokolwiek' +Ksiazka.new.cokolwiek # => NoMethodError: undefined method `cokolwiek' + +# Gdy włączamy lub rozszerzamy muduły, wykonywane są tzw. wywołania zwrotne + +module PrzykladowyModul + def self.included(baza) + baza.extend(MotodyKlasowe) + baza.send(:include, MetodyInstancji) + end + + module MotodyKlasowe + def cos + 'cos' + end + end + + module MetodyInstancji + def xyz + 'xyz' + end + end +end + +class Cokolwiek + include PrzykladowyModul +end + +Cokolwiek.cos # => 'cos' +Cokolwiek.xyz # => NoMethodError: undefined method `xyz' +Cokolwiek.new.cos # => NoMethodError: undefined method `cos' +Cokolwiek.new.xyz # => 'qux' +``` + +## Dodatkowe źródła +### Polskie + +- [Dokumentacja](https://www.ruby-lang.org/pl/documentation/quickstart/) + +### Angielskie + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. -- cgit v1.2.3 From 7837603c56de212f68c9806b31f19d139ba6998d Mon Sep 17 00:00:00 2001 From: Marcin Klocek Date: Thu, 12 Nov 2015 20:26:01 +0100 Subject: Adjust Polish translations for Ruby --- pl-pl/ruby-pl.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/pl-pl/ruby-pl.html.markdown b/pl-pl/ruby-pl.html.markdown index 36f9a9bf..73b1a7d8 100644 --- a/pl-pl/ruby-pl.html.markdown +++ b/pl-pl/ruby-pl.html.markdown @@ -109,15 +109,15 @@ wypelnienie = 'użyć interpolacji stringa' # Łączenie stringów, ale nie liczb -'hello ' + 'world' #=> "hello world" -'hello ' + 3 #=> TypeError: can't convert Fixnum into String -'hello ' + 3.to_s #=> "hello 3" +'hej ' + 'świecie' #=> "hej świecie" +'hej ' + 3 #=> TypeError: can't convert Fixnum into String +'hej ' + 3.to_s #=> "hej 3" # Łączenie stringów i operatorów -'hello ' * 3 #=> "hello hello hello " +'hej ' * 3 #=> "hej hej hej " # Dodawanie do stringa -'hello' << ' world' #=> "hello world" +'hej' << ' świecie' #=> "hej świecie" # wydrukowanie wartości wraz z nową linią na końcu puts "Drukuję!" @@ -139,8 +139,8 @@ x = y = 10 #=> 10 x #=> 10 y #=> 10 -# Zwyczajowo, używaj notacji snake_case dla nazw zmiennych -snake_case = true +# Zwyczajowo, używaj notacji nazwa_zmiennej dla nazw zmiennych +nazwa_zmiennej = true # Używaj opisowych nazw zmiennych sciezka_do_projektu = '/dobra/nazwa/' @@ -167,7 +167,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Tablice mogą zwierać różne typy danych -[1, 'hello', false] #=> [1, "hello", false] +[1, 'hej', false] #=> [1, "hej", false] # Tablice mogę być indeksowane # Od początku @@ -175,7 +175,7 @@ tablica[0] #=> 1 tablica.first #=> 1 tablica[12] #=> nil -# Podobnie jak przy arytmetyce, dostę poprzez [zmienna] +# Podobnie jak przy arytmetyce, dostęp poprzez [zmienna] # jest tylko czytelniejszą składnią # dla wywoływania metody [] na obiekcie tablica.[] 0 #=> 1 @@ -385,10 +385,10 @@ def otoczenie puts '}' end -otoczenie { puts 'hello world' } +otoczenie { puts 'hej świecie' } # { -# hello world +# hej świecie # } -- cgit v1.2.3 From 3b59da1f3d055b5fd9f0804de2142df90c7b762c Mon Sep 17 00:00:00 2001 From: Hughes Perreault Date: Thu, 12 Nov 2015 15:40:53 -0500 Subject: =?UTF-8?q?UTF-8=20->=20l'UTF-8,=20donn=C3=A9es=20conteneur=20->?= =?UTF-8?q?=20conteneurs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/hy-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/hy-fr.html.markdown b/fr-fr/hy-fr.html.markdown index 07007061..841179f5 100644 --- a/fr-fr/hy-fr.html.markdown +++ b/fr-fr/hy-fr.html.markdown @@ -54,11 +54,11 @@ True ; => True ;; variables ; les variables sont déclarées en utilisant setv, les noms de variables -; peuvent utiliser UTF-8 à l'exception de ()[]{}",'`;#| +; peuvent utiliser l'UTF-8 à l'exception de ()[]{}",'`;#| (setv a 42) (setv π 3.14159) (def *foo* 42) -;; d'autres types de données conteneur +;; d'autres types de conteneurs ; les chaînes, les listes, les tuples et dicts ; ce sont exactement les mêmes que les types de conteneurs de python "hello world" ;=> "hello world" -- cgit v1.2.3 From 312941c5e018bee87be524697b471061cf70b285 Mon Sep 17 00:00:00 2001 From: Rob Pilling Date: Fri, 13 Nov 2015 14:52:21 +0000 Subject: Correct "Casting" mention in swift markdown 'T()' is initialisation/creation, 'x as T' is casting --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index df9c5092..e3934ab1 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -46,7 +46,7 @@ let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 let intValue = 0007 // 7 let largeIntValue = 77_000 // 77000 -let label = "some text " + String(myVariable) // Casting +let label = "some text " + String(myVariable) // String construction let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation // Build Specific values -- cgit v1.2.3 From 2c33662024b3b2c9975c184d9dfb5f8f8ddd02fc Mon Sep 17 00:00:00 2001 From: Hughes Perreault Date: Fri, 13 Nov 2015 11:15:58 -0500 Subject: =?UTF-8?q?nam=20->=20nom,=20pr=C3=A9-construit=20->=20natif,=20un?= =?UTF-8?q?=20->=20a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/hy-fr.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fr-fr/hy-fr.html.markdown b/fr-fr/hy-fr.html.markdown index 841179f5..5220fb65 100644 --- a/fr-fr/hy-fr.html.markdown +++ b/fr-fr/hy-fr.html.markdown @@ -70,7 +70,7 @@ True ; => True (setv mytuple (, 1 2)) ; les dictionnaires sont des paires clé-valeur (setv dict1 {"key1" 42 "key2" 21}) -; :nam peut être utilisé pour définir des mots clés dans hy qui peuvent être +; :nom peut être utilisé pour définir des mots clés dans hy qui peuvent être ; utilisées comme clés (setv dict2 {:key1 41 :key2 20}) ; utilisez `get' pour obtenir l'élément à l'index / clé @@ -101,7 +101,7 @@ True ; => True (map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] ;; Opérations sur les séquences -; hy a des utilitaires pré-construit pour les opérations sur les séquences etc. +; hy a des utilitaires natifs pour les opérations sur les séquences etc. ; récupérez le premier élément en utilisant `first' ou `car' (setv mylist [1 2 3 4]) (setv mydict {"a" 1 "b" 2}) @@ -124,8 +124,8 @@ True ; => True (import datetime) (import [functools [partial reduce]]) ; importe fun1 et fun2 de module1 (import [matplotlib.pyplot :as plt]) ; faire une importation foo comme bar -; toutes les méthodes pré-construites de python sont accessibles à partir de hy -; a.foo(arg) est appelé (.foo un arg) +; toutes les méthodes natives de python sont accessibles à partir de hy +; a.foo(arg) est appelé (.foo a arg) (.split (.strip "hello world ")) ;=> ["hello" "world"] ;; Conditionelles -- cgit v1.2.3 From e3de8870ca586cd0f084f00cc96ea540cf022638 Mon Sep 17 00:00:00 2001 From: Hughes Perreault Date: Fri, 13 Nov 2015 11:48:48 -0500 Subject: ressemble -> ressemblent --- fr-fr/hy-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/hy-fr.html.markdown b/fr-fr/hy-fr.html.markdown index 5220fb65..bd7c6839 100644 --- a/fr-fr/hy-fr.html.markdown +++ b/fr-fr/hy-fr.html.markdown @@ -22,7 +22,7 @@ Ce tutoriel fonctionne pour hy > 0.9.12 ;; les s-expression de bases ; Les programmes Lisp sont fait d'expressions symboliques ou sexps qui -; ressemble à +; ressemblent à (some-function args) ; maintenant le quintessentiel hello world (print "hello world") -- cgit v1.2.3 From 452b0bb21912b56b862409c50f15cb2acd4ea120 Mon Sep 17 00:00:00 2001 From: Hellseher Date: Sat, 14 Nov 2015 00:24:46 +0000 Subject: [A] extra links Links : : CLiki : Awesome Common Lisp : COMMON LISP A Gentle Introduction to Symbolic Computation : Common-Lisp.net --- common-lisp.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 63183c1e..13f0023e 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -615,8 +615,15 @@ nil ; for false - and the empty list ## Further Reading [Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/) +[A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) +## Extra Info + +[CLiki](http://www.cliki.net/) +[common-lisp.net](https://common-lisp.net/) +[Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) + ## Credits. Lots of thanks to the Scheme people for rolling up a great starting -- cgit v1.2.3 From b20abcb791cf3d2b0e7274fb300c6d0e7b791da1 Mon Sep 17 00:00:00 2001 From: Hellseher Date: Sat, 14 Nov 2015 00:33:00 +0000 Subject: [E] styling links --- common-lisp.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 13f0023e..2b1f5de4 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -614,15 +614,15 @@ nil ; for false - and the empty list ## Further Reading -[Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/) -[A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) +* [Keep moving on to the Practical Common Lisp book.](http://www.gigamonkeys.com/book/) +* [A Gentle Introduction to...](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) ## Extra Info -[CLiki](http://www.cliki.net/) -[common-lisp.net](https://common-lisp.net/) -[Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) +* [CLiki](http://www.cliki.net/) +* [common-lisp.net](https://common-lisp.net/) +* [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) ## Credits. -- cgit v1.2.3 From 68c659b366b9fde2870c8938b5666550cc59054b Mon Sep 17 00:00:00 2001 From: Hughes Perreault Date: Sat, 14 Nov 2015 13:57:01 -0500 Subject: "lang: hu-hu" line was missing trying to fix issue #2013 --- hu-hu/coffeescript-hu.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hu-hu/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown index 267db4d0..b5ae2107 100644 --- a/hu-hu/coffeescript-hu.html.markdown +++ b/hu-hu/coffeescript-hu.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Xavier Yao", "http://github.com/xavieryao"] translators: - ["Tamás Diószegi", "http://github.com/ditam"] +lang: hu-hu filename: coffeescript-hu.coffee --- @@ -103,4 +104,4 @@ eat food for food in foods when food isnt 'chocolate' ## További források - [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) -- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) \ No newline at end of file +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From cde6ea6ca256a1249d222e692fde66ea76f19409 Mon Sep 17 00:00:00 2001 From: Terka Slan Date: Sat, 14 Nov 2015 20:24:51 +0100 Subject: Translated Git to Slovak[sk-sk] --- sk-sk/git.html.markdown | 525 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 525 insertions(+) create mode 100644 sk-sk/git.html.markdown diff --git a/sk-sk/git.html.markdown b/sk-sk/git.html.markdown new file mode 100644 index 00000000..b5aace7a --- /dev/null +++ b/sk-sk/git.html.markdown @@ -0,0 +1,525 @@ +--- +category: tool +tool: git + +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] + - ["Andrew Taylor", "http://github.com/andrewjt71"] +translators: + - ["Terka Slanináková", "http://github.com/TerkaSlan"] +filename: LearnGit.txt +lang: sk-sk +--- + +Git je distribuovaný systém riadenia revízií a správy zdrojového kódu. + +Funguje robením "snímkov" tvojho projektu, s ktorými ďalej pracuje na revíziach a správe zdrojových kódov. + +## Koncept Revízií + +### Čo je riadenie revízií? + +Riadenie revízií je systém, ktorý postupom času zaznamenáva zmeny súboru (súborov). + +### Centralizované Revízie VS Distribuované revízie + +* Centralizované riadenie revízií sa zameriava na synchronizáciu, sledovanie a zálohovanie súborov. +* Distribuované riadenie revízií sa zameriava na zdieľanie zmien. Kaťdá zmena má jedinečný identifikátor (id). +* Distribuované systémy nemajú definovanú štruktúru. S gitom môžeš mať centralizovaný systém v subversion (SVN) štýle. + +[Ďalšie informácie](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Prečo Používať Git? + +* Môžeš pracovať offline. +* Spolupráca s ostatnými je jednoduchá! +* Vetvenie je jednoduché! +* Zlučovanie je jednoduché! +* Git je rýchly. +* Git je flexibilný. + +## Architektúra Gitu + + +### Repozitár + +Skupina súborov, adresárov, minulých záznamov, commitov (konkrétnych revízií) a odkazy na aktuálu vetvu (HEADs). Predstav si ho ako údajovú štruktúru, kde ti každý "prvok" zdrojového kódu poskytne (okrem iného) prístup k minulým revíziam. + +Git repozitár sa skladá z .git adresára a pracovného stromu + +### .git Adresár (časť repozitára) + +.git adresár obsahuje všetky konfigurácie, logy, vetvy, odkaz na aktuálnu vetvu (HEAD) a ostatné. +[Detailný zoznam.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Pracovný Strom (Working Tree - časť repozitára) + +Toto sú adresáre a súbory v tvojom repozitári. Tiež sa tomu hovorí pracovný adresár. + +### Index (časť .git adresára) + +Index je také odpočívadlo Gitu. Je to v podstate vrstva, ktorá oddeľuje pracovný strom od Git repozitára. Toto dáva vývojárom viac možností nad tým, čo do repozitára naozaj pošlú. + +### Commit + +Commit je "snímka" zmien, či manipulácií s tvojím Pracovným Stromom. Ak si napríklad pridal 5 súborov a odstránil 2 ďalšie, tieto zmeny budú zachytené v commite. Ten môže (ale nemusí) byť zverejnený (pushed) do iných repozitárov. + +### Vetva (Branch) + +Vetva je ukazateľ na posledný vykonaný commit. Po ďalších commitnutiach sa ukazateľ bude automaticky posúvať na ten najnovší. + +### Tag + +Tag je označenie špecifického bodu v minulosti. Typicky sa používa na značenie vydaných verzií (v1.0, atď). + +### HEAD a head (časť .git adresára) + +HEAD je ukazateľ na aktuálnu vetvu. Repozitár má len 1 *aktívny* HEAD. +head je ukazateľ, ktorý môže ukazovať na akýkoľvek commit. Repozitár môže mať niekoľko headov. + +### Štádia Gitu +* Modified - Súbor bol zmenený, no nebol ešte commitnutý do Git Databázy. +* Staged - Zmenený súbor, ktorý pôjde do najbližšieho commit snímku. +* Committed - Súbory boli commitnuté do Git Databázy. + +### Koncepčné zdroje + +* [Git Pre Informatikov](http://eagain.net/articles/git-for-computer-scientists/) +* [Git Pre Designerov](http://hoth.entp.com/output/git_for_designers.html) + + +## Príkazy + + +### init + +Vytvorí prázdny Git repozitár. Jeho nastavenia, uložené informácie a mnoho iného sú uložené v adresári (zložke) s názvom ".git". + +```bash +$ git init +``` + +### config + +Konfiguruj nastavenia. Či už pre repozitár, samotný systém, alebo globálne konfigurácie (súbor pre globálny config je `~/.gitconfig`). + + +```bash +# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne) +$ git config --global user.email "MôjEmail@Zoho.com" +$ git config --global user.name "Moje Meno " +``` + +[Prečítaj si viac o git configu.](http://git-scm.com/docs/git-config) + +### pomoc + +Máš tiež prístup k extrémne detailnej dokumentácií pre každý príkaz (po anglicky). Hodí sa, ak potrebuješ pripomenúť semantiku. + +```bash +# Rýchlo zobraz všetky dostupné príkazy +$ git help + +# Zobraz všetky dostupné príkazy +$ git help -a + +# Zobraz konkrétnu pomoc - použivateľský manuál +# git help +$ git help add +$ git help commit +$ git help init +# alebo git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignoruj súbory + +Zámerne prestaneš sledovať súbor(y) a zložky. Typicky sa používa pre súkromné a dočasné súbory, ktoré by boli inak zdieľané v repozitári. +```bash +$ echo "temp/" >> .gitignore +$ echo "private_key" >> .gitignore +``` + + +### status + +Na zobrazenie rozdielov medzi indexovými súbormi (tvoj pracovný repozitár) a aktuálnym HEAD commitom. + + +```bash +# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely +$ git status + +# Zisti iné vychytávky o git statuse +$ git help status +``` + +### add + +Pripraví súbory na commit pridaním do tzv. staging indexu. Ak ich nepridáš pomocou `git add` do staging indexu, nebudú zahrnuté v commitoch! + +```bash +# pridá súbor z tvojho pracovného adresára +$ git add HelloWorld.java + +# pridá súbor z iného adresára +$ git add /cesta/k/súboru/HelloWorld.c + +# Môžeš použiť regulárne výrazy! +$ git add ./*.java +``` +Tento príkaz len pridáva súbory do staging indexu, necommituje ich do repozitára. + +### branch + +Spravuj svoje vetvy. Môžeš ich pomocou tohto príkazu zobraziť, meniť, vytvoriť, či zmazať. + +```bash +# zobraz existujúce vetvy a vzdialené repozitáre +$ git branch -a + +# vytvor novú vetvu +$ git branch myNewBranch + +# vymaž vetvu +$ git branch -d myBranch + +# premenuj vetvu +# git branch -m +$ git branch -m mojaStaraVetva mojaNovaVetva + +# zmeň opis vetvy +$ git branch myBranchName --edit-description +``` + +### tag + +Spravuj svoje tagy + +```bash +# Zobraz tagy +$ git tag +# Vytvor tag so správou +# -m špecifikuje správu, ktorá bude s tagom uložená. +# Ak nešpeficikuješ správu pri tagu so správou, +# Git spustí tvoj editor, aby si ju napísal. +$ git tag -a v2.0 -m 'moja verzia 2.0' +# Ukáž informácie o tagu +# Zobrazí zadané informácie, dátum tagnutia commitu +# a správu pred zobrazením informácií o commite. +$ git show v2.0 +# Zverejní (pushne) jediný tag do vzdialeného repozitára +$ git push origin v2.0 +# Zverejní viacero tagov do vzdialeného repozitára +$ git push origin --tags +``` + +### checkout + +Aktualizuje všetky súbory v pracovnom strome, aby odpovedali verzií v indexe, alebo v inom strome. + +```bash +# Aktualizuj strom, aby odpovedal (predvolene) +# hlavnej vetve repozitáru (master branch) +$ git checkout +# Aktualizuj strom, aby odpovedal konrkétnej vetve +$ git checkout menoVetvy +# Vytvor novú vetvu & prepni sa na ňu +# ekvivalentný príkaz: "git branch ; git checkout " +$ git checkout -b nováVetva +``` + +### clone + +"Naklonuje", alebo vytvorí kópiu existujúceho repozitára do nového adresára. Tiež pridá špeciálne ďiaľkovo-monitorujúce vetvy (remote-tracking branches), ktoré ti umožnia zverejňovať do vzdialených vetiev. + +```bash +# Naklonuj learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git +# naklonuj iba konkrétnu vetvu +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Uloží aktuálny obsah indexu v novom "commite". Ten obsahuje vytvorené zmeny a s nimi súvisiace správy vytvorené použivateľom. + +```bash +# commitni so správou +$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c" + +# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni. +$ git commit -a -m "Zmenil som foo.php a vymazal bar.php" + +# zmeň posledný commit (toto nahradí predchádzajúci commit novým) +$ git commit --amend -m "Správna správa" +``` + +### diff + +Ukáže rozdiel medzi súborom v pracovnom repozitári, indexe a commitoch. + +```bash +# Ukáž rozdiel medzi pracovným repozitárom a indexom. +$ git diff + +# Ukáž rozdiely medzi indexom a najnovším commitom. +$ git diff --cached + +# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom. +$ git diff HEAD +``` + +### grep + +Umožní ti rýchlo prehľadávať repozitár. + +Možná konfigurácia: + +```bash +# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku +$ git config --global grep.lineNumber true + +# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Vďaka Travisovi Jefferymu za túto sekciu +# Hľadaj "názovPremennej" vo všetkých java súboroch +$ git grep 'názovPremennej' -- '*.java' + +# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google je tvoj kamarát; pre viac príkladov skoč na +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Zobral commity do repozitára. + +```bash +# Zobraz všetky commity +$ git log + +# Zobraz iba správy a referencie commitov +$ git log --oneline + +# Zobraz zlúčené (merged) commity +$ git log --merges + +# Zobraz všetky commity vo forme ASCII grafu +$ git log --graph +``` + +### merge + +"Zlúč" zmeny externých commitov do aktuálnej vetvy. + +```bash +# Zlúč vybranú vetvu do aktuálnej. +$ git merge názovVetvy + +# Vždy vytvor zlučovací commit +$ git merge --no-ff názovVetvy +``` + +### mv + +Premenuj, alebo presuň súbor + +```bash +# Premenuj súbor +$ git mv HelloWorld.c HelloNewWorld.c + +# Presuň súbor +$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c + +# "Nasilu" premenuj, alebo presuň +# "existujúciSúbor" už v adresári existuje, bude prepísaný +$ git mv -f môjSúbor existujúciSúbor +``` + +### pull + +Uloží obsah repozitára a zlúči ho s inou vetvou. + +```bash +# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien +# zo vzdialených "origin" a "master" vetiev. +# git pull +$ git pull origin master + +# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu +# zlúčením nových zmien zo vzdialenej vetvy +$ git pull + +# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase) +# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull , git rebase " +$ git pull origin master --rebase +``` + +### push + +Zverejní a zlúči zmeny z lokálnej do vzdialenej vetvy. + +```bash +# Zverejni a zlúč zmeny z lokálneho repozitára do +# vzdialených vetiev s názvom "origin" a "master". +# git push +$ git push origin master + +# Predvolene git zverejní a zlúči zmeny z +# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej +$ git push + +# Na spojenie lokálnej vetvy so vzdialenou pridaj -u: +$ git push -u origin master +# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz: +$ git push +``` + +### stash + +Umožní ti opustiť chaotický stav pracovného adresára a uloží ho na zásobník nedokončených zmien, ku ktorým sa môžeš kedykoľvek vrátiť. + +Povedzme, že si urobil nejaké zmeny vo svojom git repozitári, ale teraz potrebuješ pullnúť zo vzdialenej repo. Keďže máš necommitnuté zmeny, príkaz `git pull` nebude fungovať. Namiesto toho môžeš použiť `git stash` a uložiť svoje nedokončené zmeny na zásobník! + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Teraz môžeš uložiť vzdialenú vetvu! + +```bash +git pull +``` +`...zmeny sa zaznamenajú...` + +Over, či je všetko v poriadku + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +Môžeš si pozrieť, čo za chaos je na zásobníku cez `git stash list`. +Nedokončené zmeny sú uložené ako Last-In-First-Out (Prvý dnu, posledný von) štruktúra, navrchu sa objavia najnovšie zmeny. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 added the index file +stash@{1}: WIP on master: c264051 Revert "added file_size" +stash@{2}: WIP on master: 21d80a5 added number to log +``` + +Keď so zmenami budeš chcieť pracovať, odstráň ich zo stacku. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add ..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` urobí presne to isté + +Hotovo, môžeš pokračovať v práci! + +[Čítaj viac.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) + +### rebase (pozor) + +Zober všetky zmeny commitnuté do vetvy a aplikuj ich na inú vetvu. +*Tento príkaz nerob na verejných repozitároch*. + +```bash +# Aplikuj commity z experimentálnej vetvy na master +# git rebase +$ git rebase master experimentBranch +``` + +[Čítaj viac.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (pozor) + +Resetni HEAD (ukazateľ na aktuálnu vetvu) do konrkétneho stavu. To ti umožní vziať späť zlúčenia, zverejnenia, commity, pridania atď. Je to užitočný, no nebezpečný príkaz, pokiaľ nevieš, čo robíš. + +```bash +# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený) +$ git reset + +# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše) +$ git reset --hard + +# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený) +# všetky zmeny sú zachované v adresári. +$ git reset 31f2bb1 + +# Presunie vrchol aktuálnuej vetvy naopak do konkrétneho commitu +# a zosúladí ju s pracovným adresárom (vymaže nekomitnuté zmeny). +$ git reset --hard 31f2bb1 +``` +### revert + +Vezme naspäť ("od-urobí") commit. Nezamieňaj s resetom, ktorý obnoví stav +projektu do predchádzajúceho bodu v čase. Revert pridá nový commit, inverzný tomu, ktorý chceš vymazať, tým ho od-urobí. + +```bash +# Vezmi späť konkrétny commit +$ git revert +``` + +### rm + +Opak od git add, rm odstráni súbory z aktuálneho pracovného stromu. + +```bash +# odstráň HelloWorld.c +$ git rm HelloWorld.c + +# Odstráň súbor z vnoreného adresára +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Ďalšie informácie + +* [tryGit - Zábavný interaktívny spôsob, ako sa naučiť Git.](http://try.github.io/levels/1/challenges/1) + +* [Udemy Git Tutoriál: Kompletný návod](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Git Immersion - Návod, ktorý Ťa prevedie základmi Gitu](http://gitimmersion.com/) + +* [git-scm - Video Tutoriály](http://git-scm.com/videos) + +* [git-scm - Dokumentácia](http://git-scm.com/docs) + +* [Atlassian Git - Tutoriály & Postupy](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys](http://www.gitguys.com/) + +* [Git - jednoducho](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) + +* [Úvod do Gitu a GitHubu pre začiatočníkov (Tutoriál)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From 42e8218146de7ac1a35c9f24ee40eefc574fdb0d Mon Sep 17 00:00:00 2001 From: Terka Slan Date: Sun, 15 Nov 2015 22:25:18 +0100 Subject: Translated git to Slovak and repaired formatting --- sk-sk/git.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sk-sk/git.html.markdown b/sk-sk/git.html.markdown index b5aace7a..e68de3f5 100644 --- a/sk-sk/git.html.markdown +++ b/sk-sk/git.html.markdown @@ -1,7 +1,6 @@ --- category: tool tool: git - contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Leo Rudberg" , "http://github.com/LOZORD"] @@ -10,8 +9,8 @@ contributors: - ["Andrew Taylor", "http://github.com/andrewjt71"] translators: - ["Terka Slanináková", "http://github.com/TerkaSlan"] -filename: LearnGit.txt lang: sk-sk +filename: LearnGit-sk.txt --- Git je distribuovaný systém riadenia revízií a správy zdrojového kódu. -- cgit v1.2.3 From 70fa51fa36a8d2e3fbc258cbac6b37e45766bdae Mon Sep 17 00:00:00 2001 From: Terka Slan Date: Mon, 16 Nov 2015 23:07:44 +0100 Subject: Added LearnGit-sk.txt and adjusted the markdown file --- sk-sk/LearnGit-sk.txt | 208 ++++++++++++++++++++++++++++++++++++++++++++++++ sk-sk/git.html.markdown | 5 +- 2 files changed, 210 insertions(+), 3 deletions(-) create mode 100644 sk-sk/LearnGit-sk.txt diff --git a/sk-sk/LearnGit-sk.txt b/sk-sk/LearnGit-sk.txt new file mode 100644 index 00000000..070a0489 --- /dev/null +++ b/sk-sk/LearnGit-sk.txt @@ -0,0 +1,208 @@ +$ git init + +# Zobraz a Nastav Základné Konfiguračné Premenné (Globálne) +$ git config --global user.email "MôjEmail@Zoho.com" +$ git config --global user.name "Moje Meno + +# Rýchlo zobraz všetky dostupné príkazy +$ git help + +# Zobraz všetky dostupné príkazy +$ git help -a + +# Zobraz konkrétnu pomoc - použivateľský manuál +# git help +$ git help add +$ git help commit +$ git help init +# alebo git --help +$ git add --help +$ git commit --help +$ git init --help + +# Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely +$ git status +# Zistí iné vychytávky o git statuse +$ git help status + +# pridá súbor z tvojho pracovného adresára +$ git add HelloWorld.java + +# pridá súbor z iného adresára +$ git add /cesta/k/súboru/HelloWorld.c + +# Môžeš použiť regulárne výrazy! +$ git add ./*.java + +# zobraz existujúce vetvy a vzdialené repozitáre +$ git branch -a + +# vytvor novú vetvu +$ git branch myNewBranch + +# vymaž vetvu +$ git branch -d myBranch + +# premenuj vetvu +# git branch -m +$ git branch -m mojaStaraVetva mojaNovaVetva + +# zmeň opis vetvy +$ git branch myBranchName --edit-description + +# Zobrazí tagy +$ git tag +# Vytvorí tag so správou +# -m špecifikuje správu, ktorá bude s tagom uložená. +# Ak nešpeficikuješ správu pri tagu so správou, +# Git spustí tvoj editor, aby si ju napísal. +$ git tag -a v2.0 -m 'moja verzia 2.0' + +# Ukáž informácie o tagu +# Zobrazí zadané informácie, dátum tagnutia commitu +# a správu pred zobrazením informácií o commite. +$ git show v2.0 + +# Zverejní (pushne) jediný tag do vzdialeného repozitára +$ git push origin v2.0 + +# Zverejní viacero tagov do vzdialeného repozitára +$ git push origin --tags + +# Aktualizuj strom, aby odpovedal (predvolene) +# hlavnej vetve repozitáru (master branch) +$ git checkout + +# Aktualizuj strom, aby odpovedal konrkétnej vetve +$ git checkout menoVetvy + +# Vytvor novú vetvu & prepni sa na ňu +# ekvivalentný príkaz: "git branch ; git checkout " +$ git checkout -b nováVetva + +# Naklonuj learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git + +# povrchné klonovanie - rýchlejšie, uloží iba najnovšiu snímku +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + +# naklonuj iba konkrétnu vetvu +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch + +# commitni so správou +$ git commit -m "Pridal som multiplyNumbers() funkciu do HelloWorld.c" + +# automaticky pridaj zmenené a vymazané súbory do staging indexu, potom ich commitni. +$ git commit -a -m "Zmenil som foo.php a vymazal bar.php" + +# zmeň posledný commit (toto nahradí predchádzajúci commit novým) +$ git commit --amend -m "Správna správa" + +# Ukáž rozdiel medzi pracovným repozitárom a indexom. +$ git diff + +# Ukáž rozdiely medzi indexom a najnovším commitom. +$ git diff --cached + +# Ukáž rozdiely medzi pracovným adresárom a najnovším commitom. +$ git diff HEAD + +# Nastav, aby sa vo výsledkoch vyhľadávania zobrazovalo číslo riadku +$ git config --global grep.lineNumber true + +# Urob výsledky vyhľadávania čitateľnejšie, vrátane zoskupovania +$ git config --global alias.g "grep --break --heading --line-number" + +# Vďaka Travisovi Jefferymu za túto sekciu +# Hľadaj "názovPremennej" vo všetkých java súboroch +$ git grep 'názovPremennej' -- '*.java' + +# Hľadaj riadok, ktorý obsahuje "názovPoľa" a "add" alebo "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) + +# Zobraz všetky commity +$ git log + +# Zobraz iba správy a referencie commitov +$ git log --oneline + +# Zobraz zlúčené (merged) commity +$ git log --merges + +# Zobraz všetky commity vo forme ASCII grafu +$ git log --graph + +# Zlúč vybranú vetvu do aktuálnej. +$ git merge názovVetvy + +# Vždy vytvor zlučovací commit +$ git merge --no-ff názovVetvy + +# Premenuj súbor +$ git mv HelloWorld.c HelloNewWorld.c + +# Presuň súbor +$ git mv HelloWorld.c ./nová/cesta/HelloWorld.c + +# "Nasilu" premenuj, alebo presuň +# "existujúciSúbor" už v adresári existuje, bude prepísaný +$ git mv -f môjSúbor existujúciSúbor + +# Aktualizuje tvoj lokálny repozitár zlúčením nových zmien +# zo vzdialených "origin" a "master" vetiev. +# git pull +$ git pull origin master + +# Predvolene, git pull aktualizuje tvoju aktuálnu vetvu +# zlúčením nových zmien zo vzdialenej vetvy +$ git pull + +# Zlúč zmeny zo vzdialenej vetvy a presuň vetvu do nového základného commitu (rebase) +# vetva commitne na tvoj lokálny repozitár, ekvivalentný príkaz: "git pull , git rebase " +$ git pull origin master --rebase + +# Zverejni a zlúč zmeny z lokálneho repozitára do +# vzdialených vetiev s názvom "origin" a "master". +# git push +$ git push origin master + +# Predvolene git zverejní a zlúči zmeny z +# aktuálnej vetvy do vzdialenej vetvy s ňou spojenej +$ git push + +# Na spojenie lokálnej vetvy so vzdialenou pridaj -u: +$ git push -u origin master +# Kedykoľvek budeš chcieť zverejniť z rovnakej lokálnej vetvy, použi príkaz: +$ git push + +# Aplikuj commity z experimentálnej vetvy na master +# git rebase +$ git rebase master experimentBranch + +# Resetni index (vrstvu medzi pracovným stromom a Git repozitárom), aby odpovedal najnovšiemu commitu (adresár ostane nezmenený) +$ git reset + +# Resetni index, aby odpovedal najnovšiemu commitu (adresár sa prepíše) +$ git reset --hard + +# Presunie vrchol aktuálnuej vetvy do konkrétneho commitu (adresár ostane nezmenený) +# všetky zmeny sú zachované v adresári. +$ git reset 31f2bb1 + +# Vezmi späť konkrétny commit +$ git revert + +# odstráň HelloWorld.c +$ git rm HelloWorld.c + +# Odstráň súbor z vnoreného adresára +$ git rm /pather/to/the/file/HelloWorld.c + + + + + + + + + diff --git a/sk-sk/git.html.markdown b/sk-sk/git.html.markdown index e68de3f5..21741406 100644 --- a/sk-sk/git.html.markdown +++ b/sk-sk/git.html.markdown @@ -154,7 +154,7 @@ Na zobrazenie rozdielov medzi indexovými súbormi (tvoj pracovný repozitár) a # Zobrazí vetvu, nesledované súbory, zmeny a ostatné rozdiely $ git status -# Zisti iné vychytávky o git statuse +# Zistí iné vychytávky o git statuse $ git help status ``` @@ -404,9 +404,8 @@ Saved working directory and index state \ Teraz môžeš uložiť vzdialenú vetvu! ```bash -git pull +$ git pull ``` -`...zmeny sa zaznamenajú...` Over, či je všetko v poriadku -- cgit v1.2.3 From 913830a6b37ed27588e17673d60bace5235816b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miko=C5=82aj=20Rozwadowski?= Date: Mon, 16 Nov 2015 23:09:22 +0100 Subject: Fix typos, improve the language --- pl-pl/python-pl.html.markdown | 159 +++++++++++++++++++++--------------------- 1 file changed, 81 insertions(+), 78 deletions(-) diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown index ade1d7ca..023c3e6b 100644 --- a/pl-pl/python-pl.html.markdown +++ b/pl-pl/python-pl.html.markdown @@ -30,7 +30,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron # Pojedyncze komentarze oznaczamy takim symbolem. """ Wielolinijkowe napisy zapisywane są przy użyciu - trzech znaków cudzysłowiu i często + potrójnych cudzysłowów i często wykorzystywane są jako komentarze. """ @@ -47,11 +47,11 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron 10 * 2 # => 20 35 / 5 # => 7 -# Dzielenie może być kłopotliwe. Poniższe to dzielenie +# Dzielenie może być kłopotliwe. Poniższe działanie to dzielenie # całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany. 5 / 2 # => 2 -# Aby to naprawić musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. +# Aby to naprawić, musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. 2.0 # To liczba zmiennoprzecinkowa, tzw. float 11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej @@ -65,7 +65,7 @@ działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stron # Operator modulo - wyznaczanie reszty z dzielenia 7 % 3 # => 1 -# Potęgowanie (x do potęgi ytej) +# Potęgowanie (x do potęgi y-tej) 2**4 # => 16 # Wymuszanie pierwszeństwa w nawiasach @@ -83,7 +83,7 @@ False or True #=> True # Prawda 2 == True #=> False k1 == True #=> True -# aby zanegować użyj "not" +# aby zanegować, użyj "not" not True # => False not False # => True @@ -112,7 +112,7 @@ not False # => True # Napisy można dodawać! "Witaj " + "świecie!" # => "Witaj świecie!" -# ... a nawet mnożone +# ... a nawet mnożyć "Hej" * 3 # => "HejHejHej" # Napis może być traktowany jako lista znaków @@ -124,7 +124,7 @@ not False # => True # Jednak nowszym sposobem formatowania jest metoda "format". # Ta metoda jest obecnie polecana: "{0} są {1}".format("napisy", "fajne") -# Jeśli nie chce ci się liczyć użyj słów kluczowych. +# Jeśli nie chce ci się liczyć, użyj słów kluczowych. "{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") # None jest obiektem @@ -135,12 +135,12 @@ None # => None "etc" is None # => False None is None # => True -# Operator 'is' testuje identyczność obiektów. To nie jest zbyt +# Operator 'is' testuje identyczność obiektów. Nie jest to zbyt # pożyteczne, gdy działamy tylko na prostych wartościach, # ale przydaje się, gdy mamy do czynienia z obiektami. -# None, 0, i pusty napis "" są odpowiednikami logicznego False. -# Wszystkie inne wartości są True +# None, 0 i pusty napis "" są odpowiednikami logicznego False. +# Wszystkie inne wartości są uznawane za prawdę (True) bool(0) # => False bool("") # => False @@ -149,20 +149,20 @@ bool("") # => False ## 2. Zmienne i zbiory danych #################################################### -# Python ma wyrażenie wypisujące "print" we wszystkich wersjach 2.x, ale -# zostało usunięte z wersji 3. -print "Jestem Python. Miło poznać!" -# Python ma też funkcję "print" dostępną w wersjach 2.7 and 3... +# Python ma instrukcję wypisującą "print" we wszystkich wersjach 2.x, ale +# została ona usunięta z wersji 3. +print "Jestem Python. Miło Cię poznać!" +# Python ma też funkcję "print" dostępną w wersjach 2.7 i 3... # ale w 2.7 musisz dodać import (odkomentuj): # from __future__ import print_function print("Ja też jestem Python! ") # Nie trzeba deklarować zmiennych przed przypisaniem. -jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i kładki _ +jakas_zmienna = 5 # Konwencja mówi: używaj małych liter i znaków podkreślenia _ jakas_zmienna # => 5 # Próba dostępu do niezadeklarowanej zmiennej da błąd. -# Przejdź do sekcji Obsługa wyjątków po więcej... +# Przejdź do sekcji Obsługa wyjątków, aby dowiedzieć się więcej... inna_zmienna # Wyrzuca nazwę błędu # "if" może być użyte jako wyrażenie @@ -173,7 +173,7 @@ li = [] # Możesz zacząć od wypełnionej listy inna_li = [4, 5, 6] -# Dodaj na koniec używając "append" +# Dodaj na koniec, używając "append" li.append(1) # li to teraz [1] li.append(2) # li to teraz [1, 2] li.append(4) # li to teraz [1, 2, 4] @@ -185,7 +185,7 @@ li.append(3) # li to znowu [1, 2, 4, 3]. # Dostęp do list jak do każdej tablicy li[0] # => 1 -# Użyj = aby nadpisać wcześniej wypełnione miejsca w liście +# Aby nadpisać wcześniej wypełnione miejsca w liście, użyj znaku = li[0] = 42 li[0] # => 42 li[0] = 1 # Uwaga: ustawiamy starą wartość @@ -195,7 +195,7 @@ li[-1] # => 3 # Jeżeli wyjdziesz poza zakres... li[4] # ... zobaczysz IndexError -# Możesz tworzyć wyniki. +# Możesz też tworzyć wycinki. li[1:3] # => [2, 4] # Bez początku li[2:] # => [4, 3] @@ -213,12 +213,12 @@ del li[2] # li to teraz [1, 2, 3] # Listy można dodawać li + inna_li # => [1, 2, 3, 4, 5, 6] -# Uwaga: wartości poszczególnych list się nie zmieniają. +# Uwaga: wartości oryginalnych list li i inna_li się nie zmieniają. # Do łączenia list użyj "extend()" li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6] -# Sprawdź czy jest w liście używając "in" +# Sprawdź, czy element jest w liście używając "in" 1 in li # => True # "len()" pokazuje długość listy @@ -238,7 +238,7 @@ tup[:2] # => (1, 2) # Można rozpakować krotki i listy do poszczególych zmiennych a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3 -# Jeżeli zapomnisz nawiasów automatycznie tworzone są krotki +# Jeżeli zapomnisz nawiasów, automatycznie tworzone są krotki d, e, f = 4, 5, 6 # Popatrz jak prosto zamienić wartości e, d = d, e # d to teraz 5 a e to 4 @@ -252,28 +252,28 @@ pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3} # Podglądany wartość pelen_slownik["one"] # => 1 -# Wypisz wszystkie klucze używając "keys()" +# Wypisz wszystkie klucze, używając "keys()" pelen_slownik.keys() # => ["trzy", "dwa", "raz"] -# Uwaga: słowniki nie gwarantują kolejności występowania kluczy. +# Uwaga: słowniki nie zapamiętują kolejności kluczy. # A teraz wszystkie wartości "values()" pelen_slownik.values() # => [3, 2, 1] # Uwaga: to samo dotyczy wartości. -# Sprawdzanie czy występuje to "in" +# Sprawdzanie czy klucz występuje w słowniku za pomocą "in" "raz" in pelen_slownik # => True 1 in pelen_slownik # => False # Próba dobrania się do nieistniejącego klucza da KeyError pelen_slownik["cztery"] # KeyError -# Użyj "get()" method aby uniknąć KeyError +# Użyj metody "get()", aby uniknąć błędu KeyError pelen_slownik.get("raz") # => 1 pelen_slownik.get("cztery") # => None # Metoda get zwraca domyślną wartość gdy brakuje klucza pelen_slownik.get("one", 4) # => 1 pelen_slownik.get("cztery", 4) # => 4 -# zauważ, że pelen_slownik.get("cztery") jest wciąż => None +# zauważ, że pelen_slownik.get("cztery") wciąż zwraca => None # (get nie ustawia wartości słownika) # przypisz wartość do klucza podobnie jak w listach @@ -284,12 +284,12 @@ pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5 pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5 -# Teraz zbiory (set) ... cóż zbiory (to po prostu listy ale bez potórzeń) +# Teraz zbiory (set) - działają jak zwykłe listy, ale bez potórzeń pusty_zbior = set() # Inicjalizujemy "set()" pewnymi wartościami jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4]) -# kolejność nie jest gwarantowana, nawet gdy wydaje się posortowane +# kolejność nie jest zachowana, nawet gdy wydaje się posortowane inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4]) # Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru @@ -298,7 +298,7 @@ pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # Dodaj więcej elementów przez "add()" pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5} -# Znajdź przecięcie zbiorów używając & +# Znajdź przecięcie (część wspólną) zbiorów, używając & inny_zbior = {3, 4, 5, 6} pelen_zbior & other_set # => {3, 4, 5} @@ -317,32 +317,32 @@ pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} ## 3. Kontrola przepływu #################################################### -# Tworzymy zmienną some_var -some_var = 5 +# Tworzymy zmienną jakas_zm +jakas_zm = 5 -# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie! -# wypisze "some_var jest mniejsza niż 10" -if some_var > 10: - print("some_var jest wieksza niż 10") -elif some_var < 10: # This elif clause is optional. - print("some_var jest mniejsza niż 10") -else: # This is optional too. - print("some_var jest równa 10") +# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia w Pythonie są ważne! +# Poniższy kod wypisze "jakas_zm jest mniejsza niż 10" +if jakas_zm > 10: + print("jakas_zm jest wieksza niż 10") +elif some_var < 10: # Opcjonalna klauzula elif + print("jakas_zm jest mniejsza niż 10") +else: # Również opcjonalna klauzula else + print("jakas_zm jest równa 10") """ -Pętla for iteruje po elementach listy wypisując: +Pętla for iteruje po elementach listy, wypisując: pies to ssak kot to ssak mysz to ssak """ for zwierze in ["pies", "kot", "mysz"]: - # Możesz użyć % aby stworzyć sformatowane napisy - print("%s to ssak" % zwierze) + # Użyj metody format, aby umieścić wartość zmiennej w ciągu + print("{0} to ssak".format(zwierze)) """ "range(liczba)" zwraca listę liczb -od zera do danej liczby: +z przedziału od zera do wskazanej liczby (bez niej): 0 1 2 @@ -352,7 +352,7 @@ for i in range(4): print(i) """ -While to pętla która jest wykonywana dopóki spełniony jest warunek: +While to pętla, która jest wykonywana, dopóki spełniony jest warunek: 0 1 2 @@ -363,46 +363,46 @@ while x < 4: print(x) x += 1 # Skrót od x = x + 1 -# Wyjątki wyłapujemy używając try, except +# Wyjątki wyłapujemy, używając try i except # Działa w Pythonie 2.6 i wyższych: try: - # Użyj "raise" aby wyrzucić wyjąte + # Użyj "raise" aby wyrzucić wyjątek raise IndexError("To błąd indeksu") except IndexError as e: - pass # Pass to brak reakcji na błąd. Zazwyczaj nanosisz tu poprawki. + pass # Pass to brak reakcji na błąd. Zwykle opisujesz tutaj, jak program ma się zachować w przypadku błędu. except (TypeError, NameError): - pass # kilka wyjątków może być przechwyce razem. + pass # kilka wyjątków można przechwycić jednocześnie. else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku. #################################################### -## 4. Funkcjie +## 4. Funkcje #################################################### -# Użyj "def" aby stworzyć nową funkcję +# Użyj "def", aby stworzyć nową funkcję def dodaj(x, y): - print("x to %s a y to %s" % (x, y)) - return x + y # słówko kluczowe return zwraca wynik działania + print("x to %s, a y to %s" % (x, y)) + return x + y # słowo kluczowe return zwraca wynik działania -# Tak wywołuje się funkcję z parametrami (args): -dodaj(5, 6) # => wypisze "x to 5 a y to 6" i zwróci 11 +# Tak wywołuje się funkcję z parametrami: +dodaj(5, 6) # => wypisze "x to 5, a y to 6" i zwróci 11 # Innym sposobem jest wywołanie z parametrami nazwanymi. dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia. -# Można też stworzyć funkcję, które przyjmują różną ilość parametrów -# nienazwanych args, co będzie interpretowane jako krotka jeśli nie użyjesz * +# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów pozycyjnych, +# które zostaną przekazana jako krotka, pisząc w definicji funkcji "*args" def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) -# Można też stworzyć funkcję, które przyjmują różną ilość parametrów -# nazwanych kwargs, które będa interpretowane jako słownik jeśli nie dasz ** +# Można też stworzyć funkcję, które przyjmują zmienną liczbę parametrów +# nazwanych kwargs, które zostaną przekazane jako słownik, pisząc w definicji funkcji "**kwargs" def keyword_args(**kwargs): return kwargs @@ -410,12 +410,12 @@ def keyword_args(**kwargs): keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"} -# Możesz też to pomieszać +# Możesz też przyjmować jednocześnie zmienną liczbę parametrów pozycyjnych i nazwanych def all_the_args(*args, **kwargs): print(args) print(kwargs) """ -all_the_args(1, 2, a=3, b=4) wyrzuci: +all_the_args(1, 2, a=3, b=4) wypisze: (1, 2) {"a": 3, "b": 4} """ @@ -435,7 +435,7 @@ def pass_all_the_args(*args, **kwargs): print varargs(*args) print keyword_args(**kwargs) -# Zakres widoczności +# Zasięg zmiennych x = 5 def setX(num): @@ -461,14 +461,14 @@ def rob_dodawacz(x): dodaj_10 = rob_dodawacz(10) dodaj_10(3) # => 13 -# Są również funkcje nienazwane "lambda" +# Są również funkcje anonimowe "lambda" (lambda x: x > 2)(3) # => True -# Są także wbudowane funkcje wysokiego poziomu +# Python ma też wbudowane funkcje wyższego rzędu (przyjmujące inną funkcje jako parametr) map(add_10, [1, 2, 3]) # => [11, 12, 13] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -# Można używać wyrażeń listowych do mapowania (map) i filtrowania (filter) +# Można używać wyrażeń listowych (list comprehensions) do mapowania i filtrowania [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] @@ -485,18 +485,18 @@ class Czlowiek(object): # Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji. # Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają - # obietky lub atrybuty, który żyją tylko w kontrolowanej przez - # użytkownika przestrzeni nazw. Nie używaj ich we własnych metodach. + # specjalne obiekty lub atrybuty wykorzystywane wewnętrznie przez Pythona. + # Nie używaj ich we własnych metodach. def __init__(self, nazwa): # przypisz parametr "nazwa" do atrybutu instancji self.nazwa = nazwa - # Metoda instancji. Wszystkie metody biorą "self" jako pierwszy argument + # Metoda instancji. Wszystkie metody przyjmują "self" jako pierwszy argument def mow(self, wiadomosc): return "%s: %s" % (self.nazwa, wiadomosc) # Metoda klasowa współdzielona przez instancje. - # Ma wywołującą klasę jako pierwszy argument. + # Przyjmuje wywołującą klasę jako pierwszy argument. @classmethod def daj_gatunek(cls): return cls.gatunek @@ -540,7 +540,8 @@ print(ceil(3.7)) # => 4.0 print(floor(3.7)) # => 3.0 # Można zaimportować wszystkie funkcje z danego modułu. -# Ostrzeżenie: nie jest to polecane. +# Uwaga: nie jest to polecane, bo później w kodzie trudno połapać się, +# która funkcja pochodzi z którego modułu. from math import * # Można skracać nazwy modułów. @@ -550,7 +551,7 @@ math.sqrt(16) == m.sqrt(16) # => True from math import sqrt math.sqrt == m.sqrt == sqrt # => True -# Moduły pythona to zwykłe skrypty napisane w tym języku. Możesz +# Moduły Pythona to zwykłe skrypty napisane w tym języku. Możesz # pisać własne i importować je. Nazwa modułu to nazwa pliku. # W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu. @@ -568,14 +569,16 @@ def podwojne_liczby(iterowalne): yield i + i # Generatory tworzą wartości w locie. -# W przeciwienstwie do wygenerowania wartości raz i ich zachowania, -# powstają one na bieżąco, w wyniku iteracji. To oznacza, że wartości -# większe niż 15 nie będą przetworzone w funkcji "podwojne_liczby". +# Zamiast generować wartości raz i zapisywać je (np. w liście), +# generator tworzy je na bieżąco, w wyniku iteracji. To oznacza, +# że w poniższym przykładzie wartości większe niż 15 nie będą przetworzone +# w funkcji "podwojne_liczby". # Zauważ, że xrange to generator, który wykonuje tę samą operację co range. # Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci, -# a xrange tworzy obiekt generatora zamiast tworzyć całą listę jak range. -# Użyto podkreślinika, aby odróżnić nazwę zmiennej od słówka kluczowego -# Pythona. +# a xrange tworzy obiekt generatora zamiast budować całą listę jak range. + +# Aby odróżnić nazwę zmiennej od nazwy zarezerwowanej w Pythonie, używamy +# zwykle na końcu znaku podkreślenia xrange_ = xrange(1, 900000000) # poniższa pętla będzie podwajać liczby aż do 30 @@ -587,7 +590,7 @@ for i in podwojne_liczby(xrange_): # Dekoratory # w tym przykładzie "beg" jest nakładką na "say" -# Beg wywołuje say. Jeśli say_please jest prawdziwe wtedy wzracana wartość +# Beg wywołuje say. Jeśli say_please jest prawdziwe, wtedy zwracana wartość # zostanie zmieniona from functools import wraps -- cgit v1.2.3 From e538185c0a3fbbfef7017744a44e1a98a7e50565 Mon Sep 17 00:00:00 2001 From: Zoffix Znet Date: Tue, 17 Nov 2015 13:47:55 -0500 Subject: $! is not available inside the CATCH{} --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 43327edb..fce1dca5 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -738,7 +738,7 @@ try { # You can throw an exception using `die`: die X::AdHoc.new(payload => 'Error !'); -# You can access the last exception with `$!` (usually used in a `CATCH` block) +# You can access the last exception with `$!` (use `$_` in a `CATCH` block) # There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`, # which is a kind of "unthrown exception". They're not thrown until you tried to look -- cgit v1.2.3 From 946b4f260220cc4caaaa9ab7d45109148579ca5f Mon Sep 17 00:00:00 2001 From: Michel Antoine Date: Wed, 18 Nov 2015 23:39:51 -0800 Subject: Add French Javascript ES6 --- fr-fr/javascript-fr.html.markdown | 275 +++++++++++++++++++++++++++++++++----- 1 file changed, 243 insertions(+), 32 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 15478cdb..fd1d40a3 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -6,23 +6,26 @@ contributors: filename: javascript-fr.js translators: - ['@nbrugneaux', 'https://nicolasbrugneaux.me'] + - ['Michel Antoine', 'https://github.com/antoin-m'] lang: fr-fr --- JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995. Le langage avait à l'origine pour but d'être un langage de scripting simple pour les sites web, complétant le Java (à ne pas confondre avec JavaScript) -pour des applications web complexes. Mais son intégration très proche et -simple des pages web, ainsi que le support natif des navigateurs a rendu -le JavaScript incontournable aujourd'hui tant bien dans le front-end que +pour des applications web complexes. Mais son intégration très proche et +simple des pages web, ainsi que le support natif des navigateurs a rendu +le JavaScript incontournable aujourd'hui tant bien dans le front-end que dans le back-end. En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à -Node.JS, un projet qui offre un environnement indépendant dans lequel un -interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome, +Node.JS, un projet qui offre un environnement indépendant dans lequel un +interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome, peut être utilisé directement côté serveur pour exécuter des programmes écrits en JavaScript. +ECMAScript (la norme du langage Javascript) entre en version 6. Cette version introduit de nombreuses mises à jour tout en restant rétrocompatible. L'implémentation de ces nouvelles fonctionnalités est en cours et celles-ci ne sont donc pas forcément compatibles avec tous les navigateurs. + ```js // Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs, /* et les commentaires sur plusieurs lignes commencent avec slash-étoile @@ -31,7 +34,7 @@ en JavaScript. // Toutes les expressions peuvent finir par ; doStuff(); -// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés +// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés // lors de l’interprétation aux sauts de ligne, sauf exceptions doStuff() @@ -79,6 +82,12 @@ false; // faux "abc"; 'Hello, world'; +// *ES6:* Les chaines de caractères peuvent être crées en utilisant un modèle +// entouré des quotes inverses (`) à la place des quotes classiques (' ou "). +// Les variables sont interprétées avec ${var} +let banta = "Harry", santa = "Hermione"; +`${banta}, your santa is ${santa}.` // = "Harry, your santa is Hermione." + // La négation utilise le symbole ! !true; // = false !false; // = true @@ -117,26 +126,34 @@ false; // faux // Il y a également null et undefined null; // utilisé pour une non-valeur -undefined; // utilisé pour une valeur actuellement non présente (cependant, +undefined; // utilisé pour une valeur actuellement non présente (cependant, // undefined est aussi une valeur valide) // false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste // est 'presque-vrai' (truthy) // Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0') +// *ES6:* Introduction d'un nouveau type primitif : Symbol +var symbol_one = Symbol(); +var symbol_two = Symbol('This is optional description, for debugging'); +typeof symbol_one === 'symbol' // = true + +// *ES6:* Un Symbol est immutable et unique +Symbol() === Symbol() // = false +Symbol('learnx') === Symbol('learnx') // = false /////////////////////////////////// -// 2. Variables, Tableaux et Objets +// 2. Variables, Tableaux, Objets, Maps et Sets -// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est +// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est // dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =. var someVar = 5; // si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict) someOtherVar = 10; -// ... mais la variable aura une portée globale (plus communément trouvé en tant -// que "global scope" en anglais), et non pas une portée limitée à la fonction +// ... mais la variable aura une portée globale (plus communément trouvé en tant +// que "global scope" en anglais), et non pas une portée limitée à la fonction // dans laquelle vous l'aviez définie. // Les variables déclarées et non assignées sont undefined par défaut @@ -145,6 +162,32 @@ var someThirdVar = undefined; // ... sont deux déclarations identiques. +// Il est possible de déclarer plusieurs variables en séparant leur déclaration +// avec l'opérateur virgule +var someFourthVar = 2, someFifthVar = 4; + +// *ES6:* Les variables peuvent maintenant être déclarées avec les mots-clés +// `let` et `const` +let someSixthVar = 6; +const someSeventhVar = 7; + +// *ES6:* Le mot-clé `let` attache la variable au block de code et non à la fonction +// à l'inverse de `var` +for (let i = 0; i < 10; i++) { + x += 10; +} +i; // = raises ReferenceError + +// *ES6:* Les variables "const" doivent être assignées lors de l'initialisation +const someEighthVar = 7; +const someNinthVar; // raises SyntaxError + +// *ES6:* Modifier une variable constante ne lève par d'erreur mais échoue +// silencieusement +const someNinthVar = 9; +someNinthVar = 10; +someNinthVar; // = 9 + // Il y a des raccourcis pour les opérations mathématiques: someVar += 5; // équivalent pour someVar = someVar + 5; someVar *= 10; // de même, someVar = someVar * 100; @@ -165,6 +208,22 @@ myArray.length; // = 4 // Ajout/Modification à un index spécifique myArray[3] = 'Hello'; +// *ES6:* Les Arrays peuvent maintenant être déstructurés en utilisant le pattern matching +var [a, b] = [1, 2]; +var [a, , b] = [1, -2, 2] + +a; // = 1 +b; // = 2 + +// *ES6:* La déstructuration peut échouer silencieusement. +// Il est aussi possible d'utiliser des valeurs par défaut +var [a] = []; +a; // = undefined; +var [a = 1] = []; +a; // = 1; +var [a = 1] = [2]; +a; // = 2; + // Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres // langages : ils sont une liste non-ordonnée de paires clé-valeur. var myObj = {key1: 'Hello', key2: 'World'}; @@ -179,12 +238,82 @@ myObj['my other key']; // = 4 // .. ou avec un point si la clé est un identifiant valide. myObj.myKey; // = 'myValue' +// *ES6:* Un Symbol peut être utilisé en tant que clé. Puisque ceux-ci sont uniques, +// le seul moyen d'accéder à la propriété est d'avoir une référence sur ce Symbol. +myObj["key"] = "public value"; +myObj[Symbol("key")] = "secret value"; +myObj[Symbol("key")]; // = undefined + // Les objets sont eux aussi modifiables. myObj.myThirdKey = true; // Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined myObj.myFourthKey; // = undefined +// *ES6:* Comme les Arrays, les Objects peuvent être déstructurés en utilisant le pattern matching +var {foo} = {foo: "bar"}; +foo // = "bar" + +// *ES6:* Les Objects déstructurés peuvent utiliser des noms de variables différents +// de ceux d'origine grâce au pattern matching +var {foo, moo: baz} = {foo: "bar", moo: "car"}; +foo // = "bar" +baz // = "car" + +// *ES6:* Il est possible d'utiliser des valeurs par défaut lor de la déstructuration d'un Object +var {foo="bar"} = {moo: "car"}; +foo // = "bar" + +// *ES6:* Une erreur lors de la déstructuration restera silencieuse +var {foo} = {}; +foo // = undefined + +// *ES6:* ES6 ajoute les iterateurs. Pour accéder à l'iterateur de n'importe quel +// objet il faut utiliser la clé `Symbol.iterator`. +var iterator1 = myArr[Symbol.iterator]; // = returns iterator function + +// *ES6:* Si l'objet possède une valeur à la clé `Symbol.iterator` alors la +// collection est itérable +if (typeof myObj[Symbol.iterator] !== "undefined") { + console.log("You can iterate over myObj"); +} + +// *ES6:* En utilisant la méthode next() de l'iterateur nous recevons un objet +// avec deux propriétés : `value` et `done` +var iterator = myArr[Symbol.iterator]; // myArr = [1,2] +var myArrItem = null; + +myArrItem = iterator.next(); +myArrItem.value; // = 1 +myArrItem.done; // = false + +myArrItem = iterator.next(); +myArrItem.value; // = 2 +myArrItem.done; // = false + +myArrItem = iterator.next(); +myArrItem.value; // = undefined +myArrItem.done; // = true + +// *ES6:* Les Maps sont des objets itérables de type clé-valeur. +// Il est possible de créer une nouvelle map en utilisant `new Map()` +var myMap = new Map(); + +// *ES6:* Il est possible d'ajouter un couple clé-valeur avec la méthode `.set()`, +// de récupérer une valeur avec `.get()`, +// de vérifier qu'une clé existe avec `.has()` +// et enfin de supprimer un couple clé-valeur avec `.delete()` + +myMap.set("name", "Douglas"); +myMap.get("name"); // = "Douglas" +myMap.has("name"); // = true +myMap.delete("name"); + +// *ES6:* Les Sets sont des ensembles de valeurs uniques. +// Il est possible de créer un set avec `new Set()`. +// Toute valeur non unique est ignorée. +var mySet = new Set([1,2,2]); +console.log([...mySet]); // = [1,2] /////////////////////////////////// // 3. Logique et structures de contrôle @@ -198,7 +327,7 @@ else if (count === 4) { // uniquement quand count est 4 } else { - // le reste du temps, si ni 3, ni 4. + // le reste du temps, si ni 3, ni 4. } // De même pour while. @@ -264,7 +393,21 @@ function myFunction(thing){ } myFunction('foo'); // = 'FOO' -// Les fonctions JavaScript sont des objets de première classe, donc peuvent +// Attention, la valeur à retourner doit se trouver sur la même ligne que +// le mot-clé `return` sinon la fonction retournera systématiquement `undefined` +function myFunction(){ + return // <- semicolon automatically inserted here + {thisIsAn: 'object literal'} +} +myFunction(); // = undefined + +// *ES6:* Les paramètres des fonctions peuvent désormais avoir des valeurs par défaut +function default(x, y = 2) { + return x + y; +} +default(10); // == 12 + +// Les fonctions JavaScript sont des objets de première classe, donc peuvent // être réassignées à d'autres variables et passées en tant que paramètres pour // d'autres fonctions function myFunction(){ @@ -274,13 +417,17 @@ setTimeout(myFunction, 5000); // Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi // que Node.js le rendent disponible -// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être +// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être // anonymes setTimeout(function(){ // ce code s'exécutera dans 5 secondes }, 5000); -// Le Javascript crée uniquement un scope, une portée d'action limitée, pour +// *ES6:* Introduction d'un sucre syntaxique permettant de créer +// une fonction anonyme de la forme : `param => returnValue`. +setTimeout(() => console.log('5 seconds, are up.'), 5000); + +// Le Javascript crée uniquement un scope, une portée d'action limitée, pour // les fonctions, et pas dans les autres blocs. if (true){ var i = 5; @@ -293,7 +440,7 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre var temporary = 5; // Nous pouvons accéder au scope global en assignant à l'objet global, // qui dans les navigateurs est "window". Il est différent dans Node.js, - // le scope global sera en fait local au module dans lequel vous + // le scope global sera en fait local au module dans lequel vous // vous trouvez. http://nodejs.org/api/globals.html window.permanent = 10; })(); @@ -302,8 +449,8 @@ i; // = 5 - et non undefined comme vous pourriez vous y attendre temporary; // raises ReferenceError permanent; // = 10 -// Une des fonctionnalités les plus puissantes de Javascript est le système de -// closures. Si une fonction est définie dans une autre fonction, alors la +// Une des fonctionnalités les plus puissantes de Javascript est le système de +// closures. Si une fonction est définie dans une autre fonction, alors la // fonction interne aura accès aux variables de la fonction parente, même si // celle-ci a déjà finie son exécution. function sayHelloInFiveSeconds(name){ @@ -318,6 +465,18 @@ function sayHelloInFiveSeconds(name){ } sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec +// *ES6:* Les paramètres des fonctions appelées avec un tableau en entré +// préfixé par `...` vont se peupler avec les éléments du tableau +function spread(x, y, z) { + return x + y + z; +} +spread(...[1,2,3]); // == 6 + +// *ES6:* Les fonctions peuvent recevoir les paramètres dans un tableau en utilisant l'opérateur `...` +function spread(x, y, z) { + return x + y + z; +} +spread(...[1,2,3]); // == 6 /////////////////////////////////// // 5. Encore plus à propos des Objets; Constructeurs and Prototypes @@ -340,7 +499,7 @@ myObj = { }; myObj.myFunc(); // = 'Hello world!' -// La valeur de "this" change de par l'endroit où la fonction est appelée, et +// La valeur de "this" change de par l'endroit où la fonction est appelée, et // non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle // est appelée hors du contexte l'objet. var myFunc = myObj.myFunc; @@ -356,7 +515,7 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = 'HELLO WORLD!' // Le contexte correspond à la valeur de "this". -// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this, +// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this, // pour une fonction quand elle est appelée grâce à "call" ou "apply". var anotherFunc = function(s){ return this.myString + s; @@ -371,19 +530,19 @@ Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la -// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser +// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la +// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser // "bind" pour garder une référence à la fonction avec ce "this". var boundFunc = anotherFunc.bind(myObj); boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!' -// "bind" peut aussi être utilisé pour créer une application partielle de la +// "bind" peut aussi être utilisé pour créer une application partielle de la // fonction (curry) var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est +// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est // crée et mis à disposition de la fonction via "this". Ces fonctions sont // communément appelées constructeurs. var MyConstructor = function(){ @@ -395,8 +554,8 @@ myNewObj.myNumber; // = 5 // Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à // une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype. -// Quelques implémentations de JS vous laissent accéder au prototype avec la -// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard +// Quelques implémentations de JS vous laissent accéder au prototype avec la +// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard // et ne fonctionne pas dans certains des navigateurs actuels. var myObj = { myString: 'Hello world!' @@ -478,7 +637,7 @@ String.prototype.firstCharacter = function(){ 'abc'.firstCharacter(); // = 'a' // C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles -// fonctionnalités de JavaScript dans de plus anciens environnements, tels que +// fonctionnalités de JavaScript dans de plus anciens environnements, tels que // les vieux navigateurs. //Par exemple, Object.create est assez récent, mais peut être implémenté grâce à @@ -492,31 +651,83 @@ if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe return new Constructor(); } } + +// *ES6:* Les objets peuvent être équipés de proxies qui permettent d'intercepter +// les actions sur leurs propriétés. Voici comment créer un proxy sur un objet : +var proxyObject = new Proxy(object, handler); + +// *ES6:* Les méthodes d'un objet handler sont appelées lors de l'interception d'une action. +// La méthode `.get()` est appelée à chaque lecture d'une propriété +// tandis que la méthode `.set()` est appelée à chaque écriture. +var handler = { + get (target, key) { + console.info('Get on property' + key); + return target[key]; + }, + set (target, key, value) { + console.info('Set on property' + key); + return true; + } +} + +// *ES6:* Les classes peuvent désormais être définies en utilisant le mot-clé `class`. +// Le constructeur s'appelle `constructor` et les méthodes statiques utilisent le mot-clé `static` +class Foo { + constructor() {console.log("constructing Foo");} + bar() {return "bar";} + static baz() {return "baz";} +} + +// *ES6:* Les objets issus des classes sont initialisés avec le mot-clé `new`. +// Il est possible d'hériter d'une classe avec le mot-clé `extends` +var FooObject = new Foo(); // = "constructing Foo" +class Zoo extends Foo {} + +// *ES6:* Les méthodes statiques doivent être appelées par la classe, les autres méthodes par l'objet +Foo.baz() // = "baz" +FooObject.bar() // = "bar" + +// *ES6:* Il est désormais possible d'exporter des valeurs en tant que module. +// Les exports peuvent être n'importe quel objet, valeur ou fonction. +var api = { + foo: "bar", + baz: "ponyfoo" +}; +export default api; + +// *ES6:* La syntaxe `export default` permet d'exporter l'objet sans en changer le nom. +// Il y a plusieurs façons de l'importer: +import coolapi from "api"; // = importe le module dans la variable `coolapi` +import {foo, baz} from "api"; // = importe les attributs `foo` et `baz` du module +import {foo as moo, baz} from "api"; // = importe les attributs `foo` (en le renommant `moo`) et `baz` du module +import _, {map} from "api"; // = importe les exports par défaut ET `map` +import * as coolapi from "api"; // = importe le namespace global du module + ``` ## Pour aller plus loin (en anglais) The [Mozilla Developer Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une -excellente documentation pour le Javascript dans les navigateurs. Et contient +excellente documentation pour le Javascript dans les navigateurs. Et contient également un wiki pour s'entraider. MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) recouvre les principaux sujets vus ici. Le guide est délibérément uniquement -à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous +à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous plutôt ici : [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges. +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges. [JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth un guide pour vous éviter les faux-amis dans le JavaScript. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire. +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire. -En addition aux contributeurs de cet article, du contenu provient du +En addition aux contributeurs de cet article, du contenu provient du "Python tutorial" de Louie Dinh, et de [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) sur le réseau Mozilla. -- cgit v1.2.3 From f2d6b50bd439e971386f775228d2b9960daa0efd Mon Sep 17 00:00:00 2001 From: Michel Antoine Date: Wed, 18 Nov 2015 23:54:39 -0800 Subject: Remove the iterator part and add for..in and for..of --- fr-fr/javascript-fr.html.markdown | 43 +++++++++++++++------------------------ 1 file changed, 16 insertions(+), 27 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index fd1d40a3..f1977dac 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -268,33 +268,6 @@ foo // = "bar" var {foo} = {}; foo // = undefined -// *ES6:* ES6 ajoute les iterateurs. Pour accéder à l'iterateur de n'importe quel -// objet il faut utiliser la clé `Symbol.iterator`. -var iterator1 = myArr[Symbol.iterator]; // = returns iterator function - -// *ES6:* Si l'objet possède une valeur à la clé `Symbol.iterator` alors la -// collection est itérable -if (typeof myObj[Symbol.iterator] !== "undefined") { - console.log("You can iterate over myObj"); -} - -// *ES6:* En utilisant la méthode next() de l'iterateur nous recevons un objet -// avec deux propriétés : `value` et `done` -var iterator = myArr[Symbol.iterator]; // myArr = [1,2] -var myArrItem = null; - -myArrItem = iterator.next(); -myArrItem.value; // = 1 -myArrItem.done; // = false - -myArrItem = iterator.next(); -myArrItem.value; // = 2 -myArrItem.done; // = false - -myArrItem = iterator.next(); -myArrItem.value; // = undefined -myArrItem.done; // = true - // *ES6:* Les Maps sont des objets itérables de type clé-valeur. // Il est possible de créer une nouvelle map en utilisant `new Map()` var myMap = new Map(); @@ -347,6 +320,22 @@ for (var i = 0; i < 5; i++){ // sera exécutée 5 fois } +// La boucle for...in permet d'itérer sur les noms des propriétés d'un objet +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} +description; // = "Paul Ken 18 " + +// *ES6:* La boucle for...of permet d'itérer sur les propriétés d'un objet +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x of person){ + description += x + " "; +} +description; // = "Paul Ken 18 " + // && est le "et" logique, || est le "ou" logique if (house.size === 'big' && house.colour === 'blue'){ house.contains = 'bear'; -- cgit v1.2.3 From 5a62ebbc85cf8c7436ba071b87fb4a584275ebbf Mon Sep 17 00:00:00 2001 From: Byaruhanga Franklin Date: Thu, 19 Nov 2015 15:51:08 +0300 Subject: Replaced 'or' with a semicolons Replaced 'or' with a semicolons since the paragraph above is talking about using semicolons --- erlang.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/erlang.html.markdown b/erlang.html.markdown index d6ed7b86..a57f295f 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -177,7 +177,7 @@ is_dog(A) -> false. % A guard sequence is either a single guard or a series of guards, separated % by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at % least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`. -is_pet(A) when is_atom(A), (A =:= dog) or (A =:= cat) -> true; +is_pet(A) when is_atom(A), (A =:= dog);(A =:= cat) -> true; is_pet(A) -> false. % Warning: not all valid Erlang expressions can be used as guard expressions; -- cgit v1.2.3 From 20eb659e7bb16bbb133774e8e1d916869e1beb10 Mon Sep 17 00:00:00 2001 From: Terka Slan Date: Thu, 19 Nov 2015 17:59:11 +0100 Subject: Translated latex to slovak --- sk-sk/latex.html.markdown.tex | 227 ++++++++++++++++++++++++++++++++++++++++++ sk-sk/learn-latex-sk.tex | 209 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 436 insertions(+) create mode 100644 sk-sk/latex.html.markdown.tex create mode 100644 sk-sk/learn-latex-sk.tex diff --git a/sk-sk/latex.html.markdown.tex b/sk-sk/latex.html.markdown.tex new file mode 100644 index 00000000..5e2f9c7f --- /dev/null +++ b/sk-sk/latex.html.markdown.tex @@ -0,0 +1,227 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Terka Slanináková", "http://github.com/TerkaSlan"] +filename: learn-latex-sk.tex +--- + +```tex +% Všetky komentáre začínajú s % +% Viac-riadkové komentáre sa nedajú urobiť + +% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer + +% Každý LaTeX príkaz začína s opačným lomítkom (\) + +% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu +% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď. +% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu. +\documentclass[12pt]{article} + +% Ďalej definujeme balíčky, ktoré dokuemnt používa. +% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami. +% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček. +\usepackage{caption} +\usepackage{float} +\usepackage[utf8]{inputenc} +% Tu môžme definovať ostatné vlastnosti dokumentu! +% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok" +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková} +% Vygeneruje dnešný dátum +\date{\today} +\title{Nauč sa LaTeX za Y Minút!} +% Teraz môžme začať pracovať na samotnom dokumente. +% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble") +\begin{document} +% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu. +\maketitle + +% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy. +% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke, +% no pred hlavnými sekciami tela.. +% Tento príkaz je tiež dostupný v triedach article a report. +% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract +% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom +\renewcommand\abstractname{Abstrakt} + +\begin{abstract} +LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu! +\end{abstract} + +% Príkazy pre sekciu sú intuitívne +% Všetky nadpisy sekcií sú pridané automaticky do obsahu. +\section{Úvod} +Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)! + +\section{Ďalšia sekcia} +Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu. + +\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne. +Zdá sa mi, že treba ďalšiu. + +\subsubsection{Pytagoras} +To je ono! +\label{subsec:pytagoras} + +% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu. +% Toto funguje aj na iné príkazy. +\section*{Toto je nečíslovaná sekcia} +Všetky číslované byť nemusia! + +\section{Nejaké poznámočky} +Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak +potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do +zdrojového kódu. \\ + +\section{Zoznamy} +Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam. +\begin{enumerate} % "enumerate" spustí číslovanie prvkov. + % \item povie LaTeXu, ako že treba pripočítať 1 + \item Vlašský šalát. + \item 5 rožkov. + \item 3 Horalky. + % číslovanie môžeme pozmeniť použitím [] + \item[koľko?] Stredne veľkých guličkoviek. + + Ja už nie som položka zoznamu, no stále som časť "enumerate". + +\end{enumerate} % Všetky prostredia končia s "end". + +\section{Matika} + +Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\ + +Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať; +Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\ + +Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch. +Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\ +% Všimni si, že som pridal $ pred a po symboloch. Je to +% preto, lebo pri písaní sme v textovom móde, +% no matematické symboly existujú len v matematickom. +% Vstúpime doňho z textového práve '$' znamienkami. +% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto. +% Do matematického módu sa dá dostať aj s \[\] + +\[a^2 + b^2 = c^2 \] + +Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$. +Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal! + +Operátory sú dôležitou súčasťou matematických dokumentov: +goniometrické funkcie ($\sin$, $\cos$, $\tan$), +logaritmy and exponenciálne výrazy ($\log$, $\exp$), +limity ($\lim$), atď. +majú pred-definované LaTeXové príkazy. +Napíšme si rovnicu, nech vidíme, ako to funguje: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatívne komplexné zlomky sa píšu ako +% \frac{čitateľ}{menovateľ} +$\frac{n!}{k!(n - k)!}$ \\ + +Rovnice tiež môžeme zadať v "rovnicovom prostredí". + +% Takto funguje rovnicové prostredie +\begin{equation} % vstúpi do matematického módu + c^2 = a^2 + b^2. + \label{eq:pythagoras} % na odkazovanie +\end{equation} % všetky \begin príkazy musia mať konečný príkaz. + +Teraz môžeme odkázať na novovytvorenú rovnicu! +Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie. + +Sumácie a Integrály sa píšu príkazmi sum a int: + +% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú) +% v rovnicovom prostredí. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Obrázky} + +Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok. +\renewcommand\figurename{Obrázok} +\begin{figure}[H] % H značí možnosť zarovnania. + \centering % nacentruje obrázok na stránku + % Vloží obrázok na 80% šírky stránky. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Zakomentované kvôli kompilácií, použi svoju predstavivosť :). + \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} +% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj +\renewcommand\tablename{Tabuľka} + +\subsection{Tabuľky} +Tabuľky sa vkládajú podobne ako obrázky. + +\begin{table}[H] + \caption{Nadpis tabuľky.} + % zátvorky: {} hovoria ako sa vykreslí každý riadok. + % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz! + \begin{tabular}{c|cc} + Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $ + \hline % horizontálna čiara + 1 & Ladislav & Meliško \\ + 2 & Eva & Máziková + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Už čoskoro :) + +\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)} +Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom. +Toto sa robí vo verbatim prostredí. + +% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.) +% ale verbatim je to najzákladnejšie, čo môžeš použiť. +\begin{verbatim} + print("Hello World!") + a%b; pozri! Vo verbatime môžme použiť % znamienka. + random = 4; #priradené randomným hodom kockou +\end{verbatim} + +\section{Kompilácia} + +Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš? +(áno, tento dokument sa musí kompilovať). \\ +Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov: + \begin{enumerate} + \item Napíš dokument v čistom texte (v "zdrojáku"). + \item Skompiluj zdroják na získanie pdfka. + Kompilácia by mala vyzerať nasledovne (v Linuxe): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie. +Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte. + +\section{Koniec} + +To je zatiaľ všetko! + +% koniec dokumentu +\end{document} +``` + +## Viac o LaTeXe (anglicky) + +* Úžasná LaTeX wikikniha: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* Naozajstný tutoriál: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/sk-sk/learn-latex-sk.tex b/sk-sk/learn-latex-sk.tex new file mode 100644 index 00000000..5cc7b11f --- /dev/null +++ b/sk-sk/learn-latex-sk.tex @@ -0,0 +1,209 @@ +% Všetky komentáre začínajú s % +% Viac-riadkové komentáre sa nedajú urobiť + +% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer + +% Každý LaTeX príkaz začína s opačným lomítkom (\) + +% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu +% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď. +% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu. +\documentclass[12pt]{article} + +% Ďalej definujeme balíčky, ktoré dokuemnt používa. +% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami. +% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček. +\usepackage{caption} +\usepackage{float} +\usepackage[utf8]{inputenc} +% Tu môžme definovať ostatné vlastnosti dokumentu! +% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok" +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková} +% Vygeneruje dnešný dátum +\date{\today} +\title{Nauč sa LaTeX za Y Minút!} +% Teraz môžme začať pracovať na samotnom dokumente. +% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble") +\begin{document} +% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu. +\maketitle + +% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy. +% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke, +% no pred hlavnými sekciami tela.. +% Tento príkaz je tiež dostupný v triedach article a report. +% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract +% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom +\renewcommand\abstractname{Abstrakt} + +\begin{abstract} +LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu! +\end{abstract} + +% Príkazy pre sekciu sú intuitívne +% Všetky nadpisy sekcií sú pridané automaticky do obsahu. +\section{Úvod} +Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)! + +\section{Ďalšia sekcia} +Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu. + +\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne. +Zdá sa mi, že treba ďalšiu. + +\subsubsection{Pytagoras} +To je ono! +\label{subsec:pytagoras} + +% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu. +% Toto funguje aj na iné príkazy. +\section*{Toto je nečíslovaná sekcia} +Všetky číslované byť nemusia! + +\section{Nejaké poznámočky} +Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak +potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do +zdrojového kódu. \\ + +\section{Zoznamy} +Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam. +\begin{enumerate} % "enumerate" spustí číslovanie prvkov. + % \item povie LaTeXu, ako že treba pripočítať 1 + \item Vlašský šalát. + \item 5 rožkov. + \item 3 Horalky. + % číslovanie môžeme pozmeniť použitím [] + \item[koľko?] Stredne veľkých guličkoviek. + + Ja už nie som položka zoznamu, no stále som časť "enumerate". + +\end{enumerate} % Všetky prostredia končia s "end". + +\section{Matika} + +Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\ + +Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať; +Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\ + +Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch. +Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\ +% Všimni si, že som pridal $ pred a po symboloch. Je to +% preto, lebo pri písaní sme v textovom móde, +% no matematické symboly existujú len v matematickom. +% Vstúpime doňho z textového práve '$' znamienkami. +% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto. +% Do matematického módu sa dá dostať aj s \[\] + +\[a^2 + b^2 = c^2 \] + +Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$. +Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal! + +Operátory sú dôležitou súčasťou matematických dokumentov: +goniometrické funkcie ($\sin$, $\cos$, $\tan$), +logaritmy and exponenciálne výrazy ($\log$, $\exp$), +limity ($\lim$), atď. +majú pred-definované LaTeXové príkazy. +Napíšme si rovnicu, nech vidíme, ako to funguje: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatívne komplexné zlomky sa píšu ako +% \frac{čitateľ}{menovateľ} +$\frac{n!}{k!(n - k)!}$ \\ + +Rovnice tiež môžeme zadať v "rovnicovom prostredí". + +% Takto funguje rovnicové prostredie +\begin{equation} % vstúpi do matematického módu + c^2 = a^2 + b^2. + \label{eq:pythagoras} % na odkazovanie +\end{equation} % všetky \begin príkazy musia mať konečný príkaz. + +Teraz môžeme odkázať na novovytvorenú rovnicu! +Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie. + +Sumácie a Integrály sa píšu príkazmi sum a int: + +% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú) +% v rovnicovom prostredí. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Obrázky} + +Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok. +\renewcommand\figurename{Obrázok} +\begin{figure}[H] % H značí možnosť zarovnania. + \centering % nacentruje obrázok na stránku + % Vloží obrázok na 80% šírky stránky. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Zakomentované kvôli kompilácií, použi svoju predstavivosť :). + \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} +% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj +\renewcommand\tablename{Tabuľka} + +\subsection{Tabuľky} +Tabuľky sa vkládajú podobne ako obrázky. + +\begin{table}[H] + \caption{Nadpis tabuľky.} + % zátvorky: {} hovoria ako sa vykreslí každý riadok. + % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz! + \begin{tabular}{c|cc} + Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $ + \hline % horizontálna čiara + 1 & Ladislav & Meliško \\ + 2 & Eva & Máziková + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Už čoskoro :) + +\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)} +Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom. +Toto sa robí vo verbatim prostredí. + +% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.) +% ale verbatim je to najzákladnejšie, čo môžeš použiť. +\begin{verbatim} + print("Hello World!") + a%b; pozri! Vo verbatime môžme použiť % znamienka. + random = 4; #priradené randomným hodom kockou +\end{verbatim} + +\section{Kompilácia} + +Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš? +(áno, tento dokument sa musí kompilovať). \\ +Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov: + \begin{enumerate} + \item Napíš dokument v čistom texte (v "zdrojáku"). + \item Skompiluj zdroják na získanie pdfka. + Kompilácia by mala vyzerať nasledovne (v Linuxe): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie. +Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte. + +\section{Koniec} + +To je zatiaľ všetko! + +% koniec dokumentu +\end{document} -- cgit v1.2.3 From bb1e07bbb7d6555d8875c03b82c5a05f8cf06c37 Mon Sep 17 00:00:00 2001 From: Kate Reading Date: Thu, 19 Nov 2015 11:23:19 -0800 Subject: Clarified grammar in LearnCSharp comment about naming files relative to the classes they contain. Otherwise the two comment lines blended together and were a little comfusing. --- csharp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index dfdd98de..677c2591 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -45,8 +45,8 @@ using System.Data.Entity; // Using this code from another source file: using Learning.CSharp; namespace Learning.CSharp { - // Each .cs file should at least contain a class with the same name as the file - // you're allowed to do otherwise, but shouldn't for sanity. + // Each .cs file should at least contain a class with the same name as the file. + // You're allowed to do otherwise, but shouldn't for sanity. public class LearnCSharp { // BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before -- cgit v1.2.3 From dff8b792c6ba946302af52e3fba113e8364ea214 Mon Sep 17 00:00:00 2001 From: Ryan Gonzalez Date: Thu, 19 Nov 2015 17:53:49 -0600 Subject: Fix typo in Perl 6 example (closes #2025) --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 9f55718c..1829f964 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -373,7 +373,7 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return say join(' ', @array[15..*]); #=> 15 16 17 18 19 # which is equivalent to: say join(' ', @array[-> $n { 15..$n }]); -# Note: if you try to do either of those with an infinite loop, +# Note: if you try to do either of those with an infinite array, # you'll trigger an infinite loop (your program won't finish) # You can use that in most places you'd expect, even assigning to an array -- cgit v1.2.3 From 30e364f4108fc077343a8722f3d80150f0d250fe Mon Sep 17 00:00:00 2001 From: Louis Christopher Date: Sat, 21 Nov 2015 19:28:59 +0530 Subject: Fixed erroneous output stated in a comment range( start = lower limit, End is < Upper limit , Step) The upper limit is never printed. Fixed the error. --- python3.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index 1f9d0e42..3ba57738 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -425,7 +425,6 @@ by step. If step is not indicated, the default value is 1. prints: 4 6 - 8 """ for i in range(4, 8, 2): print(i) -- cgit v1.2.3 From 3c4a2ff91c6d52ccc928e1c26a28e1fdcbc7c064 Mon Sep 17 00:00:00 2001 From: Louis Christopher Date: Sat, 21 Nov 2015 19:44:23 +0530 Subject: Fixed erroneous output and added a little clarity on the matter list.index(argument) would return the index of the item in the list that first matched the argument It will not return the value stored at the index of the argument as it was prior. Added some more clarity to the subject as well. --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 3ba57738..8cc03320 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -224,8 +224,8 @@ li.remove(2) # Raises a ValueError as 2 is not in the list # Insert an element at a specific index li.insert(1, 2) # li is now [1, 2, 3] again -# Get the index of the first item found -li.index(2) # => 3 +# Get the index of the first item found matching the argument +li.index(2) # => 1 li.index(4) # Raises a ValueError as 4 is not in the list # You can add lists -- cgit v1.2.3 From 7933ea3ce029a3418bac04210e0dd7f0f27e275d Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sat, 21 Nov 2015 19:08:39 +0100 Subject: Applies a1ed02d6fad2b39137f52c6a04264a59e237d747 to translations --- cs-cz/python3.html.markdown | 2 +- es-es/python3-es.html.markdown | 2 +- fr-fr/python3-fr.html.markdown | 2 +- ru-ru/python3-ru.html.markdown | 2 +- tr-tr/python3-tr.html.markdown | 2 +- zh-cn/python3-cn.html.markdown | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown index 6d2fd1eb..b498046a 100644 --- a/cs-cz/python3.html.markdown +++ b/cs-cz/python3.html.markdown @@ -566,7 +566,7 @@ Clovek.odkaslej_si() # => "*ehm*" # Lze importovat moduly import math -print(math.sqrt(16)) # => 4 +print(math.sqrt(16.0)) # => 4 # Lze také importovat pouze vybrané funkce z modulu from math import ceil, floor diff --git a/es-es/python3-es.html.markdown b/es-es/python3-es.html.markdown index 1c69481a..d30af1c8 100644 --- a/es-es/python3-es.html.markdown +++ b/es-es/python3-es.html.markdown @@ -478,7 +478,7 @@ Humano.roncar() #=> "*roncar*" # Puedes importar módulos import math -print(math.sqrt(16)) #=> 4 +print(math.sqrt(16)) #=> 4.0 # Puedes obtener funciones específicas desde un módulo from math import ceil, floor diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown index 04d0a55d..3d60157c 100644 --- a/fr-fr/python3-fr.html.markdown +++ b/fr-fr/python3-fr.html.markdown @@ -627,7 +627,7 @@ Human.grunt() # => "*grunt*" # On peut importer des modules import math -print(math.sqrt(16)) # => 4 +print(math.sqrt(16)) # => 4.0 # On peut importer des fonctions spécifiques d'un module from math import ceil, floor diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index 2a7b3f7b..2b6b59a7 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -549,7 +549,7 @@ Human.grunt() #=> "*grunt*" # Вы можете импортировать модули import math -print(math.sqrt(16)) #=> 4 +print(math.sqrt(16)) #=> 4.0 # Вы можете импортировать отдельные функции модуля from math import ceil, floor diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown index 2477c5da..c7de2922 100644 --- a/tr-tr/python3-tr.html.markdown +++ b/tr-tr/python3-tr.html.markdown @@ -538,7 +538,7 @@ Insan.grunt() # => "*grunt*" # Modülleri içe aktarabilirsiniz import math -print(math.sqrt(16)) # => 4 +print(math.sqrt(16)) # => 4.0 # Modülden belirli bir fonksiyonları alabilirsiniz from math import ceil, floor diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown index c223297c..76455a46 100644 --- a/zh-cn/python3-cn.html.markdown +++ b/zh-cn/python3-cn.html.markdown @@ -535,7 +535,7 @@ Human.grunt() # => "*grunt*" # 用import导入模块 import math -print(math.sqrt(16)) # => 4 +print(math.sqrt(16)) # => 4.0 # 也可以从模块中导入个别值 from math import ceil, floor -- cgit v1.2.3 From e7dc56273f07066e2b4da1c02e3f723b8da834a0 Mon Sep 17 00:00:00 2001 From: Leslie Zhang Date: Mon, 23 Nov 2015 09:14:49 +0800 Subject: Replace Hash#has_key? with Hash#key? 1. Replace Hash#has_key? with Hash#key? 2. Replace Hash#has_value? with Hash#value? --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 243f788b..cf1a18e3 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -230,8 +230,8 @@ new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] # Check existence of keys and values in hash -new_hash.has_key?(:defcon) #=> true -new_hash.has_value?(3) #=> true +new_hash.key?(:defcon) #=> true +new_hash.value?(3) #=> true # Tip: Both Arrays and Hashes are Enumerable # They share a lot of useful methods such as each, map, count, and more -- cgit v1.2.3 From 50fca171c53ca5c1de63c9a09ca457df0767f713 Mon Sep 17 00:00:00 2001 From: "C. Bess" Date: Mon, 23 Nov 2015 13:12:49 -0600 Subject: - added error handling example - add do-try-catch examples - add throw example --- swift.html.markdown | 40 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index df9c5092..33ff8451 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -345,6 +345,44 @@ let namesTable = NamesTable(names: ["Me", "Them"]) let name = namesTable[1] print("Name is \(name)") // Name is Them +// +// MARK: Error Handling +// + +// The `ErrorType` protocol is used when throwing errors to catch +enum MyError: ErrorType { + case BadValue(msg: String) + case ReallyBadValue(msg: String) +} + +// functions marked with `throws` must be called using `try` +func fakeFetch(value: Int) throws -> String { + guard 7 == value else { + throw MyError.ReallyBadValue(msg: "Some really bad value") + } + + return "test" +} + +func testTryStuff() { + // assumes there will be no error thrown, otherwise a runtime exception is raised + let _ = try! fakeFetch(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(7) + + do { + // normal try operation that provides error handling via `catch` block + try fakeFetch(1) + } catch MyError.BadValue(let msg) { + print("Error message: \(msg)") + } catch { + // must be exhaustive + } +} +testTryStuff() + // // MARK: Classes // @@ -559,7 +597,7 @@ class MyShape: Rect { // `extension`s: Add extra functionality to an already existing type -// Square now "conforms" to the `Printable` protocol +// Square now "conforms" to the `CustomStringConvertible` protocol extension Square: CustomStringConvertible { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" -- cgit v1.2.3 From 92a736f5e06473d454f197b8017dc542ba8c404c Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:02:00 -0500 Subject: Added solidity --- solidity.html.markdown | 381 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 381 insertions(+) create mode 100644 solidity.html.markdown diff --git a/solidity.html.markdown b/solidity.html.markdown new file mode 100644 index 00000000..6409828a --- /dev/null +++ b/solidity.html.markdown @@ -0,0 +1,381 @@ +--- +language: Solidity +filename: learnSolidity.sol +contributors: + - ["Nemil Dalal", "https://www.nemil.com"] +--- + +Solidity is a statically typed, contract programming language for [Ethereum](https://www.ethereum.org/) that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. + +Solidity lets you program on Ethereum, a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. + +As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. + +```javascript +// Let's start with a simple Bank contract, before diving into to the key components of the language + +// Start with a Natspec comment (the three slashes) that can be used +// for documentation - and as descriptive data for UI elements +/// @title A simple deposit/withdrawal bank built on Bitcoin + +// All contracts are declared and named (in CamelCase) +contract AcmeBank { + // Declare state variables outside a function, + // these are persistent throughout the life of the contract + + // a dictionary that maps addresses to balances + mapping (address -> uint) balances; + + // the 'public' makes 'owner' externally readable by users or contracts + // (but not writeable), the 'constant' means this value to be + // changed after initialization + address public constant owner; + + // Constructor, can receive one or many variables here + function AcmeBank() { + // msg is a default variable that provides both the + // contract messager's address and amount + owner = msg.address; + // the owner has no additional rights, we're setting it for + // illustrative purposes + } + + function deposit(uint balance) { + balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable + + return balances[msg.sender]; + } + + function withdraw(uint withdrawAmount) returns (uint remainingBalance) { + if(balances[msg.sender] >= withdrawAmount) { + balances[msg.sender] -= withdrawAmount; + balances[msg.sender].send(withdrawAmount); + + return balances[msg.sender]; + } + } + + // The 'constant' prevents the function from editing state variables + function balance() constant { + return balances[msg.sender]; + } + + // Fallback function + // This function is called if invalid data is sent or ether without data; + // Added so that ether sent to this contract is reverted if the contract fails + // otherwise, the sender loses their money; you should add this in most contracts + function () { throw; } +} +// End example + +// Now let's go through the basics of Solidity + +// 1. DATA TYPES +// uint is the data type typically used for currency (there are no doubles +// or floats) and for dates +uint x; +int const a = 8; // int of 256 bits, cannot be changed after instantiation +uint8 b; +int64 c; +// int256 is same as int +// For both int and uint, you can explicitly set space in steps of 8, +// e.g., int8, int16 +uint248 e; + +// Type casting +int x = int(b) + +bool b = true; // or do 'var b = true;' for inferred typing + +// Addresses - holds 20 byte/160 bit Ethereum addresses to another contract +// ('Contract Account)') or person/external entity ('External Account') +address public owner; // Add 'public' field to indicate publicly/externally accessible, a getter is automatically created, but NOT a setter + +// All addresses can be sent ether in the following way: +owner.send(SOME_BALANCE); // returns false on failure +owner.balance; // the balance of the owner + +// Bytes are provided from 1 to 32 +byte a; // byte is same as bytes1 +bytes32 b; + +// Dynamically sized +bytes m; // A special array, same as byte[] (but packed tightly) +// same as bytes, but does not allow length or index access (for now) +string n = 'hello'; + +// Type inference +// var does inferred typing based on first assignment, +// can't be used in functions parameters +var a = true; +// there are edge cases where inference leads to a value being set (e.g., an uint 8) +// that is different from what the user wanted (uint16), so use carefully + +// by default, all values are set to 0 on instantiation + +// Delete can be called on most types, and will set the values to 0 +uint x = 5; +delete(x); // x is now 0 + +// 2. DATA STRUCTURES +// Arrays +bytes32[] names; +uint newLength = names.push("John"); // adding returns new length of the array +// Length +names.length; // get length +names.length = 1; // lengths can also be set, unlike many other languages + +// Dictionaries (any type to any other type) +mapping (string -> uint) public balances; +balances["john"] = 1; +console.log(balances[jill]); // is 0, all non-set key values return zeroes +// The 'public' lets you do the following from another contract +contractName.balances("john"); // returns 1 +// The 'public' keyword here created a getter (but not setter) that behaves like the following: +function balances(address _account) returns (uint balance) { + return balances[_account]; +} + +// To delete +delete(balances["John"]); +delete(balances); // deletes all elements + +// Unlike languages like Javascript, you cannot iterate through all elements in +// a map, without knowing the source keys + +// Structs and enums + struct Bank { // note the capital + address owner; + uint balance; + } +Bank b = Bank({ + owner: msg.sender, + balance: 5 +}); +delete(b); // set all values to 0, except any mappings + +// Enums +enum State { Created, Locked, Inactive }; +State public state; // Declare variable from enum +state = State.Created; + +// 3. Variables of note +// storage - A persistent storage hash (does not need to be declared) +storage['abc'] = 'def'; // maps 256 bit words to 256 bit words + +// tx - This transaction +tx.origin // address, sender of the transaction +tx.gasprice // uint, gas price of the transaction + +// msg - The current message received by the contract +msg.sender; // address, The address of the sender +msg.value; // uint, The amount of gas provided to this contract in wei +msg.data // bytes, complete call data + +// balance of the current contract (both contract and external accounts +// have balances) - often used at the end of a contracts life to send the +// remaining balance to a party +this.balance +// block +now // uint, current time, alias for block.timestamp +block.number // uint, current block number +block.difficulty // uint, current block difficulty +block.blockhash(1) // returns bytes32, only provides for most recent 256 block + +// 4. FUNCTIONS AND MORE +// A. Functions +// Simple function +function increment(uint x) returns (uint) { + x += 1; + return x; +} + +// Functions can return many arguments, and by specifying the returned arguments +// you don't need to explicity return +function increment(uint x, uint y) returns (uint x, uint y) { + x += 1; + y += 1; +} +// This function would have been called like this, and assigned to a tuple +uint (a,b) = increment(1,1); + +// The 'constant' indicates and ensures that a function does not/cannot change the persistent variables +uint y; + +function increment(uint x) constant returns (uint x) { + x += 1; + y += 1; // this line would fail + // as y is a state variable, and can't be changed in a constant function +} + +// There are a few 'function visibility specifiers' that can be placed where 'constant' +// is, which include: +// internal (can only be called by an internal function, not one external to the contract) +// public - visibile externally and internally +// private - only visible in the current contract + +// Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable +function a() { + var z = b; + b(); +} + +function b() { + +} + +// B. Events +// Events are an easy way to notify external listeners that something changed +// You typically decalre them after your contract parameters +event Sent(address from, address to, uint amount); + +// You then call it in a function, when you want to trigger it +sent(from, to, amount); + +// For an external party (a contract or external entity), to watch +// for an event, you write the following: +Coin.Sent().watch({}, '', function(error, result) { + if (!error) { + console.log("Coin transfer: " + result.args.amount + + " coins were sent from " + result.args.from + + " to " + result.args.to + "."); + console.log("Balances now:\n" + + "Sender: " + Coin.balances.call(result.args.from) + + "Receiver: " + Coin.balances.call(result.args.to)); + } +} +// This is a common paradigm for one contract to depend on another (e.g., a +// contract that depends on the current exchange rate provided by another +// contract) + +// C. Modifiers +// Modifiers let you validate inputs to functions +// The '_' (underscore) must be included, and is an indicator that the +// function being called should be placed there +modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } + +// You can then append it right after the function declaration +function test() + onlyBefore() +{ + +} + +// 5. BRANCHING AND LOOPS + +// All basic logic blocks work - including if/else, for, while, break, continue, return +// switch is not provided +// Syntax is the same as javascript, but there is no type conversion from +// non-boolean to boolean + +// 6. CALLING AN EXTERNAL CONTRACT + +contract infoFeed { + function info() returns (uint ret) { return 42; } +} + +contract Consumer { + InfoFeed feed; // create a variable that will point to a contract on the blockchain + function setFeed(address addr) { + // Link to the contract by creating on the address + feed = InfoFeed(addr); + } + function callFeed() { + // T final parentheses call the contract, optionally adding + // custom value or gas numbers + feed.info.value(10).gas(800)(); + } +} + +// 7. CONTRACT DESIGN PATTERNS + +// A. Obfuscation +// Remember that all variables are publicly viewable on the blockchain, so +// anything that needs some privacy needs to be obfuscated (e.g., hashed) + +// B. Throwing +// Throwing +throw; // throwing is easily done, and reverts unused money to the sender +// You can't currently catch + +// A common design pattern is: +if (!addr.send(123)) { + throw; +} + +// C. Suicide +// Suicide +suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) + +// D. Storage optimization +// Reading and writing can be expensive, as data needs to be stored in the +// blockchain forever - this encourages smart ways to use memory (eventually, +// compilation may better handle this, but for now there are benefits to +// planning your data structures) + +// *** EXAMPLE: Let's do a more complex example *** +// [TODO: Decide what a more complex example looks like, needs a few // characteristics: +// - has a 'constant' state variable +// - has a state machine (uses modifier) +// - sends money to an address +// - gets information from another contract (we'll show code for both contracts) +// - Shows inheritance +// - show variables being passed in on instantiation (and guard code to throw if variables not provided) +// Ideas: +// - crowdfunding? +// - Peer to peer insurance +// ] + +// *** END EXAMPLE *** + +// Some final points +// 7. NATIVE FUNCTIONS + +// Currency units +// By default, currency is defined using wei, the smallest unit of Ether +uint minAmount = 1 wei; +uint a = 1 finney; // 1 ether = 1000 finney +// There are a number of other units, see: http://ether.fund/tool/converter + +// Time units +1 == 1 second +1 minutes == 60 seconds + + +// You typically multiply a variable times the unit, as these units are not +// directly stored in a variable +uint x = 5; +(x * 1 days); // 5 days + +// Be careful about leap seconds and leap years when using equality statements for time (instead, prefer greater than/less than) + +// Cryptography +// All strings passed are concatenated before the hash is run +sha3("ab", "cd"); +ripemd160("abc"); +sha256("def"); + +// These are natspec comments, when a user is asked to confirm a transaction +/// +/** */ + +// 8. COMMON MISTAKES +// A few common mistakes +// You cannot restrict a human or computer from reading the content of +// your transaction or a transaction's state + +// All data to the start of time is stored in the blockchain, so you and +// anyone can observe all previous data states + +// 9. STYLE NOTES +// Use 4 spaces for indentation +// (Python's PEP8 is used as the baseline style guide, including its general philosophy) +``` + +## Additional resources +- [Solidity Docs](https://ethereum.github.io/solidity/docs/home/) +- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. +- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) +- [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) + +Feel free to send a pull request with any edits - or email nemild -/at-/ gmail \ No newline at end of file -- cgit v1.2.3 From d5bcbceb21954d0f8739fb841fc511aa32c2bcc6 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:07:17 -0500 Subject: Fixed withdrawal check --- solidity.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 6409828a..79debed6 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -49,7 +49,10 @@ contract AcmeBank { function withdraw(uint withdrawAmount) returns (uint remainingBalance) { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - balances[msg.sender].send(withdrawAmount); + + if (!balances[msg.sender].send(withdrawAmount)) { + balances[msg.sender] += withdrawAmount; + } return balances[msg.sender]; } -- cgit v1.2.3 From 08f3ee3687fc18286fdb3825f0fc1fd74c086798 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 23 Nov 2015 16:39:05 -0500 Subject: Added remove function --- solidity.html.markdown | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 79debed6..bcbdec5f 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -35,15 +35,13 @@ contract AcmeBank { function AcmeBank() { // msg is a default variable that provides both the // contract messager's address and amount - owner = msg.address; - // the owner has no additional rights, we're setting it for - // illustrative purposes + owner = msg.address; // msg.address refers to the address of the contract creator } function deposit(uint balance) { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable - return balances[msg.sender]; + return balances[msg.sender]; // msg.sender refers to the contract caller } function withdraw(uint withdrawAmount) returns (uint remainingBalance) { @@ -58,6 +56,13 @@ contract AcmeBank { } } + // It's good practice to have a remove function, which disables this contract + function remove () { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } + } + // The 'constant' prevents the function from editing state variables function balance() constant { return balances[msg.sender]; -- cgit v1.2.3 From 1f4738cbc75f789992270c3926cf9cdd30c4674a Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 24 Nov 2015 00:09:10 -0500 Subject: Several fixes per Andreas's feedback --- solidity.html.markdown | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index bcbdec5f..88ccd817 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -14,28 +14,30 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language +// START EXAMPLE // Start with a Natspec comment (the three slashes) that can be used // for documentation - and as descriptive data for UI elements /// @title A simple deposit/withdrawal bank built on Bitcoin // All contracts are declared and named (in CamelCase) +// They are similar to 'class' in other languages (and allow capabilities like inheritance) contract AcmeBank { // Declare state variables outside a function, // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address -> uint) balances; + mapping (address => uint) balances; // the 'public' makes 'owner' externally readable by users or contracts // (but not writeable), the 'constant' means this value to be // changed after initialization - address public constant owner; + address public owner; // Constructor, can receive one or many variables here function AcmeBank() { // msg is a default variable that provides both the // contract messager's address and amount - owner = msg.address; // msg.address refers to the address of the contract creator + owner = msg.sender; // msg.sender refers to the address of the contract creator } function deposit(uint balance) { @@ -48,7 +50,7 @@ contract AcmeBank { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - if (!balances[msg.sender].send(withdrawAmount)) { + if (!msg.sender.send(withdrawAmount)) { balances[msg.sender] += withdrawAmount; } @@ -56,7 +58,7 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this contract + // It's good practice to have a remove function, which disables this contract - but does mean that users have to trust the owner function remove () { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner @@ -74,7 +76,7 @@ contract AcmeBank { // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } } -// End example +// END EXAMPLE // Now let's go through the basics of Solidity @@ -82,7 +84,7 @@ contract AcmeBank { // uint is the data type typically used for currency (there are no doubles // or floats) and for dates uint x; -int const a = 8; // int of 256 bits, cannot be changed after instantiation +int constant a = 8; // int of 256 bits, cannot be changed after instantiation uint8 b; int64 c; // int256 is same as int @@ -134,7 +136,7 @@ names.length; // get length names.length = 1; // lengths can also be set, unlike many other languages // Dictionaries (any type to any other type) -mapping (string -> uint) public balances; +mapping (string => uint) public balances; balances["john"] = 1; console.log(balances[jill]); // is 0, all non-set key values return zeroes // The 'public' lets you do the following from another contract @@ -322,13 +324,14 @@ suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the add // planning your data structures) // *** EXAMPLE: Let's do a more complex example *** -// [TODO: Decide what a more complex example looks like, needs a few // characteristics: +// [TODO: Decide what a more complex example looks like, needs a few characteristics: // - has a 'constant' state variable // - has a state machine (uses modifier) // - sends money to an address // - gets information from another contract (we'll show code for both contracts) // - Shows inheritance // - show variables being passed in on instantiation (and guard code to throw if variables not provided) +// - Shows the swapping out of a contract // Ideas: // - crowdfunding? // - Peer to peer insurance @@ -375,7 +378,9 @@ sha256("def"); // All data to the start of time is stored in the blockchain, so you and // anyone can observe all previous data states -// 9. STYLE NOTES +// 9. TESTING + +// 10. STYLE NOTES // Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) ``` -- cgit v1.2.3 From 083eb1c4a5ef1da2249ad9640bc2f62cf9f95af0 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Fri, 27 Nov 2015 00:19:06 +0100 Subject: [PowerShell/en] intro --- powershell.html.markdown | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 powershell.html.markdown diff --git a/powershell.html.markdown b/powershell.html.markdown new file mode 100644 index 00000000..5ec18afb --- /dev/null +++ b/powershell.html.markdown @@ -0,0 +1,56 @@ +--- +category: tool +tool: powershell +contributors: + - ["Wouter Van Schandevijl", "https://github.com/laoujin"] +filename: LearnPowershell.ps1 +--- + +PowerShell is the Windows scripting language and configuration management framework from Microsoft built on the .NET Framework. Windows 7 and up ship with PowerShell. +Nearly all examples below can be a part of a shell script or executed directly in the shell. + +A key difference with Bash is that it is mostly objects that you manipulate rather than plain text. + +[Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) + +```powershell +# As you already figured, comments start with # + +# Simple hello world example: +echo Hello world! +# echo is an alias for Write-Output (=cmdlet) +# Most cmdlets and functions follow the Verb-Noun naming convention + +# Each command starts on a new line, or after semicolon: +echo 'This is the first line'; echo 'This is the second line' + +# Declaring a variable looks like this: +$Variable="Some string" +# Or like this: +$Variable1 = "Another string" + +# Using the variable: +echo $Variable +echo "$Variable" +echo '$($Variable + '1')' +echo @" +This is a Here-String +$Variable +"@ +# Note that ' (single quote) won't expand the variables! +# Here-Strings also work with single quote + +# Builtin variables: +# There are some useful builtin variables, like +echo "Booleans: $TRUE and $FALSE" +echo "Empty value: $NULL" +echo "Last program's return value: $?" +echo "Script's PID: $PID" +echo "Number of arguments passed to script: $#" +echo "All arguments passed to script: $Args" +echo "Script's arguments separated into different variables: $1 $2..." + +# Reading a value from input: +$Name = Read-Host "What's your name?" +echo "Hello, $Name!" +[int]$Age = Read-Host "What's your age?" \ No newline at end of file -- cgit v1.2.3 From 4d44e241d72b160c31e74db29ff389371d35579f Mon Sep 17 00:00:00 2001 From: Laoujin Date: Fri, 27 Nov 2015 01:07:45 +0100 Subject: [PowerShell/en] execution-policy, builtin variables, configure your shell --- powershell.html.markdown | 60 ++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index 5ec18afb..2a7deee1 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -13,6 +13,22 @@ A key difference with Bash is that it is mostly objects that you manipulate rath [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) +If you are uncertain about your environment: +```powershell +Get-ExecutionPolicy -List +Set-ExecutionPolicy AllSigned +# Execution policies include: +# - Restricted: Scripts won't run. +# - RemoteSigned: Downloaded scripts run only if signed by a trusted publisher. +# - AllSigned: Scripts need to be signed by a trusted publisher. +# - Unrestricted: Run all scripts. +help about_Execution_Policies # for more info + +# Current PowerShell version: +$PSVersionTable +``` + +The tutorial starts here: ```powershell # As you already figured, comments start with # @@ -25,17 +41,18 @@ echo Hello world! echo 'This is the first line'; echo 'This is the second line' # Declaring a variable looks like this: -$Variable="Some string" +$aString="Some string" # Or like this: -$Variable1 = "Another string" +$aNumber = 5 # Using the variable: -echo $Variable -echo "$Variable" -echo '$($Variable + '1')' +echo $aString +echo "Interpolation: $aString" +echo "`$aString has length of $($aString.length)" +echo '$aString' echo @" This is a Here-String -$Variable +$aString "@ # Note that ' (single quote) won't expand the variables! # Here-Strings also work with single quote @@ -45,12 +62,35 @@ $Variable echo "Booleans: $TRUE and $FALSE" echo "Empty value: $NULL" echo "Last program's return value: $?" +echo "Exit code of last run Windows-based program: $LastExitCode" +echo "The last token in the last line received by the session: $$" +echo "The first token: $^" echo "Script's PID: $PID" -echo "Number of arguments passed to script: $#" -echo "All arguments passed to script: $Args" -echo "Script's arguments separated into different variables: $1 $2..." +echo "Full path of current script directory: $PSScriptRoot" +echo 'Full path of current script: ' + $MyInvocation.MyCommand.Path +echo "FUll path of current directory: $Pwd" +echo "Bound arguments in a function, script or code block: $PSBoundParameters" +echo "Unbound arguments: $($Args -join ', ')." ######################## MOVE THIS TO FUNCTIONS +# More builtins: `help about_Automatic_Variables` # Reading a value from input: $Name = Read-Host "What's your name?" echo "Hello, $Name!" -[int]$Age = Read-Host "What's your age?" \ No newline at end of file +[int]$Age = Read-Host "What's your age?" + + + + +``` + + +Configuring your shell +```powershell +# $Profile is the full path for your `Microsoft.PowerShell_profile.ps1` +# All code there will be executed when the PS session starts +if (-not (Test-Path $Profile)) { + New-Item -Type file -Path $Profile -Force + notepad $Profile +} +# More info: `help about_profiles` +``` \ No newline at end of file -- cgit v1.2.3 From bc47915c8f09fc586e47fd37fef76f6d27a0a8b8 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Fri, 27 Nov 2015 02:37:30 +0100 Subject: [PowerShell/en] control-flow, pipeline, getting help --- powershell.html.markdown | 96 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index 2a7deee1..be802916 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -28,6 +28,18 @@ help about_Execution_Policies # for more info $PSVersionTable ``` +Getting help: +```powershell +# Find commands +Get-Command about_* # alias: gcm +Get-Command -Verb Add +Get-Alias ps +Get-Alias -Definition Get-Process + +Get-Help ps | less # alias: help +ps | Get-Member # alias: gm +``` + The tutorial starts here: ```powershell # As you already figured, comments start with # @@ -44,8 +56,10 @@ echo 'This is the first line'; echo 'This is the second line' $aString="Some string" # Or like this: $aNumber = 5 +$aList = 1,2,3,4,5 +$aHashtable = @{name1='val1'; name2='val2'} -# Using the variable: +# Using variables: echo $aString echo "Interpolation: $aString" echo "`$aString has length of $($aString.length)" @@ -78,7 +92,87 @@ $Name = Read-Host "What's your name?" echo "Hello, $Name!" [int]$Age = Read-Host "What's your age?" +# Control Flow +# We have the usual if structure: +if ($Age -is [string]) { + echo 'But.. $Age cannot be a string!' +} elseif ($Age -lt 12 -and $Age -gt 0) { + echo 'Child (Less than 12. Greater than 0)' +} else { + echo 'Adult' +} +# Switch statements are more powerfull compared to most languages +$val = "20" +switch($val) { + { $_ -eq 42 } { "The answer equals 42"; break } + '20' { "Exactly 20"; break } + { $_ -like 's*' } { "Case insensitive"; break } + { $_ -clike 's*'} { "clike, ceq, cne for case sensitive"; break } + { $_ -notmatch '^.*$'} { "Regex matching. cnotmatch, cnotlike, ..."; break } + { 'x' -contains 'x'} { "FALSE! -contains is for lists!"; break } + default { "Others" } +} + +# The classic for +for($i = 1; $i -le 10; $i++) { + "Loop number $i" +} +# Or shorter +1..10 | % { "Loop number $_" } + +# PowerShell also offers +foreach ($var in 'val1','val2','val3') { echo $var } +# while () {} +# do {} while () +# do {} until () + + +# List files and directories in the current directory +ls # or `dir` +cd ~ # goto home + +Get-Alias ls # -> Get-ChildItem +# Uh!? These cmdlets have generic names because unlike other scripting +# languages, PowerShell does not only operate in the current directory. +cd HKCU: # go to the HKEY_CURRENT_USER registry hive + +# Get all providers in your session +Get-PSProvider + +# Cmdlets have parameters that control their execution: +Get-ChildItem -Filter *.txt -Name # Get just the name of all txt files +# Only need to type as much of a parameter name until it is no longer ambiguous +ls -fi *.txt -n # -f is not possible because -Force also exists +# Use `Get-Help Get-ChildItem -Full` for a complete overview + +# Results of the previous cmdlet can be passed to the next as input. +# grep cmdlet filters the input with provided patterns. +# `$_` is the current object in the pipeline object. +ls | Where-Object { $_.Name -match 'c' } | Export-CSV export.txt +ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File export.html + +# If you get confused in the pipeline use `Get-Member` for an overview +# of the available methods and properties of the pipelined objects: +ls | Get-Member +Get-Date | gm + +# ` is the line continuation character. Or end the line with a | +Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM ` + | Stop-Process -WhatIf + +Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List + +# Use % as a shorthand for ForEach-Object +(a,b,c) | ForEach-Object ` + -Begin { "Starting"; $counter = 0 } ` + -Process { "Processing $_"; $counter++ } ` + -End { "Finishing: $counter" } + +# Get-Process as a table with three columns +# The third column is the value of the VM property in MB and 2 decimal places +# Computed columns can be written more succinctly as: `@{n='lbl';e={$_}` +ps | Format-Table ID,Name,@{name='VM(MB)';expression={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize ``` -- cgit v1.2.3 From 0b7c612c3ed5c82b05bca22bcf3622e37fe55581 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Fri, 27 Nov 2015 03:49:34 +0100 Subject: [PowerShell/en] IO, Interesting Projects, Not Covered, Exception Handling, UseFull stuff, max line 80. --- powershell.html.markdown | 144 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 129 insertions(+), 15 deletions(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index be802916..6f38c45c 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -6,10 +6,14 @@ contributors: filename: LearnPowershell.ps1 --- -PowerShell is the Windows scripting language and configuration management framework from Microsoft built on the .NET Framework. Windows 7 and up ship with PowerShell. -Nearly all examples below can be a part of a shell script or executed directly in the shell. +PowerShell is the Windows scripting language and configuration management +framework from Microsoft built on the .NET Framework. Windows 7 and up ship +with PowerShell. +Nearly all examples below can be a part of a shell script or executed directly +in the shell. -A key difference with Bash is that it is mostly objects that you manipulate rather than plain text. +A key difference with Bash is that it is mostly objects that you manipulate +rather than plain text. [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) @@ -38,6 +42,10 @@ Get-Alias -Definition Get-Process Get-Help ps | less # alias: help ps | Get-Member # alias: gm + +Show-Command Get-EventLog # Display GUI to fill in the parameters + +Update-Help # Run as admin ``` The tutorial starts here: @@ -49,20 +57,21 @@ echo Hello world! # echo is an alias for Write-Output (=cmdlet) # Most cmdlets and functions follow the Verb-Noun naming convention -# Each command starts on a new line, or after semicolon: +# Each command starts on a new line, or after a semicolon: echo 'This is the first line'; echo 'This is the second line' # Declaring a variable looks like this: $aString="Some string" # Or like this: -$aNumber = 5 +$aNumber = 5 -as [double] $aList = 1,2,3,4,5 +$aString = $aList -join '--' # yes, -split exists also $aHashtable = @{name1='val1'; name2='val2'} # Using variables: echo $aString echo "Interpolation: $aString" -echo "`$aString has length of $($aString.length)" +echo "`$aString has length of $($aString.Length)" echo '$aString' echo @" This is a Here-String @@ -84,15 +93,14 @@ echo "Full path of current script directory: $PSScriptRoot" echo 'Full path of current script: ' + $MyInvocation.MyCommand.Path echo "FUll path of current directory: $Pwd" echo "Bound arguments in a function, script or code block: $PSBoundParameters" -echo "Unbound arguments: $($Args -join ', ')." ######################## MOVE THIS TO FUNCTIONS +echo "Unbound arguments: $($Args -join ', ')." # More builtins: `help about_Automatic_Variables` -# Reading a value from input: -$Name = Read-Host "What's your name?" -echo "Hello, $Name!" -[int]$Age = Read-Host "What's your age?" +# Inline another file (dot operator) +. .\otherScriptName.ps1 -# Control Flow + +### Control Flow # We have the usual if structure: if ($Age -is [string]) { echo 'But.. $Age cannot be a string!' @@ -127,7 +135,14 @@ foreach ($var in 'val1','val2','val3') { echo $var } # do {} while () # do {} until () +# Exception handling +try {} catch {} finally {} +try {} catch [System.NullReferenceException] { + echo $_.Exception | Format-List -Force +} + +### Providers # List files and directories in the current directory ls # or `dir` cd ~ # goto home @@ -140,6 +155,8 @@ cd HKCU: # go to the HKEY_CURRENT_USER registry hive # Get all providers in your session Get-PSProvider + +### Pipeline # Cmdlets have parameters that control their execution: Get-ChildItem -Filter *.txt -Name # Get just the name of all txt files # Only need to type as much of a parameter name until it is no longer ambiguous @@ -171,10 +188,96 @@ Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List # Get-Process as a table with three columns # The third column is the value of the VM property in MB and 2 decimal places -# Computed columns can be written more succinctly as: `@{n='lbl';e={$_}` -ps | Format-Table ID,Name,@{name='VM(MB)';expression={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize +# Computed columns can be written more verbose as: +# `@{name='lbl';expression={$_}` +ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize + + +### Functions +# The [string] attribute is optional. +function foo([string]$name) { + echo "Hey $name, have a function" +} + +# Calling your function +foo "Say my name" + +# Functions with named parameters, parameter attributes, parsable documention +<# +.SYNOPSIS +Setup a new website +.DESCRIPTION +Creates everything your new website needs for much win +.PARAMETER siteName +The name for the new website +.EXAMPLE +New-Website -Name FancySite -Po 5000 +New-Website SiteWithDefaultPort +New-Website siteName 2000 # ERROR! Port argument could not be validated +('name1','name2') | New-Website -Verbose +#> +function New-Website() { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [Alias('name')] + [string]$siteName, + [ValidateSet(3000,5000,8000)] + [int]$port = 3000 + ) + BEGIN { Write-Verbose 'Creating new website(s)' } + PROCESS { echo "name: $siteName, port: $port" } + END { Write-Verbose 'Website(s) created' } +} + +### It's all .NET +# A PS string is in fact a .NET System.String +# All .NET methods and properties are thus available +'string'.ToUpper().Replace('G', 'ggg') +# Or more powershellish +'string'.ToUpper() -replace 'G', 'ggg' +# Unsure how that .NET method is called again? +'string' | gm + +# Syntax for calling static .NET methods +[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') + +# Note that .NET functions MUST be called with parentheses +# while PS functions CANNOT be called with parentheses +$writer = New-Object System.IO.StreamWriter($path, $true) +$writer.Write([Environment]::NewLine) +$write.Dispose() + +### IO +# Reading a value from input: +$Name = Read-Host "What's your name?" +echo "Hello, $Name!" +[int]$Age = Read-Host "What's your age?" + +# Test-Path, Split-Path, Join-Path, Resolve-Path +# Get-Content filename # returns a string[] +# Set-Content, Add-Content, Clear-Content +Get-Command ConvertTo-*,ConvertFrom-* + + +### Useful stuff +# Refresh your PATH +$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") +# Find Python in path +$env:PATH.Split(";") | Where-Object { $_ -like "*python*"} + +# Change working directory without having to remember previous path +Push-Location c:\temp # change working directory to c:\temp +Pop-Location # change back to previous working directory + +# Unblock a directory after download +Get-ChildItem -Recurse | Unblock-File + +# Open Windows Explorer in working directory +ii . ``` @@ -187,4 +290,15 @@ if (-not (Test-Path $Profile)) { notepad $Profile } # More info: `help about_profiles` -``` \ No newline at end of file +``` + +Interesting Projects +* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell videos +* [PSake](https://github.com/psake/psake) Build automation tool +* [Pester](https://github.com/pester/Pester) BDD Testing Framework + +Not covered +* WMI: Windows Management Intrumentation (Get-CimInstance) +* Multitasking: Start-Job -scriptBlock {...}, +* Code Signing +* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command) \ No newline at end of file -- cgit v1.2.3 From 3cbcf0e98368d58b708fd945f96d7996386f57ed Mon Sep 17 00:00:00 2001 From: Laoujin Date: Fri, 27 Nov 2015 04:05:53 +0100 Subject: [PowerShell/en] More usefull snippets and interesting projects --- powershell.html.markdown | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index 6f38c45c..ce9cfa72 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -278,6 +278,17 @@ Get-ChildItem -Recurse | Unblock-File # Open Windows Explorer in working directory ii . + +# Any key to exit +$host.UI.RawUI.ReadKey() +return + +# Create a shortcut +$WshShell = New-Object -comObject WScript.Shell +$Shortcut = $WshShell.CreateShortcut($link) +$Shortcut.TargetPath = $file +$Shortcut.WorkingDirectory = Split-Path $file +$Shortcut.Save() ``` @@ -290,12 +301,18 @@ if (-not (Test-Path $Profile)) { notepad $Profile } # More info: `help about_profiles` +# For a more usefull shell, be sure to check the project PSReadLine below ``` Interesting Projects -* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell videos +* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials +* [PSGet](https://github.com/psget/psget) NuGet for PowerShell +* [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!) +* [Posh-Git](https://github.com/dahlbyk/posh-git/) Fancy Git Prompt (Recommended!) * [PSake](https://github.com/psake/psake) Build automation tool * [Pester](https://github.com/pester/Pester) BDD Testing Framework +* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` that reads your mind +* [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead) Not covered * WMI: Windows Management Intrumentation (Get-CimInstance) -- cgit v1.2.3 From 276390e4583ffe471fd90d527fd0ef1c96510119 Mon Sep 17 00:00:00 2001 From: Wouter Van Schandevijl Date: Fri, 27 Nov 2015 05:44:22 +0100 Subject: [Powershell/en] Deleted a left-over from the bash turorial --- powershell.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index ce9cfa72..9c521b27 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -164,7 +164,6 @@ ls -fi *.txt -n # -f is not possible because -Force also exists # Use `Get-Help Get-ChildItem -Full` for a complete overview # Results of the previous cmdlet can be passed to the next as input. -# grep cmdlet filters the input with provided patterns. # `$_` is the current object in the pipeline object. ls | Where-Object { $_.Name -match 'c' } | Export-CSV export.txt ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File export.html @@ -318,4 +317,4 @@ Not covered * WMI: Windows Management Intrumentation (Get-CimInstance) * Multitasking: Start-Job -scriptBlock {...}, * Code Signing -* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command) \ No newline at end of file +* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command) -- cgit v1.2.3 From 8738cef0ad36614b80df63d8d942c6c1416f3e8e Mon Sep 17 00:00:00 2001 From: Serg Date: Fri, 27 Nov 2015 12:36:10 +0200 Subject: Update javascript-ua.html.markdown Updated according to [Andre Polykanine ](https://github.com/Oire) comments. --- uk-ua/javascript-ua.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index dae27d32..2c534d83 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -5,8 +5,8 @@ contributors: - ["Ariel Krakowski", "http://www.learneroo.com"] filename: javascript-ua.js translators: - - ["Ivan Neznayu", "https://github.com/IvanEh"] - - ["Serhii Maksymchuk", "https://maximchuk.tk"] + - ["Ivan", "https://github.com/IvanEh"] + - ["Serhii Maksymchuk", "https://github.com/Serg-Maximchuk"] lang: uk-ua --- @@ -73,7 +73,7 @@ false; // Рядки створюються за допомогою подвійних та одинарних лапок 'абв'; -"Світ, привіт!"; +"Привіт, світе!"; // Для логічного заперечення використовується знак оклику. !true; // = false @@ -139,7 +139,7 @@ var someVar = 5; // якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ... someOtherVar = 10; -// ... але ваша змінна буде створена в глобальному контексті, а не там, де +// ... але вашу змінну буде створено в глобальному контексті, а не там, де // ви її оголосили // Змінні, які оголошені без присвоєння, автоматично приймають значення undefined @@ -160,7 +160,7 @@ var myArray = ["Привіт", 45, true]; // Індексація починається з нуля myArray[1]; // = 45 -// Масиви можна змінювати, як і їх довжину +// Масиви в JavaScript змінюють довжину при додаванні нових елементів myArray.push("Привіт"); myArray.length; // = 4 @@ -258,7 +258,7 @@ function myFunction(thing) { } myFunction("foo"); // = "FOO" -// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж +// Зверніть увагу, що значення яке буде повернено, повинно починатися на тому ж // рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined // через автоматичну вставку крапки з комою function myFunction() @@ -280,7 +280,7 @@ setTimeout(myFunction, 5000); // setTimeout не є частиною мови, але реалізований в браузерах і Node.js // Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати -// анонімну функцію прямо в якості аргумента іншої функції +// анонімну функцію як аргумент іншої функції setTimeout(function() { // Цей код буде виконано через п’ять секунд }, 5000); @@ -303,7 +303,7 @@ i; // = 5, а не undefined, як це звичайно буває в інши temporary; // повідомлення про помилку ReferenceError permanent; // = 10 -// Замикання - один з найпотужніших інтрументів JavaScript. Якщо функція визначена +// Замикання - один з найпотужніших інструментів JavaScript. Якщо функція визначена // всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої // функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції function sayHelloInFiveSeconds(name) { @@ -409,7 +409,7 @@ myObj.meaningOfLife; // = 42 // Аналогічно для функцій myObj.myFunc(); // = "Hello, world!" -// Якщо інтерпретатор не знайде властивість в прототипі, то він продовжить пошук +// Якщо інтерпретатор не знайде властивості в прототипі, то він продовжить пошук // в прототипі прототипа і так далі myPrototype.__proto__ = { myBoolean: true -- cgit v1.2.3 From aca3a4382e2eeb16e383eeb9fbd6689e4caba131 Mon Sep 17 00:00:00 2001 From: Serg Date: Fri, 27 Nov 2015 12:39:27 +0200 Subject: Update javascript-ua.html.markdown Small fixes --- uk-ua/javascript-ua.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index 2c534d83..9614f9ca 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -3,7 +3,7 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] -filename: javascript-ua.js +filename: javascript-uk.js translators: - ["Ivan", "https://github.com/IvanEh"] - ["Serhii Maksymchuk", "https://github.com/Serg-Maximchuk"] @@ -160,7 +160,7 @@ var myArray = ["Привіт", 45, true]; // Індексація починається з нуля myArray[1]; // = 45 -// Масиви в JavaScript змінюють довжину при додаванні нових елементів +// Масиви в JavaScript змінюють свою довжину при додаванні нових елементів myArray.push("Привіт"); myArray.length; // = 4 -- cgit v1.2.3 From 3c048d79adddea0e8ada7ff2af6445160ac000fc Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Fri, 27 Nov 2015 15:30:23 -0800 Subject: Make typescript indentation consistently 2 spaces --- typescript.html.markdown | 52 ++++++++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index e9135510..26f1fcd9 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -83,23 +83,23 @@ mySearch = function(src: string, sub: string) { // Classes - members are public by default class Point { // Properties - x: number; + 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 - 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; - } + constructor(x: number, public y: number = 0) { + this.x = x; + } - // Functions - dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + // Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } - // Static members - static origin = new Point(0, 0); + // Static members + static origin = new Point(0, 0); } var p1 = new Point(10 ,20); @@ -107,15 +107,15 @@ var 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 - } + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Explicit call to the super class constructor is mandatory + } - // Overwrite - dist() { - var d = super.dist(); - return Math.sqrt(d * d + this.z * this.z); - } + // Overwrite + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } } // Modules, "." can be used as separator for sub modules @@ -139,19 +139,19 @@ var s2 = new G.Square(10); // Generics // Classes class Tuple { - constructor(public item1: T1, public item2: T2) { - } + constructor(public item1: T1, public item2: T2) { + } } // Interfaces interface Pair { - item1: T; - item2: T; + item1: T; + item2: T; } // And functions var pairToTuple = function(p: Pair) { - return new Tuple(p.item1, p.item2); + return new Tuple(p.item1, p.item2); }; var tuple = pairToTuple({ item1:"hello", item2:"world"}); -- cgit v1.2.3 From 90a7e8ac4910e0ab754ce1801d6743fb6c70eaba Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 28 Nov 2015 19:44:24 +0100 Subject: [PowerShell/en] Markdown ```powershell didn't render properly --- powershell.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index ce9cfa72..70935993 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -18,7 +18,7 @@ rather than plain text. [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) If you are uncertain about your environment: -```powershell +``` Get-ExecutionPolicy -List Set-ExecutionPolicy AllSigned # Execution policies include: @@ -33,7 +33,7 @@ $PSVersionTable ``` Getting help: -```powershell +``` # Find commands Get-Command about_* # alias: gcm Get-Command -Verb Add @@ -49,7 +49,7 @@ Update-Help # Run as admin ``` The tutorial starts here: -```powershell +``` # As you already figured, comments start with # # Simple hello world example: @@ -293,7 +293,7 @@ $Shortcut.Save() Configuring your shell -```powershell +``` # $Profile is the full path for your `Microsoft.PowerShell_profile.ps1` # All code there will be executed when the PS session starts if (-not (Test-Path $Profile)) { -- cgit v1.2.3 From 2099ec480194f747d4292b9d253e4fa416b35188 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 30 Nov 2015 22:22:42 +0700 Subject: Moved ua-ua files to uk-ua --- uk-ua/bash-ua.html.markdown | 296 ++++++++++++++++++++++++++++++++++++++++++++ uk-ua/json-ua.html.markdown | 67 ++++++++++ 2 files changed, 363 insertions(+) create mode 100644 uk-ua/bash-ua.html.markdown create mode 100644 uk-ua/json-ua.html.markdown diff --git a/uk-ua/bash-ua.html.markdown b/uk-ua/bash-ua.html.markdown new file mode 100644 index 00000000..b7e4a5ba --- /dev/null +++ b/uk-ua/bash-ua.html.markdown @@ -0,0 +1,296 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Ehreshi Ivan", "https://github.com/IvanEh"] +lang: uk-ua +--- + +Bash - командна оболонка unix (unix shell), що також розповсюджувалась як оболонка для +операційної системи GNU і зараз використовується як командна оболонка за замовчуванням +для Linux i Max OS X. +Почти все нижеприведенные примеры могут быть частью shell-скриптов или исполнены напрямую в shell. +Майже всі приклади, що наведені нижче можуть бути частиною shell-скриптів або +виконані в оболонці + +[Більш детально тут.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Перший рядок скрипта - це shebang, який вказує системі, як потрібно виконувати +# скрипт. Як ви вже зрозуміли, коментарі починаються з #. Shebang - тоже коментар + +# Простий приклад hello world: +echo Hello world! + +# Окремі команди починаються з нового рядка або розділяються крапкою з комкою: +echo 'Перший рядок'; echo 'Другий рядок' + +# Оголошення змінної +VARIABLE="Просто рядок" + +# Але не так! +VARIABLE = "Просто рядок" +# Bash вирішить, що VARIABLE - це команда, яку він може виконати, +# і видасть помилку, тому що не зможе знайти її + +# І так також не можна писати: +VARIABLE= 'Просто рядок' +# Bash сприйме рядок 'Просто рядок' як команду. Але такої команди не має, тому +# видасть помилку. +# (тут 'VARIABLE=' інтерпретується як присвоєння тільки в контексті +# виконання команди 'Просто рядок') + +# Використання змінних: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# Коли ви використовуєте змінну - присвоюєте значення, експортуєте і т.д. - +# пишіть її імя без $. А для отримання значення змінної використовуйте $. +# Одинарні лапки ' не розкривають значення змінних + +# Підстановка рядків в змінні +echo ${VARIABLE/Просто/A} +# Цей вираз замінить перше входження підрядка "Просто" на "А" + +# Отримання підрядка із рядка +LENGTH=7 +echo ${VARIABLE:0:LENGTH} +# Цей вираз поверне тільки перші 7 символів змінної VARIABLE + +# Значення за замовчуванням +echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} +# Це спрацює при відсутності значення (FOO=) і при пустому рядку (FOO="") +# Нуль (FOO=0) поверне 0. +# Зауважте, що у всіх випадках значення самої змінної FOO не зміниться + +# Вбудовані змінні: +# В bash є корисні вбудовані змінні, наприклад +echo "Значення, яке було повернуте в останній раз: $?" +echo "PID скрипта: $$" +echo "Кількість аргументів: $#" +echo "Аргументи скрипта: $@" +echo "Аргументи скрипта, розподілені по різним змінним: $1 $2..." + +# Зчитування змінних з пристроїв введення +echo "Як вас звати?" +read NAME # Зверніть увагу, що вам не потрібно оголошувати нову змінну +echo Привіт, $NAME! + +# В bash є звичайна умовна конструкція if: +# наберіть 'man test', щоб переглянути детальну інформацію про формати умов +if [ $NAME -ne $USER ] +then + echo "Ім’я користувача не збігається з введеним" +else + echo "Ім’я збігаєтьяс з іменем користувача" +fi + +# Зауважте! якщо $Name пуста, bash інтерпретує код вище як: +if [ -ne $USER ] +# що є неправильним синтаксисом +# тому безпечний спосіб використання потенційно пустих змінних має вигляд: +if [ "$Name" -ne $USER ] ... +# коли $Name пуста, інтерпретується наступним чином: +if [ "" -ne $USER ] ... +# що працює як і очікувалося + +# Умовне виконання (conditional execution) +echo "Виконується завжди" || echo "Виконається, якщо перша команда завершиться з помилкою" +echo "Виконується завжди" && echo "Виконається, якщо перша команда завершиться успішно" + +# Щоб використати && і || у конструкції if, потрібно декілька пар дужок: +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "Виконається, якщо $NAME="Steve" i AGE=15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "Виконається, якщо NAME="Steve" або NAME="Zach"." +fi + +# Вирази позначаються наступним форматом: +echo $(( 10 + 5 )) + +# На відмінно від інших мов програмування, Bash - це командна оболонка, а +# отже, працює в контексті поточної директорії +ls + +# Ця команда може використовуватися з опціями +ls -l # Показати кожен файл і директорію на окремому рядку + +# Результат попередньої команди можна перенаправити на вхід наступної. +# Команда grep фільтрує вхід по шаблону. +# Таким чином ми можемо переглянути тільки *.txt файли в поточній директорії: +ls -l | grep "\.txt" + +# Ви можете перенаправ вхід і вихід команди (stdin, stdout, stderr). +# Наступна команда означає: читати із stdin, поки не зустрінеться ^EOF$, і +# перезаписати 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 + +# Запуск hello.py з різними варіантами перенаправлення stdin, +# stdout, stderr (стандартні потоки введення, виведення і помилок): +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Поток помилок перезапише фпйл, якщо цей файл існує +# тому, якщо ви хочете дописувати до файлу, використовуйте ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Перезаписати output.txt, дописати error.err і порахувати кількість рядків: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Запустити команду і вивести її файловий дескриптор (див.: man fd; наприклад /dev/fd/123) +echo <(echo "#helloworld") + +# Перезаписати output.txt рядком "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Подчистить временные файлы с подробным выводом ('-i' - интерактивый режим) +# Очистити тимчасові файли з детальним виводом (додайте '-i' +# для інтерактивного режиму) +rm -v output.out error.err output-and-error.log + +# Команди можуть бути підставлені в інші команди використовуючи $(): +# наступна команда виводить кількість файлів і директорій в поточній директорії +echo "Тут $(ls | wc -l) елементів." + +# Те саме можна зробити використовуючи зворотні лапки +# Але вони не можуть бути вкладеними, тому перший варіант бажаніший +echo "Тут `ls | wc -l` елементів." + +# В Bash є структура case, яка схожа на switch в Java и C++: +case "$VARIABLE" in + # перерахуйте шаблони, які будуть використовуватися в якості умов + 0) echo "Тут нуль.";; + 1) echo "Тут один.";; + *) echo "Не пусте значення.";; +esac + +# Цикл for перебирає елементи передані в аргумент: +# Значення $VARIABLE буде напечатано тричі. +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# Aбо можна використати звичний синтаксис for: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Цикл for можно використати, щоб виконувати дії над файлами. +# Цей код запустить команду 'cat' для файлів file1 и file2 +for VARIABLE in file1 file2 +do + cat "$VARIABLE" +done + +# ... або дії над виводом команд +# Запустимо cat для виведення із ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + +# Цикл while: +while [ true ] +do + echo "Тіло циклу..." + break +done + +# Ви також можете оголосити функцію +# Оголошення: +function foo () +{ + echo "Аргументи функції доступні так само, як і аргументи скрипта: $@" + echo "$1 $2..." + echo "Це функція" + return 0 +} + +# Або просто +bar () +{ + echo "Інший спосіб оголошення функцій!" + return 0 +} + +# Виклик функцій +foo "Мое имя" $NAME + +# Є багато корисних команд: +# вивести останні 10 рядків файла file.txt +tail -n 10 file.txt +# вивести перші 10 рядків файла file.txt +head -n 10 file.txt +# відсортувати рядки file.txt +sort file.txt +# відібрати або пропустити рядки, що дублюються (з опцією -d відбирає) +uniq -d file.txt +# вивести тільки першу колонку перед символом ',' +cut -d ',' -f 1 file.txt +# замінити кожне 'okay' на 'great' у файлі file.txt (підтримується regex) +sed -i 's/okay/great/g' file.txt +# вивести в stdout все рядки з file.txt, що задовольняють шаблону regex; +# цей приклад виводить рядки, що починаються на foo і закінчуються на bar: +grep "^foo.*bar$" file.txt +# використайте опцію -c, щоб вивести кількість входжень +grep -c "^foo.*bar$" file.txt +# чтобы искать по строке, а не шаблону regex, используйте fgrep (или grep -F) +# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrea (або grep -F) +fgrep "^foo.*bar$" file.txt + +# Читайте вбудовану документацію Bash командою 'help': +help +help help +help for +help return +help source +help . + +# Читайте Bash man-документацію +apropos bash +man 1 bash +man bash + +# Читайте документацію info (? для допомоги) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Читайте bash info документацію: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown new file mode 100644 index 00000000..8ee12a93 --- /dev/null +++ b/uk-ua/json-ua.html.markdown @@ -0,0 +1,67 @@ +--- +language: json +filename: learnjson-ru.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Ehreshi Ivan", "https://github.com/IvanEh"] +lang: uk-ua +--- + +JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом +"Learn X in Y Minutes". + +В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють +використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього +поля, але все-таки краще такого уникати для кращої сумісності + +```json +{ + "ключ": "значеннь", + + "ключі": "завжди мають бути обгорнуті в подвійні лапки", + "числа": 0, + "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".", + "логічний тип": true, + "нічого": null, + + "велике число": 1.2e+100, + + "об’єкти": { + "коментар": "Більшість ваших структур будуть складатися з об’єктів", + + "масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5], + + "інший об’єкт": { + "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно." + } + }, + + "безглуздя": [ + { + "джерело калія": ["банани"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "нео"], + [0, 0, 0, 1] + ] + ], + + "альтернативнтй стиль": { + "коментар": "Гляньте!" + , "позиція коми": "неважлива, поки вона знаходиться до наступного поля" + , "інший коментар": "класно" + }, + + "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON." +} + +Одиничний масив значень теж є правильним JSON + +[1, 2, 3, "text", true] + + +``` -- cgit v1.2.3 From 700f3e7a1cb6ef5b905eac7ec3fe3aa2e713c079 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 15:45:03 -0500 Subject: Many minor updates --- solidity.html.markdown | 226 +++++++++++++++++++++++++++++++------------------ 1 file changed, 145 insertions(+), 81 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 88ccd817..0fa1fddc 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -14,7 +14,7 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language -// START EXAMPLE +// ** START EXAMPLE ** // Start with a Natspec comment (the three slashes) that can be used // for documentation - and as descriptive data for UI elements /// @title A simple deposit/withdrawal bank built on Bitcoin @@ -22,31 +22,30 @@ As Solidity and Ethereum are under active development, experimental or beta feat // All contracts are declared and named (in CamelCase) // They are similar to 'class' in other languages (and allow capabilities like inheritance) contract AcmeBank { - // Declare state variables outside a function, + // Declare state variables outside a function, // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address => uint) balances; + mapping (address => uint) balances; + + // the 'public' makes 'owner' externally readable by users or contracts + // (but not writeable) - + address public owner; - // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable), the 'constant' means this value to be - // changed after initialization - address public owner; - // Constructor, can receive one or many variables here function AcmeBank() { - // msg is a default variable that provides both the + // msg is a default variable that provides both the // contract messager's address and amount owner = msg.sender; // msg.sender refers to the address of the contract creator } - - function deposit(uint balance) { + + function deposit(uint balance) public { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable return balances[msg.sender]; // msg.sender refers to the contract caller } - function withdraw(uint withdrawAmount) returns (uint remainingBalance) { + function withdraw(uint withdrawAmount) public returns (uint remainingBalance) { if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; @@ -58,8 +57,9 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this contract - but does mean that users have to trust the owner - function remove () { + // It's good practice to have a remove function, which disables this + // contract - but does mean that users have to trust the owner + function remove() { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner } @@ -71,29 +71,35 @@ contract AcmeBank { } // Fallback function - // This function is called if invalid data is sent or ether without data; + // The fallback function is called if none of the other functions matches the given function identifier. + // It is often meant to be called when invalid data is sent or ether without data. // Added so that ether sent to this contract is reverted if the contract fails // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } } -// END EXAMPLE +// ** END EXAMPLE ** // Now let's go through the basics of Solidity -// 1. DATA TYPES +// 1. DATA TYPES AND ASSOCIATED METHOD // uint is the data type typically used for currency (there are no doubles // or floats) and for dates -uint x; -int constant a = 8; // int of 256 bits, cannot be changed after instantiation +uint x; + + +// with 'constant', the compiler replaces each occurence with the acutal value +// int of 256 bits, cannot be changed after instantiation +int constant a = 8; +int256 constant a = 8; // same effect as line above, here the 256 is explict + +// For both int and uint, you can explicitly set space in steps of 8 +// e.g., int8, int16 uint8 b; int64 c; -// int256 is same as int -// For both int and uint, you can explicitly set space in steps of 8, -// e.g., int8, int16 uint248 e; // Type casting -int x = int(b) +int x = int(b); bool b = true; // or do 'var b = true;' for inferred typing @@ -115,21 +121,22 @@ bytes m; // A special array, same as byte[] (but packed tightly) string n = 'hello'; // Type inference -// var does inferred typing based on first assignment, +// var does inferred typing based on first assignment, // can't be used in functions parameters var a = true; -// there are edge cases where inference leads to a value being set (e.g., an uint 8) +// there are edge cases where inference leads to a value being set (e.g., an uint 8) // that is different from what the user wanted (uint16), so use carefully // by default, all values are set to 0 on instantiation -// Delete can be called on most types, and will set the values to 0 +// Delete can be called on most types, and will set the values to 0 by assignment uint x = 5; delete(x); // x is now 0 // 2. DATA STRUCTURES // Arrays -bytes32[] names; +bytes32[5] nicknames; // static array +bytes32[] names; // dynamic array uint newLength = names.push("John"); // adding returns new length of the array // Length names.length; // get length @@ -153,13 +160,13 @@ delete(balances); // deletes all elements // Unlike languages like Javascript, you cannot iterate through all elements in // a map, without knowing the source keys -// Structs and enums +// Structs and enums struct Bank { // note the capital address owner; uint balance; } Bank b = Bank({ - owner: msg.sender, + owner: msg.sender, balance: 5 }); delete(b); // set all values to 0, except any mappings @@ -168,29 +175,39 @@ delete(b); // set all values to 0, except any mappings enum State { Created, Locked, Inactive }; State public state; // Declare variable from enum state = State.Created; +// enums can be explicitly converted to ints -// 3. Variables of note -// storage - A persistent storage hash (does not need to be declared) -storage['abc'] = 'def'; // maps 256 bit words to 256 bit words +// Data locations: Memory vs. storage - all complex types (arrays, structs) have a data location +// 'memory' does not persist, 'storage' does +// Default is 'storage' for local and state variables; 'memory' for function parameters -// tx - This transaction -tx.origin // address, sender of the transaction -tx.gasprice // uint, gas price of the transaction +// 3. Variables of note +// ** this ** +this; // the address of the current contract +// 'balance' often used at the end of a contracts life to send the +// remaining balance to a party +this.balance; +this.someFunction(); // calls a function externally (via a message call, not via an internal jump) -// msg - The current message received by the contract +// ** msg - The current message received by the contract ** ** msg.sender; // address, The address of the sender msg.value; // uint, The amount of gas provided to this contract in wei -msg.data // bytes, complete call data +msg.data; // bytes, complete call data +msg.gas; // remaining gas -// balance of the current contract (both contract and external accounts -// have balances) - often used at the end of a contracts life to send the -// remaining balance to a party -this.balance -// block +// ** tx - This transaction ** +tx.origin; // address, sender of the transaction +tx.gasprice; // uint, gas price of the transaction + +// ** block - Information about the current block ** now // uint, current time, alias for block.timestamp -block.number // uint, current block number -block.difficulty // uint, current block difficulty -block.blockhash(1) // returns bytes32, only provides for most recent 256 block +block.number; // uint, current block number +block.difficulty; // uint, current block difficulty +block.blockhash(1); // returns bytes32, only provides for most recent 256 blocks +block.gasLimit(); + +// ** storage - A persistent storage hash (does not need to be declared) ** +storage['abc'] = 'def'; // maps 256 bit words to 256 bit words // 4. FUNCTIONS AND MORE // A. Functions @@ -236,13 +253,13 @@ function b() { // B. Events // Events are an easy way to notify external listeners that something changed -// You typically decalre them after your contract parameters +// You typically declare them after your contract parameters event Sent(address from, address to, uint amount); // You then call it in a function, when you want to trigger it sent(from, to, amount); -// For an external party (a contract or external entity), to watch +// For an external party (a contract or external entity), to watch // for an event, you write the following: Coin.Sent().watch({}, '', function(error, result) { if (!error) { @@ -254,53 +271,89 @@ Coin.Sent().watch({}, '', function(error, result) { "Receiver: " + Coin.balances.call(result.args.to)); } } -// This is a common paradigm for one contract to depend on another (e.g., a +// This is a common paradigm for one contract to depend on another (e.g., a // contract that depends on the current exchange rate provided by another // contract) // C. Modifiers -// Modifiers let you validate inputs to functions -// The '_' (underscore) must be included, and is an indicator that the +// Modifiers let you validate inputs to functions such as a minimal balance or user authentication +// It's similar to a guard clause in other languages + +// The '_' (underscore) must be included as the last line in the function body, and is an indicator that the // function being called should be placed there modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } // You can then append it right after the function declaration -function test() - onlyBefore() -{ - +function changeOwner(newOwner) + onlyBefore(someTime) + { + owner = newOwner; } // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return // switch is not provided -// Syntax is the same as javascript, but there is no type conversion from -// non-boolean to boolean -// 6. CALLING AN EXTERNAL CONTRACT +// Syntax is the same as javascript, but there is no type conversion from +// non-boolean to boolean, so comparison operators must be used to get the boolean value + +// 6. OBJECTS/CONTRACTS +// A. Calling an external contract contract infoFeed { function info() returns (uint ret) { return 42; } } contract Consumer { InfoFeed feed; // create a variable that will point to a contract on the blockchain - function setFeed(address addr) { + + // Set feed to an existing contract + function setFeed(address addr) { // Link to the contract by creating on the address - feed = InfoFeed(addr); + feed = InfoFeed(addr); } - function callFeed() { - // T final parentheses call the contract, optionally adding + + // Set feed based to a new instance of the contract + function createNewFeed() { + feed = new InfoFeed(); + } + + function callFeed() { + // T final parentheses call the contract, optionally adding // custom value or gas numbers feed.info.value(10).gas(800)(); } } +// B. Inheritance + +// Order matters, last inherited contract (i.e., 'def') can override parts of the previously +// inherited contracts +contact MyContract is abc, def("a custom argument to def") { + +// Override function + + function z() { + if (msg.sender == owner) { + def.z(); // call overridden function + } + } + + }; + +// C. Import + +import "filename"; +import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; + +// Importing is under active development and will change +// Importing cannot currently be done at the command line + // 7. CONTRACT DESIGN PATTERNS // A. Obfuscation -// Remember that all variables are publicly viewable on the blockchain, so +// Remember that all variables are publicly viewable on the blockchain, so // anything that needs some privacy needs to be obfuscated (e.g., hashed) // B. Throwing @@ -317,26 +370,34 @@ if (!addr.send(123)) { // Suicide suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) +// This is a common pattern that lets the owner end the contract +function remove() { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } +} + // D. Storage optimization -// Reading and writing can be expensive, as data needs to be stored in the -// blockchain forever - this encourages smart ways to use memory (eventually, -// compilation may better handle this, but for now there are benefits to +// Reading and writing can be expensive, as data needs to be stored in the +// blockchain forever - this encourages smart ways to use memory (eventually, +// compilation may better handle this, but for now there are benefits to // planning your data structures) // *** EXAMPLE: Let's do a more complex example *** + +// ** START EXAMPLE ** // [TODO: Decide what a more complex example looks like, needs a few characteristics: // - has a 'constant' state variable -// - has a state machine (uses modifier) +// - has a state machine (and uses modifier) // - sends money to an address // - gets information from another contract (we'll show code for both contracts) // - Shows inheritance // - show variables being passed in on instantiation (and guard code to throw if variables not provided) -// - Shows the swapping out of a contract +// - Shows the swapping out of a contract address // Ideas: // - crowdfunding? // - Peer to peer insurance // ] - // *** END EXAMPLE *** // Some final points @@ -353,7 +414,7 @@ uint a = 1 finney; // 1 ether = 1000 finney 1 minutes == 60 seconds -// You typically multiply a variable times the unit, as these units are not +// You typically multiply a variable times the unit, as these units are not // directly stored in a variable uint x = 5; (x * 1 days); // 5 days @@ -366,22 +427,22 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); -// These are natspec comments, when a user is asked to confirm a transaction -/// -/** */ +// 8. COMMON MISTAKES/MISCONCEPTIONS +// A few common mistakes and misconceptions: -// 8. COMMON MISTAKES -// A few common mistakes -// You cannot restrict a human or computer from reading the content of +// A. You cannot restrict a human or computer from reading the content of // your transaction or a transaction's state -// All data to the start of time is stored in the blockchain, so you and -// anyone can observe all previous data states +// All data to the start of time is stored in the blockchain, so you and +// anyone can observe all previous data stats -// 9. TESTING +// When you don't specify public on a variable, you are indicating that other *contracts* can't +// read the data - but any person can still read the data -// 10. STYLE NOTES -// Use 4 spaces for indentation +// TODO + +// 9. STYLE NOTES +// Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) ``` @@ -391,4 +452,7 @@ sha256("def"); - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) -Feel free to send a pull request with any edits - or email nemild -/at-/ gmail \ No newline at end of file +## Information purposefully excluded +- Libraries + +Feel free to send a pull request with any edits - or email nemild -/at-/ gmail -- cgit v1.2.3 From 3d19a951926f52b7cafca301919233f4cda513ff Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Mon, 30 Nov 2015 12:48:13 -0800 Subject: [TypeScript/fr] Make TypeScript indentation consistently 2 spaces fr version of #2041 --- fr-fr/typescript-fr.html.markdown | 58 +++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown index b8807104..52d34650 100644 --- a/fr-fr/typescript-fr.html.markdown +++ b/fr-fr/typescript-fr.html.markdown @@ -87,22 +87,22 @@ mySearch = function(src: string, sub: string) { // Les membres des classes sont publiques par défaut. class Point { - // Propriétés - x: number; - - // Constructeur - Les mots clés "public" et "private" dans ce contexte - // génèrent le code de la propriété et son initialisation dans le - // constructeur. Ici, "y" sera défini de la même façon que "x", - // mais avec moins de code. Les valeurs par défaut sont supportées. - constructor(x: number, public y: number = 0) { - this.x = x; - } + // Propriétés + x: number; + + // Constructeur - Les mots clés "public" et "private" dans ce contexte + // génèrent le code de la propriété et son initialisation dans le + // constructeur. Ici, "y" sera défini de la même façon que "x", + // mais avec moins de code. Les valeurs par défaut sont supportées. + constructor(x: number, public y: number = 0) { + this.x = x; + } - // Fonctions - dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + // Fonctions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } - // Membres statiques - static origin = new Point(0, 0); + // Membres statiques + static origin = new Point(0, 0); } var p1 = new Point(10 ,20); @@ -110,17 +110,17 @@ var p2 = new Point(25); // y sera 0 // Héritage class Point3D extends Point { - constructor(x: number, y: number, public z: number = 0) { - // Un appel explicite au constructeur de la super classe - // est obligatoire. - super(x, y); - } + constructor(x: number, y: number, public z: number = 0) { + // Un appel explicite au constructeur de la super classe + // est obligatoire. + super(x, y); + } - // Redéfinition - dist() { - var d = super.dist(); - return Math.sqrt(d * d + this.z * this.z); - } + // Redéfinition + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } } // Modules, "." peut être utilisé comme un séparateur de sous modules. @@ -144,19 +144,19 @@ var s2 = new G.Square(10); // Génériques // Classes class Tuple { - constructor(public item1: T1, public item2: T2) { - } + constructor(public item1: T1, public item2: T2) { + } } // Interfaces interface Pair { - item1: T; - item2: T; + item1: T; + item2: T; } // Et fonctions var pairToTuple = function(p: Pair) { - return new Tuple(p.item1, p.item2); + return new Tuple(p.item1, p.item2); }; var tuple = pairToTuple({ item1:"hello", item2:"world"}); -- cgit v1.2.3 From ec6172fc5e904c65e672ca22bbc6102a94a60ec9 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 15:48:47 -0500 Subject: Formatting --- solidity.html.markdown | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 0fa1fddc..2adfc00b 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -81,12 +81,12 @@ contract AcmeBank { // Now let's go through the basics of Solidity -// 1. DATA TYPES AND ASSOCIATED METHOD + +// 1. DATA TYPES AND ASSOCIATED METHODS // uint is the data type typically used for currency (there are no doubles // or floats) and for dates uint x; - // with 'constant', the compiler replaces each occurence with the acutal value // int of 256 bits, cannot be changed after instantiation int constant a = 8; @@ -133,6 +133,7 @@ var a = true; uint x = 5; delete(x); // x is now 0 + // 2. DATA STRUCTURES // Arrays bytes32[5] nicknames; // static array @@ -181,6 +182,7 @@ state = State.Created; // 'memory' does not persist, 'storage' does // Default is 'storage' for local and state variables; 'memory' for function parameters + // 3. Variables of note // ** this ** this; // the address of the current contract @@ -209,6 +211,7 @@ block.gasLimit(); // ** storage - A persistent storage hash (does not need to be declared) ** storage['abc'] = 'def'; // maps 256 bit words to 256 bit words + // 4. FUNCTIONS AND MORE // A. Functions // Simple function @@ -290,6 +293,7 @@ function changeOwner(newOwner) owner = newOwner; } + // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return @@ -298,6 +302,7 @@ function changeOwner(newOwner) // Syntax is the same as javascript, but there is no type conversion from // non-boolean to boolean, so comparison operators must be used to get the boolean value + // 6. OBJECTS/CONTRACTS // A. Calling an external contract @@ -350,6 +355,7 @@ import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; // Importing is under active development and will change // Importing cannot currently be done at the command line + // 7. CONTRACT DESIGN PATTERNS // A. Obfuscation @@ -383,6 +389,8 @@ function remove() { // compilation may better handle this, but for now there are benefits to // planning your data structures) + + // *** EXAMPLE: Let's do a more complex example *** // ** START EXAMPLE ** @@ -400,7 +408,7 @@ function remove() { // ] // *** END EXAMPLE *** -// Some final points + // 7. NATIVE FUNCTIONS // Currency units @@ -427,6 +435,7 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); + // 8. COMMON MISTAKES/MISCONCEPTIONS // A few common mistakes and misconceptions: @@ -441,6 +450,7 @@ sha256("def"); // TODO + // 9. STYLE NOTES // Use 4 spaces for indentation // (Python's PEP8 is used as the baseline style guide, including its general philosophy) -- cgit v1.2.3 From 4b7d7e3d2e86e6e2d5b95b518864ecd89392d7c0 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:01:51 -0500 Subject: Spelling and grammar --- solidity.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2adfc00b..3e47f080 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -72,7 +72,7 @@ contract AcmeBank { // Fallback function // The fallback function is called if none of the other functions matches the given function identifier. - // It is often meant to be called when invalid data is sent or ether without data. + // Typically, called when invalid data is sent to the contract or ether without data. // Added so that ether sent to this contract is reverted if the contract fails // otherwise, the sender loses their money; you should add this in most contracts function () { throw; } @@ -87,10 +87,10 @@ contract AcmeBank { // or floats) and for dates uint x; -// with 'constant', the compiler replaces each occurence with the acutal value +// with 'constant', the compiler replaces each occurrence with the actual value // int of 256 bits, cannot be changed after instantiation int constant a = 8; -int256 constant a = 8; // same effect as line above, here the 256 is explict +int256 constant a = 8; // same effect as line above, here the 256 is explicit // For both int and uint, you can explicitly set space in steps of 8 // e.g., int8, int16 @@ -221,7 +221,7 @@ function increment(uint x) returns (uint) { } // Functions can return many arguments, and by specifying the returned arguments -// you don't need to explicity return +// you don't need to explicitly return function increment(uint x, uint y) returns (uint x, uint y) { x += 1; y += 1; @@ -241,7 +241,7 @@ function increment(uint x) constant returns (uint x) { // There are a few 'function visibility specifiers' that can be placed where 'constant' // is, which include: // internal (can only be called by an internal function, not one external to the contract) -// public - visibile externally and internally +// public - visible externally and internally // private - only visible in the current contract // Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable -- cgit v1.2.3 From 8ef890b0de22d9fd14572f4ac171a238ea4f3f20 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:14:26 -0500 Subject: Added sample contracts --- solidity.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/solidity.html.markdown b/solidity.html.markdown index 3e47f080..2b461a95 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -462,6 +462,10 @@ sha256("def"); - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +## Sample contracts +- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) +- [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) + ## Information purposefully excluded - Libraries -- cgit v1.2.3 From add8f68f1acdceca1b9e09d6458627c515e73047 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 16:51:53 -0500 Subject: Add exposition around example bank --- solidity.html.markdown | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2b461a95..77648e51 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -13,6 +13,10 @@ As Solidity and Ethereum are under active development, experimental or beta feat ```javascript // Let's start with a simple Bank contract, before diving into to the key components of the language +// This bank has three main capabilities: +// - deposit +// - withdrawal +// - check balance // ** START EXAMPLE ** // Start with a Natspec comment (the three slashes) that can be used @@ -57,14 +61,6 @@ contract AcmeBank { } } - // It's good practice to have a remove function, which disables this - // contract - but does mean that users have to trust the owner - function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } - } - // The 'constant' prevents the function from editing state variables function balance() constant { return balances[msg.sender]; @@ -406,6 +402,14 @@ function remove() { // - crowdfunding? // - Peer to peer insurance // ] + // It's good practice to have a remove function, which disables this + // contract - but does mean that users have to trust the owner + // For a decentralized bank without a trusted part + function remove() { + if(msg.sender == owner) { // Only let the contract creator do this + suicide(owner); // suicide makes this contract inactive, and returns funds to the owner + } + } // *** END EXAMPLE *** -- cgit v1.2.3 From 541c278de4b253090b27a1ef126f5ed27e050f7c Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 30 Nov 2015 17:23:41 -0500 Subject: Minor updates --- solidity.html.markdown | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 77648e51..298b01f3 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -30,10 +30,13 @@ contract AcmeBank { // these are persistent throughout the life of the contract // a dictionary that maps addresses to balances - mapping (address => uint) balances; + // the private means that other contracts can't see balances + // but the data is still available to all other parties on the + // blockchain + mapping (address => uint) private balances; // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable) - + // (but not writeable) address public owner; // Constructor, can receive one or many variables here @@ -125,9 +128,10 @@ var a = true; // by default, all values are set to 0 on instantiation -// Delete can be called on most types, and will set the values to 0 by assignment +// Delete can be called on most types +// (it does NOT destroy the value, but rather sets the value to 0 by assignment) uint x = 5; -delete(x); // x is now 0 +delete x; // x is now 0 // 2. DATA STRUCTURES @@ -151,8 +155,8 @@ function balances(address _account) returns (uint balance) { } // To delete -delete(balances["John"]); -delete(balances); // deletes all elements +delete balances["John"]; +delete balances; // deletes all elements // Unlike languages like Javascript, you cannot iterate through all elements in // a map, without knowing the source keys @@ -166,7 +170,7 @@ Bank b = Bank({ owner: msg.sender, balance: 5 }); -delete(b); // set all values to 0, except any mappings +delete b; // set all variables in struct to 0, except any mappings // Enums enum State { Created, Locked, Inactive }; @@ -226,6 +230,7 @@ function increment(uint x, uint y) returns (uint x, uint y) { uint (a,b) = increment(1,1); // The 'constant' indicates and ensures that a function does not/cannot change the persistent variables +// Constant function execute locally, not on the blockchain uint y; function increment(uint x) constant returns (uint x) { @@ -469,6 +474,7 @@ sha256("def"); ## Sample contracts - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) - [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) +- [State of Dapps](http://dapps.ethercasts.com/) ## Information purposefully excluded - Libraries -- cgit v1.2.3 From ccb05ba98a5b411029e8d7c1e7ea2cd7d87bced4 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 1 Dec 2015 20:37:23 +0700 Subject: Removed old ua-ua --- ua-ua/bash-ua.html.markdown | 296 -------------------------------------------- ua-ua/json-ua.html.markdown | 67 ---------- 2 files changed, 363 deletions(-) delete mode 100644 ua-ua/bash-ua.html.markdown delete mode 100644 ua-ua/json-ua.html.markdown diff --git a/ua-ua/bash-ua.html.markdown b/ua-ua/bash-ua.html.markdown deleted file mode 100644 index 2c930ad1..00000000 --- a/ua-ua/bash-ua.html.markdown +++ /dev/null @@ -1,296 +0,0 @@ ---- -category: tool -tool: bash -contributors: - - ["Max Yankov", "https://github.com/golergka"] - - ["Darren Lin", "https://github.com/CogBear"] - - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] - - ["Denis Arh", "https://github.com/darh"] - - ["akirahirose", "https://twitter.com/akirahirose"] - - ["Anton Strömkvist", "http://lutic.org/"] - - ["Rahil Momin", "https://github.com/iamrahil"] - - ["Gregrory Kielian", "https://github.com/gskielian"] - - ["Etan Reisner", "https://github.com/deryni"] -translators: - - ["Ehreshi Ivan", "https://github.com/IvanEh"] -lang: ua-ua ---- - -Bash - командна оболонка unix (unix shell), що також розповсюджувалась як оболонка для -операційної системи GNU і зараз використовується як командна оболонка за замовчуванням -для Linux i Max OS X. -Почти все нижеприведенные примеры могут быть частью shell-скриптов или исполнены напрямую в shell. -Майже всі приклади, що наведені нижче можуть бути частиною shell-скриптів або -виконані в оболонці - -[Більш детально тут.](http://www.gnu.org/software/bash/manual/bashref.html) - -```bash -#!/bin/bash -# Перший рядок скрипта - це shebang, який вказує системі, як потрібно виконувати -# скрипт. Як ви вже зрозуміли, коментарі починаються з #. Shebang - тоже коментар - -# Простий приклад hello world: -echo Hello world! - -# Окремі команди починаються з нового рядка або розділяються крапкою з комкою: -echo 'Перший рядок'; echo 'Другий рядок' - -# Оголошення змінної -VARIABLE="Просто рядок" - -# Але не так! -VARIABLE = "Просто рядок" -# Bash вирішить, що VARIABLE - це команда, яку він може виконати, -# і видасть помилку, тому що не зможе знайти її - -# І так також не можна писати: -VARIABLE= 'Просто рядок' -# Bash сприйме рядок 'Просто рядок' як команду. Але такої команди не має, тому -# видасть помилку. -# (тут 'VARIABLE=' інтерпретується як присвоєння тільки в контексті -# виконання команди 'Просто рядок') - -# Використання змінних: -echo $VARIABLE -echo "$VARIABLE" -echo '$VARIABLE' -# Коли ви використовуєте змінну - присвоюєте значення, експортуєте і т.д. - -# пишіть її імя без $. А для отримання значення змінної використовуйте $. -# Одинарні лапки ' не розкривають значення змінних - -# Підстановка рядків в змінні -echo ${VARIABLE/Просто/A} -# Цей вираз замінить перше входження підрядка "Просто" на "А" - -# Отримання підрядка із рядка -LENGTH=7 -echo ${VARIABLE:0:LENGTH} -# Цей вираз поверне тільки перші 7 символів змінної VARIABLE - -# Значення за замовчуванням -echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} -# Це спрацює при відсутності значення (FOO=) і при пустому рядку (FOO="") -# Нуль (FOO=0) поверне 0. -# Зауважте, що у всіх випадках значення самої змінної FOO не зміниться - -# Вбудовані змінні: -# В bash є корисні вбудовані змінні, наприклад -echo "Значення, яке було повернуте в останній раз: $?" -echo "PID скрипта: $$" -echo "Кількість аргументів: $#" -echo "Аргументи скрипта: $@" -echo "Аргументи скрипта, розподілені по різним змінним: $1 $2..." - -# Зчитування змінних з пристроїв введення -echo "Як вас звати?" -read NAME # Зверніть увагу, що вам не потрібно оголошувати нову змінну -echo Привіт, $NAME! - -# В bash є звичайна умовна конструкція if: -# наберіть 'man test', щоб переглянути детальну інформацію про формати умов -if [ $NAME -ne $USER ] -then - echo "Ім’я користувача не збігається з введеним" -else - echo "Ім’я збігаєтьяс з іменем користувача" -fi - -# Зауважте! якщо $Name пуста, bash інтерпретує код вище як: -if [ -ne $USER ] -# що є неправильним синтаксисом -# тому безпечний спосіб використання потенційно пустих змінних має вигляд: -if [ "$Name" -ne $USER ] ... -# коли $Name пуста, інтерпретується наступним чином: -if [ "" -ne $USER ] ... -# що працює як і очікувалося - -# Умовне виконання (conditional execution) -echo "Виконується завжди" || echo "Виконається, якщо перша команда завершиться з помилкою" -echo "Виконується завжди" && echo "Виконається, якщо перша команда завершиться успішно" - -# Щоб використати && і || у конструкції if, потрібно декілька пар дужок: -if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] -then - echo "Виконається, якщо $NAME="Steve" i AGE=15." -fi - -if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] -then - echo "Виконається, якщо NAME="Steve" або NAME="Zach"." -fi - -# Вирази позначаються наступним форматом: -echo $(( 10 + 5 )) - -# На відмінно від інших мов програмування, Bash - це командна оболонка, а -# отже, працює в контексті поточної директорії -ls - -# Ця команда може використовуватися з опціями -ls -l # Показати кожен файл і директорію на окремому рядку - -# Результат попередньої команди можна перенаправити на вхід наступної. -# Команда grep фільтрує вхід по шаблону. -# Таким чином ми можемо переглянути тільки *.txt файли в поточній директорії: -ls -l | grep "\.txt" - -# Ви можете перенаправ вхід і вихід команди (stdin, stdout, stderr). -# Наступна команда означає: читати із stdin, поки не зустрінеться ^EOF$, і -# перезаписати 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 - -# Запуск hello.py з різними варіантами перенаправлення stdin, -# stdout, stderr (стандартні потоки введення, виведення і помилок): -python hello.py < "input.in" -python hello.py > "output.out" -python hello.py 2> "error.err" -python hello.py > "output-and-error.log" 2>&1 -python hello.py > /dev/null 2>&1 -# Поток помилок перезапише фпйл, якщо цей файл існує -# тому, якщо ви хочете дописувати до файлу, використовуйте ">>": -python hello.py >> "output.out" 2>> "error.err" - -# Перезаписати output.txt, дописати error.err і порахувати кількість рядків: -info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err -wc -l output.out error.err - -# Запустити команду і вивести її файловий дескриптор (див.: man fd; наприклад /dev/fd/123) -echo <(echo "#helloworld") - -# Перезаписати output.txt рядком "#helloworld": -cat > output.out <(echo "#helloworld") -echo "#helloworld" > output.out -echo "#helloworld" | cat > output.out -echo "#helloworld" | tee output.out >/dev/null - -# Подчистить временные файлы с подробным выводом ('-i' - интерактивый режим) -# Очистити тимчасові файли з детальним виводом (додайте '-i' -# для інтерактивного режиму) -rm -v output.out error.err output-and-error.log - -# Команди можуть бути підставлені в інші команди використовуючи $(): -# наступна команда виводить кількість файлів і директорій в поточній директорії -echo "Тут $(ls | wc -l) елементів." - -# Те саме можна зробити використовуючи зворотні лапки -# Але вони не можуть бути вкладеними, тому перший варіант бажаніший -echo "Тут `ls | wc -l` елементів." - -# В Bash є структура case, яка схожа на switch в Java и C++: -case "$VARIABLE" in - # перерахуйте шаблони, які будуть використовуватися в якості умов - 0) echo "Тут нуль.";; - 1) echo "Тут один.";; - *) echo "Не пусте значення.";; -esac - -# Цикл for перебирає елементи передані в аргумент: -# Значення $VARIABLE буде напечатано тричі. -for VARIABLE in {1..3} -do - echo "$VARIABLE" -done - -# Aбо можна використати звичний синтаксис for: -for ((a=1; a <= 3; a++)) -do - echo $a -done - -# Цикл for можно використати, щоб виконувати дії над файлами. -# Цей код запустить команду 'cat' для файлів file1 и file2 -for VARIABLE in file1 file2 -do - cat "$VARIABLE" -done - -# ... або дії над виводом команд -# Запустимо cat для виведення із ls. -for OUTPUT in $(ls) -do - cat "$OUTPUT" -done - -# Цикл while: -while [ true ] -do - echo "Тіло циклу..." - break -done - -# Ви також можете оголосити функцію -# Оголошення: -function foo () -{ - echo "Аргументи функції доступні так само, як і аргументи скрипта: $@" - echo "$1 $2..." - echo "Це функція" - return 0 -} - -# Або просто -bar () -{ - echo "Інший спосіб оголошення функцій!" - return 0 -} - -# Виклик функцій -foo "Мое имя" $NAME - -# Є багато корисних команд: -# вивести останні 10 рядків файла file.txt -tail -n 10 file.txt -# вивести перші 10 рядків файла file.txt -head -n 10 file.txt -# відсортувати рядки file.txt -sort file.txt -# відібрати або пропустити рядки, що дублюються (з опцією -d відбирає) -uniq -d file.txt -# вивести тільки першу колонку перед символом ',' -cut -d ',' -f 1 file.txt -# замінити кожне 'okay' на 'great' у файлі file.txt (підтримується regex) -sed -i 's/okay/great/g' file.txt -# вивести в stdout все рядки з file.txt, що задовольняють шаблону regex; -# цей приклад виводить рядки, що починаються на foo і закінчуються на bar: -grep "^foo.*bar$" file.txt -# використайте опцію -c, щоб вивести кількість входжень -grep -c "^foo.*bar$" file.txt -# чтобы искать по строке, а не шаблону regex, используйте fgrep (или grep -F) -# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrea (або grep -F) -fgrep "^foo.*bar$" file.txt - -# Читайте вбудовану документацію Bash командою 'help': -help -help help -help for -help return -help source -help . - -# Читайте Bash man-документацію -apropos bash -man 1 bash -man bash - -# Читайте документацію info (? для допомоги) -apropos info | grep '^info.*(' -man info -info info -info 5 info - -# Читайте bash info документацію: -info bash -info bash 'Bash Features' -info bash 6 -info --apropos bash -``` diff --git a/ua-ua/json-ua.html.markdown b/ua-ua/json-ua.html.markdown deleted file mode 100644 index 6281ea56..00000000 --- a/ua-ua/json-ua.html.markdown +++ /dev/null @@ -1,67 +0,0 @@ ---- -language: json -filename: learnjson-ru.json -contributors: - - ["Anna Harren", "https://github.com/iirelu"] - - ["Marco Scannadinari", "https://github.com/marcoms"] -translators: - - ["Ehreshi Ivan", "https://github.com/IvanEh"] -lang: ua-ua ---- - -JSON - це надзвичайно простий формат обміну даними. Це мабуть буде найлегшим курсом -"Learn X in Y Minutes". - -В загальному випадку в JSON немає коментарів, але більшість парсерів дозволяють -використовувати коментарі в С-стилі(//, /\* \*/). Можна залишити кому після останнього -поля, але все-таки краще такого уникати для кращої сумісності - -```json -{ - "ключ": "значеннь", - - "ключі": "завжди мають бути обгорнуті в подвійні лапки", - "числа": 0, - "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".", - "логічний тип": true, - "нічого": null, - - "велике число": 1.2e+100, - - "об’єкти": { - "коментар": "Більшість ваших структур будуть складатися з об’єктів", - - "масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5], - - "інший об’єкт": { - "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно." - } - }, - - "безглуздя": [ - { - "джерело калія": ["банани"] - }, - [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, "нео"], - [0, 0, 0, 1] - ] - ], - - "альтернативнтй стиль": { - "коментар": "Гляньте!" - , "позиція коми": "неважлива, поки вона знаходиться до наступного поля" - , "інший коментар": "класно" - }, - - "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON." -} - -Одиничний масив значень теж є правильним JSON - -[1, 2, 3, "text", true] - - -``` -- cgit v1.2.3 From 5a0f2ef998cce1343080660e0a0c6dbcc43dfe2f Mon Sep 17 00:00:00 2001 From: Elena Bolshakova Date: Wed, 2 Dec 2015 14:53:18 +0300 Subject: typo --- ru-ru/perl-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown index 0e68116c..a907ba41 100644 --- a/ru-ru/perl-ru.html.markdown +++ b/ru-ru/perl-ru.html.markdown @@ -129,7 +129,7 @@ open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; # Читать из файлового дескриптора можно с помощью оператора "<>". -# В скалярном контексте он читает одру строку из файла, в списковом -- +# В скалярном контексте он читает одну строку из файла, в списковом -- # читает сразу весь файл, сохраняя по одной строке в элементе массива: my $line = <$in>; -- cgit v1.2.3 From 91ed76340d139a9201262880a0cbbcbe200650f2 Mon Sep 17 00:00:00 2001 From: Jesus Tinoco Date: Wed, 2 Dec 2015 18:49:47 +0100 Subject: Fixing typo in ruby-es.html.markdown --- es-es/ruby-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown index 1cf334e3..37b09e8d 100644 --- a/es-es/ruby-es.html.markdown +++ b/es-es/ruby-es.html.markdown @@ -97,7 +97,7 @@ y #=> 10 # Por convención, usa snake_case para nombres de variables snake_case = true -# Usa nombres de variables descriptivas +# Usa nombres de variables descriptivos ruta_para_la_raiz_de_un_projecto = '/buen/nombre/' ruta = '/mal/nombre/' -- cgit v1.2.3 From 0737d9be0bfdedc11842b39f8422123ac329f524 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=20Polykanine=20A=2EK=2EA=2E=20Menelion=20Elens=C3=BA?= =?UTF-8?q?l=C3=AB?= Date: Wed, 2 Dec 2015 21:59:12 +0200 Subject: Resolving conflict in #1710 --- d.html.markdown | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 9ebba385..ecb9e3ac 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -218,7 +218,7 @@ void main() { // from 1 to 100. Easy! // Just pass lambda expressions as template parameters! - // You can pass any old function you like, but lambdas are convenient here. + // You can pass any function you like, but lambdas are convenient here. auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) .reduce!((a, b) => a + b); @@ -228,7 +228,7 @@ void main() { ``` Notice how we got to build a nice Haskellian pipeline to compute num? -That's thanks to a D innovation know as Uniform Function Call Syntax. +That's thanks to a D innovation know as Uniform Function Call Syntax (UFCS). With UFCS, we can choose whether to write a function call as a method or free function call! Walter wrote a nice article on this [here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) @@ -238,21 +238,23 @@ is of some type A on any expression of type A as a method. I like parallelism. Anyone else like parallelism? Sure you do. Let's do some! ```c +// Let's say we want to populate a large array with the square root of all +// consecutive integers starting from 1 (up until the size of the array), and we +// want to do this concurrently taking advantage of as many cores as we have +// available. + import std.stdio; import std.parallelism : parallel; import std.math : sqrt; void main() { - // We want take the square root every number in our array, - // and take advantage of as many cores as we have available. + // Create your large array auto arr = new double[1_000_000]; - // Use an index, and an array element by reference, - // and just call parallel on the array! + // Use an index, access every array element by reference (because we're + // going to change each element) and just call parallel on the array! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); } } - - ``` -- cgit v1.2.3 From b9cde57bc7efdfd9b9ba8e5fdbe9932c11562d0d Mon Sep 17 00:00:00 2001 From: Anton Pastukhoff Date: Thu, 3 Dec 2015 17:04:28 +0500 Subject: Update d-ru.html.markdown fixed typo --- ru-ru/d-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index cbd5b127..ecd6c44c 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -17,7 +17,7 @@ D - это С++, сделанный правильно. комментарий */ /+ - // вложенные кометарии + // вложенные комментарии /* еще вложенные комментарии */ -- cgit v1.2.3 From 5a1ccececa4ae0211aba96cea5709267678e73e6 Mon Sep 17 00:00:00 2001 From: Bohdan Shtepan Date: Thu, 3 Dec 2015 17:19:34 +0200 Subject: Adds c++-ru --- ru-ru/c++-ru.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 ru-ru/c++-ru.html.markdown diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown new file mode 100644 index 00000000..9e62ee0c --- /dev/null +++ b/ru-ru/c++-ru.html.markdown @@ -0,0 +1,12 @@ +--- +language: c++ +filename: learncpp-ru.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] +translators: + - ["Bohdan Shtepan", "http://modern-dev.com"] +lang: ru-ru +--- \ No newline at end of file -- cgit v1.2.3 From 9e7bd0263972b588ebe41ee6382a86b06d6bd4db Mon Sep 17 00:00:00 2001 From: Bohdan Shtepan Date: Thu, 3 Dec 2015 19:41:19 +0200 Subject: Starts translation --- ru-ru/c++-ru.html.markdown | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index 9e62ee0c..c1c5599b 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -9,4 +9,13 @@ contributors: translators: - ["Bohdan Shtepan", "http://modern-dev.com"] lang: ru-ru ---- \ No newline at end of file +--- + +C++ - компилируемый, статически типизированный язык программирования общего назначения, который, +[как заявляет создатель языка Бьёрн Страуструп](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +был разработан как + +- "лучшая замена C" +- язык с поддержкой абстракции данных +- язык с поддержкой объектно-ориентированого программирования +- язык с поддержкой обобщенного программирования \ No newline at end of file -- cgit v1.2.3 From 5cf95634321084fd104df23fa5a9fbb6167fbc21 Mon Sep 17 00:00:00 2001 From: Bohdan Shtepan Date: Thu, 3 Dec 2015 20:11:29 +0200 Subject: Language overview --- ru-ru/c++-ru.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index c1c5599b..7fb8b9da 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Matt Kline", "https://github.com/mrkline"] - ["Geoff Liu", "http://geoffliu.me"] - ["Connor Waters", "http://github.com/connorwaters"] + - ["Bohdan Shtepan", "http://modern-dev.com"] translators: - ["Bohdan Shtepan", "http://modern-dev.com"] lang: ru-ru @@ -18,4 +19,10 @@ C++ - компилируемый, статически типизированн - "лучшая замена C" - язык с поддержкой абстракции данных - язык с поддержкой объектно-ориентированого программирования -- язык с поддержкой обобщенного программирования \ No newline at end of file +- язык с поддержкой обобщенного программирования + +Хотя его синтаксис может показаться более трудным или сложным для понимания, чем в более современных языках, +он широко применяется т.к. код написанный на C++ компилируется в набор инструкций, которые могут быть выполнены напрямую +процессором. C++ широко используется для разработки программного обеспечения, являясь одним из самых популярных языков +программирования. Область его применения включает создание операционных систем, разнообразных прикладных программ, драйверов +устройств, приложений для встраиваемых систем, высокопроизводительных серверов, а также развлекательных приложений (игр). \ No newline at end of file -- cgit v1.2.3 From 410cc03b09870be6da4931725120b44f93b3bcfc Mon Sep 17 00:00:00 2001 From: Robb Shecter Date: Thu, 3 Dec 2015 14:27:24 -0800 Subject: Updating dev environment installation info --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 936744a0..34eee748 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -426,7 +426,7 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater greater = filter (>= p) xs ``` -Haskell is easy to install. Get it [here](http://www.haskell.org/platform/). +There are two popular ways to install Haskell: The traditional [Cabal-based installation](http://www.haskell.org/platform/), and the newer [Stack-based process](https://www.stackage.org/install). You can find a much gentler introduction from the excellent [Learn you a Haskell](http://learnyouahaskell.com/) or -- cgit v1.2.3 From 3f91dff4282962a30e30c4831c328a682dfc4924 Mon Sep 17 00:00:00 2001 From: JustBlah Date: Fri, 4 Dec 2015 06:12:54 +0200 Subject: Commas added. --- ru-ru/objective-c-ru.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index bebd36d3..e987dd53 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -387,13 +387,13 @@ if ([myClass respondsToSelector:selectorVar]) { // Проверяет содер NSNumber height; } -// Для доступа к public переменной, объявленной в интерфейсе используйте '_' перед названием переменной: +// Для доступа к public переменной, объявленной в интерфейсе, используйте '_' перед названием переменной: _count = 5; // Ссылается на "int count" из интерфейса MyClass -// Получение доступа к переменной, объявленной в имлементации происходит следующим образом: -distance = 18; // Ссылается на "long distance" из имлементации MyClass +// Получение доступа к переменной, объявленной в реализации происходит следующим образом: +distance = 18; // Ссылается на "long distance" из реализации MyClass // Для использования в иплементации переменной, объявленной в интерфейсе с помощью @property, // следует использовать @synthesize для создания переменной аксессора: -@synthesize roString = _roString; // Теперь _roString доступна в @implementation (имплементации интерфейса) +@synthesize roString = _roString; // Теперь _roString доступна в @implementation (реализации интерфейса) // Вызывается в первую очередь, перед вызовом других медотов класса или инициализации других объектов + (void)initialize @@ -507,7 +507,7 @@ distance = 18; // Ссылается на "long distance" из имлемент @end // Теперь, если мы хотим создать объект Truck - грузовик, мы должны создать подкласс класса Car, что -// изменит функционал Car и позволит вести себя подобно грузовику. Но что если мы хотим только добавить +// изменит функционал Car и позволит вести себя подобно грузовику. Но что, если мы хотим только добавить // определенный функционал в уже существующий класс Car? Например - чистка автомобиля. Мы просто создадим // категорию, которая добавит несколько методов для чистки автомобиля в класс Car: // @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h) -- cgit v1.2.3 From 83f3d7dc3bacab40bdee1c545fa92edb17777bf2 Mon Sep 17 00:00:00 2001 From: Bohdan Shtepan Date: Sat, 5 Dec 2015 04:23:07 +0200 Subject: Translated "Comparision to C", "Function overloading", "Default arguments" and "Namespaces" sections --- ru-ru/c++-ru.html.markdown | 873 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 871 insertions(+), 2 deletions(-) diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index 7fb8b9da..99798bbb 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -6,7 +6,6 @@ contributors: - ["Matt Kline", "https://github.com/mrkline"] - ["Geoff Liu", "http://geoffliu.me"] - ["Connor Waters", "http://github.com/connorwaters"] - - ["Bohdan Shtepan", "http://modern-dev.com"] translators: - ["Bohdan Shtepan", "http://modern-dev.com"] lang: ru-ru @@ -25,4 +24,874 @@ C++ - компилируемый, статически типизированн он широко применяется т.к. код написанный на C++ компилируется в набор инструкций, которые могут быть выполнены напрямую процессором. C++ широко используется для разработки программного обеспечения, являясь одним из самых популярных языков программирования. Область его применения включает создание операционных систем, разнообразных прикладных программ, драйверов -устройств, приложений для встраиваемых систем, высокопроизводительных серверов, а также развлекательных приложений (игр). \ No newline at end of file +устройств, приложений для встраиваемых систем, высокопроизводительных серверов, а также развлекательных приложений (игр). + +```c++ +////////////////// +// Сравнение с C +////////////////// + +// C++ практически представляет собой надмножество C и имеет схожий синтаксис +// для объявления переменных, примитивов и функций. + +// Также как и в С, точкой входа в программу является функция с именем main, +// которая возвращает целочисленное значение. +// Это значение является кодом ответа программы. +// Смотрите https://goo.gl/JYGKyv для более подробной информации. +int main(int argc, char** argv) +{ + // Аргументы командной строки переданные в программу хранятся в переменных + // argc и argv, также как и в C. + // argc указывает на количество аргументов, + // а argv является масивом C-подобных строк (char*), который непосредсвенно + // содержит аргументы. + // Первым аргументом всегда передается имя программы. + // argc и argv могут быть опущены если вы не планируете работать с аругментамы + // коммандной строки. + // Тогда сигнатура функции будет иметь следующий вид int main() + + // Возвращаемое значение 0 указывает на успешное завершение программы. + return 0; +} + +// Тем не менее, C++ имеет свои отличия: + +// В C++, символьные литералы являются символами. +sizeof('c') == sizeof(char) == 1 + +// В С, символьные литералы - целые числа. +sizeof('c') == sizeof(int) + + +// C++ имеет строго прототипирование. +void func(); // функция, которая не принимает аргументов. + +// In C +void func(); // функция, которая может принять сколько угодно аргументов. + +// Использование nullptr вместо NULL в C++. +int* ip = nullptr; + +// Стандартные заголовочные файлы С доступны в С++, +// но с префиксом "с" и не имеют суффикса .h. +#include + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////////////////// +// Перегрузка функций +/////////////////////// + +// С++ поддерживает перегрузку функций, при условии, +// что каждая функция принимает различные параметры. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // Использование void print(const char*) + print(15); // Использование void print(int) +} + +///////////////////////////// +// Аргументы функций по умолчанию +///////////////////////////// + +// Вы можете предоставить аргументы по умолчанию для функции, +// если они не предоставлены при вызове функции. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Здесь что-то делаем с числами +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Аргументы по умолчанию должен быть в конце списка аргументов. + +void invalidDeclaration(int a = 1, int b) // Ошибка! +{ +} + + +///////////// +// Пространства имен +///////////// + +// Пространства имен предоставляют отдельные области для переменной, +// функции и других объявлений. +// Пространства имен могут быть вложенными. + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // конец пространства имен Nested +} // конец пространства имен First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // Включает все функци с пространства имен Second в текущую область видиомти. + // Обратите внимание, что простой вызов foo() больше не работает, + // так как теперь не ясно вызываем ли мы foo с пространства имен Second или + // из глобальной области видимости. + using namespace Second; + + Second::foo(); // напечатает "This is Second::foo" + First::Nested::foo(); // напечатает "This is First::Nested::foo" + ::foo(); // напечатает "This is global foo" +} + +/////////////// +// Ввод/Вывод +/////////////// + +// C++ input and output uses streams +// cin, cout, and cerr represent stdin, stdout, and stderr. +// << is the insertion operator and >> is the extraction operator. + +#include // Include for I/O streams + +using namespace std; // Streams are in the std namespace (standard library) + +int main() +{ + int myInt; + + // Prints to stdout (or terminal/screen) + cout << "Enter your favorite number:\n"; + // Takes in input + cin >> myInt; + + // cout can also be formatted + cout << "Your favorite number is " << myInt << "\n"; + // prints "Your favorite number is " + + cerr << "Used for error messages"; +} + +////////// +// Строки +////////// + +// Strings in C++ are objects and have many member functions +#include + +using namespace std; // Strings are also in the namespace std (standard library) + +string myString = "Hello"; +string myOtherString = " World"; + +// + is used for concatenation. +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// C++ strings are mutable and have value semantics. +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// References +///////////// + +// In addition to pointers like the ones in C, +// C++ has _references_. +// These are pointer types that cannot be reassigned once set +// and cannot be null. +// They also have the same syntax as the variable itself: +// No * is needed for dereferencing and +// & (address of) is not used for assignment. + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // This creates a reference to foo. +fooRef += ". Hi!"; // Modifies foo through the reference +cout << fooRef; // Prints "I am foo. Hi!" + +// Doesn't reassign "fooRef". This is the same as "foo = bar", and +// foo == "I am bar" +// after this line. +cout << &fooRef << endl; //Prints the address of foo +fooRef = bar; +cout << &fooRef << endl; //Still prints the address of foo +cout << fooRef; // Prints "I am bar" + +//The address of fooRef remains the same, i.e. it is still referring to foo. + + +const string& barRef = bar; // Create a const reference to bar. +// Like C, const values (and pointers and references) cannot be modified. +barRef += ". Hi!"; // Error, const references cannot be modified. + +// Sidetrack: Before we talk more about references, we must introduce a concept +// called a temporary object. Suppose we have the following code: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// What happens in the second line is actually: +// - a string object is returned from tempObjectFun +// - a new string is constructed with the returned object as argument to the +// constructor +// - the returned object is destroyed +// The returned object is called a temporary object. Temporary objects are +// created whenever a function returns an object, and they are destroyed at the +// end of the evaluation of the enclosing expression (Well, this is what the +// standard says, but compilers are allowed to change this behavior. Look up +// "return value optimization" if you're into this kind of details). So in this +// code: +foo(bar(tempObjectFun())) + +// assuming foo and bar exist, the object returned from tempObjectFun is +// passed to bar, and it is destroyed before foo is called. + +// Now back to references. The exception to the "at the end of the enclosing +// expression" rule is if a temporary object is bound to a const reference, in +// which case its life gets extended to the current scope: + +void constReferenceTempObjectFun() { + // constRef gets the temporary object, and it is valid until the end of this + // function. + const string& constRef = tempObjectFun(); + ... +} + +// Another kind of reference introduced in C++11 is specifically for temporary +// objects. You cannot have a variable of its type, but it takes precedence in +// overload resolution: + +void someFun(string& s) { ... } // Regular reference +void someFun(string&& s) { ... } // Reference to temporary object + +string foo; +someFun(foo); // Calls the version with regular reference +someFun(tempObjectFun()); // Calls the version with temporary reference + +// For example, you will see these two versions of constructors for +// std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// Idea being if we are constructing a new string from a temporary object (which +// is going to be destroyed soon anyway), we can have a more efficient +// constructor that "salvages" parts of that temporary string. You will see this +// concept referred to as "move semantics". + +///////////////////// +// Enums +///////////////////// + +// Enums are a way to assign a value to a constant most commonly used for +// easier visualization and reading of code +enum ECarTypes +{ + Sedan, + Hatchback, + SUV, + Wagon +}; + +ECarTypes GetPreferredCarType() +{ + return ECarTypes::Hatchback; +} + +// As of C++11 there is an easy way to assign a type to the enum which can be +// useful in serialization of data and converting enums back-and-forth between +// the desired type and their respective constants +enum ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // The enum is implicitly converted to a uint8_t due to its declared enum type + WriteByteToFile(InputCarType); +} + +// On the other hand you may not want enums to be accidentally cast to an integer +// type or to other enums so it is instead possible to create an enum class which +// won't be implicitly converted +enum class ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // Won't compile even though ECarTypes is a uint8_t due to the enum + // being declared as an "enum class"! + WriteByteToFile(InputCarType); +} + +////////////////////////////////////////// +// Classes and object-oriented programming +////////////////////////////////////////// + +// First example of classes +#include + +// Declare a class. +// Classes are usually declared in header (.h or .hpp) files. +class Dog { + // Member variables and functions are private by default. + std::string name; + int weight; + +// All members following this are public +// until "private:" or "protected:" is found. +public: + + // Default constructor + Dog(); + + // Member function declarations (implementations to follow) + // Note that we use std::string here instead of placing + // using namespace std; + // above. + // Never put a "using namespace" statement in a header. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // Functions that do not modify the state of the object + // should be marked as const. + // This allows you to call them if given a const reference to the object. + // Also note the functions must be explicitly declared as _virtual_ + // in order to be overridden in derived classes. + // Functions are not virtual by default for performance reasons. + virtual void print() const; + + // Functions can also be defined inside the class body. + // Functions defined as such are automatically inlined. + void bark() const { std::cout << name << " barks!\n"; } + + // Along with constructors, C++ provides destructors. + // These are called when an object is deleted or falls out of scope. + // This enables powerful paradigms such as RAII + // (see below) + // The destructor should be virtual if a class is to be derived from; + // if it is not virtual, then the derived class' destructor will + // not be called if the object is destroyed through a base-class reference + // or pointer. + virtual ~Dog(); + +}; // A semicolon must follow the class definition. + +// Class member functions are usually implemented in .cpp files. +Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// Objects (such as strings) should be passed by reference +// if you are modifying them or const reference if you are not. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Notice that "virtual" is only needed in the declaration, not the definition. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // prints "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.print(); // prints "Dog is Barkley and weighs 10 kg" + return 0; +} // prints "Goodbye Barkley" + +// Inheritance: + +// This class inherits everything public and protected from the Dog class +// as well as private but may not directly access private members/methods +// without a public or protected method for doing so +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner); + + // Override the behavior of the print function for all OwnedDogs. See + // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // for a more general introduction if you are unfamiliar with + // subtype polymorphism. + // The override keyword is optional but makes sure you are actually + // overriding the method in a base class. + void print() const override; + +private: + std::string owner; +}; + +// Meanwhile, in the corresponding .cpp file: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Call the print function in the base Dog class + std::cout << "Dog is owned by " << owner << "\n"; + // Prints "Dog is and weights " + // "Dog is owned by " +} + +////////////////////////////////////////// +// Initialization and Operator Overloading +////////////////////////////////////////// + +// In C++ you can overload the behavior of operators such as +, -, *, /, etc. +// This is done by defining a function which is called +// whenever the operator is used. + +#include +using namespace std; + +class Point { +public: + // Member variables can be given default values in this manner. + double x = 0; + double y = 0; + + // Define a default constructor which does nothing + // but initialize the Point to the default value (0, 0) + Point() { }; + + // The following syntax is known as an initialization list + // and is the proper way to initialize class member values + Point (double a, double b) : + x(a), + y(b) + { /* Do nothing except initialize the values */ } + + // Overload the + operator. + Point operator+(const Point& rhs) const; + + // Overload the += operator + Point& operator+=(const Point& rhs); + + // It would also make sense to add the - and -= operators, + // but we will skip those for brevity. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Create a new point that is the sum of this one and rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // This calls the Point + operator + // Point up calls the + (function) with right as its parameter + Point result = up + right; + // Prints "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////// +// Templates +///////////////////// + +// Templates in C++ are mostly used for generic programming, though they are +// much more powerful than generic constructs in other languages. They also +// support explicit and partial specialization and functional-style type +// classes; in fact, they are a Turing-complete functional language embedded +// in C++! + +// We start with the kind of generic programming you might be familiar with. To +// define a class or function that takes a type parameter: +template +class Box { +public: + // In this class, T can be used as any other type. + void insert(const T&) { ... } +}; + +// During compilation, the compiler actually generates copies of each template +// with parameters substituted, so the full definition of the class must be +// present at each invocation. This is why you will see template classes defined +// entirely in header files. + +// To instantiate a template class on the stack: +Box intBox; + +// and you can use it as you would expect: +intBox.insert(123); + +// You can, of course, nest templates: +Box > boxOfBox; +boxOfBox.insert(intBox); + +// Until C++11, you had to place a space between the two '>'s, otherwise '>>' +// would be parsed as the right shift operator. + +// You will sometimes see +// template +// instead. The 'class' keyword and 'typename' keywords are _mostly_ +// interchangeable in this case. For the full explanation, see +// http://en.wikipedia.org/wiki/Typename +// (yes, that keyword has its own Wikipedia page). + +// Similarly, a template function: +template +void barkThreeTimes(const T& input) +{ + input.bark(); + input.bark(); + input.bark(); +} + +// Notice that nothing is specified about the type parameters here. The compiler +// will generate and then type-check every invocation of the template, so the +// above function works with any type 'T' that has a const 'bark' method! + +Dog fluffy; +fluffy.setName("Fluffy") +barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. + +// Template parameters don't have to be classes: +template +void printMessage() { + cout << "Learn C++ in " << Y << " minutes!" << endl; +} + +// And you can explicitly specialize templates for more efficient code. Of +// course, most real-world uses of specialization are not as trivial as this. +// Note that you still need to declare the function (or class) as a template +// even if you explicitly specified all parameters. +template<> +void printMessage<10>() { + cout << "Learn C++ faster in only 10 minutes!" << endl; +} + +printMessage<20>(); // Prints "Learn C++ in 20 minutes!" +printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" + + +///////////////////// +// Exception Handling +///////////////////// + +// The standard library provides a few exception types +// (see http://en.cppreference.com/w/cpp/error/exception) +// but any type can be thrown an as exception +#include +#include + +// All exceptions thrown inside the _try_ block can be caught by subsequent +// _catch_ handlers. +try { + // Do not allocate exceptions on the heap using _new_. + throw std::runtime_error("A problem occurred"); +} + +// Catch exceptions by const reference if they are objects +catch (const std::exception& ex) +{ + std::cout << ex.what(); +} + +// Catches any exception not caught by previous _catch_ blocks +catch (...) +{ + std::cout << "Unknown exception caught"; + throw; // Re-throws the exception +} + +/////// +// RAII +/////// + +// RAII stands for "Resource Acquisition Is Initialization". +// It is often considered the most powerful paradigm in C++ +// and is the simple concept that a constructor for an object +// acquires that object's resources and the destructor releases them. + +// To understand how this is useful, +// consider a function that uses a C file handle: +void doSomethingWithAFile(const char* filename) +{ + // To begin with, assume nothing can fail. + + FILE* fh = fopen(filename, "r"); // Open the file in read mode. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Close the file handle. +} + +// Unfortunately, things are quickly complicated by error handling. +// Suppose fopen can fail, and that doSomethingWithTheFile and +// doSomethingElseWithIt return error codes if they fail. +// (Exceptions are the preferred way of handling failure, +// but some programmers, especially those with a C background, +// disagree on the utility of exceptions). +// We now have to check each call for failure and close the file handle +// if a problem occurred. +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in read mode + if (fh == nullptr) // The returned pointer is null on failure. + return false; // Report that failure to the caller. + + // Assume each function returns false if it failed + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // Propagate the error. + } + + fclose(fh); // Close the file handle so it doesn't leak. + return true; // Indicate success +} + +// C programmers often clean this up a little bit using goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indicate success + +failure: + fclose(fh); + return false; // Propagate the error +} + +// If the functions indicate errors using exceptions, +// things are a little cleaner, but still sub-optimal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in read mode + if (fh == nullptr) + throw std::runtime_error("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Be sure to close the file if an error occurs. + throw; // Then re-throw the exception. + } + + fclose(fh); // Close the file + // Everything succeeded +} + +// Compare this to the use of C++'s file stream class (fstream) +// fstream uses its destructor to close the file. +// Recall from above that destructors are automatically called +// whenever an object falls out of scope. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream is short for input file stream + std::ifstream fh(filename); // Open the file + + // Do things with the file + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // The file is automatically closed here by the destructor + +// This has _massive_ advantages: +// 1. No matter what happens, +// the resource (in this case the file handle) will be cleaned up. +// Once you write the destructor correctly, +// It is _impossible_ to forget to close the handle and leak the resource. +// 2. Note that the code is much cleaner. +// The destructor handles closing the file behind the scenes +// without you having to worry about it. +// 3. The code is exception safe. +// An exception can be thrown anywhere in the function and cleanup +// will still occur. + +// All idiomatic C++ code uses RAII extensively for all resources. +// Additional examples include +// - Memory using unique_ptr and shared_ptr +// - Containers - the standard library linked list, +// vector (i.e. self-resizing array), hash maps, and so on +// all automatically destroy their contents when they fall out of scope. +// - Mutexes using lock_guard and unique_lock + +// containers with object keys of non-primitive values (custom classes) require +// compare function in the object itself or as a function pointer. Primitives +// have default comparators, but you can override it. +class Foo { +public: + int j; + Foo(int a) : j(a) {} +}; +struct compareFunction { + bool operator()(const Foo& a, const Foo& b) const { + return a.j < b.j; + } +}; +//this isn't allowed (although it can vary depending on compiler) +//std::map fooMap; +std::map fooMap; +fooMap[Foo(1)] = 1; +fooMap.find(Foo(1)); //true + +///////////////////// +// Fun stuff +///////////////////// + +// Aspects of C++ that may be surprising to newcomers (and even some veterans). +// This section is, unfortunately, wildly incomplete; C++ is one of the easiest +// languages with which to shoot yourself in the foot. + +// You can override private methods! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // Overrides Foo::bar! +}; + + +// 0 == false == NULL (most of the time)! +bool* pt = new bool; +*pt = 0; // Sets the value points by 'pt' to false. +pt = 0; // Sets 'pt' to the null pointer. Both lines compile without warnings. + +// nullptr is supposed to fix some of that issue: +int* pt2 = new int; +*pt2 = nullptr; // Doesn't compile +pt2 = nullptr; // Sets pt2 to null. + +// There is an exception made for bools. +// This is to allow you to test for null pointers with if(!ptr), +// but as a consequence you can assign nullptr to a bool directly! +*pt = nullptr; // This still compiles, even though '*pt' is a bool! + + +// '=' != '=' != '='! +// Calls Foo::Foo(const Foo&) or some variant (see move semantics) copy +// constructor. +Foo f2; +Foo f1 = f2; + +// Calls Foo::Foo(const Foo&) or variant, but only copies the 'Foo' part of +// 'fooSub'. Any extra members of 'fooSub' are discarded. This sometimes +// horrifying behavior is called "object slicing." +FooSub fooSub; +Foo f1 = fooSub; + +// Calls Foo::operator=(Foo&) or variant. +Foo f1; +f1 = f2; + + +// How to truly clear a container: +class Foo { ... }; +vector v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// Following line sets size of v to 0, but destructors don't get called +// and resources aren't released! +v.empty(); +v.push_back(Foo()); // New value is copied into the first Foo we inserted + +// Truly destroys all values in v. See section about temporary objects for +// explanation of why this works. +v.swap(vector()); + +``` +Further Reading: + +An up-to-date language reference can be found at + + +Additional resources may be found at -- cgit v1.2.3 From aad2d2b6f2e44f7647d0512dea263029c1d4d1fa Mon Sep 17 00:00:00 2001 From: Bohdan Shtepan Date: Sat, 5 Dec 2015 16:07:14 +0200 Subject: Adds complete translation --- ru-ru/c++-ru.html.markdown | 582 ++++++++++++++++++++++----------------------- 1 file changed, 289 insertions(+), 293 deletions(-) diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index 99798bbb..5137ec1f 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -162,7 +162,7 @@ void foo() int main() { - // Включает все функци с пространства имен Second в текущую область видиомти. + // Включает все функци с пространства имен Second в текущую область видимости. // Обратите внимание, что простой вызов foo() больше не работает, // так как теперь не ясно вызываем ли мы foo с пространства имен Second или // из глобальной области видимости. @@ -177,26 +177,26 @@ int main() // Ввод/Вывод /////////////// -// C++ input and output uses streams -// cin, cout, and cerr represent stdin, stdout, and stderr. -// << is the insertion operator and >> is the extraction operator. +// Вводи и вывод в C++ использует потоки +// cin, cout и cerr предоставлнеы методами stdin, stdout и stderr. +// << - оператор вставки, >> - оператор извлечения. -#include // Include for I/O streams +#include // Включение файла для работы с потоками Ввода\Вывода. -using namespace std; // Streams are in the std namespace (standard library) +using namespace std; // Потоки доступны в пространстве имен std (стандартная библиотека) int main() { int myInt; - // Prints to stdout (or terminal/screen) + // Выводит stdout (или терминал\экран) cout << "Enter your favorite number:\n"; - // Takes in input + // Принимает ввод cin >> myInt; - // cout can also be formatted + // cout может принимать форматирование cout << "Your favorite number is " << myInt << "\n"; - // prints "Your favorite number is " + // напечатает "Your favorite number is " cerr << "Used for error messages"; } @@ -205,35 +205,35 @@ int main() // Строки ////////// -// Strings in C++ are objects and have many member functions +// Строки в C++ являются объектами и имеют много функций-членов. #include -using namespace std; // Strings are also in the namespace std (standard library) +using namespace std; // Строки также доступны в пространстве имен std (стандартная библиотек) string myString = "Hello"; string myOtherString = " World"; -// + is used for concatenation. +// + используется для конкатенации строк. cout << myString + myOtherString; // "Hello World" cout << myString + " You"; // "Hello You" -// C++ strings are mutable and have value semantics. +// Строки в C++ могут изменяться и имеют семантику значений. myString.append(" Dog"); cout << myString; // "Hello Dog" ///////////// -// References +// Ссылки ///////////// -// In addition to pointers like the ones in C, -// C++ has _references_. -// These are pointer types that cannot be reassigned once set -// and cannot be null. -// They also have the same syntax as the variable itself: -// No * is needed for dereferencing and -// & (address of) is not used for assignment. +// В добавок к указателям доступных в C, +// C++ имеет _ссылки_. +// Это такой тип указателя, который не может быть переназначен после инициализации +// и не может иметь значения null. +// Ссылки имеют схожий с переменными синтаксис: +// * больше не используется для разыменования и +// & (адрес) не используется для назначения. using namespace std; @@ -241,84 +241,80 @@ string foo = "I am foo"; string bar = "I am bar"; -string& fooRef = foo; // This creates a reference to foo. -fooRef += ". Hi!"; // Modifies foo through the reference -cout << fooRef; // Prints "I am foo. Hi!" +string& fooRef = foo; // Здесь создается указатель на foo. +fooRef += ". Hi!"; // Изменяет foo по ссылке +cout << fooRef; // Печатает "I am foo. Hi!" -// Doesn't reassign "fooRef". This is the same as "foo = bar", and +// Не переназначает "fooRef". Это тоже самое как "foo = bar", и // foo == "I am bar" -// after this line. -cout << &fooRef << endl; //Prints the address of foo +// после этой строчки. +cout << &fooRef << endl; // Печатает адрес foo fooRef = bar; -cout << &fooRef << endl; //Still prints the address of foo -cout << fooRef; // Prints "I am bar" +cout << &fooRef << endl; // По-прежнему печатает адрес foo +cout << fooRef; // Печатает "I am bar" -//The address of fooRef remains the same, i.e. it is still referring to foo. +// Адрес fooRef остается тем же, то есть он по-прежнему ссылается на foo. -const string& barRef = bar; // Create a const reference to bar. -// Like C, const values (and pointers and references) cannot be modified. -barRef += ". Hi!"; // Error, const references cannot be modified. +const string& barRef = bar; // Создает const со ссылкой на bar. +// Также как и C, значения const (и указателей и ссылок) не могут быть изменены. +barRef += ". Hi!"; // Ошибка, указатель const не может быть изменен. -// Sidetrack: Before we talk more about references, we must introduce a concept -// called a temporary object. Suppose we have the following code: +// Обходной путь: Прежде чем мы рассмотрим указатели более детально, нам нужно ознакомится +// с концепцией известной как "временный объект". Представьте, что мы имеем следующий код string tempObjectFun() { ... } string retVal = tempObjectFun(); -// What happens in the second line is actually: -// - a string object is returned from tempObjectFun -// - a new string is constructed with the returned object as argument to the -// constructor -// - the returned object is destroyed -// The returned object is called a temporary object. Temporary objects are -// created whenever a function returns an object, and they are destroyed at the -// end of the evaluation of the enclosing expression (Well, this is what the -// standard says, but compilers are allowed to change this behavior. Look up -// "return value optimization" if you're into this kind of details). So in this -// code: +// Вот что на самом деле происходит во второй строе: +// - tempObjectFun возвращает строковый объект +// - с возвращаемого объекта создается новая строка в качестве аргумента конструктору +// - возвращаемый объект уничтожается +// Возвращаемый объект называется временным объектом. Временные объекты создаются +// когда функция возвращает объект, и уничтожаются в конце выполнения обрамляющего +// выражения (По крайней мере, так это описывает спецификация, хотя компиляторы могут +// изменять это поведение. Для более подробной информации смотрите "оптимизация +// возвращаемого значения". Таким образом в этом коде: foo(bar(tempObjectFun())) -// assuming foo and bar exist, the object returned from tempObjectFun is -// passed to bar, and it is destroyed before foo is called. +// предполагая, что foo и bar существуют, объект возвращаемый tempObjectFun передается +// в bar, и уничтожается перед вызовом foo. -// Now back to references. The exception to the "at the end of the enclosing -// expression" rule is if a temporary object is bound to a const reference, in -// which case its life gets extended to the current scope: +// Возвращаемся к указателям. Исключением для правила "в конце выполнения обрамляющего +// выражения" является временный объект привязанный к ссылке const, в этом случае +// его жизненный цикл продлевается до текущей области видимости: void constReferenceTempObjectFun() { - // constRef gets the temporary object, and it is valid until the end of this - // function. + // constRef получает временный объект, и он действителен до конца этой функции. const string& constRef = tempObjectFun(); ... } -// Another kind of reference introduced in C++11 is specifically for temporary -// objects. You cannot have a variable of its type, but it takes precedence in -// overload resolution: +// В C++11 предоставлен еще один тип ссылок специально для временных объектов. +// objects. Вы не можете объявить переменную этого типа, но он имеет приоритет в +// в резолюции перегрузки: -void someFun(string& s) { ... } // Regular reference -void someFun(string&& s) { ... } // Reference to temporary object +void someFun(string& s) { ... } // Обычная ссылка +void someFun(string&& s) { ... } // Ссылка на временный объект string foo; -someFun(foo); // Calls the version with regular reference -someFun(tempObjectFun()); // Calls the version with temporary reference +someFun(foo); // Выполняет версию с обычной ссылкой +someFun(tempObjectFun()); // Выполняет версию с временной ссылкой. -// For example, you will see these two versions of constructors for -// std::basic_string: +// Например, существуют следующие две версии конструктора std::basic_string: basic_string(const basic_string& other); basic_string(basic_string&& other); -// Idea being if we are constructing a new string from a temporary object (which -// is going to be destroyed soon anyway), we can have a more efficient -// constructor that "salvages" parts of that temporary string. You will see this -// concept referred to as "move semantics". +// Идея в том, если мы конструируем новую строку из временного объекта (который +// так или иначе будет уничтожен), мы можем использовать более эффективный конструктор, +// который "спасает" части этой временной строки. Эта концепция была названа +// "move semantics". ///////////////////// -// Enums +// Перечисления ///////////////////// -// Enums are a way to assign a value to a constant most commonly used for -// easier visualization and reading of code +// Перечисления - способ объявления констант и установки их значений в основном +// использующийся для упрощения чтения кода. enum ECarTypes { Sedan, @@ -332,9 +328,9 @@ ECarTypes GetPreferredCarType() return ECarTypes::Hatchback; } -// As of C++11 there is an easy way to assign a type to the enum which can be -// useful in serialization of data and converting enums back-and-forth between -// the desired type and their respective constants +// На момент выхода C++11 есть простой способ назначения типа перечисления, что +// полезно в случае сериализации данных и преобразований между конечным типом и +// соответствующими константами. enum ECarTypes : uint8_t { Sedan, // 0 @@ -345,18 +341,19 @@ enum ECarTypes : uint8_t void WriteByteToFile(uint8_t InputValue) { - // Serialize the InputValue to a file + // Сериализуем InputValue в файл } void WritePreferredCarTypeToFile(ECarTypes InputCarType) { - // The enum is implicitly converted to a uint8_t due to its declared enum type + // Перечисление неявно преобразуется в uint8_t из-за раннее объявленного + // типа перечисления. WriteByteToFile(InputCarType); } -// On the other hand you may not want enums to be accidentally cast to an integer -// type or to other enums so it is instead possible to create an enum class which -// won't be implicitly converted +// С другой стороны, чтобы избежать случайного приведения к целочисленному типу или +// другому перечислению, вы можете создать класс перечисления, который не будет +// преобразовываться неявно. enum class ECarTypes : uint8_t { Sedan, // 0 @@ -367,78 +364,78 @@ enum class ECarTypes : uint8_t void WriteByteToFile(uint8_t InputValue) { - // Serialize the InputValue to a file + // Сериализуем InputValue в файл } void WritePreferredCarTypeToFile(ECarTypes InputCarType) { - // Won't compile even though ECarTypes is a uint8_t due to the enum - // being declared as an "enum class"! + // Хотя ECarTypes имеет тип uint8_t, код не будет скомпилирован из-за того, + // что перечисление было объявлено как класс перечисления. WriteByteToFile(InputCarType); } ////////////////////////////////////////// -// Classes and object-oriented programming +// Классы и объектно-ориентированное программирование ////////////////////////////////////////// -// First example of classes +// Пример классов #include -// Declare a class. -// Classes are usually declared in header (.h or .hpp) files. +// Объявление класса. +// Обычно классы объявляют в заголовочном (.h или .hpp) файле. class Dog { - // Member variables and functions are private by default. + // Переменный-члены и функции являются частными по умолчанию. std::string name; int weight; -// All members following this are public -// until "private:" or "protected:" is found. +// Все члены после этой сроки являются открытыми +// пока "private:" или "protected:" не будет объявлено. public: - // Default constructor + // Конструктор по умолчанию Dog(); - // Member function declarations (implementations to follow) - // Note that we use std::string here instead of placing + // Объявление функций-членов + // Обратите внимание, мы используем std::string здесь вместо использования // using namespace std; - // above. - // Never put a "using namespace" statement in a header. + // выше. + // Никогда не размещайте выражение "using namespace" в заголовке. void setName(const std::string& dogsName); void setWeight(int dogsWeight); - // Functions that do not modify the state of the object - // should be marked as const. - // This allows you to call them if given a const reference to the object. - // Also note the functions must be explicitly declared as _virtual_ - // in order to be overridden in derived classes. - // Functions are not virtual by default for performance reasons. + // Функции, которые не изменяют состояние объекта, + // должны быть помечены как const. + // Это позволяет вызывать их если дана const ссылка на объект. + // Обратите внимание, функции должны быть явно объявлены как _virtual_ + // если вы хотите перегрузить их в производных классах. + // Функции не являются виртуальными по умолчания для повышения производительности. virtual void print() const; - // Functions can also be defined inside the class body. - // Functions defined as such are automatically inlined. + // Такде функции могут быть определены внутри тела класса. + // Функции, определенные следующим образом, автоматически встроены. void bark() const { std::cout << name << " barks!\n"; } - // Along with constructors, C++ provides destructors. - // These are called when an object is deleted or falls out of scope. - // This enables powerful paradigms such as RAII - // (see below) - // The destructor should be virtual if a class is to be derived from; - // if it is not virtual, then the derived class' destructor will - // not be called if the object is destroyed through a base-class reference + // Наряду с конструкторами, в C++ есть деструкторы. + // Они вызываются, когда объект удаляется или выпадает с области видимости. + // Это активирует мощную парадигму программирования известную как RAII + // (смотрите ниже) + // Деструктор должен быть виртуальным, если класс будет производным. + // Если он не виртуальный, тогда деструктор производного класса не будет вызван + // если объект удален по ссылке или указателю базового класса. // or pointer. virtual ~Dog(); -}; // A semicolon must follow the class definition. +}; // Определение класса должно завершатся точкой с запятой. -// Class member functions are usually implemented in .cpp files. +// Функции-члены класса, как правило, реализуются в .cpp файлах. Dog::Dog() { std::cout << "A dog has been constructed\n"; } -// Objects (such as strings) should be passed by reference -// if you are modifying them or const reference if you are not. +// Объекты (такие как строки) должны передаваться по ссылке если вы будете +// изменять их, или const-ссылке если нет. void Dog::setName(const std::string& dogsName) { name = dogsName; @@ -449,7 +446,7 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// Notice that "virtual" is only needed in the declaration, not the definition. +// Обратите внимание, "virtual" требуется только в объявлении, не в определении. void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -461,35 +458,34 @@ Dog::~Dog() } int main() { - Dog myDog; // prints "A dog has been constructed" + Dog myDog; // Печатает "A dog has been constructed" myDog.setName("Barkley"); myDog.setWeight(10); - myDog.print(); // prints "Dog is Barkley and weighs 10 kg" + myDog.print(); // Печатает "Dog is Barkley and weighs 10 kg" return 0; -} // prints "Goodbye Barkley" +} // Печатает "Goodbye Barkley" -// Inheritance: +// Интерфейсы: -// This class inherits everything public and protected from the Dog class -// as well as private but may not directly access private members/methods -// without a public or protected method for doing so +// Этот класс наследует все открытые и защищенные члены класса Dog +// также как и все закрытые, но не может непосредственно получить доступ к закрытым +// членам\методам без открытых или защищенных методов для этого. class OwnedDog : public Dog { void setOwner(const std::string& dogsOwner); - // Override the behavior of the print function for all OwnedDogs. See - // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping - // for a more general introduction if you are unfamiliar with - // subtype polymorphism. - // The override keyword is optional but makes sure you are actually - // overriding the method in a base class. + // Переопределяем поведение функции печати для всех OwnedDog. Смотрите + // https://goo.gl/3kuH2x для боле общего введения, если вы не знакомы + // с концепцией полиморфизма подтипов (включения). + // Ключевое слово override является необязательным, но указывает что метод + // на самом деле перегружается в базовом классе. void print() const override; private: std::string owner; }; -// Meanwhile, in the corresponding .cpp file: +// Тем временем, в соответствующем .cpp файле: void OwnedDog::setOwner(const std::string& dogsOwner) { @@ -498,53 +494,54 @@ void OwnedDog::setOwner(const std::string& dogsOwner) void OwnedDog::print() const { - Dog::print(); // Call the print function in the base Dog class + Dog::print(); // Вызывает функцию print в базовом классе Dog std::cout << "Dog is owned by " << owner << "\n"; - // Prints "Dog is and weights " + // Печатает "Dog is and weights " // "Dog is owned by " } ////////////////////////////////////////// -// Initialization and Operator Overloading +// Инициализация и перегрузка операторов. ////////////////////////////////////////// -// In C++ you can overload the behavior of operators such as +, -, *, /, etc. -// This is done by defining a function which is called -// whenever the operator is used. +// В C++ вы можете перегрузить поведение таких операторов: +, -, *, / и др.. +// Это делается путем определения функции, которая вызывается, +// когда используется оператор. #include using namespace std; class Point { public: - // Member variables can be given default values in this manner. + // Значения по умолчанию для переменных-членов могут быть установлены + // следующим образом. double x = 0; double y = 0; - // Define a default constructor which does nothing - // but initialize the Point to the default value (0, 0) + // Определяем новый конструктор, который инициализирует Point со значениями + // по умолчанию (0, 0) Point() { }; - // The following syntax is known as an initialization list - // and is the proper way to initialize class member values + // Следующий синтаксис известен как список инициализации и является верным способом + // инициализировать значения членов класса. Point (double a, double b) : x(a), y(b) - { /* Do nothing except initialize the values */ } + { /* Ничего не делайте кроме инициализации значений */ } - // Overload the + operator. + // Перегружаем оперот +. Point operator+(const Point& rhs) const; - // Overload the += operator + // Перегружаем оператор +=. Point& operator+=(const Point& rhs); - // It would also make sense to add the - and -= operators, - // but we will skip those for brevity. + // Имеет смысл добавить перегрузку операторов - и -=, + // но для краткости мы опустим эти детали. }; Point Point::operator+(const Point& rhs) const { - // Create a new point that is the sum of this one and rhs. + // Создает новую точку, которая является суммой этой точки и rhs. return Point(x + rhs.x, y + rhs.y); } @@ -558,59 +555,58 @@ Point& Point::operator+=(const Point& rhs) int main () { Point up (0,1); Point right (1,0); - // This calls the Point + operator - // Point up calls the + (function) with right as its parameter + // Здесь происходит вызов оператора + класса Point + // Точка "up" вызывает + (функция) с параметром "right" Point result = up + right; - // Prints "Result is upright (1,1)" + // Печатает "Result is upright (1,1)" cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; return 0; } ///////////////////// -// Templates +// Шаблоны ///////////////////// -// Templates in C++ are mostly used for generic programming, though they are -// much more powerful than generic constructs in other languages. They also -// support explicit and partial specialization and functional-style type -// classes; in fact, they are a Turing-complete functional language embedded -// in C++! +// Шаблоны в С++, в основном, используются для обобщенного программирования, хотя +// они гораздо более мощны чем дженерики в других языках. Они также поддерживают +// явные, частные и функциональные типы классов; на самом деле, они являются +// тьюринг-полным языком встроенным в C++! -// We start with the kind of generic programming you might be familiar with. To -// define a class or function that takes a type parameter: +// Мы начнем с наиболее распространенного типа обобщенного программирования. Чтобы +// определить класс или функцию, которая принимает параметр типа: template class Box { public: - // In this class, T can be used as any other type. + // В этом классе T может быть любого типа. void insert(const T&) { ... } }; -// During compilation, the compiler actually generates copies of each template -// with parameters substituted, so the full definition of the class must be -// present at each invocation. This is why you will see template classes defined -// entirely in header files. +// Во время компиляции, компилятор фактически генерирует копии каждого шаблона +// с замещенными параметрами, по-этому полное определение класса должно присутствовать +// при каждом вызове. Именно по-этому классы шаблонов полностью определены в +// заголовочных файлах. -// To instantiate a template class on the stack: +// Чтобы создать экземпляр класса шаблона на стеке: Box intBox; -// and you can use it as you would expect: +// и вы можете использовать его, как и ожидалось: intBox.insert(123); -// You can, of course, nest templates: +// Вы, конечно, можете использовать вложенные шаблоны: Box > boxOfBox; boxOfBox.insert(intBox); -// Until C++11, you had to place a space between the two '>'s, otherwise '>>' -// would be parsed as the right shift operator. +// Вплоть до С++11, вы должны были ставить пробел между двумя символами '>', иначе '>>' +// принимался парсером, как оператор правого сдвига. -// You will sometimes see +// Иногда вы можете увидеть // template -// instead. The 'class' keyword and 'typename' keywords are _mostly_ -// interchangeable in this case. For the full explanation, see +// вместо этого. В этом случае, ключевые слова 'class' и 'typename' _в основном_ +// взаимозаменяемыми. Для более подробной информации смотрите // http://en.wikipedia.org/wiki/Typename -// (yes, that keyword has its own Wikipedia page). +// (да-да, это ключевое слово имеет собственную страничку на вики). -// Similarly, a template function: +// Аналогичным образом, шаблонная функция: template void barkThreeTimes(const T& input) { @@ -619,115 +615,115 @@ void barkThreeTimes(const T& input) input.bark(); } -// Notice that nothing is specified about the type parameters here. The compiler -// will generate and then type-check every invocation of the template, so the -// above function works with any type 'T' that has a const 'bark' method! +// Обратите внимание, что здесь ничего не указано о типе параметра. Компилятор +// будет генерировать и затем проверять тип каждый вызов шаблона, по-этому +// данная функция работает с любым типом 'T', который имеет метод 'bark'. Dog fluffy; fluffy.setName("Fluffy") -barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. +barkThreeTimes(fluffy); // Печатает "Fluffy barks" три раза. -// Template parameters don't have to be classes: +//Параметры шаблона не должны быть классами: template void printMessage() { cout << "Learn C++ in " << Y << " minutes!" << endl; } -// And you can explicitly specialize templates for more efficient code. Of -// course, most real-world uses of specialization are not as trivial as this. -// Note that you still need to declare the function (or class) as a template -// even if you explicitly specified all parameters. +// В конце концов, вы можете явно специализировать шаблоны для более эффективного +// кода. Конечно, большинство реальных случаев использования специализации +// не так тривиально, как это. Обратите внимание, вам все еще нужно явно объявить +// функцию (или класс) в качестве шаблона, даже если вы явно указали все параметры. template<> void printMessage<10>() { cout << "Learn C++ faster in only 10 minutes!" << endl; } -printMessage<20>(); // Prints "Learn C++ in 20 minutes!" -printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" +printMessage<20>(); // Печатает "Learn C++ in 20 minutes!" +printMessage<10>(); // Печатает "Learn C++ faster in only 10 minutes!" ///////////////////// -// Exception Handling +// Обработка исключений ///////////////////// -// The standard library provides a few exception types -// (see http://en.cppreference.com/w/cpp/error/exception) -// but any type can be thrown an as exception +// Стандартная библиотека предоставляет несколько типов исключений +// (смотрите http://en.cppreference.com/w/cpp/error/exception) +// но, в принципе, любой тип может быть брошен в качестве исключения. #include #include -// All exceptions thrown inside the _try_ block can be caught by subsequent -// _catch_ handlers. +// Все исключения брошены внутри блока _try_ могут быть пойманы в последующем блоке +// _catch_. try { - // Do not allocate exceptions on the heap using _new_. + // Не выделяйте память в куче для исключений с помощью ключевого слова _new_. throw std::runtime_error("A problem occurred"); } -// Catch exceptions by const reference if they are objects +// Поймайте исключение по константной ссылке, если они являются объектами catch (const std::exception& ex) { std::cout << ex.what(); } -// Catches any exception not caught by previous _catch_ blocks +// Ловит любое исключение не пойманное предыдущим блоком _catch_ catch (...) { std::cout << "Unknown exception caught"; - throw; // Re-throws the exception + throw; // Повторный выброс исключения } /////// -// RAII +// Получение ресурса есть инициализация (RAII) /////// -// RAII stands for "Resource Acquisition Is Initialization". -// It is often considered the most powerful paradigm in C++ -// and is the simple concept that a constructor for an object -// acquires that object's resources and the destructor releases them. +// Программная идиома объектно-ориентированного программирования, смысл которой +// заключается в том, что с помощью тех или иных программных механизмов получение +// некоторого ресурса неразрывно совмещается с инициализацией, а освобождение - +// с уничтожением объекта. -// To understand how this is useful, -// consider a function that uses a C file handle: +// Чтобы понять на сколько это полезно, +// рассмотрим функцию, которая использует обработчик файлов в С: void doSomethingWithAFile(const char* filename) { - // To begin with, assume nothing can fail. + // Для начала, предположим, ничего не может потерпеть неудачу. - FILE* fh = fopen(filename, "r"); // Open the file in read mode. + FILE* fh = fopen(filename, "r"); // Открываем файл в режиме чтения. doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); - fclose(fh); // Close the file handle. + fclose(fh); // Закрываем обработчик файла. } -// Unfortunately, things are quickly complicated by error handling. -// Suppose fopen can fail, and that doSomethingWithTheFile and -// doSomethingElseWithIt return error codes if they fail. -// (Exceptions are the preferred way of handling failure, -// but some programmers, especially those with a C background, -// disagree on the utility of exceptions). -// We now have to check each call for failure and close the file handle -// if a problem occurred. +// К сожалению, вещи быстро осложняется обработкой ошибок. +// Предположим fopen может потерпеть неудачу, тогда doSomethingWithTheFile и +// doSomethingElseWithIt вернут коды ошибок если потерпят неудачу. +// (Исключения являются предпочтительным способом обработки ошибок, +// но некоторые программисты, особенно те, кто имеет большой опыт работы с С, +// не согласны с аргументами о полезности исключений). +// Теперь мы должны проверить каждый вызов на наличие ошибок и закрыть обработчик +// файла если таковы есть. bool doSomethingWithAFile(const char* filename) { - FILE* fh = fopen(filename, "r"); // Open the file in read mode - if (fh == nullptr) // The returned pointer is null on failure. - return false; // Report that failure to the caller. + FILE* fh = fopen(filename, "r"); // Открывает файл в режиме чтения + if (fh == nullptr) // В случае неудачи возвращаемый указатель принимает null. + return false; // Сообщает об неудаче вызывающему. - // Assume each function returns false if it failed + // Предположим, каждая функция возвращает false в случае неудачи if (!doSomethingWithTheFile(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // Propagate the error. + fclose(fh); // Закрываем обработчик файл чтобы не было утечек + return false; // Сообщает об ошибке. } if (!doSomethingElseWithIt(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // Propagate the error. + fclose(fh); // Закрываем обработчик файл чтобы не было утечек + return false; // Сообщает об ошибке. } - fclose(fh); // Close the file handle so it doesn't leak. - return true; // Indicate success + fclose(fh); // Закрываем обработчик файл чтобы не было утечек + return true; // Указывает на успех } -// C programmers often clean this up a little bit using goto: +// C-программисты часто упорядочивают это с помощью goto: bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); @@ -741,18 +737,18 @@ bool doSomethingWithAFile(const char* filename) goto failure; fclose(fh); // Close the file - return true; // Indicate success + return true; // Указывает на успех failure: fclose(fh); - return false; // Propagate the error + return false; // Сообщает об ошибке. } -// If the functions indicate errors using exceptions, -// things are a little cleaner, but still sub-optimal. +// Если функции указывают на ошибки с помощью исключений, вещи становятся проще, +// но все еще не оптимальны. void doSomethingWithAFile(const char* filename) { - FILE* fh = fopen(filename, "r"); // Open the file in read mode + FILE* fh = fopen(filename, "r"); // Открываем файл в режиме чтения if (fh == nullptr) throw std::runtime_error("Could not open the file."); @@ -761,52 +757,51 @@ void doSomethingWithAFile(const char* filename) doSomethingElseWithIt(fh); } catch (...) { - fclose(fh); // Be sure to close the file if an error occurs. - throw; // Then re-throw the exception. + fclose(fh); // Убедитесь, что закрываете файл, если происходит ошибка. + throw; // Затем повторно бросает исключение. } fclose(fh); // Close the file - // Everything succeeded + // Успех } -// Compare this to the use of C++'s file stream class (fstream) -// fstream uses its destructor to close the file. -// Recall from above that destructors are automatically called -// whenever an object falls out of scope. +// Сравните это с использованием класса потока файла (fstream) в С++, который +// использует свой деструктор чтобы закрыть файл. Еще раз взгляните выше, +// деструктор вызывается автоматически, когда объект выпадает из области видимости. void doSomethingWithAFile(const std::string& filename) { - // ifstream is short for input file stream - std::ifstream fh(filename); // Open the file + // ifstream определяет файловый поток + std::ifstream fh(filename); // Открыть файл - // Do things with the file + // Что-то делать с файлом doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); -} // The file is automatically closed here by the destructor - -// This has _massive_ advantages: -// 1. No matter what happens, -// the resource (in this case the file handle) will be cleaned up. -// Once you write the destructor correctly, -// It is _impossible_ to forget to close the handle and leak the resource. -// 2. Note that the code is much cleaner. -// The destructor handles closing the file behind the scenes -// without you having to worry about it. -// 3. The code is exception safe. -// An exception can be thrown anywhere in the function and cleanup -// will still occur. - -// All idiomatic C++ code uses RAII extensively for all resources. -// Additional examples include -// - Memory using unique_ptr and shared_ptr -// - Containers - the standard library linked list, -// vector (i.e. self-resizing array), hash maps, and so on -// all automatically destroy their contents when they fall out of scope. -// - Mutexes using lock_guard and unique_lock - -// containers with object keys of non-primitive values (custom classes) require -// compare function in the object itself or as a function pointer. Primitives -// have default comparators, but you can override it. +} // Здесь файл автоматически закрывается в деструкторе. + +// Это имеет _огромнейшие_ преимущества: +// 1. Неважно, что произойдет, +// ресурсы (в данном случае обработчик файлов) будут очищены. +// После того, как вы правильно напишите деструктор, +// Больше будет _не возможно_ закрыть обработчик файлов или допустить утечку. +// 2. Обратите внимание, что код намного проще. +// Деструктор закрывает файловый поток "за кулисами" и вам больше не нужно об +// этом беспокоится. +// 3. Код устойчив к исключениям. +// Исключение может быть брошено в любом месте в функции и это никак не повлияет +// на очистку. + +// Весь идиоматический код на С++ широко использует RAII для всех ресурсов. +// Дополнительные примеры включат +// - Использование памяти unique_ptr и shared_ptr +// - Контейнеры - стандартная библиотека связанных списков, векторы +// (т.е. самоизменяемые массивы), хэш-карты и все остальное автоматически +// уничтожается сразу-же, когда выходит за пределы области видимости. +// - Ипользование мютексов lock_guard и unique_lock + +// Контейнеры с пользовательскими классами в качестве ключей требуют +// функций-компаратор в самом объекте или как указатель на функцию. Примитивы +// имеют компараторы по умолчанию, но вы можете перегрузить их. class Foo { public: int j; @@ -817,81 +812,82 @@ struct compareFunction { return a.j < b.j; } }; -//this isn't allowed (although it can vary depending on compiler) -//std::map fooMap; +// это не допускается (хотя это может варьироваться в зависимости от компилятора) +// std::map fooMap; std::map fooMap; fooMap[Foo(1)] = 1; fooMap.find(Foo(1)); //true ///////////////////// -// Fun stuff +// Веселые вещи ///////////////////// -// Aspects of C++ that may be surprising to newcomers (and even some veterans). -// This section is, unfortunately, wildly incomplete; C++ is one of the easiest -// languages with which to shoot yourself in the foot. +// Аспекты С++, которые могут быть удивительными для новичком (и даже для некоторых +// ветеранов). Этот раздел, к сожалению, очень неполон. С++ является одним из самых +// простых языков, где очень легко выстрелить себе в ногу. -// You can override private methods! +// Вы можете перегрузить приватные методы! class Foo { virtual void bar(); }; class FooSub : public Foo { - virtual void bar(); // Overrides Foo::bar! + virtual void bar(); // Перегружает Foo::bar! }; -// 0 == false == NULL (most of the time)! +// 0 == false == NULL (в основном)! bool* pt = new bool; -*pt = 0; // Sets the value points by 'pt' to false. -pt = 0; // Sets 'pt' to the null pointer. Both lines compile without warnings. +*pt = 0; // Устанавливает значение указателя 'pt' в false. +pt = 0; // Устанавливает значение 'pt' в нулевой указатель. Обе линии проходят + // компиляцию без ошибок. -// nullptr is supposed to fix some of that issue: +// nullptr приходит на помощь: int* pt2 = new int; -*pt2 = nullptr; // Doesn't compile -pt2 = nullptr; // Sets pt2 to null. +*pt2 = nullptr; // Не пройдет компиляцию +pt2 = nullptr; // Устанавливает pt2 в null. -// There is an exception made for bools. -// This is to allow you to test for null pointers with if(!ptr), -// but as a consequence you can assign nullptr to a bool directly! -*pt = nullptr; // This still compiles, even though '*pt' is a bool! +// Существует исключение для булевых значений. +// Это позволит вам проверить указатели с помощью if(!ptr), +// но как следствие вы можете установить nullptr в bool напрямую! +*pt = nullptr; // Это по прежнему проходит компиляцию, даже если '*pt' - bool! // '=' != '=' != '='! -// Calls Foo::Foo(const Foo&) or some variant (see move semantics) copy -// constructor. +// Вызывает Foo::Foo(const Foo&) или некий вариант (смотрите "move semantics") +// копирования конструктора. Foo f2; Foo f1 = f2; -// Calls Foo::Foo(const Foo&) or variant, but only copies the 'Foo' part of -// 'fooSub'. Any extra members of 'fooSub' are discarded. This sometimes -// horrifying behavior is called "object slicing." +// Вызывает Foo::Foo(const Foo&) или вариант, но копирует только часть 'Foo' из +// 'fooSub'. Любые другие члены 'fooSub' пропускаются. Иногда это ужасное поведение +// называют "object slicing." FooSub fooSub; Foo f1 = fooSub; -// Calls Foo::operator=(Foo&) or variant. +// Вызывает Foo::operator=(Foo&) или вариант. Foo f1; f1 = f2; -// How to truly clear a container: +// Как по-настоящему очистить контейнер: class Foo { ... }; vector v; for (int i = 0; i < 10; ++i) v.push_back(Foo()); -// Following line sets size of v to 0, but destructors don't get called -// and resources aren't released! +// В слудующей точке размер v устанавливается в 0, но деструктор не вызывается +// и не происходит очистка ресурсов! v.empty(); -v.push_back(Foo()); // New value is copied into the first Foo we inserted +v.push_back(Foo()); // Новые значения копируются в первый вставленный Foo -// Truly destroys all values in v. See section about temporary objects for -// explanation of why this works. +// Настоящие уничтожение всех значений v. Смотрите раздел о временном объекте +// для объяснения того, как это работает. v.swap(vector()); ``` -Further Reading: +Дальнейшее чтение: -An up-to-date language reference can be found at +Наиболее полное и обновленное руководство по С++ можно найти на -Additional resources may be found at +Дополнительные ресурсы могут быть найдены на -- cgit v1.2.3 From ad19e8803a4ebc21f16d3407cf64f368b0745597 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Sat, 5 Dec 2015 15:18:15 +0100 Subject: [PowerShell/en]: didn't recognize code blocks --- powershell.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/powershell.html.markdown b/powershell.html.markdown index 4bc1ab39..8920d254 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -18,6 +18,7 @@ rather than plain text. [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) If you are uncertain about your environment: + ``` Get-ExecutionPolicy -List Set-ExecutionPolicy AllSigned @@ -33,6 +34,7 @@ $PSVersionTable ``` Getting help: + ``` # Find commands Get-Command about_* # alias: gcm @@ -49,6 +51,7 @@ Update-Help # Run as admin ``` The tutorial starts here: + ``` # As you already figured, comments start with # @@ -292,6 +295,7 @@ $Shortcut.Save() Configuring your shell + ``` # $Profile is the full path for your `Microsoft.PowerShell_profile.ps1` # All code there will be executed when the PS session starts -- cgit v1.2.3 From 73fbc7f75512ac61493e4f82f0fc5108229124f3 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Sun, 6 Dec 2015 00:00:07 +0800 Subject: Rename file by adding -tw suffix. --- zh-tw/python-tw.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index c4706c43..472b39ab 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -7,7 +7,7 @@ contributors: - ["evuez", "http://github.com/evuez"] translators: - ["Michael Yeh", "https://hinet60613.github.io/"] -filename: learnpython.py +filename: learnpython-tw.py lang: zh-tw --- -- cgit v1.2.3 From d75d8e133a5d7d2e23c7afc1ea16ec68db61cff7 Mon Sep 17 00:00:00 2001 From: Max Goldstein Date: Tue, 8 Dec 2015 15:06:37 -0500 Subject: Add Elm --- elm.html.markdown | 346 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 elm.html.markdown diff --git a/elm.html.markdown b/elm.html.markdown new file mode 100644 index 00000000..8c191509 --- /dev/null +++ b/elm.html.markdown @@ -0,0 +1,346 @@ +--- +language: Elm +contributors: + - ["Max Goldstein", "http://maxgoldste.in/"] +--- + +Elm is a functional reactive programming language that compiles to (client-side) +JavaScript. Elm is statically typed, meaning that the compiler catches most +errors immediately and provides a clear and understandable error message. Elm is +great for designing user interfaces and games for the web. + + +```haskell +-- Single line comments start with two dashes. +{- Multiline comments can be enclosed in a block like this. +{- They can be nested. -} +-} + +{-- The Basics --} + +-- Arithmetic +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 + +-- Every number literal without a decimal point can be either an Int or a Float. +33 / 2 -- 16.5 with floating point division +33 // 2 -- 16 with integer division + +-- Exponents +5 ^ 2 -- 25 + +-- Booleans +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Strings and characters +"This is a string." +'a' -- character +'You cant use single quotes for strings.' -- error! + +-- Strings can be appended +"Hello " ++ "world!" -- "Hello world!" + +{-- Lists, Tuples, and Records --} + +-- Every element in a list must have the same type. +["the", "quick", "brown", "fox"] +[1, 2, 3, 4, 5] +-- The second example can also be written with two dots. +[1..5] + +-- Append lists just like strings +[1..5] ++ [6..10] == [1..10] -- True + +-- To add one item, use "cons" +0 :: [1..5] -- [0, 1, 2, 3, 4, 5] + +-- The head and tail of a list are returned as a Maybe. Instead of checking +-- every value to see if it's null, you deal with missing values explicitly. +List.head [1..5] -- Just 1 +List.tail [1..5] -- Just [2, 3, 4, 5] +List.head [] -- Nothing + +-- Every element in a tuple can be a different type, but a tuple has a +-- fixed length. +("elm", 42) + +-- Access the elements of a pair with the first and second functions. +-- (This is a shortcut; we'll come to the "real way" in a bit.) +fst ("elm", 42) -- "elm" +snd ("elm", 42) -- 42 + +-- Records are like tuples but the fields have names. +-- Notice that equals signs, not colons, are used. +{ x = 3, y = 7} + +-- Access a field with a dot and the field name. +{ x = 3, y = 7}.x -- 3 + +-- Or with an accessor fuction, a dot and then the field name. +.y { x = 3, y = 7} -- 7 + +-- Update the fields of a record. (It must have the fields already.) +{ person | + name = "George" } + +{ physics | + position = physics.position + physics.velocity, + velocity = physics.velocity + physics.acceleration } + +{-- Control Flow --} + +-- If statements always have an else, and the branches must be the same type. +if powerLevel > 9000 then + "WHOA!" +else + "meh" + +-- If statements can be chained. +if n < 0 then + "n is negative" +else if n > 0 then + "n is positive" +else + "n is zero" + +-- Use case statements to pattern match on different possibilities. +case aList of + [] -> "matches the empty list" + x::xs -> "matches a list of at least one item whose head is " ++ toString x + +case List.head aList of + Just x -> "The head is " ++ toString x + Nothing -> "The list was empty" + +{-- Functions --} + +-- Elm's syntax for functions is very minimal, relying mostly on whitespace +-- rather than parentheses and curly brackets. There is no "return" keyword. + +-- Define a function with its name, arguments, an equals sign, and the body. +multiply a b = + a * b + +-- Apply (call) a function by passing it arguments (no commas necessay). +multiply 7 6 -- 42 + +-- Partially apply a function by passing only some of its arguments. +-- Then give that function a new name. +double = + multiply 2 + +-- Constants are similar, except there are no arguments. +answer = + 42 + +-- Pass functions as arguments to other functions. +List.map double [1..4] -- [2, 4, 6, 8] + +-- Or write an anonymous function. +List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8] + +-- You can pattern match in function definitions when there's only one case. +-- This function takes one tuple rather than two arguments. +area (width, height) = + width * height + +area (6, 7) -- 42 + +-- Use curly brackets to pattern match record field names +-- Use let to define intermediate values +volume {width, height, depth} = + let + area = width * height + in + area * depth + +volume { width = 3, height = 2, depth = 7 } -- 42 + +-- Functions can be recursive +fib n = + if n < 2 then + 1 + else + fib (n - 1) + fib (n - 2) + +List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34] + +listLength aList = + case aList of + [] -> 0 + x::xs -> 1 + listLength xs + +-- Function application happens before any infix operation +cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 +-- First degrees is applied to 30, then the result is passed to the trig +-- functions, which is then squared, and the addition happens last. + +{-- Types and Type Annotations --} + +-- The compiler will infer the type of every value in your program. +-- Types are always uppercase. Read x : T as "x has type T". +-- Some common types, which you might see in Elm's REPL. +5 : Int +6.7 : Float +"hello" : String +True : Bool + +-- Functions have types too. Read -> as "goes to". Think of the rightmost type +-- as the type of the return value. +not : Bool -> Bool +round : Float -> Int + +-- When you define a value, it's good practice to write its type above it. +-- The annotation is a form of documentation, which is verified by the compiler. +double : Int -> Int +double x = x * 2 + +-- Function arguments are passed in parentheses. +-- Lowercase types are type variables: they can be any type, as long as each +-- call is consistent. +List.map : (a -> b) -> List a -> List b +-- "List dot map has type a-goes-to-b, goes to list of a, goes to list of b." + +-- There are three special lowercase types: number, comparable, and appendable. +-- Numbers allow you to use arithmetic on Ints and Floats. +-- Comparable allows you to order numbers and strings, like a < b. +-- Appendable things can be combined with a ++ b. + +{-- Type Aliases and Union Types --} + +-- When you write a record or tuple, its type already exists. +-- (Notice that record types use colon and record values use equals.) +origin : { x : Float, y : Float, z : Float } +origin = + { x = 0, y = 0, z = 0 } + +-- You can give existing types a nice name with a type alias. +type alias Point3D = { x : Float, y : Float, z : Float } + +-- If you alias a record, you can use the name as a constructor function. +otherOrigin : Point3D +otherOrigin = Point3D 0 0 0 + +-- But it's still the same type, you can equate them +origin == otherOrigin -- True + +-- By contrast, defining a union type creates a type that didn't exist before. +-- A union type is so called because it can be one of many possibilities. +-- Each of the possibilities is represented as a "tag". +type Direction = North | South | East | West + +-- Tags can carry other values of known type. This can work recursively. +type IntTree = Leaf | Node Int IntTree IntTree + +-- "Leaf" and "Node" are the tags. Everything following a tag is a type. +-- Tags can be used as values or functions. +root : IntTree +root = Node 7 Leaf Leaf + +-- Union types (and type aliases) can use type variables. +type Tree a = Leaf | Node a (Tree a) (Tree a) + +-- You can pattern match union tags. The uppercase tags must be matched exactly. +-- The lowercase variables will match anything. Underscore also matches +-- anything, but signifies that you aren't using it. +leftmostElement : Tree a -> Maybe a +leftmostElement tree = + case tree of + Leaf -> Nothing + Node x Leaf _ -> Just x + Node _ subtree _ -> leftmostElement subtree + +-- That's pretty much it for the language itself. Now let's see how to organize +-- and run your code. + +{-- Modules and Imports --} + +-- The core libraries are organized into modulues, as are any third-party +-- libraries you may use. For large projects, you can define your own modulues. + +-- Put this at the top of the file. If omitted, you're in Main. +module Name where + +-- By default, everything is exported. +-- Limit what values and types are exported +module Name (Type, value) where + +-- One common pattern is to export a union type but not its tags. This is known +-- as an "opaque type", and is frequently used in libraries. + +-- Import code from other modules to use it in this one +-- Places Dict in scope, so you can call Dict.insert +import Dict + +-- Imports the Dict module and the Dict type, so your annotations don't have to +-- say Dict.Dict. You can still use Dict.insert. +import Dict exposing (Dict) + +-- Rename an import. +import Graphics.Collage as C + +{-- Ports --} + +-- A port indicates that you will be communicating with the outside world. +-- Ports are only allowed in the Main module. + +-- An incoming port is just a type signature. +port clientID : Int + +-- An outgoing port has a defintion. +port clientOrders : List String +port clientOrders = ["Books", "Groceries", "Furniture"] + +-- We won't go into the details, but you set up callbacks in JavaScript to send +-- on incoming ports and receive on outgoing ports. + +{-- Command Line Tools --} + +-- Compile a file. +$ elm make MyFile.elm + +-- The first time you do this, Elm will install the core libraries and create +-- elm-package.json, where information about your project is kept. + +-- The reactor is a server that compiles and runs your files. +-- Click the wrench next to file names to enter the time-travelling debugger! +$ elm reactor + +-- Experiment with simple expressions in a Read-Eval-Print Loop. +$ elm repl + +-- Packages are identified by GitHub username and repo name. +-- Install a new package, and record it in elm-package.json. +$ elm package install evancz/elm-html + +-- Elm's package manager enforces semantic versioning, so minor version bumps +-- will never break your build! +``` + +The Elm language is surprisingly small. You can now look through almost any Elm +source code and have a rough idea of what is going on. However, the possibilties +for error-resistant and easy-to-refactor code are endless! + +Here are some useful resources. + +* The [Elm website](http://elm-lang.org/). Includes: + * Links to the [installers](http://elm-lang.org/install) + * [Documentation guides](http://elm-lang.org/docs), including the [syntax reference](http://elm-lang.org/docs/syntax) + * Lots of helpful [examples](http://elm-lang.org/examples) + +* Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of: + * [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default + * Data structures like [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [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) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) + +* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay with examples on how to organize code into components. + +* The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful. + + +Go out and write some Elm! -- cgit v1.2.3 From 2f85645c9f988663c2f584fb23392d873fc3c8e9 Mon Sep 17 00:00:00 2001 From: Anton Davydov Date: Wed, 9 Dec 2015 00:03:06 +0300 Subject: [common-lisp/en] Fix code in examples --- common-lisp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 2b1f5de4..9a23bc26 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -339,7 +339,7 @@ nil ; for false - and the empty list ;; The () in the above is the list of arguments for the function (defun hello (name) - (format nil "Hello, ~a " name)) + (format nil "Hello, ~a" name)) (hello "Steve") ; => "Hello, Steve" @@ -430,7 +430,7 @@ nil ; for false - and the empty list (defun walker (n) (if (zerop n) :walked - (walker (1- n)))) + (walker (- n 1)))) (walker 5) ; => :walked -- cgit v1.2.3 From dbfb19bb5779e84add18a19ebc36833e748e69d9 Mon Sep 17 00:00:00 2001 From: Lari Kovanen Date: Wed, 9 Dec 2015 13:24:35 +0100 Subject: Fixed filename and grammatical error. --- sv-se/json-sv.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown index 8b76ebad..c2ee36dd 100644 --- a/sv-se/json-sv.html.markdown +++ b/sv-se/json-sv.html.markdown @@ -1,6 +1,6 @@ --- language: json -filename: learnjson.json +filename: learnjson-sv.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] @@ -30,7 +30,7 @@ C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa "stora tal": 1.2e+100, "objekt": { - "kommentar": "Det flesta datastukturerna i JSON kommer i form av objekt.", + "kommentar": "De flesta datastukturerna i JSON kommer i form av objekt.", "matris": [0, 1, 2, 3, "Matriser kan innehålla vad som helst.", 5], -- cgit v1.2.3 From fb4f346686e49658d3d74f6656b20138649cfedd Mon Sep 17 00:00:00 2001 From: we-build-dreams Date: Thu, 10 Dec 2015 12:21:21 +0000 Subject: Update elm.html.markdown only typos --- elm.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/elm.html.markdown b/elm.html.markdown index 8c191509..f8564c4b 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -76,13 +76,13 @@ snd ("elm", 42) -- 42 -- Records are like tuples but the fields have names. -- Notice that equals signs, not colons, are used. -{ x = 3, y = 7} +{ x = 3, y = 7 } -- Access a field with a dot and the field name. -{ x = 3, y = 7}.x -- 3 +{ x = 3, y = 7 }.x -- 3 -- Or with an accessor fuction, a dot and then the field name. -.y { x = 3, y = 7} -- 7 +.y { x = 3, y = 7 } -- 7 -- Update the fields of a record. (It must have the fields already.) { person | @@ -126,7 +126,7 @@ case List.head aList of multiply a b = a * b --- Apply (call) a function by passing it arguments (no commas necessay). +-- Apply (call) a function by passing it arguments (no commas necessary). multiply 7 6 -- 42 -- Partially apply a function by passing only some of its arguments. @@ -168,7 +168,7 @@ fib n = else fib (n - 1) + fib (n - 2) -List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34] +List.map fib [0..8] -- [1, 1, 2, 3, 5, 8, 13, 21, 34] listLength aList = case aList of -- cgit v1.2.3 From 38f2fb9a0bbd478bbbb4ccce0b33d1dcd34aa63a Mon Sep 17 00:00:00 2001 From: MichalMartinek Date: Thu, 10 Dec 2015 22:45:40 +0100 Subject: Update sass.html.markdown --- cs-cz/sass.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cs-cz/sass.html.markdown b/cs-cz/sass.html.markdown index e890debe..0d2fca64 100644 --- a/cs-cz/sass.html.markdown +++ b/cs-cz/sass.html.markdown @@ -1,12 +1,12 @@ --- language: sass -filename: learnsass.scss +filename: learnsass-cz.scss contributors: - ["Laura Kyle", "https://github.com/LauraNK"] - ["Sean Corrales", "https://github.com/droidenator"] translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] - +lang: cs-cz --- Sass je rozšíření jazyka CSS, který přidává nové vlastnosti jako proměnné, zanořování, mixiny a další. -- cgit v1.2.3 From 8bc9ebe08d792f560939db1e39077c800d15497b Mon Sep 17 00:00:00 2001 From: Mario Martinez Date: Fri, 11 Dec 2015 11:01:23 -0600 Subject: Updated to sdkman instead of GVM for installing groovy --- groovy.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index 8fb1b346..37e3b20c 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -13,8 +13,8 @@ Groovy - A dynamic language for the Java platform [Read more here.](http://groov /* Set yourself up: - 1) Install GVM - http://gvmtool.net/ - 2) Install Groovy: gvm install groovy + 1) Install SDKMAN - http://sdkman.io/ + 2) Install Groovy: sdk install groovy 3) Start the groovy console by typing: groovyConsole */ -- cgit v1.2.3 From 8d7085893535825ea6879e3f29ee0eb614a16f9b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Fri, 11 Dec 2015 13:07:01 -0500 Subject: Few minor fixes --- solidity.html.markdown | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 298b01f3..7f925918 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -5,9 +5,9 @@ contributors: - ["Nemil Dalal", "https://www.nemil.com"] --- -Solidity is a statically typed, contract programming language for [Ethereum](https://www.ethereum.org/) that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. +Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. -Solidity lets you program on Ethereum, a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. +Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. @@ -46,7 +46,7 @@ contract AcmeBank { owner = msg.sender; // msg.sender refers to the address of the contract creator } - function deposit(uint balance) public { + function deposit(uint balance) public returns (uint) { balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable return balances[msg.sender]; // msg.sender refers to the contract caller @@ -65,7 +65,7 @@ contract AcmeBank { } // The 'constant' prevents the function from editing state variables - function balance() constant { + function balance() constant returns (uint) { return balances[msg.sender]; } @@ -90,6 +90,7 @@ uint x; // int of 256 bits, cannot be changed after instantiation int constant a = 8; int256 constant a = 8; // same effect as line above, here the 256 is explicit +uint constant VERSION_ID = 0x123A1; // A hex constant // For both int and uint, you can explicitly set space in steps of 8 // e.g., int8, int16 @@ -285,12 +286,14 @@ Coin.Sent().watch({}, '', function(error, result) { // The '_' (underscore) must be included as the last line in the function body, and is an indicator that the // function being called should be placed there -modifier onlyBefore(uint _time) { if (now >= _time) throw; _ } +modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } +modifier onlyOwner { if (msg.sender == owner) _ } // You can then append it right after the function declaration function changeOwner(newOwner) - onlyBefore(someTime) - { +onlyAfter(someTime) +onlyOwner() +{ owner = newOwner; } @@ -298,7 +301,7 @@ function changeOwner(newOwner) // 5. BRANCHING AND LOOPS // All basic logic blocks work - including if/else, for, while, break, continue, return -// switch is not provided +// Unlike other languages, the 'switch' statement is NOT provided // Syntax is the same as javascript, but there is no type conversion from // non-boolean to boolean, so comparison operators must be used to get the boolean value @@ -377,7 +380,7 @@ if (!addr.send(123)) { // Suicide suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) -// This is a common pattern that lets the owner end the contract +// This is a common contract pattern that lets the owner end the contract, and receive remaining funds function remove() { if(msg.sender == owner) { // Only let the contract creator do this suicide(owner); // suicide makes this contract inactive, and returns funds to the owner @@ -391,7 +394,6 @@ function remove() { // planning your data structures) - // *** EXAMPLE: Let's do a more complex example *** // ** START EXAMPLE ** @@ -472,6 +474,7 @@ sha256("def"); - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) ## Sample contracts +- [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) - [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) -- cgit v1.2.3 From f854fe1111186a9b8ba36c8d6ed057461f376b35 Mon Sep 17 00:00:00 2001 From: Anton Pastukhoff Date: Sat, 12 Dec 2015 14:43:56 +0500 Subject: Update d-ru.html.markdown --- ru-ru/d-ru.html.markdown | 138 ++++++++++++++++++++++++++--------------------- 1 file changed, 78 insertions(+), 60 deletions(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index ecd6c44c..0a8726c9 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -1,16 +1,17 @@ ---- +/*--- language: d filename: learnd-ru.d contributors: - ["Anton Pastukhov", "http://dprogramming.ru/"] - ["Robert Brights-Gray", "http://lhs-blog.info/"] + - ["Andre Polykanine", "http://oire.me/"] lang: ru-ru --- D - современный компилируемый язык общего назначения с Си-подобным синтаксисом, который сочетает удобство, продуманный дизайн и высокую производительность. D - это С++, сделанный правильно. -```d +```d */ // Welcome to D! Это однострочный комментарий /* многострочный @@ -53,7 +54,7 @@ void main() int a; // объявление переменной типа int (32 бита) float b = 12.34; // тип с плавающей точкой -double с = 56.78; // тип с плавающей точкой (64 бита) +double c = 56.78; // тип с плавающей точкой (64 бита) /* Численные типы в D, за исключением типов с плавающей точкой и типов @@ -63,15 +64,17 @@ double с = 56.78; // тип с плавающей точкой (64 бита) uint d = 10; ulong e = 11; bool b = true; // логический тип char d = 'd'; // UTF-символ, 8 бит. D поддерживает UTF "из коробки" -wchar = 'é'; // символ UTF-16 +wchar e = 'é'; // символ UTF-16 dchar f; // и даже UTF-32, если он вам зачем-то понадобится string s = "для строк есть отдельный тип, это не просто массив char-ов из Си"; wstring ws = "поскольку у нас есть wchar, должен быть и wstring"; dstring ds = "...и dstring, конечно"; +string кириллица = "Имена переменных должны быть в Unicode, но не обязательно на латинице."; + typeof(a) b = 6; // typeof возвращает тип своего выражения. - // В результате, b имеет такой же тип как и a + // В результате, b имеет такой же тип, как и a // Тип переменной, помеченной ключевым словом auto, // присваивается компилятором исходя из значения этой переменной @@ -84,11 +87,11 @@ int[] arr2 = [1, 2, 3, 4]; // динамический массив int[string] aa = ["key1": 5, "key2": 6]; // ассоциативный массив /* - Cтроки и массивы в D — встроенные типы. Для их использования не нужно + Строки и массивы в D — встроенные типы. Для их использования не нужно подключать ни внешние, ни даже стандартную библиотеку, хотя в последней есть множество дополнительных инструментов для работы с ними. */ -immutalbe int ia = 10; // неизменяемый тип, +immutable int ia = 10; // неизменяемый тип, // обозначается ключевым словом immutable ia += 1; // — вызовет ошибку на этапе компиляции @@ -100,7 +103,7 @@ enum myConsts = { Const1, Const2, Const3 }; writeln("Имя типа : ", int.stringof); // int writeln("Размер в байтах : ", int.sizeof); // 4 writeln("Минимальное значение : ", int.min); // -2147483648 -writeln("Максимальное значениеe : ", int.max); // 2147483647 +writeln("Максимальное значение : ", int.max); // 2147483647 writeln("Начальное значение : ", int.init); // 0. Это значение, // присвоенное по умолчанию @@ -111,17 +114,13 @@ writeln("Начальное значение : ", int.init); // 0. Эт /*** Приведение типов ***/ -// Простейший вариант -int i; -double j = double(i) / 2; - // to!(имя типа)(выражение) - для большинства конверсий import std.conv : to; // функция "to" - часть стандартной библиотеки, а не языка double d = -1.75; short s = to!short(d); // s = -1 /* - cast - если вы знаете, что делаете. Кроме того, это единственный способ + cast - если вы знаете, что делаете. Кроме того, это единственный способ преобразования типов-указателей в "обычные" и наоборот */ void* v; @@ -129,7 +128,7 @@ int* p = cast(int*)v; // Для собственного удобства можно создавать псевдонимы // для различных встроенных объектов -alias int newInt; // теперь можно обращаться к int так, как будто бы это newInt +alias int newInt; // теперь можно обращаться к newInt так, как будто бы это int newInt a = 5; alias newInt = int; // так тоже допустимо @@ -203,6 +202,25 @@ switch (a) { break; } +// в D есть констукция "final switch". Она не может содержать секцию "defaul" +// и применяется, когда все перечисляемые в switch варианты должны быть +// обработаны явным образом + +int dieValue = 1; +final switch (dieValue) { + case 1: + writeln("You won"); + break; + + case 2, 3, 4, 5: + writeln("It's a draw"); + break; + + case 6: + writeln("I won"); + break; +} + // while while (a > 10) { // .. @@ -245,31 +263,33 @@ foreach (c; "hello") { foreach (number; 10..15) { writeln(number); // численные интервалы можно указывать явным образом + // этот цикл выведет значения с 10 по 15, но не 15, + // поскольку диапазон не включает в себя верхнюю границу } // foreach_reverse - в обратную сторону -auto container = [ 1, 2, 3 ]; +auto container = [1, 2, 3]; foreach_reverse (element; container) { writefln("%s ", element); // 3, 2, 1 } // foreach в массивах и им подобных структурах не меняет сами структуры -int[] a = [1,2,3,4,5]; +int[] a = [1, 2 ,3 ,4 ,5]; foreach (elem; array) { elem *= 2; // сам массив останется неизменным } -writeln(a); // вывод: [1,2,3,4,5] Т.е изменений нет +writeln(a); // вывод: [1, 2, 3, 4, 5] Т.е изменений нет // добавление ref приведет к тому, что массив будет изменяться foreach (ref elem; array) { - elem *= 2; // сам массив останется неизменным + elem *= 2; } -writeln(a); // [2,4,6,8,10] +writeln(a); // [2, 4, 6, 8, 10] -// foreach умеет расчитывать индексы элементов -int[] a = [1,2,3,4,5]; +// foreach умеет рассчитывать индексы элементов +int[] a = [1, 2, 3, 4, 5]; foreach (ind, elem; array) { writeln(ind, " ", elem); // через ind - доступен индекс элемента, // а через elem - сам элемент @@ -288,7 +308,7 @@ int test(int argument) { } -// В D используется унифицированныйй синтаксис вызова функций +// В D используется единый синтаксис вызова функций // (UFCS, Uniform Function Call Syntax), поэтому так тоже можно: int var = 42.test(); @@ -299,11 +319,11 @@ int var2 = 42.test; int var3 = 42.test.test; /* - Аргументы в функцию передаются по значению (т. е. функция работает не с + Аргументы в функцию передаются по значению (т.е. функция работает не с оригинальными значениями, переданными ей, а с их локальными копиями. Исключение составляют объекты классов, которые передаются по ссылке. Кроме того, любой параметр можно передать в функцию по ссылке с помощью - ключевого слова ref + ключевого слова "ref" */ int var = 10; @@ -318,7 +338,7 @@ void fn2(ref int arg) { fn1(var); // var все еще = 10 fn2(var); // теперь var = 11 -// Возвращаемое значение тоже может быть auto, +// Возвращаемое значение тоже может быть auto, // если его можно "угадать" из контекста auto add(int x, int y) { return x + y; @@ -373,13 +393,13 @@ printFloat(a); // использование таких функций - сам // без посредства глобальных переменных или массивов uint remMod(uint a, uint b, out uint modulus) { - uint remainder = a / b; + uint remainder = a / b; modulus = a % b; return remainder; } uint modulus; // пока в этой переменной ноль -uint rem = remMod(5,2,modulus); // наша "хитрая" функция, и теперь, +uint rem = remMod(5, 2, modulus); // наша "хитрая" функция, и теперь // в modulus - остаток от деления writeln(rem, " ", modulus); // вывод: 2 1 @@ -400,9 +420,9 @@ struct MyStruct { MyStruct str1; // Объявление переменной с типом MyStruct str1.a = 10; // Обращение к полю str1.b = 20; -auto result = str1.multiply(); -MyStruct str2 = {4, 8} // Объявление + инициальзация в стиле Си -auto str3 = MyStruct(5, 10); // Объявление + инициальзация в стиле D +auto result = str1.multiply(); +MyStruct str2 = {4, 8} // Объявление + инициализация в стиле Си +auto str3 = MyStruct(5, 10); // Объявление + инициализация в стиле D // области видимости полей и методов - 3 способа задания @@ -420,7 +440,7 @@ struct MyStruct2 { } /* в дополнение к знакомым public, private и protected, в D есть еще - область видимости "package". Поля и методы с этим атрибутам будут + область видимости "package". Поля и методы с этим атрибутом будут доступны изо всех модулей, включенных в "пакет" (package), но не за его пределами. package - это "папка", в которой может храниться несколько модулей. Например, в "import.std.stdio", "std" - это @@ -428,8 +448,8 @@ struct MyStruct2 { */ package: string d; - - /* помимо этого, имеется еще один модификатор - export, который позволяет + + /* помимо этого, имеется еще один модификатор - export, который позволяет использовать объявленный с ним идентификатор даже вне самой программы ! */ export: @@ -442,10 +462,10 @@ struct MyStruct3 { // в этом случае пустой конструктор добавляется компилятором writeln("Hello, world!"); } - - - // а вот это конструкция, одна из интересных идиом и представлет собой - // конструктор копирования, т.е конструктор возвращающий копию структуры. + + + // а вот это конструкция - одна из интересных идиом и представляет собой + // конструктор копирования, т.е конструктор, возвращающий копию структуры. // Работает только в структурах. this(this) { @@ -488,7 +508,7 @@ class Outer { int foo() { - return m; // можно обращаться к полям "родительского" класса + return m; // можно обращаться к полям "внешнего" класса } } } @@ -497,10 +517,10 @@ class Outer class Base { int a = 1; float b = 2.34; - - - // это статический метод, т.е метод который можно вызывать обращаясь - // классу напрямую, а не через создание экземпляра объекта + + + // это статический метод, т.е метод который можно вызывать, обращаясь + // к классу напрямую, а не через создание экземпляра объекта static void multiply(int x, int y) { writeln(x * y); @@ -511,13 +531,13 @@ Base.multiply(2, 5); // используем статический метод. class Derived : Base { string c = "Поле класса - наследника"; - - + + // override означает то, что наследник предоставит свою реализацию метода, // переопределив метод базового класса override static void multiply(int x, int y) { - super.multiply(x, y); // super - это ссылка на класс-предок или базовый класс + super.multiply(x, y); // super - это ссылка на класс-предок, или базовый класс writeln(x * y * 2); } } @@ -538,7 +558,7 @@ class Derived : FC { // это вызовет ошибку float b; } -// Абстрактный класс не можен быть истанциирован, но может иметь наследников +// Абстрактный класс не может быть истанциирован, но может иметь наследников abstract class AC { int a; } @@ -547,8 +567,8 @@ auto ac = new AC(); // это вызовет ошибку class Implementation : AC { float b; - - // final перед методом нефинального класса означает запрет возможности + + // final перед методом нефинального класса означает запрет возможности // переопределения метода final void test() { @@ -560,7 +580,7 @@ auto impl = new Implementation(); // ОК -/*** Микшины (mixins) ***/ +/*** Примеси (mixins) ***/ // В D можно вставлять код как строку, если эта строка известна на этапе // компиляции. Например: @@ -583,8 +603,8 @@ void main() { /*** Шаблоны ***/ /* - Шаблон функции. Эта функция принимает аргументы разеых типов, которые - подсталяются вместо T на этапе компиляции. "T" - это не специальный + Шаблон функции. Эта функция принимает аргументы разных типов, которые + подставляются вместо T на этапе компиляции. "T" - это не специальный символ, а просто буква. Вместо "T" может быть любое слово, кроме ключевого. */ void print(T)(T value) { @@ -633,8 +653,8 @@ class Stack(T) void main() { /* - восклицательный знак - признак шаблона В данном случае мы создаем - класс и указывем, что "шаблонное" поле будет иметь тип string + восклицательный знак - признак шаблона. В данном случае мы создаем + класс и указываем, что "шаблонное" поле будет иметь тип string */ auto stack = new Stack!string; @@ -660,9 +680,7 @@ void main() { несколько единообразных функций, определяющих, _как_ мы получаем доступ к элементам контейнера, вместо того, чтобы описывать внутреннее устройство этого контейнера. Сложно? На самом деле не очень. -*/ -/* Простейший вид диапазона - Input Range. Для того, чтобы превратить любой контейнер в Input Range, достаточно реализовать для него 3 метода: - empty - проверяет, пуст ли контейнер @@ -706,8 +724,8 @@ struct StudentRange void main(){ auto school = School([ - Student("Mike", 1), - Student("John", 2) , + Student("Mike", 1), + Student("John", 2) , Student("Dan", 3) ]); auto range = StudentRange(school); @@ -730,6 +748,6 @@ void main(){ ``` ## Что дальше? -[Официальный сайт](http://dlang.org/) -[Онлайн-книга](http://ddili.org/ders/d.en/) -[Официальная вики](http://wiki.dlang.org/) +- [Официальный сайт](http://dlang.org/) +- [Онлайн-книга](http://ddili.org/ders/d.en/) +- [Официальная вики](http://wiki.dlang.org/) -- cgit v1.2.3 From 5e6a0269b32bccca6872075dfd2b6be031236874 Mon Sep 17 00:00:00 2001 From: Anton Pastukhoff Date: Sat, 12 Dec 2015 14:44:12 +0500 Subject: Update d-ru.html.markdown --- ru-ru/d-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 0a8726c9..645eceeb 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -1,4 +1,4 @@ -/*--- +--- language: d filename: learnd-ru.d contributors: @@ -11,7 +11,7 @@ D - современный компилируемый язык общего на который сочетает удобство, продуманный дизайн и высокую производительность. D - это С++, сделанный правильно. -```d */ +```d // Welcome to D! Это однострочный комментарий /* многострочный -- cgit v1.2.3 From 3663b10bfab490e65f22a345e98d352ef93876e8 Mon Sep 17 00:00:00 2001 From: Anton Pastukhoff Date: Sat, 12 Dec 2015 14:46:10 +0500 Subject: Update d-ru.html.markdown --- ru-ru/d-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 645eceeb..fad5c69b 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -263,7 +263,7 @@ foreach (c; "hello") { foreach (number; 10..15) { writeln(number); // численные интервалы можно указывать явным образом - // этот цикл выведет значения с 10 по 15, но не 15, + // этот цикл выведет значения с 10 по 14, но не 15, // поскольку диапазон не включает в себя верхнюю границу } -- cgit v1.2.3 From 7b8929f0cc477fe5db4e189c4ce3d6a7fdbdc3fd Mon Sep 17 00:00:00 2001 From: Anton Pastukhoff Date: Sat, 12 Dec 2015 14:47:02 +0500 Subject: Update d-ru.html.markdown --- ru-ru/d-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index fad5c69b..8f4233fd 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -713,7 +713,7 @@ struct StudentRange return students.length == 0; } - ref Student front() { + Student front() { return students[0]; } -- cgit v1.2.3 From fd26c8ddfb6d4bfa969b323a2e98ce1b74bc8127 Mon Sep 17 00:00:00 2001 From: John Rocamora Date: Sat, 12 Dec 2015 17:51:23 -0500 Subject: Added missing semicolon --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 6b452b1b..f4aa2f5a 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -149,7 +149,7 @@ namespace First { namespace Second { void foo() { - printf("This is Second::foo\n") + printf("This is Second::foo\n"); } } -- cgit v1.2.3 From 4aca8f16dfec1a9341648b0ff1724ada01cdc2b0 Mon Sep 17 00:00:00 2001 From: Max Goldstein Date: Sun, 13 Dec 2015 13:29:50 -0500 Subject: [elm/en] Minor copyediting --- elm.html.markdown | 68 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/elm.html.markdown b/elm.html.markdown index 8c191509..67a0006d 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -38,11 +38,10 @@ not False -- True 1 < 10 -- True -- Strings and characters -"This is a string." -'a' -- character -'You cant use single quotes for strings.' -- error! +"This is a string because it uses double quotes." +'a' -- characters in single quotes --- Strings can be appended +-- Strings can be appended. "Hello " ++ "world!" -- "Hello world!" {-- Lists, Tuples, and Records --} @@ -53,10 +52,10 @@ not False -- True -- The second example can also be written with two dots. [1..5] --- Append lists just like strings +-- Append lists just like strings. [1..5] ++ [6..10] == [1..10] -- True --- To add one item, use "cons" +-- To add one item, use "cons". 0 :: [1..5] -- [0, 1, 2, 3, 4, 5] -- The head and tail of a list are returned as a Maybe. Instead of checking @@ -64,6 +63,7 @@ not False -- True List.head [1..5] -- Just 1 List.tail [1..5] -- Just [2, 3, 4, 5] List.head [] -- Nothing +-- List.functionName means the function lives in the List module. -- Every element in a tuple can be a different type, but a tuple has a -- fixed length. @@ -74,23 +74,24 @@ List.head [] -- Nothing fst ("elm", 42) -- "elm" snd ("elm", 42) -- 42 --- Records are like tuples but the fields have names. --- Notice that equals signs, not colons, are used. +-- Records are like tuples but the fields have names. The order of fields +-- doesn't matter. Notice that record values use equals signs, not colons. { x = 3, y = 7} -- Access a field with a dot and the field name. { x = 3, y = 7}.x -- 3 --- Or with an accessor fuction, a dot and then the field name. +-- Or with an accessor fuction, which is a dot and the field name on its own. .y { x = 3, y = 7} -- 7 -- Update the fields of a record. (It must have the fields already.) { person | name = "George" } -{ physics | - position = physics.position + physics.velocity, - velocity = physics.velocity + physics.acceleration } +-- Update multiple fields at once, using the current values. +{ particle | + position = particle.position + particle.velocity, + velocity = particle.velocity + particle.acceleration } {-- Control Flow --} @@ -111,11 +112,15 @@ else -- Use case statements to pattern match on different possibilities. 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 +-- Pattern matches go in order. If we put [x] last, it would never match because +-- x::xs also matches (xs would be the empty list). Matches do not "fall through". +-- Pattern match on a Maybe. case List.head aList of Just x -> "The head is " ++ toString x - Nothing -> "The list was empty" + Nothing -> "The list was empty." {-- Functions --} @@ -151,8 +156,8 @@ area (width, height) = area (6, 7) -- 42 --- Use curly brackets to pattern match record field names --- Use let to define intermediate values +-- Use curly brackets to pattern match record field names. +-- Use let to define intermediate values. volume {width, height, depth} = let area = width * height @@ -161,7 +166,7 @@ volume {width, height, depth} = volume { width = 3, height = 2, depth = 7 } -- 42 --- Functions can be recursive +-- Functions can be recursive. fib n = if n < 2 then 1 @@ -170,12 +175,13 @@ fib n = List.map fib [0..8] -- [1, 1, 2, 3, 5, 8,13, 21, 34] +-- Another recursive function (use List.length in real code). listLength aList = case aList of [] -> 0 x::xs -> 1 + listLength xs --- Function application happens before any infix operation +-- Function calls happen before any infix operator. Parens indicate precedence. cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 -- First degrees is applied to 30, then the result is passed to the trig -- functions, which is then squared, and the addition happens last. @@ -191,7 +197,7 @@ cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 True : Bool -- Functions have types too. Read -> as "goes to". Think of the rightmost type --- as the type of the return value. +-- as the type of the return value, and the others as arguments. not : Bool -> Bool round : Float -> Int @@ -226,7 +232,7 @@ type alias Point3D = { x : Float, y : Float, z : Float } otherOrigin : Point3D otherOrigin = Point3D 0 0 0 --- But it's still the same type, you can equate them +-- But it's still the same type, so you can equate them. origin == otherOrigin -- True -- By contrast, defining a union type creates a type that didn't exist before. @@ -236,14 +242,15 @@ type Direction = North | South | East | West -- Tags can carry other values of known type. This can work recursively. type IntTree = Leaf | Node Int IntTree IntTree - -- "Leaf" and "Node" are the tags. Everything following a tag is a type. + -- Tags can be used as values or functions. root : IntTree root = Node 7 Leaf Leaf -- Union types (and type aliases) can use type variables. type Tree a = Leaf | Node a (Tree a) (Tree a) +-- "The type tree of a is a leaf, or a node of a, tree of a, and tree of a." -- You can pattern match union tags. The uppercase tags must be matched exactly. -- The lowercase variables will match anything. Underscore also matches @@ -260,21 +267,20 @@ leftmostElement tree = {-- Modules and Imports --} --- The core libraries are organized into modulues, as are any third-party --- libraries you may use. For large projects, you can define your own modulues. +-- The core libraries are organized into modules, as are any third-party +-- libraries you may use. For large projects, you can define your own modules. -- Put this at the top of the file. If omitted, you're in Main. module Name where --- By default, everything is exported. --- Limit what values and types are exported -module Name (Type, value) where +-- By default, everything is exported. You can specify exports explicity. +module Name (MyType, myValue) where -- One common pattern is to export a union type but not its tags. This is known -- as an "opaque type", and is frequently used in libraries. --- Import code from other modules to use it in this one --- Places Dict in scope, so you can call Dict.insert +-- Import code from other modules to use it in this one. +-- Places Dict in scope, so you can call Dict.insert. import Dict -- Imports the Dict module and the Dict type, so your annotations don't have to @@ -318,6 +324,8 @@ $ elm repl -- Install a new package, and record it in elm-package.json. $ elm package install evancz/elm-html +-- See what changed between versions of a package. +$ elm package diff evancz/elm-html 3.0.0 4.0.2 -- Elm's package manager enforces semantic versioning, so minor version bumps -- will never break your build! ``` @@ -335,12 +343,14 @@ Here are some useful resources. * Documentation for [Elm's core libraries](http://package.elm-lang.org/packages/elm-lang/core/latest/). Take note of: * [Basics](http://package.elm-lang.org/packages/elm-lang/core/latest/Basics), which is imported by default - * Data structures like [Array](http://package.elm-lang.org/packages/elm-lang/core/latest/Array), [Dict](http://package.elm-lang.org/packages/elm-lang/core/latest/Dict), and [Set](http://package.elm-lang.org/packages/elm-lang/core/latest/Set) + * [Maybe](http://package.elm-lang.org/packages/elm-lang/core/latest/Maybe) and its cousin [Result](http://package.elm-lang.org/packages/elm-lang/core/latest/Result), commonly used for missing values or error handling + * Data structures like [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), and [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) and [decoding](http://package.elm-lang.org/packages/elm-lang/core/latest/Json-Decode) -* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay with examples on how to organize code into components. +* [The Elm Architecture](https://github.com/evancz/elm-architecture-tutorial#the-elm-architecture). An essay by Elm's creator with examples on how to organize code into components. * The [Elm mailing list](https://groups.google.com/forum/#!forum/elm-discuss). Everyone is friendly and helpful. +* [Scope in Elm](https://github.com/elm-guides/elm-for-js/blob/master/Scope.md#scope-in-elm) and [How to Read a Type Annotation](https://github.com/elm-guides/elm-for-js/blob/master/How%20to%20Read%20a%20Type%20Annotation.md#how-to-read-a-type-annotation). More community guides on the basics of Elm, written for JavaScript developers. Go out and write some Elm! -- cgit v1.2.3 From 0b8a0526249264c7ac34069adf3159f2b72771a8 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 18:03:47 -0500 Subject: Add info on references, modules, and objects These topics are central to modern usage of Perl. --- perl.html.markdown | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 125 insertions(+), 7 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 1b86f410..85f3974e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -5,6 +5,7 @@ language: perl filename: learnperl.pl contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Dan Book", "http://github.com/Grinnz"] --- Perl 5 is a highly capable, feature-rich programming language with over 25 years of development. @@ -14,7 +15,6 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a number sign. - #### Perl variable types # Variables begin with a sigil, which is a symbol showing the type. @@ -37,7 +37,9 @@ my @animals = ("camel", "llama", "owl"); my @numbers = (23, 42, 69); my @mixed = ("camel", 42, 1.23); - +# Array elements are accessed using square brackets, with a $ to indicate +# one value will be returned. +my $second = $animals[1]; ## Hashes # A hash represents a set of key/value pairs: @@ -50,11 +52,39 @@ my %fruit_color = ( apple => "red", banana => "yellow", ); + +# Hash elements are accessed using curly braces, again with the $ sigil. +my $color = $fruit_color{apple}; + # Scalars, arrays and hashes are documented more fully in perldata. # (perldoc perldata). -# More complex data types can be constructed using references, which allow you -# to build lists and hashes within lists and hashes. +#### References + +# More complex data types can be constructed using references, which allow +# you to build arrays and hashes within arrays and hashes. + +my $array_ref = \@array; +my $hash_ref = \%hash; +my @array_of_arrays = (\@array1, \@array2, \@array3); + +# You can also create anonymous arrays or hashes, returning a reference: + +my $fruits = ["apple", "banana"]; +my $colors = {apple => "red", banana => "yellow"}; + +# References can be dereferenced by prefixing the appropriate sigil. + +my @fruits_array = @$fruits; +my %colors_hash = %$colors; + +# As a shortcut, the arrow operator can be used to dereference and access a +# single value. + +my $first = $array_ref->[0]; +my $value = $hash_ref->{banana}; + +# See perlreftut and perlref for more in-depth documentation on references. #### Conditional and looping constructs @@ -105,6 +135,9 @@ for (@elements) { # the Perlish post-condition way again print for @elements; +# iterating through the keys and values of a referenced hash +print $hash_ref->{$_} for keys %$hash_ref; + #### Regular expressions # Perl's regular expression support is both broad and deep, and is the subject @@ -151,11 +184,96 @@ sub logger { # Now we can use the subroutine just as any other built-in function: logger("We have a logger subroutine!"); -``` -#### Using Perl modules +#### Modules + +# A module is a set of Perl code, usually subroutines, which can be used in +# other Perl code. It is usually stored in a file with the extension .pm so +# that Perl can find it. + +package MyModule; + +sub trim { + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + return $string; +} + +1; + +# From elsewhere: + +use MyModule; +MyModule::trim($string); + +# The Exporter module can help with making subroutines exportable, so they +# can be used like this: + +use MyModule 'trim'; +trim($string); + +# Many Perl modules can be downloaded from CPAN (http://www.cpan.org/) and +# provide a range of features to help you avoid reinventing the wheel. A +# number of popular modules like Exporter are included with the Perl +# distribution itself. See perlmod for more details on modules in Perl. + +#### Objects + +# Objects in Perl are just references that know which class (package) they +# belong to, so that methods (subroutines) called on it can be found there. +# The bless function is used in constructors (usually new) to set this up. +# However, you never need to call it yourself if you use a module like Moose +# or Moo (see below). + +package MyCounter; + +sub new { + my $class = shift; + my $self = {count => 0}; + return bless $self, $class; +} + +sub count { + my $self = shift; + return $self->{count}; +} + +sub increment { + my $self = shift; + $self->{count}++; +} + +1; + +# Methods can be called on a class or object instance with the arrow operator. + +my $counter = MyCounter->new; +print $counter->count, "\n"; # 0 +$counter->increment; +print $counter->count, "\n"; # 1 + +# The modules Moose and Moo from CPAN can help you set up your object classes. +# They provide a constructor and simple syntax for declaring attributes. This +# class can be used equivalently to the one above. + +package MyCounter; +use Moo; + +has 'count' => (is => 'rwp', default => 0, init_arg => undef); + +sub increment { + my $self = shift; + $self->_set_count($self->count + 1); +} + +1; + +# Object-oriented programming is covered more thoroughly in perlootut, and its +# low-level implementation in Perl is covered in perlobj. +``` -Perl modules provide a range of features to help you avoid reinventing the wheel, and can be downloaded from CPAN (http://www.cpan.org/). A number of popular modules are included with the Perl distribution itself. +#### FAQ perlfaq contains questions and answers related to many common tasks, and often provides suggestions for good CPAN modules to use. -- cgit v1.2.3 From 35b3c490ce06fb94b8b51bd7f5ceb1638401fb1a Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:22:29 -0500 Subject: Add blurb about strict and warnings --- perl.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/perl.html.markdown b/perl.html.markdown index 85f3974e..ab71a6ab 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -15,6 +15,16 @@ Perl 5 runs on over 100 platforms from portables to mainframes and is suitable f ```perl # Single line comments start with a number sign. +#### Strict and warnings + +use strict; +use warnings; + +# All perl scripts and modules should include these lines. Strict causes +# compilation to fail in cases like misspelled variable names, and warnings +# will print warning messages in case of common pitfalls like concatenating +# to an undefined value. + #### Perl variable types # Variables begin with a sigil, which is a symbol showing the type. -- cgit v1.2.3 From 88af462c699b9f48310a9624bb6bbe94b7101af1 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:39:37 -0500 Subject: use strict and warnings in example modules --- perl.html.markdown | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/perl.html.markdown b/perl.html.markdown index ab71a6ab..d919e00e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -202,6 +202,8 @@ logger("We have a logger subroutine!"); # that Perl can find it. package MyModule; +use strict; +use warnings; sub trim { my $string = shift; @@ -237,6 +239,8 @@ trim($string); # or Moo (see below). package MyCounter; +use strict; +use warnings; sub new { my $class = shift; @@ -268,7 +272,7 @@ print $counter->count, "\n"; # 1 # class can be used equivalently to the one above. package MyCounter; -use Moo; +use Moo; # imports strict and warnings has 'count' => (is => 'rwp', default => 0, init_arg => undef); -- cgit v1.2.3 From 16d879d712878e2d1aa262dc1218b6543aec99c9 Mon Sep 17 00:00:00 2001 From: Dan Book Date: Sun, 13 Dec 2015 19:51:57 -0500 Subject: add missing use line --- perl.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/perl.html.markdown b/perl.html.markdown index d919e00e..61e8cd0e 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -262,6 +262,7 @@ sub increment { # Methods can be called on a class or object instance with the arrow operator. +use MyCounter; my $counter = MyCounter->new; print $counter->count, "\n"; # 0 $counter->increment; -- cgit v1.2.3 From 16cc4d464e135560c5d9f1495b6d9cd871e7182d Mon Sep 17 00:00:00 2001 From: Mark Green Date: Wed, 16 Dec 2015 16:47:32 +0000 Subject: Add a Factor tutorial --- factor.html | 182 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 factor.html diff --git a/factor.html b/factor.html new file mode 100644 index 00000000..a0726420 --- /dev/null +++ b/factor.html @@ -0,0 +1,182 @@ +--- +language: factor +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnfactor.factor +--- + +Factor is a modern stack-based language, based on Forth, created by Slava Pestov. + +Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. + +``` +! This is a comment + +! Like Forth, all programming is done by manipulating the stack. +! Stating a literal value pushes it onto the stack. +5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode + +! Those numbers get added to the stack, from left to right. +! .s prints out the stack non-destructively. +.s ! 5 2 3 56 76 23 65 + +! Arithmetic works by manipulating data on the stack. +5 4 + ! No output + +! `.` pops the top result from the stack and prints it. +. ! 9 + +! More examples of arithmetic: +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 + +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 + +! A number of words are provided to manipulate the stack, collectively known as shuffle words. + +3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 +2 5 swap / ! swap the top with the second element: 5 / 2 +4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 +1 2 3 nip .s ! remove the second item (similar to drop): 1 3 +1 2 clear .s ! wipe out the entire stack +1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 +1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 + +! Creating Words +! The `:` word sets Factor into compile mode until it sees the `;` word. +: square ( n -- n ) dup * ; ! No output +5 square . ! 25 + +! We can view what a word does too. +! \ suppresses evaluation of a word and pushes its identifier on the stack instead. +\ square see ! : square ( n -- n ) dup * ; + +! After the name of the word to create, the declaration between brackets gives the stack effect. +! We can use whatever names we like inside the declaration: +: weirdsquare ( camel -- llama ) dup * ; + +! Provided their count matches the word's stack effect: +: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong +: doubledup ( a -- a a a ) dup dup ; ! Ok +: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok + +! Where Factor differs from Forth is in the use of quotations. +! A quotation is a block of code that is pushed on the stack as a value. +! [ starts quotation mode; ] ends it. +[ 2 + ] ! Quotation that adds 2 is left on the stack +4 swap call . ! 6 + +! And thus, higher order words. TONS of higher order words. +2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3 +3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4 +1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4 +4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 ) +1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values +2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack + +! Conditionals +! Any value is true except the built-in value f. +! A built-in value t does exist, but its use isn't essential. +! Conditionals are higher order words as with the combinators above. + +5 [ "Five is true" . ] when ! Five is true +0 [ "Zero is true" . ] when ! Zero is true +f [ "F is true" . ] when ! No output +f [ "F is false" . ] unless ! F is false +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true + +! By default the conditionals consume the value under test, but starred variants +! leave it alone if it's true: + +5 [ . ] when* ! 5 +f [ . ] when* ! No output, empty stack, f is consumed because it's false + + +! Loops +! You've guessed it.. these are higher order words too. + +5 [ . ] each-integer ! 0 1 2 3 4 +4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 +5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello + +! Here's a list: +{ 2 4 6 8 } ! Goes on the stack as one item + +! Loop through the list: +{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9 +{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack + +! Loop reducing or building lists: +{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } +{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 +1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } +1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } + +! If all else fails, a general purpose while loop: +1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times + ! Yes, it's hard to read + ! That's what all those variant loops are for + +! Variables +! Usually Factor programs are expected to keep all data on the stack. +! Using named variables makes refactoring harder (and it's called Factor for a reason) +! Global variables, if you must: + +SYMBOL: name ! Creates name as an identifying word +"Bob" name set-global ! No output +name get-global . ! "Bob" + +! Named local variables are considered an extension but are available +! In a quotation.. +[| m n ! Quotation captures top two stack values into m and n + | m n + ] ! Read them + +! Or in a word.. +:: lword ( -- ) ! Note double colon to invoke lexical variable extension + 2 :> c ! Declares immutable variable c to hold 2 + c . ; ! Print it out + +! In a word declared this way, the input side of the stack declaration +! becomes meaningful and gives the variable names stack values are captured into +:: double ( a -- result ) a 2 * ; + +! Variables are declared mutable by ending their name with a shriek +:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a + a ! Push a + a 2 * a! ! Multiply a by 2 and store result back in a + a ; ! Push new value of a +5 mword2 ! Stack: 5 10 + +! Lists and Sequences +! We saw above how to push a list onto the stack + +0 { 1 2 3 4 } nth ! Access a particular member of a list: 1 +10 { 1 2 3 4 } nth ! Error: sequence index out of bounds +1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2 +10 { 1 2 3 4 } ?nth ! No error if out of bounds: f + +{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } +{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } +"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } +"Concat" "enate" append ! "Concatenate" - strings are sequences too +"Concatenate" "Reverse " prepend ! "Reverse Concatenate" +{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" + +! And if you want to get meta, quotations are sequences and can be dismantled.. +0 [ 2 + ] nth ! 2 +1 [ 2 + ] nth ! + +[ 2 + ] \ - suffix ! Quotation [ 2 + - ] + + +``` + +##Ready For More? + +* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html) -- cgit v1.2.3 From b19714080a8ac76c027851e9b4c80372def81f7b Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Thu, 17 Dec 2015 01:48:19 +0800 Subject: Fix some typo and non-fluency. --- zh-tw/python-tw.html.markdown | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index 472b39ab..f8602769 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -69,11 +69,11 @@ from __future__ import division # 指數 (x的y次方) 2**4 # => 16 -# 括號即先乘除後加減 +# 用括號改變運算順序 (1 + 3) * 2 # => 8 # 布林運算 -# 注意 "and" 和 "or" 的大小寫 +# 注意 "and" 和 "or" 要用小寫 True and False #=> False False or True #=> True @@ -178,7 +178,7 @@ some_var = 5 # 方便好用 lower_case_with_underscores some_var # => 5 -# 存取沒有被賦值的變數會造成例外 +# 對沒有被賦值的變數取值會造成例外 # 請參考錯誤流程部分做例外處理 some_other_var # 造成 NameError @@ -191,15 +191,15 @@ li = [] # 你可以預先填好串列內容 other_li = [4, 5, 6] -# 用append()在串列後新增東西 append +# 用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 and li is now [1, 2, 4] +li.pop() # => 3 ,此時 li 內容為 [1, 2, 4] # 然後再塞回去 -li.append(3) # li is now [1, 2, 4, 3] again. +li.append(3) # 此時 li 內容再次為 [1, 2, 4, 3] # 你可以像存取陣列一樣的存取串列 li[0] # => 1 @@ -272,7 +272,7 @@ d, e, f = 4, 5, 6 # 也可以不寫括號 # 如果不加括號,預設會產生tuple g = 4, 5, 6 # => (4, 5, 6) # 你看,交換兩個值很簡單吧 -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e # 此時 d 的值為 5 且 e 的值為 4 # 字典(Dictionary)用來儲存映射關係 @@ -289,7 +289,7 @@ filled_dict.keys() # => ["three", "two", "one"] # 你的執行結果可能與上面不同 # 譯註: 只能保證所有的key都有出現,但不保證順序 -# 用 "valuess()" 將所有的Value輸出到一個List中 +# 用 "values()" 將所有的Value輸出到一個List中 filled_dict.values() # => [3, 2, 1] # 註: 同上,不保證順序 @@ -457,16 +457,14 @@ add(5, 6) # => 輸出 "x is 5 and y is 6" 並回傳 11 add(y=6, x=5) # 這種狀況下,兩個參數的順序並不影響執行 -# 你可以定義接受多個變數的函式,這些變數是按照順序排序的 -# 如果不加*的話會被解讀為tuple +# 你可以定義接受多個變數的函式,用*來表示參數tuple def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) -# 你可以定義接受多個變數的函式,這些變數是按照keyword排序的 -# 如果不加**的話會被解讀為dictionary +# 你可以定義接受多個變數的函式,用**來表示參數dictionary def keyword_args(**kwargs): return kwargs @@ -555,6 +553,7 @@ class Human(object): # 注意前後的雙底線代表物件 # 還有被python用,但實際上是在使用者控制的命名 # 空間內的參數。你不應該自己宣告這樣的名稱。 + # 注意前後的雙底線代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 def __init__(self, name): # 將函式引入的參數 name 指定給實體的 name 參數 self.name = name -- cgit v1.2.3 From 4b4024b49581d0f80aa3ce815b726bac1af99ef7 Mon Sep 17 00:00:00 2001 From: Hinet60613 Date: Thu, 17 Dec 2015 01:51:19 +0800 Subject: Fix typo --- zh-tw/python-tw.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/zh-tw/python-tw.html.markdown b/zh-tw/python-tw.html.markdown index f8602769..553181d8 100644 --- a/zh-tw/python-tw.html.markdown +++ b/zh-tw/python-tw.html.markdown @@ -550,10 +550,8 @@ class Human(object): species = "H. sapiens" # 基礎建構函式,當class被實體化的時候會被呼叫 - # 注意前後的雙底線代表物件 - # 還有被python用,但實際上是在使用者控制的命名 - # 空間內的參數。你不應該自己宣告這樣的名稱。 - # 注意前後的雙底線代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 + # 注意前後的雙底線 + # 代表此物件或屬性雖然在使用者控制的命名空間內,但是被python使用 def __init__(self, name): # 將函式引入的參數 name 指定給實體的 name 參數 self.name = name -- cgit v1.2.3 From 299d064ecf7598144e49ef336e0abd00ccc4ae16 Mon Sep 17 00:00:00 2001 From: sarthfrey Date: Wed, 16 Dec 2015 16:41:07 -0500 Subject: Added Python Resources --- python.html.markdown | 1 + python3.html.markdown | 1 + 2 files changed, 2 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index d8f18e9b..1d6c0a19 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -726,6 +726,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) ### Dead Tree diff --git a/python3.html.markdown b/python3.html.markdown index 8cc03320..f8c22047 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -780,6 +780,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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/) ### Dead Tree -- cgit v1.2.3 From da5ace143bd2a1fdfb73d8d56774968c787a7ae2 Mon Sep 17 00:00:00 2001 From: Max Goldstein Date: Wed, 16 Dec 2015 19:55:33 -0500 Subject: Mention unit; line breaks for style --- elm.html.markdown | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/elm.html.markdown b/elm.html.markdown index f395e85b..944ab770 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -74,6 +74,10 @@ List.head [] -- Nothing fst ("elm", 42) -- "elm" snd ("elm", 42) -- 42 +-- The empty tuple, or "unit", is sometimes used as a placeholder. +-- It is the only value of its type, also called "Unit". +() + -- Records are like tuples but the fields have names. The order of fields -- doesn't matter. Notice that record values use equals signs, not colons. { x = 3, y = 7 } @@ -116,6 +120,7 @@ case aList of x::xs -> "matches a list of at least one item whose head is " ++ toString x -- Pattern matches go in order. If we put [x] last, it would never match because -- x::xs also matches (xs would be the empty list). Matches do not "fall through". +-- The compiler will alert you to missing or extra cases. -- Pattern match on a Maybe. case List.head aList of @@ -226,11 +231,13 @@ origin = { x = 0, y = 0, z = 0 } -- You can give existing types a nice name with a type alias. -type alias Point3D = { x : Float, y : Float, z : Float } +type alias Point3D = + { x : Float, y : Float, z : Float } -- If you alias a record, you can use the name as a constructor function. otherOrigin : Point3D -otherOrigin = Point3D 0 0 0 +otherOrigin = + Point3D 0 0 0 -- But it's still the same type, so you can equate them. origin == otherOrigin -- True @@ -238,23 +245,27 @@ origin == otherOrigin -- True -- By contrast, defining a union type creates a type that didn't exist before. -- A union type is so called because it can be one of many possibilities. -- Each of the possibilities is represented as a "tag". -type Direction = North | South | East | West +type Direction = + North | South | East | West -- Tags can carry other values of known type. This can work recursively. -type IntTree = Leaf | Node Int IntTree IntTree +type IntTree = + Leaf | Node Int IntTree IntTree -- "Leaf" and "Node" are the tags. Everything following a tag is a type. -- Tags can be used as values or functions. root : IntTree -root = Node 7 Leaf Leaf +root = + Node 7 Leaf Leaf -- Union types (and type aliases) can use type variables. -type Tree a = Leaf | Node a (Tree a) (Tree a) --- "The type tree of a is a leaf, or a node of a, tree of a, and tree of a." +type Tree a = + Leaf | Node a (Tree a) (Tree a) +-- "The type tree-of-a is a leaf, or a node of a, tree-of-a, and tree-of-a." --- You can pattern match union tags. The uppercase tags must be matched exactly. --- The lowercase variables will match anything. Underscore also matches --- anything, but signifies that you aren't using it. +-- Pattern match union tags. The uppercase tags will be matched exactly. The +-- lowercase variables will match anything. Underscore also matches anything, +-- but signifies that you aren't using it. leftmostElement : Tree a -> Maybe a leftmostElement tree = case tree of -- cgit v1.2.3 From ecf5050e07747f4cc33a57ea11513a7ab3f66285 Mon Sep 17 00:00:00 2001 From: Chris Warrick Date: Thu, 17 Dec 2015 16:54:53 +0100 Subject: Remove incorrect list indentation in perl-pl --- pl-pl/perl-pl.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown index 9e8ade5b..029ca006 100644 --- a/pl-pl/perl-pl.html.markdown +++ b/pl-pl/perl-pl.html.markdown @@ -163,7 +163,7 @@ z repozytorium CPAN do zrealizowania konkretnego zadania. #### Do doczytania - - [perl-tutorial](http://perl-tutorial.org/) - - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html) - - [perldoc](http://perldoc.perl.org/) - - wbudowane w Perla: `perldoc perlintro` \ No newline at end of file + - [perl-tutorial](http://perl-tutorial.org/) + - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - wbudowane w Perla: `perldoc perlintro` -- cgit v1.2.3 From 442479a3c87d41fe1abf6ad344bb8733ef924fc8 Mon Sep 17 00:00:00 2001 From: Ondrej Simek Date: Thu, 17 Dec 2015 21:30:03 +0100 Subject: [markdown/cz] Fix missing 'lang' in front matter --- cs-cz/markdown.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 637f0ab6..4cba38b4 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] filename: markdown.md +lang: cs-cz --- Markdown byl vytvořen Johnem Gruberem v roce 2004. Je zamýšlen jako lehce čitelná -- cgit v1.2.3 From d0527c0428698c325a55ee046d0897c4e70a6ccc Mon Sep 17 00:00:00 2001 From: Mark Green Date: Fri, 18 Dec 2015 01:17:08 +0000 Subject: Wolfram Language tutorial --- wolfram.md | 137 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 wolfram.md diff --git a/wolfram.md b/wolfram.md new file mode 100644 index 00000000..4514006d --- /dev/null +++ b/wolfram.md @@ -0,0 +1,137 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnwolfram.nb +--- + +The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. + +Wolfram Language has several interfaces: +* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. +* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic +* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend + +The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. + +``` +(* This is a comment *) + +(* In Mathematica instead of using these comments you can create a text cell + and annotate your code with nicely typeset text and images *) + +(* Typing an expression returns the result *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Function Call *) +(* Note, function names (and everything else) are case sensitive *) +Sin[Pi/2] (* 1 *) + +(* Alternate Syntaxes for Function Call with one parameter *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Every syntax in WL has some equivalent as a function call *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Using a variable for the first time defines it and makes it global *) +x = 5 (* 5 *) +x == 5 (* True, C-style assignment and equality testing *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *) +x (* 20 *) + +(* Because WL is based on a computer algebra system, *) +(* using undefined variables is fine, they just obstruct evaluation *) +cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *) +cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *) +% (* 15 + cow, % fetches the last return *) +% - cow (* 15, undefined variable cow cancelled out *) +moo = cow + 5 (* Beware, moo now holds an expression, not a number! *) + +(* Defining a function *) +Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS + And _ after x to indicate no pattern matching constraints *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *) +(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *) + +(* For imperative-style programming use ; to separate statements *) +(* Discards any output from LHS and runs RHS *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical + ;'s precedence is lower than := *) +MyFirst[] (* Hello World *) + +(* C-Style For Loop *) +PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Create an association *) +myHash[["Green"]] (* 2, use it *) +myHash[["Green"]] := 5 (* 5, update it *) +myHash[["Puce"]] := 3.5 (* 3.5, extend it *) +KeyDropFrom[myHash, "Green"] (* Wipes out key Green *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* And you can't do any demo of Wolfram without showing this off *) +Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2 + and allows y to be adjusted between 0-20 with a slider. + Only works on graphical frontends *) +``` + +##Ready For More? + +* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/) -- cgit v1.2.3 From dc97e779bce838ea4f1d1e51a20d78b253048406 Mon Sep 17 00:00:00 2001 From: Eric McCormick Date: Fri, 18 Dec 2015 09:35:15 -0600 Subject: replaced < and > in pre block the pre block was already inside a pre/code block in the rendered page, making it harder to read --- coldfusion.html.markdown | 50 +++++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index d49ad254..482612fe 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -233,40 +233,38 @@ ColdFusion started as a tag-based language. Almost all functionality is availabl Code for reference (Functions must return something to support IE) -
-<cfcomponent>
-	<cfset this.hello = "Hello" />
-	<cfset this.world = "world" />
-
-	<cffunction name="sayHello">
-		<cfreturn this.hello & ", " & this.world & "!" />
-	</cffunction>
+
+	
+	
+
+	
+		
+	
 	
-	<cffunction name="setHello">
-		<cfargument name="newHello" type="string" required="true" />
+	
+		
 		
-		<cfset this.hello = arguments.newHello />
+		
 		 
-		<cfreturn true />
-	</cffunction>
+		
+	
 	
-	<cffunction name="setWorld">
-		<cfargument name="newWorld" type="string" required="true" />
+	
+		
 		
-		<cfset this.world = arguments.newWorld />
+		
 		 
-		<cfreturn true />
-	</cffunction>
+		
+	
 	
-	<cffunction name="getHello">
-		<cfreturn this.hello />
-	</cffunction>
+	
+		
+	
 	
-	<cffunction name="getWorld">
-		<cfreturn this.world />
-	</cffunction>
-</cfcomponent>
-
+ + + + -- cgit v1.2.3 From e7d5e2878841aae872b293127f47e4a4d211475b Mon Sep 17 00:00:00 2001 From: Ale46 Date: Sat, 19 Dec 2015 17:09:57 +0100 Subject: fix typos/mistakes --- it-it/python-it.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/it-it/python-it.html.markdown b/it-it/python-it.html.markdown index 49bbab08..3a4099e7 100644 --- a/it-it/python-it.html.markdown +++ b/it-it/python-it.html.markdown @@ -44,7 +44,7 @@ Python 2.x. Per Python 3.x, dai un'occhiata a [Python 3 tutorial](http://learnxi # restituito in automatico il risultato intero. 5 / 2 # => 2 -# Per le divisioni con la virgbola abbiamo bisogno di parlare delle variabili floats. +# Per le divisioni con la virgola abbiamo bisogno di parlare delle variabili floats. 2.0 # Questo è un float 11.0 / 4.0 # => 2.75 ahhh...molto meglio @@ -118,7 +118,7 @@ not False # => True # Un nuovo modo per fomattare le stringhe è il metodo format. # Questo metodo è quello consigliato "{0} possono essere {1}".format("le stringhe", "formattate") -# Puoi usare della parole chiave se non vuoi contare +# Puoi usare delle parole chiave se non vuoi contare "{nome} vuole mangiare {cibo}".format(nome="Bob", cibo="lasagna") # None è un oggetto @@ -202,7 +202,7 @@ li[::-1] # => [3, 4, 2, 1] del li[2] # li è ora [1, 2, 3] # Puoi sommare le liste li + altra_li # => [1, 2, 3, 4, 5, 6] -# Nota: i valori per li ed _altri_li non sono modificati. +# Nota: i valori per li ed altra_li non sono modificati. # Concatena liste con "extend()" li.extend(altra_li) # Ora li è [1, 2, 3, 4, 5, 6] @@ -288,7 +288,7 @@ filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # Aggiungere elementi ad un set filled_set.add(5) # filled_set è ora {1, 2, 3, 4, 5} -# Fai interazioni su un set con & +# Fai intersezioni su un set con & other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} @@ -378,8 +378,8 @@ except IndexError as e: pass # Pass è solo una non-operazione. Solitamente vorrai fare un recupero. except (TypeError, NameError): pass # Eccezioni multiple possono essere gestite tutte insieme, se necessario. -else: # Optional clause to the try/except block. Must follow all except blocks - print "All good!" # Viene eseguita solo se il codice dentro try non genera eccezioni +else: # Clausola opzionale al blocco try/except. Deve seguire tutti i blocchi except + print "Tutto ok!" # Viene eseguita solo se il codice dentro try non genera eccezioni finally: # Eseguito sempre print "Possiamo liberare risorse qui" @@ -405,7 +405,7 @@ aggiungi(y=6, x=5) # Le parole chiave come argomenti possono arrivare in ogni # Puoi definire funzioni che accettano un numero variabile di argomenti posizionali -# che verranno interpretati come come tuple se non usi il * +# che verranno interpretati come tuple se non usi il * def varargs(*args): return args @@ -495,7 +495,7 @@ class Human(object): species = "H. sapiens" # Costruttore base, richiamato quando la classe viene inizializzata. - # Si noti che il doppio leading e l'underscore finali denotano oggetti + # Si noti che il doppio leading e gli underscore finali denotano oggetti # o attributi che sono usati da python ma che vivono nello spazio dei nome controllato # dall'utente. Non dovresti usare nomi di questo genere. def __init__(self, name): @@ -575,7 +575,7 @@ dir(math) ## 7. Avanzate #################################################### -# Generators help you make lazy code +# I generatori ti aiutano a fare codice pigro def double_numbers(iterable): for i in iterable: yield i + i @@ -611,7 +611,7 @@ def beg(target_function): def wrapper(*args, **kwargs): msg, say_please = target_function(*args, **kwargs) if say_please: - return "{} {}".format(msg, "Please! I am poor :(") + return "{} {}".format(msg, "Per favore! Sono povero :(") return msg return wrapper @@ -619,17 +619,17 @@ def beg(target_function): @beg def say(say_please=False): - msg = "Can you buy me a beer?" + msg = "Puoi comprarmi una birra?" 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 :( +print say() # Puoi comprarmi una birra? +print say(say_please=True) # Puoi comprarmi una birra? Per favore! Sono povero :( ``` -## Ready For More? +## Pronto per qualcosa di più? -### Free Online +### Gratis Online * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) @@ -640,7 +640,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) -### Dead Tree +### Libri cartacei * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 85e5817a6ad2a7643391da7e7cd8dcd6d6d91f9c Mon Sep 17 00:00:00 2001 From: JoaoGFarias Date: Sat, 19 Dec 2015 22:39:44 -0200 Subject: [AsymptoticNotation/PT-BR] Asymptotic Notation translation to PT-BR --- pt-br/asymptotic-notation-pt.html.markdown | 158 +++++++++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 pt-br/asymptotic-notation-pt.html.markdown diff --git a/pt-br/asymptotic-notation-pt.html.markdown b/pt-br/asymptotic-notation-pt.html.markdown new file mode 100644 index 00000000..c89fb622 --- /dev/null +++ b/pt-br/asymptotic-notation-pt.html.markdown @@ -0,0 +1,158 @@ +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["João Farias", "https://github.com/JoaoGFarias"] +--- + +# Notação Assintótica + +## O que é? + +Notação Assintótica é uma linguagem que nos permite analisar o tempo de execução + de um algoritmo através da indentificação de seu comportamento com o + crescimento da entrada oferecida. Isso também é conhecido como taxa de + crescimento do algoritmo. O algoritmo de repente torna-se lento quando o + tamanho da entrada cresce? O algoritmo mantém, em geral, seu tempo de execução + rápido mesmo com aumento da entrada? Notação Assintótica nos dá a habilidade de + responder estas questões. + +## Quais são as alternativas para responder a estas questões? + +Um modo seria contar o número de operações primitivas com diferentes tamanhos de + entrada. Apesar desta ser uma solução válida, o trabalho que ela requer, mesmo para algoritmos simples, não a justifica. + + Outro modo é fisicamente medir a quantidade de tempo que um algoritmo requer + para terminar com diferentes tamanhos de entrada. Entretanto, a precisão e + relatividade (tempo obtido seria relativo apenas à máquina onde ocorreu a + execução) deste método está limitado a variáveis de ambiente, como hardware, + poder de processamento, etc. + +## Tipos de Notação Assintótica + +Na primeira seção desse documento, descrevemos como Notação Assintótica identifica o comportamento de um algoritmo + a medida que o tamanho da entrada cresce. Imaginemos um algoritmo como uma função + *f*, *n* como o tamanho da entrada e *f(n)* sendo o tempo de execução. Então, + para dado algoritmo *f*, com entrada de tamanho *n*, você terá tempo de execução + *f(n)*. Isto resulta em um gráfico onde a coordernada Y é o tempo de execução +, a coordernada X representa o tamanho da entrada e os pontos representao o tempo +de execução para dado tamanho de entrada. + +Você pode representar a função, ou o algoritmo, com Notação Assintótica de várias +maneiras. Você pode representar um algoritmo nas formas de Melhor Caso, Pior Caso +ou Caso Médio. +A maneira mais comum de analisar um algoritmo é pelo Pior Caso. Você tipicamente +não avalia o melhor caso, porque essas condições não são atingidas com frequência. +Um bom exemplo disto seria em algoritmos de ordenação; especificamente, na adição +de elementos à árvores. O melhor caso na maioria de algoritmos pode ser de apenas +uma operação. Entretanto, na maioria dos casos, o elemento a ser adicionado terá +que percorrer a árvore de forma apropriada, o que pode causar a analise de um +ramo inteiro. +Este é o pior caso, e isto é o que você está se preparando. + +### Tipos de funções, limites e simplificação + +``` +Função Logarítmica - log n +Função Linear - an + b +Função Quadrática - an^2 + bn + c +Função Polinomial - an^z + . . . + an^2 + a*n^1 + a*n^0, onde *z* é uma constante +Função Exponencial - a^n, onde a é alguma constante +``` +Estas são as funções básicas de crescimento usadas em várias notações. A lista + começa com a de crescimento mais lento (logarítima, a de execução mais rápida) +e segue para a de crescimento mais rápido (exponencial, de execução mais lenta). +Repare que enquando *n*, a entrada, cresce, cada uma dessas funções cresce mais +rápido que quadrático, polinimial e exponencial, comparadas com logaritma e linear. + +Uma nota extremamente importante para notações é tentar usar os termos mais simples. +Isto significa descartar constantes e termos de ordem mais baixa, pois quando o +tamanho da entrada cresce para o infinito (limites matemáticos), os termos de ordem +mais baixa e constantes tornam-se irrelevantes. Por exemplo, se você tiver uma +constante muito grande, 2^9001, a simplificação não afeterá sua notação. + +Já que queremos as formas mais simples, mudemos nossa tabela um pouco... + +``` +Função Logarítmica - log n +Função Linear - n +Função Quadrática - n^2 +Função Polinomial - n^z, onde *z* é uma constante +Função Exponencial - a^n, onde *a* é uma constante +``` + +### Big-O + +Big-O, também escrita como O, é uma Notação Assintótica para o pior caso. Digamos +*f(n)* seja o tempo de exeução de um algoritmo e *g(n)) um tempo de complexidade +arbritário que você quer relacionar com seu algoritmo. *f(n)* é O(g(n)), se, para +quando constante real c (c > 0), *f(n)* <= *c g(n)* para todo tamanho de entrada +n (n > 0). + + +*Exemplo 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +`f(n)` é O(g(n))? + +`3 log n + 100` é O(log n)? + +Vejamos a definição de Big-O: + +``` +3log n + 100 <= c * log n +``` + +Há alguma constante c que satisfaça a definição para todo n? + +``` +3log n + 100 <= 150 * log n, n > 2 (Indefinido em n = 1) +``` + +Sim! A definição de Big-I for atentida, portante `f(n)` é `O(g(n))`. + +*Exemplo 2* + +``` +f(n) = 3*n^2 +g(n) = n +``` + +`f(n)` é O(g(n))? + +`3 * n^2` é O(n)? +Vejamos a definição de Big-O: + +``` +3 * n^2 <= c * n +``` + +Há alguma constante c que satisfaça a definição para todo n? + +Não, não há. `f(n)` não é O(g(n)). + +### Big-Omega +Big-Omega, também escrita como Ω, é uma Notação Assintótica para o melhor caso. + +`f(n)`é Ω(g(n)), se para qualquer constante real c (c > 0), `f(n)` é >= `c g(n)` para todo tamanho de entrada n (n > 0). + +Sinta-se livre para adicionar mais exemplos. Big-O é a notação primária usada para medir complexidade de algoritmos. + +### Notas Finais +É difícil manter esse tipo de tópico curto e você deveria ler os livros e artigos listados abaixo. Eles cobrem muito mais profundamente definições e exemplos. Mais x='Algoritms & Data Structures' virá; teremos um documento sobre analisar código em breve. + +## Livros + +* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Artigos Online + +* [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) +* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) -- cgit v1.2.3 From 7560ea819965604099a3ed1dbf4e2fa8919e929b Mon Sep 17 00:00:00 2001 From: George Gognadze Date: Thu, 24 Dec 2015 23:24:09 +0400 Subject: typo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit some type mistakes. It is: syntaxtically It should be: syntactically It is: iLoveC Better: ILoveC It is: passed to ≈the function It should be: passed to the function It is: error It should be: Error --- c.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 8226ddef..d92d2ee6 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -239,7 +239,7 @@ int main (int argc, char** argv) z = (e > f) ? e : f; // => 10 "if e > f return e, else return f." // Increment and decrement operators: - char *s = "iLoveC"; + char *s = "ILoveC"; int j = 0; s[j++]; // => "i". Returns the j-th item of s THEN increments value of j. j = 0; @@ -321,7 +321,7 @@ int main (int argc, char** argv) break; default: // if `some_integral_expression` didn't match any of the labels - fputs("error!\n", stderr); + fputs("Error!\n", stderr); exit(-1); break; } @@ -497,7 +497,7 @@ int add_two_ints(int x1, int x2) /* Functions are call by value. When a function is called, the arguments passed to -≈the function are copies of the original arguments (except arrays). Anything you +the function are copies of the original arguments (except arrays). Anything you do to the arguments in the function do not change the value of the original argument where the function was called. @@ -726,7 +726,7 @@ Header files are an important part of c as they allow for the connection of c source files and can simplify code and definitions by seperating them into seperate files. -Header files are syntaxtically similar to c source files but reside in ".h" +Header files are syntactically similar to c source files but reside in ".h" files. They can be included in your c source file by using the precompiler command #include "example.h", given that example.h exists in the same directory as the c file. -- cgit v1.2.3 From 5556d6e839796e06179afec99443bf0a63a23afa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leo=20B=C3=A4rring?= Date: Sat, 26 Dec 2015 20:15:51 +0100 Subject: changed code output to as stated in comments The comments state that Foo::Bar::inc in the package variable example should increase $Foo::Bar::n and then print it. This did not happen, as `say ++$n;` was placed outside the block of the sub Foo::Bar::inc. The commit puts `say ++$n;` inside the block of Foo::Bar::inc. --- perl6.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1829f964..1457999a 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -803,9 +803,8 @@ module Foo::Bar { my sub unavailable { # `my sub` is the default say "Can't access me from outside, I'm my !"; } + say ++$n; # increment the package variable and output its value } - - say ++$n; # lexically-scoped variables are still available } say $Foo::Bar::n; #=> 1 Foo::Bar::inc; #=> 2 -- cgit v1.2.3 From e31dc8b5a7937d25a681747d05b6227d63849c6d Mon Sep 17 00:00:00 2001 From: Owen Rodda Date: Sun, 27 Dec 2015 16:29:52 -0500 Subject: Fix #2040 --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1829f964..323bc0b3 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -103,7 +103,7 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` (Perl's "null"-like value) if I don't have + say "I might return `(Any)` (Perl's 'null'-like value) if I don't have an argument passed, or I'll return my argument"; $arg; } -- cgit v1.2.3 From 4a3538d60c156cf82598dfd06d2ae4f7e0c4404f Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Mon, 28 Dec 2015 21:43:09 +0530 Subject: Add different array declaration syntax --- julia.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/julia.html.markdown b/julia.html.markdown index ef3ea244..2810555e 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -151,12 +151,16 @@ a = Int64[] # => 0-element Int64 Array # 1-dimensional array literals can be written with comma-separated values. b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] +b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 # 2-dimentional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] +# Arrays of a particular Type +b = Int8[4, 5, 6] # => 3-element Int8 Array: [4, 5, 6] + # Add stuff to the end of a list with push! and append! push!(a,1) # => [1] push!(a,2) # => [1,2] -- cgit v1.2.3 From 6749790c8d08aa5aaa06fd0501fd6bdd012ee29b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 17:11:00 -0500 Subject: Many edits --- solidity.html.markdown | 739 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 499 insertions(+), 240 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7f925918..a6620986 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -5,134 +5,194 @@ contributors: - ["Nemil Dalal", "https://www.nemil.com"] --- -Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and computation of smart contracts, without needing centralized or trusted parties. +Solidity lets you program on [Ethereum](https://www.ethereum.org/), a +blockchain-based virtual machine that allows the creation and +computation of smart contracts, without needing centralized or trusted parties. -Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like an object in object-oriented languages, each contract contains state variables, functions, and common data types. Contract-specific features include modifier (guard) clauses, event notifiers, and custom variables. +Solidity is a statically typed, contract programming language that has +similarities to Javascript and C. Like objects in OOP, each contract contains +state variables, functions, and common data types. Contract-specific features +include modifier (guard) clauses, event notifiers for listeners, and custom +global variables. -As Solidity and Ethereum are under active development, experimental or beta features are explicitly marked, and subject to change. Pull requests welcome. +Some Ethereum contract examples include crowdfunding, voting, and blind auctions. + +As Solidity and Ethereum are under active development, experimental or beta +features are explicitly marked, and subject to change. Pull requests welcome. ```javascript -// Let's start with a simple Bank contract, before diving into to the key components of the language -// This bank has three main capabilities: -// - deposit -// - withdrawal -// - check balance +// First, a simple Bank contract +// Allows deposits, withdrawals, and balance checks -// ** START EXAMPLE ** -// Start with a Natspec comment (the three slashes) that can be used -// for documentation - and as descriptive data for UI elements -/// @title A simple deposit/withdrawal bank built on Bitcoin - -// All contracts are declared and named (in CamelCase) -// They are similar to 'class' in other languages (and allow capabilities like inheritance) -contract AcmeBank { - // Declare state variables outside a function, - // these are persistent throughout the life of the contract - - // a dictionary that maps addresses to balances - // the private means that other contracts can't see balances - // but the data is still available to all other parties on the - // blockchain +// simple_bank.sol (note .sol extension) +/* **** START EXAMPLE **** */ + +// Start with Natspec comment (the three slashes) +// used for documentation - and as descriptive data for UI elements/actions + +/// @title SimpleBank +/// @author nemild + +/* 'contract' has similarities to 'class' in other languages (class variables, +inheritance, etc.) */ +contract SimpleBank { // CamelCase + // Declare state variables outside function, persist through life of contract + + // dictionary that maps addresses to balances mapping (address => uint) private balances; - // the 'public' makes 'owner' externally readable by users or contracts - // (but not writeable) + // "private" means that other contracts can't directly query balances + // but data is still viewable to other parties on blockchain + address public owner; + // 'public' makes externally readable (not writeable) by users or contracts - // Constructor, can receive one or many variables here + // Events - publicize actions to external listeners + event DepositMade(address accountAddress, uint amount); + + // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { - // msg is a default variable that provides both the - // contract messager's address and amount - owner = msg.sender; // msg.sender refers to the address of the contract creator + // msg provides contract messager's address and amount + // msg.sender is contract caller (address of contract creator) + owner = msg.sender; } - function deposit(uint balance) public returns (uint) { - balances[msg.sender] += msg.value; // no need for "this." or "self." in front of the state variable + /// @notice Deposit ether into bank + /// @return The balance of the user after the deposit is made + function deposit() public returns (uint) { + balances[msg.sender] += msg.value; + // no "this." or "self." required with state variable + // all values initialized to 0 by default + + DepositMade(msg.sender, msg.value); // fire event - return balances[msg.sender]; // msg.sender refers to the contract caller + return balances[msg.sender]; } - function withdraw(uint withdrawAmount) public returns (uint remainingBalance) { - if(balances[msg.sender] >= withdrawAmount) { - balances[msg.sender] -= withdrawAmount; + /// @notice Withdraw ether from bank + /// @dev This does not return any excess ether sent to it + /// @param withdrawAmount amount you want to withdraw + /// @return The balance remaining for the user + function withdraw(uint withdrawAmount) public returns (uint remainingBal) { + if(balances[msg.sender] >= withdrawAmount) { + balances[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; + balances[msg.sender] += withdrawAmount; // to be safe } - return balances[msg.sender]; + return balances[msg.sender]; } } - // The 'constant' prevents the function from editing state variables + /// @notice Get balance + /// @return The balance of the user + // 'constant' prevents function from editing state variables; + // allows function to run locally/off blockchain function balance() constant returns (uint) { - return balances[msg.sender]; + return balances[msg.sender]; } - // Fallback function - // The fallback function is called if none of the other functions matches the given function identifier. - // Typically, called when invalid data is sent to the contract or ether without data. - // Added so that ether sent to this contract is reverted if the contract fails - // otherwise, the sender loses their money; you should add this in most contracts - function () { throw; } + // Fallback function - Called if other functions don't match call or + // sent ether without data + // Typically, called when invalid data is sent + // Added so ether sent to this contract is reverted if the contract fails + // otherwise, the sender's money is transferred to contract + function () { + throw; // throw reverts state to before call + } } // ** END EXAMPLE ** -// Now let's go through the basics of Solidity +// Now, the basics of Solidity // 1. DATA TYPES AND ASSOCIATED METHODS -// uint is the data type typically used for currency (there are no doubles -// or floats) and for dates +// uint used for currency amount (there are no doubles +// or floats) and for dates (in unix time) uint x; -// with 'constant', the compiler replaces each occurrence with the actual value // int of 256 bits, cannot be changed after instantiation int constant a = 8; + +// with 'constant', compiler replaces each occurrence with actual value int256 constant a = 8; // same effect as line above, here the 256 is explicit uint constant VERSION_ID = 0x123A1; // A hex constant -// For both int and uint, you can explicitly set space in steps of 8 -// e.g., int8, int16 +// Be careful that you don't overflow, and protect against attacks that do + +// For int and uint, can explicitly set space in steps of 8 up to 256 +// e.g., int8, int16, int24 uint8 b; int64 c; uint248 e; +// No random functions built in, use other contracts for randomness + // Type casting int x = int(b); bool b = true; // or do 'var b = true;' for inferred typing -// Addresses - holds 20 byte/160 bit Ethereum addresses to another contract -// ('Contract Account)') or person/external entity ('External Account') -address public owner; // Add 'public' field to indicate publicly/externally accessible, a getter is automatically created, but NOT a setter +// Addresses - holds 20 byte/160 bit Ethereum addresses +// No arithmetic allowed +address public owner; -// All addresses can be sent ether in the following way: +// Types of accounts: +// Contract account: address set on create (func of creator address, num transactions sent) +// External Account: (person/external entity): address created from public key + +// Add 'public' field to indicate publicly/externally accessible +// a getter is automatically created, but NOT a setter + +// All addresses can be sent ether owner.send(SOME_BALANCE); // returns false on failure -owner.balance; // the balance of the owner +if (owner.send) {} // typically wrap in 'if', as contract addresses have +// functions have executed on send and can fail + +// can override send by defining your own -// Bytes are provided from 1 to 32 +// Can check balance +owner.balance; // the balance of the owner (user or contract) + + +// Bytes available from 1 to 32 byte a; // byte is same as bytes1 -bytes32 b; +bytes2 b; +bytes32 c; + +// Dynamically sized bytes +bytes m; // A special array, same as byte[] array (but packed tightly) +// More expensive than byte1-byte32, so use those when possible -// Dynamically sized -bytes m; // A special array, same as byte[] (but packed tightly) // same as bytes, but does not allow length or index access (for now) -string n = 'hello'; +string n = "hello"; // stored in UTF8, note double quotes, not single +// string utility functions to be added in future +// prefer bytes32/bytes, as UTF8 uses more storage -// Type inference +// Type inferrence // var does inferred typing based on first assignment, // can't be used in functions parameters var a = true; -// there are edge cases where inference leads to a value being set (e.g., an uint 8) -// that is different from what the user wanted (uint16), so use carefully +// use carefully, inference may provide wrong type +// e.g., an int8, when a counter needs to be int16 + +// var can be used to assign function to variable +function a(uint x) returns (uint) { + return x * 2; +} +var f = a; +f(22); // call // by default, all values are set to 0 on instantiation // Delete can be called on most types -// (it does NOT destroy the value, but rather sets the value to 0 by assignment) +// (does NOT destroy value, but sets value to 0, the initial value) uint x = 5; -delete x; // x is now 0 + + +// Destructuring/Tuples +(x, y) = (2, 7); // assign/swap multiple value // 2. DATA STRUCTURES @@ -142,74 +202,97 @@ bytes32[] names; // dynamic array uint newLength = names.push("John"); // adding returns new length of the array // Length names.length; // get length -names.length = 1; // lengths can also be set, unlike many other languages +names.length = 1; // lengths can be set (for dynamic arrays in storage only) + +// multidimensional array +uint x[][5]; // arr with 5 dynamic array elements (opp order of most languages) // Dictionaries (any type to any other type) mapping (string => uint) public balances; -balances["john"] = 1; -console.log(balances[jill]); // is 0, all non-set key values return zeroes -// The 'public' lets you do the following from another contract -contractName.balances("john"); // returns 1 -// The 'public' keyword here created a getter (but not setter) that behaves like the following: +balances["charles"] = 1; +console.log(balances["ada"]); // is 0, all non-set key values return zeroes +// 'public' allows following from another contract +contractName.balances("claude"); // returns 1 +// 'public' created a getter (but not setter) like the following: function balances(address _account) returns (uint balance) { - return balances[_account]; + return balances[_account]; } +// Nested mappings +mapping (address => mapping (address => uint) balances) public custodians; + // To delete delete balances["John"]; -delete balances; // deletes all elements +delete balances; // sets all elements to 0 -// Unlike languages like Javascript, you cannot iterate through all elements in -// a map, without knowing the source keys +// Unlike other languages, CANNOT iterate through all elements in +// mapping, without knowing source keys - can build data structure +// on top to do this // Structs and enums - struct Bank { // note the capital - address owner; - uint balance; - } +struct Bank { + address owner; + uint balance; +} Bank b = Bank({ - owner: msg.sender, - balance: 5 + owner: msg.sender, + balance: 5 }); -delete b; // set all variables in struct to 0, except any mappings +// or +Bank c = Bank(msg.sender, 5); + +c.amount = 5; // set to new value +delete b; +// sets to initial value, set all variables in struct to 0, except mappings // Enums -enum State { Created, Locked, Inactive }; +enum State { Created, Locked, Inactive }; // often used for state machine State public state; // Declare variable from enum state = State.Created; // enums can be explicitly converted to ints +uint createdState = uint(State.Created); // 0 -// Data locations: Memory vs. storage - all complex types (arrays, structs) have a data location +// Data locations: Memory vs. storage vs. stack - all complex types (arrays, +// structs) have a data location // 'memory' does not persist, 'storage' does -// Default is 'storage' for local and state variables; 'memory' for function parameters +// Default is 'storage' for local and state variables; 'memory' for func params +// stack holds small local variables + +// for most types, can explicitly set which data location to use + +// 3. Simple operators +// Comparisons, bit operators and arithmetic operators are provided +// exponentiation: ** +// exclusive or: ^ +// bitwise negation: ~ -// 3. Variables of note + +// 4. Global Variables of note // ** this ** -this; // the address of the current contract -// 'balance' often used at the end of a contracts life to send the -// remaining balance to a party +this; // address of contract +// often used at end of contract life to send remaining balance to party this.balance; -this.someFunction(); // calls a function externally (via a message call, not via an internal jump) +this.someFunction(); // calls func externally via call, not via internal jump -// ** msg - The current message received by the contract ** ** -msg.sender; // address, The address of the sender -msg.value; // uint, The amount of gas provided to this contract in wei +// ** msg - Current message received by the contract ** ** +msg.sender; // address of sender +msg.value; // amount of gas provided to this contract in wei msg.data; // bytes, complete call data msg.gas; // remaining gas // ** tx - This transaction ** -tx.origin; // address, sender of the transaction -tx.gasprice; // uint, gas price of the transaction - -// ** block - Information about the current block ** -now // uint, current time, alias for block.timestamp -block.number; // uint, current block number -block.difficulty; // uint, current block difficulty -block.blockhash(1); // returns bytes32, only provides for most recent 256 blocks +tx.origin; // address of sender of the transaction +tx.gasprice; // gas price of the transaction + +// ** block - Information about current block ** +now // current time (approximately), alias for block.timestamp (uses Unix time) +block.number; // current block number +block.difficulty; // current block difficulty +block.blockhash(1); // returns bytes32, only works for most recent 256 blocks block.gasLimit(); -// ** storage - A persistent storage hash (does not need to be declared) ** +// ** storage - Persistent storage hash ** storage['abc'] = 'def'; // maps 256 bit words to 256 bit words @@ -217,55 +300,61 @@ storage['abc'] = 'def'; // maps 256 bit words to 256 bit words // A. Functions // Simple function function increment(uint x) returns (uint) { - x += 1; - return x; + x += 1; + return x; } -// Functions can return many arguments, and by specifying the returned arguments -// you don't need to explicitly return +// Functions can return many arguments, and by specifying returned arguments +// name don't need to explicitly return function increment(uint x, uint y) returns (uint x, uint y) { - x += 1; - y += 1; + x += 1; + y += 1; } -// This function would have been called like this, and assigned to a tuple +// Call previous functon uint (a,b) = increment(1,1); -// The 'constant' indicates and ensures that a function does not/cannot change the persistent variables -// Constant function execute locally, not on the blockchain +// 'constant' indicates that function does not/cannot change persistent vars +// Constant function execute locally, not on blockchain uint y; function increment(uint x) constant returns (uint x) { - x += 1; - y += 1; // this line would fail - // as y is a state variable, and can't be changed in a constant function + x += 1; + y += 1; // this line would fail + // y is a state variable, and can't be changed in a constant function } -// There are a few 'function visibility specifiers' that can be placed where 'constant' -// is, which include: -// internal (can only be called by an internal function, not one external to the contract) -// public - visible externally and internally +// 'Function Visibility specifiers' +// These can be placed where 'constant' is, including: +// public - visible externally and internally (default) +// external // private - only visible in the current contract +// internal - only visible in current contract, and those deriving from it -// Functions are hoisted (so you can call a function, even if it is declared later) - and you can assign a function to a variable +// Functions hoisted - and can assign a function to a variable function a() { - var z = b; - b(); + var z = b; + b(); } function b() { } + +// Prefer loops to recursion (max call stack depth is 1024) + // B. Events -// Events are an easy way to notify external listeners that something changed -// You typically declare them after your contract parameters -event Sent(address from, address to, uint amount); +// Events are notify external parties; easy to search and +// access events from outside blockchain (with lightweight clients) +// typically declare after contract parameters -// You then call it in a function, when you want to trigger it -sent(from, to, amount); +// Declare +event Sent(address from, address to, uint amount); // note capital first letter -// For an external party (a contract or external entity), to watch -// for an event, you write the following: +// Call +Sent(from, to, amount); + +// For an external party (a contract or external entity), to watch: Coin.Sent().watch({}, '', function(error, result) { if (!error) { console.log("Coin transfer: " + result.args.amount + @@ -276,195 +365,356 @@ Coin.Sent().watch({}, '', function(error, result) { "Receiver: " + Coin.balances.call(result.args.to)); } } -// This is a common paradigm for one contract to depend on another (e.g., a -// contract that depends on the current exchange rate provided by another -// contract) +// Common paradigm for one contract to depend on another (e.g., a +// contract that depends on current exchange rate provided by another) // C. Modifiers -// Modifiers let you validate inputs to functions such as a minimal balance or user authentication -// It's similar to a guard clause in other languages +// Modifiers validate inputs to functions such as minimal balance or user auth; +// similar to guard clause in other languages -// The '_' (underscore) must be included as the last line in the function body, and is an indicator that the +// '_' (underscore) often included as last line in body, and indicates // function being called should be placed there modifier onlyAfter(uint _time) { if (now <= _time) throw; _ } modifier onlyOwner { if (msg.sender == owner) _ } +// commonly used with state machines +modifier onlyIfState (State currState) { if (currState != State.A) _ } -// You can then append it right after the function declaration +// Append right after function declaration function changeOwner(newOwner) onlyAfter(someTime) onlyOwner() +onlyIfState(State.A) { - owner = newOwner; + owner = newOwner; } +// underscore can be included before end of body, +// but explicitly returning will skip, so use carefully +modifier checkValue(uint amount) { + _ + if (msg.value > amount) { + msg.sender.send(amount - msg.value); + } +} -// 5. BRANCHING AND LOOPS -// All basic logic blocks work - including if/else, for, while, break, continue, return -// Unlike other languages, the 'switch' statement is NOT provided +// 6. BRANCHING AND LOOPS -// Syntax is the same as javascript, but there is no type conversion from -// non-boolean to boolean, so comparison operators must be used to get the boolean value +// All basic logic blocks work - including if/else, for, while, break, continue +// return - but no switch +// Syntax same as javascript, but no type conversion from non-boolean +// to boolean (comparison operators must be used to get the boolean val) -// 6. OBJECTS/CONTRACTS -// A. Calling an external contract +// 7. OBJECTS/CONTRACTS + +// A. Calling external contract contract infoFeed { - function info() returns (uint ret) { return 42; } + function info() returns (uint ret) { return 42; } } contract Consumer { - InfoFeed feed; // create a variable that will point to a contract on the blockchain - - // Set feed to an existing contract - function setFeed(address addr) { - // Link to the contract by creating on the address - feed = InfoFeed(addr); - } - - // Set feed based to a new instance of the contract - function createNewFeed() { - feed = new InfoFeed(); - } - - function callFeed() { - // T final parentheses call the contract, optionally adding - // custom value or gas numbers - feed.info.value(10).gas(800)(); - } + InfoFeed feed; // points to contract on blockchain + + // Set feed to existing contract instance + function setFeed(address addr) { + // automatically cast, be careful; constructor is not called + feed = InfoFeed(addr); + } + + // Set feed to new instance of contract + function createNewFeed() { + feed = new InfoFeed(); // constructor called + } + + function callFeed() { + // final parentheses call contract, can optionally add + // custom ether value or gas + feed.info.value(10).gas(800)(); + } } // B. Inheritance -// Order matters, last inherited contract (i.e., 'def') can override parts of the previously -// inherited contracts -contact MyContract is abc, def("a custom argument to def") { +// Order matters, last inherited contract (i.e., 'def') can override parts of +// previously inherited contracts +contract MyContract is abc, def("a custom argument to def") { // Override function - - function z() { - if (msg.sender == owner) { - def.z(); // call overridden function + function z() { + if (msg.sender == owner) { + def.z(); // call overridden function from def + super.z(); // call immediate parent overriden function + } } - } +} - }; +// abstract function +function someAbstractFunction(uint x); +// cannot be compiled, so used in base/abstract contracts +// that are then implemented // C. Import import "filename"; import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; -// Importing is under active development and will change -// Importing cannot currently be done at the command line - - -// 7. CONTRACT DESIGN PATTERNS +// Importing under active development +// Cannot currently be done at command line -// A. Obfuscation -// Remember that all variables are publicly viewable on the blockchain, so -// anything that needs some privacy needs to be obfuscated (e.g., hashed) +// 8. OTHER KEYWORDS -// B. Throwing +// A. Throwing // Throwing -throw; // throwing is easily done, and reverts unused money to the sender -// You can't currently catch +throw; // reverts unused money to sender, state is reverted +// Can't currently catch -// A common design pattern is: +// Common design pattern is: if (!addr.send(123)) { - throw; + throw; } -// C. Suicide -// Suicide -suicide(SOME_ADDRESS); // suicide the current contract, sending funds to the address (often the creator) +// B. Selfdestruct +// selfdestruct current contract, sending funds to address (often creator) +selfdestruct(SOME_ADDRESS); + +// removes storage/code from current/future blocks +// helps thin clients, but previous data persists in blockchain -// This is a common contract pattern that lets the owner end the contract, and receive remaining funds +// Common pattern, lets owner end the contract and receive remaining funds function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } + if(msg.sender == creator) { // Only let the contract creator do this + selfdestruct(creator); // Makes contract inactive, returns funds + } } -// D. Storage optimization -// Reading and writing can be expensive, as data needs to be stored in the -// blockchain forever - this encourages smart ways to use memory (eventually, -// compilation may better handle this, but for now there are benefits to -// planning your data structures) +// May want to deactivate contract manually, rather than selfdestruct +// (ether sent to selfdestructed contract is lost) + + +// 9. CONTRACT DESIGN NOTES + +// A. Obfuscation +// Remember all variables are publicly viewable on blockchain, so +// anything that needs privacy needs to be obfuscated (e.g., hashed) + +// Steps: 1. Commit to something, 2. Reveal commitment +sha3("some_bid_amount", "some secret"); // commit + +// call contract's reveal function showing bid plus secret that hashes to SHA3 +reveal(100, "mySecret"); + +// B. Storage optimization +// Writing to blockchain can be expensive, as data stored forever encourages +// smart ways to use memory (eventually, compilation will be better, but for now +// benefits to planning data structures - and storing min amount in blockchain) + +// Cost can often be high for items like multidimensional arrays +// (cost is for storing data - not declaring unfilled variables) + +// C. Cannot restrict human or computer from reading contents of +// transaction or transaction's state + +// When 'private' specified, indicating that other *contracts* can't read +// the data directly - any other party can still read the data in blockchain +// D. All data to start of time is stored in blockchain, so +// anyone can observe all previous data and changes -// *** EXAMPLE: Let's do a more complex example *** +// E. Cron +// Contracts must be manually called to handle time-based scheduling; can create +// external code to do, or provide incentives (ether) for others to do for you +// F. State machines +// see example below for State enum and inState modifier + +// *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** // ** START EXAMPLE ** -// [TODO: Decide what a more complex example looks like, needs a few characteristics: -// - has a 'constant' state variable -// - has a state machine (and uses modifier) -// - sends money to an address -// - gets information from another contract (we'll show code for both contracts) -// - Shows inheritance -// - show variables being passed in on instantiation (and guard code to throw if variables not provided) -// - Shows the swapping out of a contract address -// Ideas: -// - crowdfunding? -// - Peer to peer insurance -// ] - // It's good practice to have a remove function, which disables this - // contract - but does mean that users have to trust the owner - // For a decentralized bank without a trusted part - function remove() { - if(msg.sender == owner) { // Only let the contract creator do this - suicide(owner); // suicide makes this contract inactive, and returns funds to the owner - } + +// CrowdFunder.sol + +/// @title CrowdFunder +/// @author nemild +contract CrowdFunder { + // Variables set on create by creator + address public creator; + address public fundRecipient; // creator may be different than recipient + uint public minimumToRaise; // required to tip, else everyone gets refund + string campaignUrl; + + // Data structures + enum State { + Fundraising, + ExpiredRefundPending, + Successful, + ExpiredRefundComplete + } + struct Contribution { + uint amount; + address contributor; } -// *** END EXAMPLE *** + // State variables + State public state = State.Fundraising; // initialize on create + uint public totalRaised; + uint public raiseBy; + Contribution[] contributions; + + event fundingReceived(address addr, uint amount, uint currentTotal); + event allRefundsSent(); + event winnerPaid(address winnerAddress); + + modifier inState(State _state) { + if (state != _state) throw; + _ + } -// 7. NATIVE FUNCTIONS + modifier isCreator() { + if (msg.sender != creator) throw; + _ + } + + modifier atEndOfLifecycle() { + if(state != State.ExpiredRefundComplete && state != State.Successful) { + throw; + } + } + + function CrowdFunder( + uint timeInHoursForFundraising, + string _campaignUrl, + address _fundRecipient, + uint _minimumToRaise) + { + creator = msg.sender; + fundRecipient = _fundRecipient; + campaignUrl = _campaignUrl; + minimumToRaise = _minimumToRaise; + raiseBy = now + (timeInHoursForFundraising * 1 hours); + } + + function contribute() + public + inState(State.Fundraising) + { + contributions.push( + Contribution({ + amount: msg.value, + contributor: msg.sender + }) // use array, so can iterate + ); + totalRaised += msg.value; + + fundingReceived(msg.sender, msg.value, totalRaised); + + checkIfFundingCompleteOrExpired(); + } + + function checkIfFundingCompleteOrExpired() { + if (totalRaised > minimumToRaise) { + state = State.Successful; + payOut(); + + // could incentivize sender who initiated state change here + } else if ( now > raiseBy ) { + state = State.ExpiredRefundPending; + refundAll(); + } + } + + function payOut() + public + inState(State.Successful) + { + if(!fundRecipient.send(this.balance)) { + throw; + } + + winnerPaid(fundRecipient); + } + + function refundAll() + public + inState(State.ExpiredRefundPending) + { + uint length = contributions.length; + for (uint i = 0; i < length; i++) { + if(!contributions[i].contributor.send(contributions[i].amount)) { + throw; + } + } + + allRefundsSent(); + state = State.ExpiredRefundComplete; + } + + function removeContract() + public + isCreator() + atEndOfLifecycle() + { + selfdestruct(msg.sender); + } + + function () { throw; } +} +// ** END EXAMPLE ** + +// 10. OTHER NATIVE FUNCTIONS // Currency units -// By default, currency is defined using wei, the smallest unit of Ether +// Currency is defined using wei, smallest unit of Ether uint minAmount = 1 wei; -uint a = 1 finney; // 1 ether = 1000 finney -// There are a number of other units, see: http://ether.fund/tool/converter +uint a = 1 finney; // 1 ether == 1000 finney +// Other units, see: http://ether.fund/tool/converter // Time units 1 == 1 second 1 minutes == 60 seconds - -// You typically multiply a variable times the unit, as these units are not -// directly stored in a variable +// Can multiply a variable times unit, as units are not stored in a variable uint x = 5; (x * 1 days); // 5 days -// Be careful about leap seconds and leap years when using equality statements for time (instead, prefer greater than/less than) +// Careful about leap seconds/years with equality statements for time +// (instead, prefer greater than/less than) // Cryptography -// All strings passed are concatenated before the hash is run +// All strings passed are concatenated before hash action sha3("ab", "cd"); ripemd160("abc"); sha256("def"); +11. LOW LEVEL FUNCTIONS +// call - low level, not often used, does not provide type safety +successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); -// 8. COMMON MISTAKES/MISCONCEPTIONS -// A few common mistakes and misconceptions: +// callcode - Code at target address executed in *context* of calling contract +// provides library functionality +someContractAddress.callcode('function_name'); -// A. You cannot restrict a human or computer from reading the content of -// your transaction or a transaction's state +// 12. STYLE NOTES +// Based on Python's PEP8 style guide -// All data to the start of time is stored in the blockchain, so you and -// anyone can observe all previous data stats +// 4 spaces for indentation +// Two lines separate contract declarations (and other top level declarations) +// Avoid extraneous spaces in parentheses +// Can omit curly braces for one line statement (if, for, etc) +// else should be placed on own line -// When you don't specify public on a variable, you are indicating that other *contracts* can't -// read the data - but any person can still read the data +// 13. NATSPEC comments - used for documentation, commenting, and external UIs +// Contract natspec - always above contract definition +/// @title Contract title +/// @author Author name -// TODO +// Function natspec +/// @notice information about what function does; shown when function to execute +/// @dev Function documentation for developer - -// 9. STYLE NOTES -// Use 4 spaces for indentation -// (Python's PEP8 is used as the baseline style guide, including its general philosophy) +// Function parameter/return value natspec +/// @param someParam Some description of what the param does +/// @return Description of the return value ``` ## Additional resources @@ -472,6 +722,8 @@ sha256("def"); - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) - [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) +- Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) @@ -481,5 +733,12 @@ sha256("def"); ## Information purposefully excluded - Libraries +- [Call keyword](http://solidity.readthedocs.org/en/latest/types.html) + +## Style +- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) + +## Future To Dos +- New keywords: protected, inheritable Feel free to send a pull request with any edits - or email nemild -/at-/ gmail -- cgit v1.2.3 From 8f9f9e53e825b346c49139769b8bbfd08d0bed4e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 17:13:20 -0500 Subject: Spacing --- solidity.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index a6620986..7de92fce 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -463,6 +463,7 @@ import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol"; // Importing under active development // Cannot currently be done at command line + // 8. OTHER KEYWORDS // A. Throwing @@ -529,6 +530,7 @@ reveal(100, "mySecret"); // F. State machines // see example below for State enum and inState modifier + // *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** // ** START EXAMPLE ** @@ -661,6 +663,7 @@ contract CrowdFunder { } // ** END EXAMPLE ** + // 10. OTHER NATIVE FUNCTIONS // Currency units @@ -686,7 +689,8 @@ sha3("ab", "cd"); ripemd160("abc"); sha256("def"); -11. LOW LEVEL FUNCTIONS + +// 11. LOW LEVEL FUNCTIONS // call - low level, not often used, does not provide type safety successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); @@ -694,6 +698,7 @@ successBoolean = someContractAddress.call('function_name', 'arg1', 'arg2'); // provides library functionality someContractAddress.callcode('function_name'); + // 12. STYLE NOTES // Based on Python's PEP8 style guide @@ -703,6 +708,7 @@ someContractAddress.callcode('function_name'); // Can omit curly braces for one line statement (if, for, etc) // else should be placed on own line + // 13. NATSPEC comments - used for documentation, commenting, and external UIs // Contract natspec - always above contract definition /// @title Contract title -- cgit v1.2.3 From 43138aef5cc6a89ec0c02db03cec61ab902acb97 Mon Sep 17 00:00:00 2001 From: ethers Date: Mon, 28 Dec 2015 16:36:48 -0800 Subject: fixes in withdraw() and msg --- solidity.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7de92fce..146d6e83 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -7,7 +7,7 @@ contributors: Solidity lets you program on [Ethereum](https://www.ethereum.org/), a blockchain-based virtual machine that allows the creation and -computation of smart contracts, without needing centralized or trusted parties. +execution of smart contracts, without needing centralized or trusted parties. Solidity is a statically typed, contract programming language that has similarities to Javascript and C. Like objects in OOP, each contract contains @@ -52,7 +52,7 @@ contract SimpleBank { // CamelCase // Constructor, can receive one or many variables here; only one allowed function AcmeBank() { - // msg provides contract messager's address and amount + // msg provides details about the message that's sent to the contract // msg.sender is contract caller (address of contract creator) owner = msg.sender; } @@ -77,12 +77,12 @@ contract SimpleBank { // CamelCase if(balances[msg.sender] >= withdrawAmount) { balances[msg.sender] -= withdrawAmount; - if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; // to be safe + if (!msg.sender.send(withdrawAmount)) { + balances[msg.sender] += withdrawAmount; // to be safe + } } - - return balances[msg.sender]; - } + + return balances[msg.sender]; } /// @notice Get balance @@ -277,7 +277,7 @@ this.someFunction(); // calls func externally via call, not via internal jump // ** msg - Current message received by the contract ** ** msg.sender; // address of sender -msg.value; // amount of gas provided to this contract in wei +msg.value; // amount of ether provided to this contract in wei msg.data; // bytes, complete call data msg.gas; // remaining gas -- cgit v1.2.3 From 65cba2b1f5405d53e498bfa96a0e407423dd9a4e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 21:53:37 -0500 Subject: Fixed mapping --- solidity.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 7de92fce..5b632c11 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -219,7 +219,7 @@ function balances(address _account) returns (uint balance) { } // Nested mappings -mapping (address => mapping (address => uint) balances) public custodians; +mapping (address => mapping (address => uint)) public custodians; // To delete delete balances["John"]; -- cgit v1.2.3 From ba3d5a6feb4a340c43b55b75516fed1d78fad9fb Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 21:58:31 -0500 Subject: Added Joseph Chow as contributor --- solidity.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 2d653bf9..b73ca0e5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -2,7 +2,8 @@ language: Solidity filename: learnSolidity.sol contributors: - - ["Nemil Dalal", "https://www.nemil.com"] + - ["Nemil Dalal", "https://www.nemil.com"] + - ["Joseph Chow", ""] --- Solidity lets you program on [Ethereum](https://www.ethereum.org/), a @@ -81,7 +82,7 @@ contract SimpleBank { // CamelCase balances[msg.sender] += withdrawAmount; // to be safe } } - + return balances[msg.sender]; } -- cgit v1.2.3 From 58ebc87f5f4114c3610633a7cd9c4264647b2448 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 22:29:19 -0500 Subject: Minor edits --- solidity.html.markdown | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index b73ca0e5..5946c1f5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -79,7 +79,9 @@ contract SimpleBank { // CamelCase balances[msg.sender] -= withdrawAmount; if (!msg.sender.send(withdrawAmount)) { - balances[msg.sender] += withdrawAmount; // to be safe + // to be safe, may be sending to contract that + // has overridden 'send' which may then fail + balances[msg.sender] += withdrawAmount; } } @@ -710,7 +712,9 @@ someContractAddress.callcode('function_name'); // else should be placed on own line -// 13. NATSPEC comments - used for documentation, commenting, and external UIs +// 13. NATSPEC COMENTS +// used for documentation, commenting, and external UIs + // Contract natspec - always above contract definition /// @title Contract title /// @author Author name @@ -740,7 +744,6 @@ someContractAddress.callcode('function_name'); ## Information purposefully excluded - Libraries -- [Call keyword](http://solidity.readthedocs.org/en/latest/types.html) ## Style - Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) -- cgit v1.2.3 From bdd8a8b0c87d58332f39facc60d6ab7d576764df Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Mon, 28 Dec 2015 22:31:48 -0500 Subject: Wording --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 5946c1f5..ebc58491 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -500,8 +500,8 @@ function remove() { // 9. CONTRACT DESIGN NOTES // A. Obfuscation -// Remember all variables are publicly viewable on blockchain, so -// anything that needs privacy needs to be obfuscated (e.g., hashed) +// All variables are publicly viewable on blockchain, so anything +// that should be totally private needs to be obfuscated (e.g., hashed w/secret) // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit -- cgit v1.2.3 From 24740321f478c25bb1dc651f6c95e11525a16781 Mon Sep 17 00:00:00 2001 From: ethers Date: Mon, 28 Dec 2015 23:45:58 -0800 Subject: update links to docs and Gitter --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index ebc58491..911aca92 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -729,17 +729,17 @@ someContractAddress.callcode('function_name'); ``` ## Additional resources -- [Solidity Docs](https://ethereum.github.io/solidity/docs/home/) +- [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/) -- [Gitter Chat room](https://gitter.im/ethereum/go-ethereum) +- [Gitter Chat room](https://gitter.im/ethereum/solidity) - [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/) - Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) ## Sample contracts - [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) -- [Consensys Contracts](https://github.com/ConsenSys/dapp-store-contracts) +- [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) ## Information purposefully excluded -- cgit v1.2.3 From 00d4fa09de191b9580dd534b8b3e6e7a297fb8d7 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Tue, 29 Dec 2015 16:59:19 +0800 Subject: Fetch lsp typo fix from upstream --- zh-cn/tmux-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 00bf35f3..64781346 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -39,7 +39,7 @@ lang: zh-cn lsp # 列出窗格 -a # 列出所有窗格 -s # 列出会话中的所有窗格 - -t # List app panes in target + -t # 列出 target 中的所有窗格 kill-window # 关闭当前窗口 -t "#" # 关闭指定的窗口 -- cgit v1.2.3 From bf609a3a0f0ce84faa617bc5c6a51b56f3571f4f Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Tue, 29 Dec 2015 17:14:18 +0800 Subject: Update tmux home page. Tmux has moved to github. --- tmux.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 868302a8..6763a781 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -240,7 +240,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | ### References -[Tmux | Home](http://tmux.sourceforge.net) +[Tmux | Home](http://tmux.github.io) [Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) -- cgit v1.2.3 From fc528c92ddbdca1d0cb3a5c8f3ad477fbc115ad9 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 10:59:01 -0500 Subject: Cleaned up data types --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index ebc58491..d84b6a68 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -117,12 +117,10 @@ uint x; // int of 256 bits, cannot be changed after instantiation int constant a = 8; - -// with 'constant', compiler replaces each occurrence with actual value int256 constant a = 8; // same effect as line above, here the 256 is explicit uint constant VERSION_ID = 0x123A1; // A hex constant +// with 'constant', compiler replaces each occurrence with actual value -// Be careful that you don't overflow, and protect against attacks that do // For int and uint, can explicitly set space in steps of 8 up to 256 // e.g., int8, int16, int24 @@ -130,6 +128,8 @@ uint8 b; int64 c; uint248 e; +// Be careful that you don't overflow, and protect against attacks that do + // No random functions built in, use other contracts for randomness // Type casting -- cgit v1.2.3 From 7e4a42d0b8cec4c0e2a6b90ad261c7755afe1136 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 11:10:39 -0500 Subject: Reorganizing later sections --- solidity.html.markdown | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 8c416be3..6705dde9 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -501,7 +501,7 @@ function remove() { // A. Obfuscation // All variables are publicly viewable on blockchain, so anything -// that should be totally private needs to be obfuscated (e.g., hashed w/secret) +// that is private needs to be obfuscated (e.g., hashed w/secret) // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit @@ -510,27 +510,28 @@ sha3("some_bid_amount", "some secret"); // commit reveal(100, "mySecret"); // B. Storage optimization -// Writing to blockchain can be expensive, as data stored forever encourages +// Writing to blockchain can be expensive, as data stored forever; encourages // smart ways to use memory (eventually, compilation will be better, but for now // benefits to planning data structures - and storing min amount in blockchain) // Cost can often be high for items like multidimensional arrays // (cost is for storing data - not declaring unfilled variables) -// C. Cannot restrict human or computer from reading contents of +// C. Data access in blockchain +// Cannot restrict human or computer from reading contents of // transaction or transaction's state -// When 'private' specified, indicating that other *contracts* can't read -// the data directly - any other party can still read the data in blockchain +// While 'private' prevents other *contracts* from reading data +// directly - any other party can still read data in blockchain -// D. All data to start of time is stored in blockchain, so +// All data to start of time is stored in blockchain, so // anyone can observe all previous data and changes -// E. Cron -// Contracts must be manually called to handle time-based scheduling; can create -// external code to do, or provide incentives (ether) for others to do for you +// D. Cron Job +// Contracts must be manually called to handle time-based scheduling; can create external +// code to regularly ping, or provide incentives (ether) for others to -// F. State machines +// E. State machines // see example below for State enum and inState modifier @@ -705,6 +706,7 @@ someContractAddress.callcode('function_name'); // 12. STYLE NOTES // Based on Python's PEP8 style guide +// Quick summary: // 4 spaces for indentation // Two lines separate contract declarations (and other top level declarations) // Avoid extraneous spaces in parentheses -- cgit v1.2.3 From d97c7be291b6bc3fb1477c30ac96b5b6cc36b9c4 Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Tue, 29 Dec 2015 13:05:45 -0500 Subject: Minor wording changes, typos --- solidity.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 6705dde9..71a44b92 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -63,7 +63,7 @@ contract SimpleBank { // CamelCase function deposit() public returns (uint) { balances[msg.sender] += msg.value; // no "this." or "self." required with state variable - // all values initialized to 0 by default + // all values set to data type's initial value by default DepositMade(msg.sender, msg.value); // fire event @@ -289,7 +289,7 @@ tx.origin; // address of sender of the transaction tx.gasprice; // gas price of the transaction // ** block - Information about current block ** -now // current time (approximately), alias for block.timestamp (uses Unix time) +now; // current time (approximately), alias for block.timestamp (uses Unix time) block.number; // current block number block.difficulty; // current block difficulty block.blockhash(1); // returns bytes32, only works for most recent 256 blocks @@ -428,7 +428,7 @@ contract Consumer { // Set feed to new instance of contract function createNewFeed() { - feed = new InfoFeed(); // constructor called + feed = new InfoFeed(); // new instance created; constructor called } function callFeed() { -- cgit v1.2.3 From 8dd19e58eeaed93f4489ae711ef72e79135d8795 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 18:56:24 +0800 Subject: Fetch tmuxinator from upstream --- zh-cn/tmux-cn.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 64781346..540bbf23 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -247,3 +247,5 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) [如何在 tmux 状态栏中显示 CPU / 内存占用百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From 9b8c680a2e2e1238f4130bc589367baf1a62119e Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 19:07:19 +0800 Subject: Update translations. --- zh-cn/tmux-cn.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 540bbf23..3b38ca6b 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -39,7 +39,7 @@ lang: zh-cn lsp # 列出窗格 -a # 列出所有窗格 -s # 列出会话中的所有窗格 - -t # 列出 target 中的所有窗格 + -t "#" # 列出指定窗口中的所有窗格 kill-window # 关闭当前窗口 -t "#" # 关闭指定的窗口 @@ -56,7 +56,7 @@ lang: zh-cn ### 快捷键 -通过“前缀”快捷键,可以控制一个已经连入的tmux会话。 +通过“前缀”快捷键,可以控制一个已经连入的 tmux 会话。 ``` ---------------------------------------------------------------------- @@ -66,7 +66,7 @@ lang: zh-cn ---------------------------------------------------------------------- ? # 列出所有快捷键 - : # 进入tmux的命令提示符 + : # 进入 tmux 的命令提示符 r # 强制重绘当前客户端 c # 创建一个新窗口 @@ -127,7 +127,7 @@ set-option -g status-utf8 on # 命令回滚/历史数量限制 set -g history-limit 2048 -# Index Start +# 从 1 开始编号,而不是从 0 开始 set -g base-index 1 # 启用鼠标 @@ -144,10 +144,10 @@ bind r source-file ~/.tmux.conf # 取消默认的前缀键 C-b unbind C-b -# 设置新的前缀键 +# 设置新的前缀键 ` set-option -g prefix ` -# 再次按下前缀键时,回到之前的窗口 +# 多次按下前缀键时,切换到上一个窗口 bind C-a last-window bind ` last-window @@ -159,7 +159,7 @@ bind F12 set-option -g prefix ` setw -g mode-keys vi set-option -g status-keys vi -# 使用 vim 风格的按键在窗格间移动 +# 使用 Vim 风格的按键在窗格间移动 bind h select-pane -L bind j select-pane -D bind k select-pane -U @@ -238,14 +238,14 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | ### 参考资料 -[Tmux 主页](http://tmux.sourceforge.net) +[Tmux 主页](http://tmux.github.io) [Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) [Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) -[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文)) -[如何在 tmux 状态栏中显示 CPU / 内存占用百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) +[如何在 tmux 状态栏中显示 CPU / 内存占用的百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) [管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From aed4bbbc36bf28a815d6751cde02b6b025452fb9 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 21:38:18 +0800 Subject: Update Wiki link --- zh-cn/tmux-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 3b38ca6b..390fd4fc 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -242,7 +242,7 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Tmux 手册](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) -[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) +[FreeBSDChina Wiki](https://wiki.freebsdchina.org/software/t/tmux) [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文)) -- cgit v1.2.3 From 4af768019ced6c179a09180adc2b0fb9adebc1d8 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 30 Dec 2015 21:54:44 +0800 Subject: Add a tmux Chinese tutorial --- zh-cn/tmux-cn.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 390fd4fc..87afa565 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -246,6 +246,8 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux_(简体中文)) +[Tmux 快速教程](http://blog.jeswang.org/blog/2013/06/24/tmux-kuai-su-jiao-cheng) + [如何在 tmux 状态栏中显示 CPU / 内存占用的百分比](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) [管理复杂 tmux 会话的工具 - tmuxinator](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From 8fdb648cbc691de5ff8f30c7bb5d0c29385a253c Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Thu, 31 Dec 2015 15:51:09 +0800 Subject: Update tmux home page, again. --- tmux.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index 6763a781..c9e3db6b 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -7,7 +7,7 @@ filename: LearnTmux.txt --- -[tmux](http://tmux.sourceforge.net) +[tmux](http://tmux.github.io) is a terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background -- cgit v1.2.3 From d56ae11e30ff85a0b8b632506abf4ec1bad1d28e Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Thu, 31 Dec 2015 16:16:02 +0800 Subject: Finish tmux translations. --- zh-cn/tmux-cn.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zh-cn/tmux-cn.html.markdown b/zh-cn/tmux-cn.html.markdown index 87afa565..cf865dce 100644 --- a/zh-cn/tmux-cn.html.markdown +++ b/zh-cn/tmux-cn.html.markdown @@ -10,9 +10,9 @@ lang: zh-cn --- -[tmux](http://tmux.sourceforge.net)是一款终端复用工具。 +[tmux](http://tmux.github.io)是一款终端复用工具。 在它的帮助下,你可以在同一个控制台上建立、访问并控制多个终端。 -你可以断开与一个tmux终端的连接,此时程序将在后台运行, +你可以断开与一个 tmux 终端的连接,此时程序将在后台运行, 当你需要时,可以随时重新连接到这个终端。 ``` @@ -70,7 +70,7 @@ lang: zh-cn r # 强制重绘当前客户端 c # 创建一个新窗口 - ! # Break the current pane out of the window. + ! # 将当前窗格从窗口中移出,成为为一个新的窗口 % # 将当前窗格分为左右两半 " # 将当前窗格分为上下两半 @@ -93,11 +93,11 @@ lang: zh-cn Left, Right M-1 到 M-5 # 排列窗格: - # 1) even-horizontal - # 2) even-vertical - # 3) main-horizontal - # 4) main-vertical - # 5) tiled + # 1) 水平等分 + # 2) 垂直等分 + # 3) 将一个窗格作为主要窗格,其他窗格水平等分 + # 4) 将一个窗格作为主要窗格,其他窗格垂直等分 + # 5) 平铺 C-Up, C-Down # 改变当前窗格的大小,每按一次增减一个单位 C-Left, C-Right -- cgit v1.2.3 From 15bd3ff223b998aad3ed2d5fc6a530adc31cb56c Mon Sep 17 00:00:00 2001 From: hyphz Date: Fri, 1 Jan 2016 01:54:11 +0000 Subject: Rename wolfram.md to wolfram.html.markdown --- wolfram.html.markdown | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++ wolfram.md | 137 -------------------------------------------------- 2 files changed, 137 insertions(+), 137 deletions(-) create mode 100644 wolfram.html.markdown delete mode 100644 wolfram.md diff --git a/wolfram.html.markdown b/wolfram.html.markdown new file mode 100644 index 00000000..4514006d --- /dev/null +++ b/wolfram.html.markdown @@ -0,0 +1,137 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnwolfram.nb +--- + +The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. + +Wolfram Language has several interfaces: +* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. +* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic +* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend + +The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. + +``` +(* This is a comment *) + +(* In Mathematica instead of using these comments you can create a text cell + and annotate your code with nicely typeset text and images *) + +(* Typing an expression returns the result *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Function Call *) +(* Note, function names (and everything else) are case sensitive *) +Sin[Pi/2] (* 1 *) + +(* Alternate Syntaxes for Function Call with one parameter *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Every syntax in WL has some equivalent as a function call *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Using a variable for the first time defines it and makes it global *) +x = 5 (* 5 *) +x == 5 (* True, C-style assignment and equality testing *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *) +x (* 20 *) + +(* Because WL is based on a computer algebra system, *) +(* using undefined variables is fine, they just obstruct evaluation *) +cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *) +cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *) +% (* 15 + cow, % fetches the last return *) +% - cow (* 15, undefined variable cow cancelled out *) +moo = cow + 5 (* Beware, moo now holds an expression, not a number! *) + +(* Defining a function *) +Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS + And _ after x to indicate no pattern matching constraints *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *) +(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *) + +(* For imperative-style programming use ; to separate statements *) +(* Discards any output from LHS and runs RHS *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical + ;'s precedence is lower than := *) +MyFirst[] (* Hello World *) + +(* C-Style For Loop *) +PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Create an association *) +myHash[["Green"]] (* 2, use it *) +myHash[["Green"]] := 5 (* 5, update it *) +myHash[["Puce"]] := 3.5 (* 3.5, extend it *) +KeyDropFrom[myHash, "Green"] (* Wipes out key Green *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* And you can't do any demo of Wolfram without showing this off *) +Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2 + and allows y to be adjusted between 0-20 with a slider. + Only works on graphical frontends *) +``` + +##Ready For More? + +* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/) diff --git a/wolfram.md b/wolfram.md deleted file mode 100644 index 4514006d..00000000 --- a/wolfram.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -language: wolfram -contributors: - - ["hyphz", "http://github.com/hyphz/"] -filename: learnwolfram.nb ---- - -The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. - -Wolfram Language has several interfaces: -* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. -* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic -* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend - -The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. - -``` -(* This is a comment *) - -(* In Mathematica instead of using these comments you can create a text cell - and annotate your code with nicely typeset text and images *) - -(* Typing an expression returns the result *) -2*2 (* 4 *) -5+8 (* 13 *) - -(* Function Call *) -(* Note, function names (and everything else) are case sensitive *) -Sin[Pi/2] (* 1 *) - -(* Alternate Syntaxes for Function Call with one parameter *) -Sin@(Pi/2) (* 1 *) -(Pi/2) // Sin (* 1 *) - -(* Every syntax in WL has some equivalent as a function call *) -Times[2, 2] (* 4 *) -Plus[5, 8] (* 13 *) - -(* Using a variable for the first time defines it and makes it global *) -x = 5 (* 5 *) -x == 5 (* True, C-style assignment and equality testing *) -x (* 5 *) -x = x + 5 (* 10 *) -x (* 10 *) -Set[x, 20] (* I wasn't kidding when I said EVERYTHING has a function equivalent *) -x (* 20 *) - -(* Because WL is based on a computer algebra system, *) -(* using undefined variables is fine, they just obstruct evaluation *) -cow + 5 (* 5 + cow, cow is undefined so can't evaluate further *) -cow + 5 + 10 (* 15 + cow, it'll evaluate what it can *) -% (* 15 + cow, % fetches the last return *) -% - cow (* 15, undefined variable cow cancelled out *) -moo = cow + 5 (* Beware, moo now holds an expression, not a number! *) - -(* Defining a function *) -Double[x_] := x * 2 (* Note := to prevent immediate evaluation of the RHS - And _ after x to indicate no pattern matching constraints *) -Double[10] (* 20 *) -Double[Sin[Pi/2]] (* 2 *) -Double @ Sin @ (Pi/2) (* 2, @-syntax avoids queues of close brackets *) -(Pi/2) // Sin // Double(* 2, //-syntax lists functions in execution order *) - -(* For imperative-style programming use ; to separate statements *) -(* Discards any output from LHS and runs RHS *) -MyFirst[] := (Print@"Hello"; Print@"World") (* Note outer parens are critical - ;'s precedence is lower than := *) -MyFirst[] (* Hello World *) - -(* C-Style For Loop *) -PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Create an association *) -myHash[["Green"]] (* 2, use it *) -myHash[["Green"]] := 5 (* 5, update it *) -myHash[["Puce"]] := 3.5 (* 3.5, extend it *) -KeyDropFrom[myHash, "Green"] (* Wipes out key Green *) -Keys[myHash] (* {Red} *) -Values[myHash] (* {1} *) - -(* And you can't do any demo of Wolfram without showing this off *) -Manipulate[y^2, {y, 0, 20}] (* Return a reactive user interface that displays y^2 - and allows y to be adjusted between 0-20 with a slider. - Only works on graphical frontends *) -``` - -##Ready For More? - -* [Wolfram Language Documentation Center](http://reference.wolfram.com/language/) -- cgit v1.2.3 From 01ab402100a08e30d6f88406a55b08b744fcb375 Mon Sep 17 00:00:00 2001 From: hyphz Date: Fri, 1 Jan 2016 01:54:45 +0000 Subject: Rename factor.html to factor.html.markdown --- factor.html | 182 --------------------------------------------------- factor.html.markdown | 182 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+), 182 deletions(-) delete mode 100644 factor.html create mode 100644 factor.html.markdown diff --git a/factor.html b/factor.html deleted file mode 100644 index a0726420..00000000 --- a/factor.html +++ /dev/null @@ -1,182 +0,0 @@ ---- -language: factor -contributors: - - ["hyphz", "http://github.com/hyphz/"] -filename: learnfactor.factor ---- - -Factor is a modern stack-based language, based on Forth, created by Slava Pestov. - -Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. - -``` -! This is a comment - -! Like Forth, all programming is done by manipulating the stack. -! Stating a literal value pushes it onto the stack. -5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode - -! Those numbers get added to the stack, from left to right. -! .s prints out the stack non-destructively. -.s ! 5 2 3 56 76 23 65 - -! Arithmetic works by manipulating data on the stack. -5 4 + ! No output - -! `.` pops the top result from the stack and prints it. -. ! 9 - -! More examples of arithmetic: -6 7 * . ! 42 -1360 23 - . ! 1337 -12 12 / . ! 1 -13 2 mod . ! 1 - -99 neg . ! -99 --99 abs . ! 99 -52 23 max . ! 52 -52 23 min . ! 23 - -! A number of words are provided to manipulate the stack, collectively known as shuffle words. - -3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 -2 5 swap / ! swap the top with the second element: 5 / 2 -4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 -1 2 3 nip .s ! remove the second item (similar to drop): 1 3 -1 2 clear .s ! wipe out the entire stack -1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 -1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 - -! Creating Words -! The `:` word sets Factor into compile mode until it sees the `;` word. -: square ( n -- n ) dup * ; ! No output -5 square . ! 25 - -! We can view what a word does too. -! \ suppresses evaluation of a word and pushes its identifier on the stack instead. -\ square see ! : square ( n -- n ) dup * ; - -! After the name of the word to create, the declaration between brackets gives the stack effect. -! We can use whatever names we like inside the declaration: -: weirdsquare ( camel -- llama ) dup * ; - -! Provided their count matches the word's stack effect: -: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong -: doubledup ( a -- a a a ) dup dup ; ! Ok -: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok - -! Where Factor differs from Forth is in the use of quotations. -! A quotation is a block of code that is pushed on the stack as a value. -! [ starts quotation mode; ] ends it. -[ 2 + ] ! Quotation that adds 2 is left on the stack -4 swap call . ! 6 - -! And thus, higher order words. TONS of higher order words. -2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3 -3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4 -1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4 -4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 ) -1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values -2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack - -! Conditionals -! Any value is true except the built-in value f. -! A built-in value t does exist, but its use isn't essential. -! Conditionals are higher order words as with the combinators above. - -5 [ "Five is true" . ] when ! Five is true -0 [ "Zero is true" . ] when ! Zero is true -f [ "F is true" . ] when ! No output -f [ "F is false" . ] unless ! F is false -2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true - -! By default the conditionals consume the value under test, but starred variants -! leave it alone if it's true: - -5 [ . ] when* ! 5 -f [ . ] when* ! No output, empty stack, f is consumed because it's false - - -! Loops -! You've guessed it.. these are higher order words too. - -5 [ . ] each-integer ! 0 1 2 3 4 -4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 -5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello - -! Here's a list: -{ 2 4 6 8 } ! Goes on the stack as one item - -! Loop through the list: -{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9 -{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack - -! Loop reducing or building lists: -{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } -{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) -{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 -1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } -1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } - -! If all else fails, a general purpose while loop: -1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times - ! Yes, it's hard to read - ! That's what all those variant loops are for - -! Variables -! Usually Factor programs are expected to keep all data on the stack. -! Using named variables makes refactoring harder (and it's called Factor for a reason) -! Global variables, if you must: - -SYMBOL: name ! Creates name as an identifying word -"Bob" name set-global ! No output -name get-global . ! "Bob" - -! Named local variables are considered an extension but are available -! In a quotation.. -[| m n ! Quotation captures top two stack values into m and n - | m n + ] ! Read them - -! Or in a word.. -:: lword ( -- ) ! Note double colon to invoke lexical variable extension - 2 :> c ! Declares immutable variable c to hold 2 - c . ; ! Print it out - -! In a word declared this way, the input side of the stack declaration -! becomes meaningful and gives the variable names stack values are captured into -:: double ( a -- result ) a 2 * ; - -! Variables are declared mutable by ending their name with a shriek -:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a - a ! Push a - a 2 * a! ! Multiply a by 2 and store result back in a - a ; ! Push new value of a -5 mword2 ! Stack: 5 10 - -! Lists and Sequences -! We saw above how to push a list onto the stack - -0 { 1 2 3 4 } nth ! Access a particular member of a list: 1 -10 { 1 2 3 4 } nth ! Error: sequence index out of bounds -1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2 -10 { 1 2 3 4 } ?nth ! No error if out of bounds: f - -{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } -{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } -"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } -"Concat" "enate" append ! "Concatenate" - strings are sequences too -"Concatenate" "Reverse " prepend ! "Reverse Concatenate" -{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" -{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" - -! And if you want to get meta, quotations are sequences and can be dismantled.. -0 [ 2 + ] nth ! 2 -1 [ 2 + ] nth ! + -[ 2 + ] \ - suffix ! Quotation [ 2 + - ] - - -``` - -##Ready For More? - -* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html) diff --git a/factor.html.markdown b/factor.html.markdown new file mode 100644 index 00000000..a0726420 --- /dev/null +++ b/factor.html.markdown @@ -0,0 +1,182 @@ +--- +language: factor +contributors: + - ["hyphz", "http://github.com/hyphz/"] +filename: learnfactor.factor +--- + +Factor is a modern stack-based language, based on Forth, created by Slava Pestov. + +Code in this file can be typed into Factor, but not directly imported because the vocabulary and import header would make the beginning thoroughly confusing. + +``` +! This is a comment + +! Like Forth, all programming is done by manipulating the stack. +! Stating a literal value pushes it onto the stack. +5 2 3 56 76 23 65 ! No output, but stack is printed out in interactive mode + +! Those numbers get added to the stack, from left to right. +! .s prints out the stack non-destructively. +.s ! 5 2 3 56 76 23 65 + +! Arithmetic works by manipulating data on the stack. +5 4 + ! No output + +! `.` pops the top result from the stack and prints it. +. ! 9 + +! More examples of arithmetic: +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 + +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 + +! A number of words are provided to manipulate the stack, collectively known as shuffle words. + +3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 +2 5 swap / ! swap the top with the second element: 5 / 2 +4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 +1 2 3 nip .s ! remove the second item (similar to drop): 1 3 +1 2 clear .s ! wipe out the entire stack +1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 +1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 + +! Creating Words +! The `:` word sets Factor into compile mode until it sees the `;` word. +: square ( n -- n ) dup * ; ! No output +5 square . ! 25 + +! We can view what a word does too. +! \ suppresses evaluation of a word and pushes its identifier on the stack instead. +\ square see ! : square ( n -- n ) dup * ; + +! After the name of the word to create, the declaration between brackets gives the stack effect. +! We can use whatever names we like inside the declaration: +: weirdsquare ( camel -- llama ) dup * ; + +! Provided their count matches the word's stack effect: +: doubledup ( a -- b ) dup dup ; ! Error: Stack effect declaration is wrong +: doubledup ( a -- a a a ) dup dup ; ! Ok +: weirddoubledup ( i -- am a fish ) dup dup ; ! Also Ok + +! Where Factor differs from Forth is in the use of quotations. +! A quotation is a block of code that is pushed on the stack as a value. +! [ starts quotation mode; ] ends it. +[ 2 + ] ! Quotation that adds 2 is left on the stack +4 swap call . ! 6 + +! And thus, higher order words. TONS of higher order words. +2 3 [ 2 + ] dip .s ! Pop top stack value, run quotation, push it back: 4 3 +3 4 [ + ] keep .s ! Copy top stack value, run quotation, push the copy: 7 4 +1 [ 2 + ] [ 3 + ] bi .s ! Run each quotation on the top value, push both results: 3 4 +4 3 1 [ + ] [ + ] bi .s ! Quotations in a bi can pull values from deeper on the stack: 4 5 ( 1+3 1+4 ) +1 2 [ 2 + ] bi@ .s ! Run the quotation on first and second values +2 [ + ] curry ! Inject the given value at the start of the quotation: [ 2 + ] is left on the stack + +! Conditionals +! Any value is true except the built-in value f. +! A built-in value t does exist, but its use isn't essential. +! Conditionals are higher order words as with the combinators above. + +5 [ "Five is true" . ] when ! Five is true +0 [ "Zero is true" . ] when ! Zero is true +f [ "F is true" . ] when ! No output +f [ "F is false" . ] unless ! F is false +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true + +! By default the conditionals consume the value under test, but starred variants +! leave it alone if it's true: + +5 [ . ] when* ! 5 +f [ . ] when* ! No output, empty stack, f is consumed because it's false + + +! Loops +! You've guessed it.. these are higher order words too. + +5 [ . ] each-integer ! 0 1 2 3 4 +4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 +5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello + +! Here's a list: +{ 2 4 6 8 } ! Goes on the stack as one item + +! Loop through the list: +{ 2 4 6 8 } [ 1 + . ] each ! Prints 3 5 7 9 +{ 2 4 6 8 } [ 1 + ] map ! Leaves { 3 5 7 9 } on stack + +! Loop reducing or building lists: +{ 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } +{ 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 +1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } +1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } + +! If all else fails, a general purpose while loop: +1 [ dup 10 < ] [ "Hello" . 1 + ] while ! Prints "Hello" 10 times + ! Yes, it's hard to read + ! That's what all those variant loops are for + +! Variables +! Usually Factor programs are expected to keep all data on the stack. +! Using named variables makes refactoring harder (and it's called Factor for a reason) +! Global variables, if you must: + +SYMBOL: name ! Creates name as an identifying word +"Bob" name set-global ! No output +name get-global . ! "Bob" + +! Named local variables are considered an extension but are available +! In a quotation.. +[| m n ! Quotation captures top two stack values into m and n + | m n + ] ! Read them + +! Or in a word.. +:: lword ( -- ) ! Note double colon to invoke lexical variable extension + 2 :> c ! Declares immutable variable c to hold 2 + c . ; ! Print it out + +! In a word declared this way, the input side of the stack declaration +! becomes meaningful and gives the variable names stack values are captured into +:: double ( a -- result ) a 2 * ; + +! Variables are declared mutable by ending their name with a shriek +:: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a + a ! Push a + a 2 * a! ! Multiply a by 2 and store result back in a + a ; ! Push new value of a +5 mword2 ! Stack: 5 10 + +! Lists and Sequences +! We saw above how to push a list onto the stack + +0 { 1 2 3 4 } nth ! Access a particular member of a list: 1 +10 { 1 2 3 4 } nth ! Error: sequence index out of bounds +1 { 1 2 3 4 } ?nth ! Same as nth if index is in bounds: 2 +10 { 1 2 3 4 } ?nth ! No error if out of bounds: f + +{ "at" "the" "beginning" } "Append" prefix ! { "Append" "at" "the" "beginning" } +{ "Append" "at" "the" } "end" suffix ! { "Append" "at" "the" "end" } +"in" 1 { "Insert" "the" "middle" } insert-nth ! { "Insert" "in" "the" "middle" } +"Concat" "enate" append ! "Concatenate" - strings are sequences too +"Concatenate" "Reverse " prepend ! "Reverse Concatenate" +{ "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" + +! And if you want to get meta, quotations are sequences and can be dismantled.. +0 [ 2 + ] nth ! 2 +1 [ 2 + ] nth ! + +[ 2 + ] \ - suffix ! Quotation [ 2 + - ] + + +``` + +##Ready For More? + +* [Factor Documentation](http://docs.factorcode.org/content/article-help.home.html) -- cgit v1.2.3 From 1f0b1bfb7a8d7abe3563015bad0110d6c319208f Mon Sep 17 00:00:00 2001 From: Borislav Kosharov Date: Sat, 2 Jan 2016 18:43:19 +0200 Subject: fix parallelism example typo --- d.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d.html.markdown b/d.html.markdown index 6f88cf84..edb3bff5 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -254,7 +254,7 @@ void main() { // Use an index, access every array element by reference (because we're // going to change each element) and just call parallel on the array! foreach(i, ref elem; parallel(arr)) { - ref = sqrt(i + 1.0); + elem = sqrt(i + 1.0); } } ``` -- cgit v1.2.3 From bde8645cc7bb7f0a88b5d106cd0bd0b7e40886d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Migda=C5=82?= Date: Sun, 3 Jan 2016 19:45:54 +0100 Subject: pep8 fixes (spaces and multiline statements) in Python readability and code style matters --- pythonstatcomp.html.markdown | 103 ++++++++++++++++++++++++------------------- 1 file changed, 57 insertions(+), 46 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 78b62e33..f8d83b98 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -9,6 +9,8 @@ This is a tutorial on how to do some typical statistical programming tasks using ```python + + # 0. Getting set up ==== """ Get set up with IPython and pip install the following: numpy, scipy, pandas, @@ -25,17 +27,17 @@ This is a tutorial on how to do some typical statistical programming tasks using already using Python, there's a benefit to sticking with one language. """ -import requests # for HTTP requests (web scraping, APIs) +import requests # for HTTP requests (web scraping, APIs) import os # web scraping r = requests.get("https://github.com/adambard/learnxinyminutes-docs") -r.status_code # if 200, request was successful -r.text # raw page source -print(r.text) # prettily formatted +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted # save the page source in a file: -os.getcwd() # check what's the working directory -f = open("learnxinyminutes.html","wb") +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html", "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -44,7 +46,7 @@ fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" fn = "pets.csv" r = requests.get(fp + fn) print(r.text) -f = open(fn,"wb") +f = open(fn, "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -58,7 +60,9 @@ f.close() you've used R, you will be familiar with the idea of the "data.frame" already. """ -import pandas as pd, numpy as np, scipy as sp +import pandas as pd +import numpy as np +import scipy as sp pets = pd.read_csv(fn) pets # name age weight species @@ -74,20 +78,20 @@ pets pets.age pets["age"] -pets.head(2) # prints first 2 rows -pets.tail(1) # prints last row +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row -pets.name[1] # 'vesuvius' -pets.species[0] # 'cat' -pets["weight"][2] # 34 +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 # in R, you would expect to get 3 rows doing this, but here you get 2: pets.age[0:2] # 0 3 # 1 6 -sum(pets.age)*2 # 28 -max(pets.weight) - min(pets.weight) # 20 +sum(pets.age) * 2 # 28 +max(pets.weight) - min(pets.weight) # 20 """ If you are doing some serious linear algebra and number-crunching, you may just want arrays, not DataFrames. DataFrames are ideal for combining columns @@ -96,7 +100,8 @@ max(pets.weight) - min(pets.weight) # 20 # 3. Charts ==== -import matplotlib as mpl, matplotlib.pyplot as plt +import matplotlib as mpl +import matplotlib.pyplot as plt %matplotlib inline # To do data vizualization in Python, use matplotlib @@ -105,13 +110,17 @@ plt.hist(pets.age); plt.boxplot(pets.weight); -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); # seaborn sits atop matplotlib and makes plots prettier import seaborn as sns -plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); +plt.scatter(pets.age, pets.weight) +plt.xlabel("age") +plt.ylabel("weight"); # there are also some seaborn-specific plotting functions # notice how seaborn automatically labels the x-axis on this barplot @@ -141,7 +150,7 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" r = requests.get(url) fp = "hre.csv" -f = open(fp,"wb") +f = open(fp, "wb") f.write(r.text.encode("UTF-8")) f.close() @@ -149,33 +158,33 @@ hre = pd.read_csv(fp) hre.head() """ - Ix Dynasty Name Birth Death Election 1 -0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN -1 NaN Carolingian Louis I 778 20 June 840 NaN -2 NaN Carolingian Lothair I 795 29 September 855 NaN -3 NaN Carolingian Louis II 825 12 August 875 NaN -4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN - - Election 2 Coronation 1 Coronation 2 Ceased to be Emperor -0 NaN 25 December 800 NaN 28 January 814 -1 NaN 11 September 813 5 October 816 20 June 840 -2 NaN 5 April 823 NaN 29 September 855 -3 NaN Easter 850 18 May 872 12 August 875 -4 NaN 29 December 875 NaN 6 October 877 - - Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 -0 NaN NaN NaN NaN -1 Charles I son NaN NaN -2 Louis I son NaN NaN -3 Lothair I son NaN NaN -4 Louis I son NaN NaN + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN """ # clean the Birth and Death columns -import re # module for regular expressions +import re # module for regular expressions -rx = re.compile(r'\d+$') # match trailing digits +rx = re.compile(r'\d+$') # match trailing digits """ This function applies the regular expression to an input column (here Birth, Death), flattens the resulting list, converts it to a Series object, and @@ -185,8 +194,9 @@ rx = re.compile(r'\d+$') # match trailing digits - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html """ + def extractYear(v): - return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + return(pd.Series(reduce(lambda x, y: x + y, map(rx.findall, v), [])).astype(int)) hre["BirthY"] = extractYear(hre.Birth) hre["DeathY"] = extractYear(hre.Death) @@ -199,17 +209,17 @@ sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); # use scipy to run a linear regression from scipy import stats -(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +(slope, intercept, rval, pval, stderr) = stats.linregress(hre.BirthY, hre.EstAge) # code source: http://wiki.scipy.org/Cookbook/LinearRegression # check the slope -slope # 0.0057672618839073328 +slope # 0.0057672618839073328 # check the R^2 value: -rval**2 # 0.020363950027333586 +rval**2 # 0.020363950027333586 # check the p-value -pval # 0.34971812581498452 +pval # 0.34971812581498452 # use seaborn to make a scatterplot and plot the linear regression trend line sns.lmplot("BirthY", "EstAge", data=hre); @@ -223,6 +233,7 @@ sns.lmplot("BirthY", "EstAge", data=hre); To see a version of the Holy Roman Emperors analysis using R, see - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R """ + ``` If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. -- cgit v1.2.3 From 746df3268afcd0307c0da434bf162632be3d53ea Mon Sep 17 00:00:00 2001 From: Bruno Volcov Date: Mon, 4 Jan 2016 17:28:36 -0200 Subject: remove contributors name --- ruby.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index b3ef2a4d..267889b1 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -13,7 +13,6 @@ contributors: - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gabriel Halley", https://github.com/ghalley] - - ["Bruno Volcov", https://github.com/volcov] --- -- cgit v1.2.3 From a5730e4ab931b8355704d35ee08acef75435bd83 Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Tue, 5 Jan 2016 13:25:56 +0530 Subject: Update --- c++.html.markdown | 48 +++++++----------------------------------------- 1 file changed, 7 insertions(+), 41 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 6033ca06..c1bacf6a 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -809,7 +809,7 @@ void doSomethingWithAFile(const std::string& filename) // object right at the location where it is invoked or passed as // an argument to a function. -// Example consider sorting a vector of pairs using the second +// For example, consider sorting a vector of pairs using the second // value of the pair vector > tester; @@ -820,7 +820,7 @@ tester.push_back(make_pair(5, 0)); // Pass a lambda expression as third argument to the sort function // sort is from the header -sort(tester.begin(), tester.end(), [](const pair &lhs, const pair &rhs) { +sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { return lhs.second < rhs.second; }); @@ -834,48 +834,22 @@ for(int i = 0; i < 3; i++){ dog_ids.push_back(i); } -int weight[3]; -weight[0] = 30, weight[1] = 50, weight[2] = 10; +int weight[3] = {30, 50, 10}; // Say you want to sort dog_ids according to the dogs' weights // So dog_ids should in the end become: [2, 0, 1] // Here's where lambda expressions come in handy -sort(dog_ids.begin(), dog_ids.end(), [weight](const int &lhs, const int &rhs) { +sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { return weight[lhs] < weight[rhs]; }); -// Note we captured "weight" in the above example. +// Note we captured "weight" by reference in the above example. // lambda are really useful for the case of structs // You can use lambda expressions instead of overloading // the "<" operator -struct dog{ - int weight, age; -}dogs[3]; - -dogs[0].weight = 30, dogs[0].age = 4; -dogs[1].weight = 40, dogs[1].age = 10; -dogs[2].weight = 20, dogs[2].age = 9; - -// Say I want to sort the dogs array by the dogs' weights - -sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { - return lhs.weight < rhs.weight; - }); -// dogs is now sorted according to their weight - -// Do something with the dogs - -// Now I want to sort the dogs by in descending order of their age - -sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { - return lhs.age > rhs.age; - }); -// dogs is now sorted in descending order of their age - - /////////////////////////////// // Range For (C++11 and above) /////////////////////////////// @@ -884,24 +858,16 @@ sort(dogs, dogs+3, [](const dog &lhs, const dog &rhs) { int arr[] = {1, 10, 3}; for(int elem: arr){ - cout< Date: Tue, 5 Jan 2016 13:36:23 +0530 Subject: Add my Changes --- c++.html.markdown | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index f4aa2f5a..31dbe064 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -820,6 +820,73 @@ std::map fooMap; fooMap[Foo(1)] = 1; fooMap.find(Foo(1)); //true +/////////////////////////////////////// +// Lambda Expressions (C++11 and above) +/////////////////////////////////////// + +// lambdas are a convenient way of defining an anonymous function +// object right at the location where it is invoked or passed as +// an argument to a function. + +// For example, consider sorting a vector of pairs using the second +// value of the pair + +vector > tester; +tester.push_back(make_pair(3, 6)); +tester.push_back(make_pair(1, 9)); +tester.push_back(make_pair(5, 0)); + +// Pass a lambda expression as third argument to the sort function +// sort is from the header + +sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { + return lhs.second < rhs.second; + }); + +// Notice the syntax of the lambda expression, +// [] in the lambda is used to "capture" variables. +// For Example: + +vector dog_ids; +// number_of_dogs = 3; +for(int i = 0; i < 3; i++){ + dog_ids.push_back(i); +} + +int weight[3] = {30, 50, 10}; + +// Say you want to sort dog_ids according to the dogs' weights +// So dog_ids should in the end become: [2, 0, 1] + +// Here's where lambda expressions come in handy + +sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { + return weight[lhs] < weight[rhs]; + }); +// Note we captured "weight" by reference in the above example. + +// lambda are really useful for the case of structs +// You can use lambda expressions instead of overloading +// the "<" operator + +/////////////////////////////// +// Range For (C++11 and above) +/////////////////////////////// + +// You can use a range for loop to iterate over a container +int arr[] = {1, 10, 3}; + +for(int elem: arr){ + cout << elem << endl; +} + +// You can use "auto" and not worry about the type of the elements of the container +// For example: + +for(auto elem: arr) { + // Do something with each element of arr +} + ///////////////////// // Fun stuff ///////////////////// -- cgit v1.2.3 From 0fbf289e3cbce3f2b6e830d5dcf1c8d3685a88a1 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 6 Jan 2016 03:14:04 +0800 Subject: Update go-fr.html.markdown --- fr-fr/go-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 16558e7e..9d8bef70 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -3,7 +3,7 @@ name: Go category: language language: Go lang: fr-fr -filename: learngo.go +filename: learngo-fr.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] -- cgit v1.2.3 From e47099866bee5e5f6d2852f4e4cbf92e4d4b0053 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 6 Jan 2016 03:17:33 +0800 Subject: Fix formatting. --- powershell.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/powershell.html.markdown b/powershell.html.markdown index 4bc1ab39..8920d254 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -18,6 +18,7 @@ rather than plain text. [Read more here.](https://technet.microsoft.com/en-us/library/bb978526.aspx) If you are uncertain about your environment: + ``` Get-ExecutionPolicy -List Set-ExecutionPolicy AllSigned @@ -33,6 +34,7 @@ $PSVersionTable ``` Getting help: + ``` # Find commands Get-Command about_* # alias: gcm @@ -49,6 +51,7 @@ Update-Help # Run as admin ``` The tutorial starts here: + ``` # As you already figured, comments start with # @@ -292,6 +295,7 @@ $Shortcut.Save() Configuring your shell + ``` # $Profile is the full path for your `Microsoft.PowerShell_profile.ps1` # All code there will be executed when the PS session starts -- cgit v1.2.3 From 1d65107a8fd74e67b2b9fe7e2e503a04d0db4df0 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 6 Jan 2016 04:13:33 +0800 Subject: Update latex-es.html.markdown --- es-es/latex-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/latex-es.html.markdown b/es-es/latex-es.html.markdown index 6743ad80..aff3c603 100644 --- a/es-es/latex-es.html.markdown +++ b/es-es/latex-es.html.markdown @@ -1,5 +1,6 @@ --- language: latex +lang: es-es contributors: - ["Chaitanya Krishna Ande", "http://icymist.github.io"] - ["Colton Kohnke", "http://github.com/voltnor"] -- cgit v1.2.3 From 4ba4c26f36f0c192af089930d11096fb1687f5ff Mon Sep 17 00:00:00 2001 From: oburdin Date: Wed, 6 Jan 2016 23:41:37 +0200 Subject: spelling --- uk-ua/json-ua.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown index 8ee12a93..120fb410 100644 --- a/uk-ua/json-ua.html.markdown +++ b/uk-ua/json-ua.html.markdown @@ -22,7 +22,7 @@ JSON - це надзвичайно простий формат обміну да "ключі": "завжди мають бути обгорнуті в подвійні лапки", "числа": 0, - "рядки": "Пρивет, світ. Допускаються всі unicode-символи разом з \"екрануванням\".", + "рядки": "Пρивіт, світ. Допускаються всі unicode-символи разом із \"екрануванням\".", "логічний тип": true, "нічого": null, @@ -34,13 +34,13 @@ JSON - це надзвичайно простий формат обміну да "масив": [0, 1, 2, 3, "масиви можуть містити будь-які типи", 5], "інший об’єкт": { - "коментра": "Об’єкти можуть містити інші об’єкти. Це дуже корисно." + "коментар": "Об’єкти можуть містити інші об’єкти. Це дуже корисно." } }, "безглуздя": [ { - "джерело калія": ["банани"] + "джерело калію": ["банани"] }, [ [1, 0, 0, 0], @@ -56,7 +56,7 @@ JSON - це надзвичайно простий формат обміну да , "інший коментар": "класно" }, - "Це було не довго": "І ви справилист. Тепер ви знаєте все про JSON." + "Це було не довго": "І ви впорались! Тепер ви знаєте все про JSON." } Одиничний масив значень теж є правильним JSON -- cgit v1.2.3 From e6866f5a26dab28d2d1b5628fbb18139c36a5139 Mon Sep 17 00:00:00 2001 From: bk2dcradle Date: Fri, 8 Jan 2016 01:21:38 +0530 Subject: More Fixes --- c++.html.markdown | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 31dbe064..44cad665 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -840,16 +840,22 @@ tester.push_back(make_pair(5, 0)); // sort is from the header sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { - return lhs.second < rhs.second; - }); + return lhs.second < rhs.second; + }); // Notice the syntax of the lambda expression, -// [] in the lambda is used to "capture" variables. -// For Example: +// [] in the lambda is used to "capture" variables +// The "Capture List" defines what from the outside of the lambda should be available inside the function body and how. +// It can be either: +// 1. a value : [x] +// 2. a reference : [&x] +// 3. any variable currently in scope by reference [&] +// 4. same as 3, but by value [=] +// Example: vector dog_ids; // number_of_dogs = 3; -for(int i = 0; i < 3; i++){ +for(int i = 0; i < 3; i++) { dog_ids.push_back(i); } @@ -861,13 +867,10 @@ int weight[3] = {30, 50, 10}; // Here's where lambda expressions come in handy sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { - return weight[lhs] < weight[rhs]; - }); + return weight[lhs] < weight[rhs]; + }); // Note we captured "weight" by reference in the above example. - -// lambda are really useful for the case of structs -// You can use lambda expressions instead of overloading -// the "<" operator +// More on Lambdas in C++ : http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 /////////////////////////////// // Range For (C++11 and above) -- cgit v1.2.3 From cc31c2f0c5032b723a1d57c971580121be07bf7f Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Thu, 7 Jan 2016 22:08:17 -0700 Subject: Fix typo referenced in Issue #2075 --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 6633b322..5082a433 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1329,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... -### Extra: the MAIN subroutime +### Extra: the MAIN subroutine # The `MAIN` subroutine is called when you run a Perl 6 file directly. # It's very powerful, because Perl 6 actually parses the arguments # and pass them as such to the sub. It also handles named argument (`--foo`) -- cgit v1.2.3 From 8ad537a9ba9889234a63c5a38caeab3e225856e4 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 8 Jan 2016 14:35:16 +0800 Subject: unfuck markdown doc --- cs-cz/markdown.html.markdown | 1 + markdown.html.markdown | 50 ++++++++++++++++++++++++++++---------------- 2 files changed, 33 insertions(+), 18 deletions(-) diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 637f0ab6..363af5e9 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -1,5 +1,6 @@ --- language: markdown +lang: cs-cz contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: diff --git a/markdown.html.markdown b/markdown.html.markdown index 8961c995..05eeecbe 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -26,6 +26,7 @@ specific to a certain parser. ## HTML Elements Markdown is a superset of HTML, so any HTML file is valid Markdown. + ```markdown + +
+```ruby
 def foobar
     puts "Hello world!"
 end
-\`\`\` 
-```
+```
The above text doesn't require indenting, plus Github will use syntax highlighting of the language you specify after the \`\`\` @@ -212,6 +216,7 @@ highlighting of the language you specify after the \`\`\` Horizontal rules (`
`) are easily added with three or more asterisks or hyphens, with or without spaces. + ```markdown *** --- @@ -228,58 +233,64 @@ the text to display in hard brackets [] followed by the url in parentheses () [Click me!](http://test.com/) ``` You can also add a link title using quotes inside the parentheses. + ```markdown [Click me!](http://test.com/ "Link to Test.com") ``` Relative paths work too. + ```markdown [Go to music](/music/). ``` + Markdown also supports reference style links. -```markdown -[Click this link][link1] for more info about it! -[Also check out this link][foobar] if you want to. -[link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "Alright!" -``` +
[Click this link][link1] for more info about it!
+[Also check out this link][foobar] if you want to.
+
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Alright!"
+ The title can also be in single quotes or in parentheses, or omitted entirely. The references can be anywhere in your document and the reference IDs can be anything so long as they are unique. There is also "implicit naming" which lets you use the link text as the id. -```markdown -[This][] is a link. -[this]: http://thisisalink.com/ -``` +
[This][] is a link.
+
+[this]: http://thisisalink.com/
+ But it's not that commonly used. ## Images Images are done the same way as links but with an exclamation point in front! + ```markdown ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") ``` + And reference style works as expected. -```markdown -![This is the alt-attribute.][myimage] -[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" -``` +
![This is the alt-attribute.][myimage]
 
+[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
## Miscellany ### Auto-links + ```markdown is equivalent to [http://testwebsite.com/](http://testwebsite.com/) ``` ### Auto-links for emails + ```markdown ``` ### Escaping characters + ```markdown I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. @@ -288,6 +299,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. ### Keyboard keys In Github Flavored Markdown, you can use a `` tag to represent keyboard keys. + ```markdown Your computer crashed? Try sending a Ctrl+Alt+Del @@ -296,6 +308,7 @@ Your computer crashed? Try sending a Tables are only available in Github Flavored Markdown and are slightly cumbersome, but if you really want it: + ```markdown | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | @@ -309,5 +322,6 @@ Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop ``` + --- For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From e4e737c37125ed831b8f4d24d2d4953814ef9722 Mon Sep 17 00:00:00 2001 From: Laoujin Date: Fri, 8 Jan 2016 19:50:57 +0100 Subject: [PowerShell/en]: fixed typos/layout. Added some extra aliases/info. --- powershell.html.markdown | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index 8920d254..fc944b85 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -247,10 +247,12 @@ function New-Website() { [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') # Note that .NET functions MUST be called with parentheses -# while PS functions CANNOT be called with parentheses +# while PS functions CANNOT be called with parentheses. +# If you do call a cmdlet/PS function with parentheses, +# it is the same as passing a single parameter list $writer = New-Object System.IO.StreamWriter($path, $true) $writer.Write([Environment]::NewLine) -$write.Dispose() +$writer.Dispose() ### IO # Reading a value from input: @@ -268,12 +270,14 @@ Get-Command ConvertTo-*,ConvertFrom-* # Refresh your PATH $env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") + # Find Python in path $env:PATH.Split(";") | Where-Object { $_ -like "*python*"} # Change working directory without having to remember previous path Push-Location c:\temp # change working directory to c:\temp Pop-Location # change back to previous working directory +# Aliases are: pushd and popd # Unblock a directory after download Get-ChildItem -Recurse | Unblock-File @@ -308,6 +312,7 @@ if (-not (Test-Path $Profile)) { ``` Interesting Projects + * [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) PowerShell tutorials * [PSGet](https://github.com/psget/psget) NuGet for PowerShell * [PSReadLine](https://github.com/lzybkr/PSReadLine/) A bash inspired readline implementation for PowerShell (So good that it now ships with Windows10 by default!) @@ -318,6 +323,7 @@ Interesting Projects * [PowerShell Community Extensions](http://pscx.codeplex.com/) (Dead) Not covered + * WMI: Windows Management Intrumentation (Get-CimInstance) * Multitasking: Start-Job -scriptBlock {...}, * Code Signing -- cgit v1.2.3 From 759a6a29aa02d53098d571999e175b4bd03a3052 Mon Sep 17 00:00:00 2001 From: ditam Date: Fri, 8 Jan 2016 21:09:47 +0100 Subject: add language label --- hu-hu/yaml-hu.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/hu-hu/yaml-hu.html.markdown b/hu-hu/yaml-hu.html.markdown index aca6cd37..37ce4cb2 100644 --- a/hu-hu/yaml-hu.html.markdown +++ b/hu-hu/yaml-hu.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Tamás Diószegi", "https://github.com/ditam"] +lang: hu-hu --- A YAML egy adat sorosító nyelv, amit úgy terveztek, hogy közvetlenül is -- cgit v1.2.3 From 15a7e7ace2e61470c5b0de667d33d06a1223ba46 Mon Sep 17 00:00:00 2001 From: SWalls Date: Sun, 10 Jan 2016 17:22:32 -0700 Subject: Changed a to b in comment about list assignment, and pluralized 'variable'. --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 8cc03320..31b5bbe1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -97,13 +97,13 @@ False or True # => True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (is vs. ==) is checks if two variable refer to the same object, but == checks +# (is vs. ==) is checks if two variables refer to the same object, but == checks # if the objects pointed to have the same values. a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] b = a # Point b at what a is pointing to b is a # => True, a and b refer to the same object b == a # => True, a's and b's objects are equal -b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = [1, 2, 3, 4] # Point b at a new list, [1, 2, 3, 4] b is a # => False, a and b do not refer to the same object b == a # => True, a's and b's objects are equal -- cgit v1.2.3 From f94dea8379b5e7a28990eac371f9c9cca19ab472 Mon Sep 17 00:00:00 2001 From: Matteo Baglini Date: Tue, 12 Jan 2016 00:32:03 +0100 Subject: Use proper string comparison syntax --- bash.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 211d2944..bd2d5984 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -83,7 +83,7 @@ echo Hello, $Name! # We have the usual if structure: # use 'man test' for more info about conditionals -if [ $Name -ne $USER ] +if [ $Name != $USER ] then echo "Your name isn't your username" else @@ -91,12 +91,12 @@ else fi # NOTE: if $Name is empty, bash sees the above condition as: -if [ -ne $USER ] +if [ != $USER ] # which is invalid syntax # so the "safe" way to use potentially empty variables in bash is: -if [ "$Name" -ne $USER ] ... +if [ "$Name" != $USER ] ... # which, when $Name is empty, is seen by bash as: -if [ "" -ne $USER ] ... +if [ "" != $USER ] ... # which works as expected # There is also conditional execution -- cgit v1.2.3 From 8ecf73a086b41a33058211f7a415b771bb04f79d Mon Sep 17 00:00:00 2001 From: Paul Brewczynski Date: Wed, 13 Jan 2016 10:01:46 +0100 Subject: Updated documentation syntax As Xcode switched to Markdown syntax, I've updated it. --- swift.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index e6bf1621..c54f8e00 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -221,9 +221,9 @@ A greet operation - A bullet in docs - Another bullet in the docs -:param: name A name -:param: day A day -:returns: A string containing the name and day value. +- Parameter name : A name +- Parameter day : A day +- Returns : A string containing the name and day value. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." -- cgit v1.2.3 From b41a699099ff3d6d770775dc73ab47466f498454 Mon Sep 17 00:00:00 2001 From: Tomy Date: Thu, 14 Jan 2016 00:01:47 +0900 Subject: translate until line 100 --- ja-jp/php.html.markdown | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 4448a1f5..0cea2041 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -39,61 +39,62 @@ Hello World Again! * 型と変数について */ -// Variables begin with the $ symbol. -// A valid variable name starts with a letter or underscore, -// followed by any number of letters, numbers, or underscores. +// 変数は"$"マークで始まります +// 有効な変数名にするには、文字またはアンダースコア(_)で始めて, +// その後はどんな数字でも、文字でも、アンダースコアで続けても構いません -// Boolean values are case-insensitive +//ブーリアン値は大文字、小文字問いません $boolean = true; // or TRUE or True $boolean = false; // or FALSE or False -// Integers +// 数値 $int1 = 12; // => 12 $int2 = -12; // => -12 -$int3 = 012; // => 10 (a leading 0 denotes an octal number) -$int4 = 0x0F; // => 15 (a leading 0x denotes a hex literal) +$int3 = 012; // => 10 (先頭の0は8進法を示す) +$int4 = 0x0F; // => 15 (先頭の0xは16進法を示す) -// Floats (aka doubles) +// floats(浮動小数) (別名double) $float = 1.234; $float = 1.2e3; $float = 7E-10; -// Delete variable +// 変数の削除 unset($int1); -// Arithmetic +// 計算式 $sum = 1 + 1; // 2 $difference = 2 - 1; // 1 $product = 2 * 2; // 4 $quotient = 2 / 1; // 2 -// Shorthand arithmetic +// 式の省略 $number = 0; -$number += 1; // Increment $number by 1 -echo $number++; // Prints 1 (increments after evaluation) -echo ++$number; // Prints 3 (increments before evaluation) -$number /= $float; // Divide and assign the quotient to $number +$number += 1; // $numberに1加算Increment $number by 1 +echo $number++; // 1 がプリントされる(式の評価の後に加算される) +echo ++$number; // 3 がプリントされる(式の評価の前に加算される) +$number /= $float; // 割り算した結果の商を$numberに割り当てる -// Strings should be enclosed in single quotes; +// 文字列はシングルクォートで囲むのが望ましいです $sgl_quotes = '$String'; // => '$String' -// Avoid using double quotes except to embed other variables +// 文字列中に、他の変数を埋め込みたい場合以外は、ダブルクォートを使用するのはやめましょう $dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' // Special characters are only escaped in double quotes +// 特殊文字はダブルクォートによってのみ、エスケープされます $escaped = "This contains a \t tab character."; $unescaped = 'This just contains a slash and a t: \t'; -// Enclose a variable in curly braces if needed +// 必要があれば、変数を波括弧で囲みます $money = "I have $${number} in the bank."; -// Since PHP 5.3, nowdocs can be used for uninterpolated multi-liners +// PHP 5.3から、nowdocs形式が変数の挿入をしない複数行の文字列の定義に使用できます $nowdoc = <<<'END' Multi line string END; -// Heredocs will do string interpolation +// ヒアドキュメント形式なら、文字列中に変数の挿入を行えます。 $heredoc = << Date: Wed, 13 Jan 2016 23:50:24 -0500 Subject: Created the first asciidoc tutorial --- asciidoc.markdown | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 asciidoc.markdown diff --git a/asciidoc.markdown b/asciidoc.markdown new file mode 100644 index 00000000..d6cfeca0 --- /dev/null +++ b/asciidoc.markdown @@ -0,0 +1,66 @@ +--- +language: asciidoc +contributors: + - ["Ryan Mavilia", "http://unoriginality.rocks/:] +filename: asciidoc.md +--- + +AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization. + +Document Header + +Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line. + +Title Only + +```asciidoc += Document Title + +First sentence of document. +``` + +Title and Author + +```asciidoc += Document Title +First Last + +Start of this document. +``` + +Multiple Authors +```asciidoc += Document Title +John Doe ; Jane Doe; Black Beard + +Start of a doc with multiple authors. +``` + +Revision Line (requires an author line) +```asciidoc += Doc Title V1 +Potato Man +v1.0, 2016-01-13 + +This article about chips is going to be fun. +``` + +Section Titles + +```asciidoc += Level 0 (may only be used in document's header) + +== Level 1

+ +=== Level 2

+ +==== Level 3

+ +===== Level 4

+ +====== Level 5
+ +======= Level 6 + +``` + -- cgit v1.2.3 From e7f1108b20a1fa5f7946ae205852751bed48b40d Mon Sep 17 00:00:00 2001 From: Tomy Date: Thu, 14 Jan 2016 21:15:25 +0900 Subject: translate 100 to 150 lines --- ja-jp/php.html.markdown | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 0cea2041..c01e2ba0 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -100,53 +100,54 @@ Multi line $sgl_quotes END; -// String concatenation is done with . +// 文字列の連結は . で行います echo 'This string ' . 'is concatenated'; -// Strings can be passed in as parameters to echo +// 別々のパラメータとしてechoに渡すこともできます echo 'Multiple', 'Parameters', 'Valid'; /******************************** - * Constants + * 定数 */ -// A constant is defined by using define() -// and can never be changed during runtime! +// 定数は define() を使って定義します +// また、実行中は変更することができないので注意が必要です! -// a valid constant name starts with a letter or underscore, -// followed by any number of letters, numbers, or underscores. +// 有効は定数は文字かアンダースコアで始めます +// それ移行のは、どんな数値でも文字列でもアンダースコアでも構いません define("FOO", "something"); +// 定義した名前をそのまま($はつけずに)使用することで、定数にアクセスできます // access to a constant is possible by direct using the choosen name echo 'This outputs '.FOO; /******************************** - * Arrays + * 配列 */ -// All arrays in PHP are associative arrays (hashmaps), +// PHPの配列はすべて連想配列です -// Associative arrays, known as hashmaps in some languages. +// 連想配列は、他の言語ではハッシュ(ハッシュマップ)として知られています -// Works with all PHP versions +// すべてのバージョンのPHPで動作します $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); -// PHP 5.4 introduced a new syntax +// PHP 5.4 から、新しいシンタックスが導入されました $associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; -echo $associative['One']; // prints 1 +echo $associative['One']; // 1とプリントされます -// List literals implicitly assign integer keys +// キーを指定しないシンプルな配列にも、自動的に数値キーが振られます $array = ['One', 'Two', 'Three']; echo $array[0]; // => "One" -// Add an element to the end of an array +// 配列の最後に要素を追加する $array[] = 'Four'; -// or +// または、次のようにも書けます array_push($array, 'Five'); -// Remove element from array +// 配列から要素を削除 unset($array[3]); /******************************** -- cgit v1.2.3 From e8c0c436c9aad0f3902a4e0826bf72de49bde12b Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Thu, 14 Jan 2016 10:17:51 -0500 Subject: Added observer pattern, per barkthin's feedback --- solidity.html.markdown | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 71a44b92..3a5e8ff5 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -506,7 +506,8 @@ function remove() { // Steps: 1. Commit to something, 2. Reveal commitment sha3("some_bid_amount", "some secret"); // commit -// call contract's reveal function showing bid plus secret that hashes to SHA3 +// call contract's reveal function in the future +// showing bid plus secret that hashes to SHA3 reveal(100, "mySecret"); // B. Storage optimization @@ -531,7 +532,45 @@ reveal(100, "mySecret"); // Contracts must be manually called to handle time-based scheduling; can create external // code to regularly ping, or provide incentives (ether) for others to -// E. State machines +// E. Observer Pattern +// An Observer Pattern lets you register as a subscriber and +// register a function which is called by the oracle (note, the oracle pays +// for this action to be run) +// Some similarities to subscription in Pub/sub + +// This is an abstract contract, both client and server classes import +// the client should implement +contract SomeOracleCallback { + function oracleCallback(int _value, uint _time, bytes32 info) external; +} + +contract SomeOracle { + SomeOracleCallback[] callbacks; // array of all subscribers + + // Register subscriber + function addSubscriber(SomeOracleCallback a) { + callbacks.push(a); + } + + function notify(value, time, info) private { + for(uint i = 0;i < callbacks.length; i++) { + // all called subscribers must implement the oracleCallback + callbacks[i].oracleCallback(value, time, info); + } + } + + function doSomething() public { + // Code to do something + + // Notify all subscribers + notify(_value, _time, _info); + } +} + +// Now, your client contract can addSubscriber by importing SampleOracleCallback +// and registering with Sample Oracle + +// F. State machines // see example below for State enum and inState modifier @@ -748,7 +787,7 @@ someContractAddress.callcode('function_name'); - Libraries ## Style -- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy) +- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy ## Future To Dos - New keywords: protected, inheritable -- cgit v1.2.3 From 1c1944acb480d9c463c59136eba5ffa19f376fdc Mon Sep 17 00:00:00 2001 From: Paul Brewczynski Date: Thu, 14 Jan 2016 19:11:45 +0100 Subject: Updated comment on documentation of Swift functions Documentation syntax is no longer reStructuredText, It's "Swift-flavored version of Markdown" http://nshipster.com/swift-documentation/ --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index c54f8e00..46996526 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -213,7 +213,7 @@ default: // required (in order to cover all possible input) // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function with Swift header docs (format as reStructedText) +// Function with Swift header docs (format as Swift-modified Markdown syntax) /** A greet operation -- cgit v1.2.3 From 810108ee73a6acc882155ec7ff1bc07983ced05e Mon Sep 17 00:00:00 2001 From: Nemil Dalal Date: Thu, 14 Jan 2016 14:01:45 -0500 Subject: Fixed error in name --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index 3a5e8ff5..a511bbb3 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -567,8 +567,8 @@ contract SomeOracle { } } -// Now, your client contract can addSubscriber by importing SampleOracleCallback -// and registering with Sample Oracle +// Now, your client contract can addSubscriber by importing SomeOracleCallback +// and registering with Some Oracle // F. State machines // see example below for State enum and inState modifier -- cgit v1.2.3 From b5bdff8f9eca5385dcd76c42cd19b17e58307584 Mon Sep 17 00:00:00 2001 From: Tomy Date: Sat, 16 Jan 2016 00:07:29 +0900 Subject: translate to 328 --- ja-jp/php.html.markdown | 85 +++++++++++++++++++++++++------------------------ 1 file changed, 44 insertions(+), 41 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index c01e2ba0..22c0561c 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -151,37 +151,39 @@ array_push($array, 'Five'); unset($array[3]); /******************************** - * Output + * 出力 */ echo('Hello World!'); -// Prints Hello World! to stdout. +// 標準出力にHello World! とプリントします +// 標準出力はブラウザーで実行していればWebページに出力されます // Stdout is the web page if running in a browser. -print('Hello World!'); // The same as echo +print('Hello World!'); // echoの結果と同じです +// echo は言語自体の構成要素であり、括弧なしで呼び出せます // echo is actually a language construct, so you can drop the parentheses. echo 'Hello World!'; -print 'Hello World!'; // So is print +print 'Hello World!'; // printも同様です $paragraph = 'paragraph'; -echo 100; // Echo scalar variables directly -echo $paragraph; // or variables +echo 100; // スカラー数値を直接出力します +echo $paragraph; // 変数も使用できます -// If short open tags are configured, or your PHP version is -// 5.4.0 or greater, you can use the short echo syntax +// PHPタグの短縮型が設定されているか、使用しているPHPのバージョンが +// 5.4.0 以上であれば、短縮echoシンタックスを使用できます ?>

2 echo $z; // => 2 @@ -189,23 +191,23 @@ $y = 0; echo $x; // => 2 echo $z; // => 0 -// Dumps type and value of variable to stdout -var_dump($z); // prints int(0) +// 変数の型と値を標準出力へダンプします +var_dump($z); // int(0) と出力されます -// Prints variable to stdout in human-readable format +// 人間が読めるフォーマットで変数を標準出力にプリントします print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) /******************************** - * Logic + * ロジック */ $a = 0; $b = '0'; $c = '1'; $d = '1'; -// assert throws a warning if its argument is not true +// assertは引数がfalseの場合、Exceptionを投げます -// These comparisons will always be true, even if the types aren't the same. +//これらの比較は型が違ったとしても、常に真です。 assert($a == $b); // equality assert($c != $a); // inequality assert($c <> $a); // alternative inequality @@ -214,32 +216,33 @@ assert($c > $b); assert($a <= $b); assert($c >= $d); -// The following will only be true if the values match and are the same type. +// 次の比較は値が等しく、かつ同じ型である場合のみ真です assert($c === $d); assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); -// spaceship operator since PHP 7 +// spaceship演算子はPHP7から使用可能です $a = 100; $b = 1000; -echo $a <=> $a; // 0 since they are equal -echo $a <=> $b; // -1 since $a < $b -echo $b <=> $a; // 1 since $b > $a +echo $a <=> $a; // 等しいので0になります +echo $a <=> $b; // $a < $b なので -1 です +echo $b <=> $a; // $b > $a なので 1 です -// Variables can be converted between types, depending on their usage. +// 変数は使用するコンテキストによって、変換されます $integer = 1; echo $integer + $integer; // => 2 $string = '1'; -echo $string + $string; // => 2 (strings are coerced to integers) +echo $string + $string; // => 2 (文字列は強制的に数値として処理されます) $string = 'one'; echo $string + $string; // => 0 -// Outputs 0 because the + operator cannot cast the string 'one' to a number +// '+'演算子は文字列'one'を数値にキャストできないので、0と出力されます +// 型のキャスティングによって、変数を指定したもう一つの型として扱うことができます // Type casting can be used to treat a variable as another type $boolean = (boolean) 1; // => true @@ -247,15 +250,15 @@ $boolean = (boolean) 1; // => true $zero = 0; $boolean = (boolean) $zero; // => false -// There are also dedicated functions for casting most types +// 型をキャストするため専用の関数も存在します $integer = 5; $string = strval($integer); -$var = null; // Null value +$var = null; // Null値 /******************************** - * Control Structures + * 制御構造 */ if (true) { @@ -274,15 +277,15 @@ if (false) { print 'Does'; } -// ternary operator +// 参考演算子 print (false ? 'Does not get printed' : 'Does'); -// ternary shortcut operator since PHP 5.3 -// equivalent of "$x ? $x : 'Does'"" +// PHP 5.3から、三項演算子の短縮形が使用できます +// $x ? $x : 'Does'と同義です $x = false; print($x ?: 'Does'); -// null coalesce operator since php 7 +// null合体演算子はPHP 7から使用できます $a = null; $b = 'Does print'; echo $a ?? 'a is not set'; // prints 'a is not set' @@ -300,29 +303,29 @@ if ($x === '0') { -// This alternative syntax is useful for templates: +// :を用いる別の構文はテンプレートで有用です ?> -This is displayed if the test is truthy. +この部分はifが真のとき表示されます -This is displayed otherwise. +それ以外の場合は、この部分が表示されます Date: Sat, 16 Jan 2016 19:30:25 +0100 Subject: [Swift/en] Deleted semicolon to be consistent - Small Fix this line let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon show off semicolon use. But after that semicolon is not used, so I removed inconsistency. --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index 46996526..46768375 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -392,7 +392,7 @@ testTryStuff() public class Shape { public func getArea() -> Int { - return 0; + return 0 } } -- cgit v1.2.3 From b8784faf28ffcda0bc8b5a122a7845ebc6b3432d Mon Sep 17 00:00:00 2001 From: Tomy Date: Sun, 17 Jan 2016 13:04:25 +0900 Subject: translate to 487 --- ja-jp/php.html.markdown | 64 +++++++++++++++++++++++++------------------------ 1 file changed, 33 insertions(+), 31 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 22c0561c..96d45f08 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -328,7 +328,7 @@ switch ($x) { //デフォルトで何かを実行します } -// While, do...while and for loops are probably familiar +// while, do, forの構文は、おそらく他の言語とも共通なものです $i = 0; while ($i < 5) { echo $i++; @@ -351,14 +351,14 @@ echo "\n"; $wheels = ['bicycle' => 2, 'car' => 4]; -// Foreach loops can iterate over arrays +//Foreachループによって、 配列を反復処理できます foreach ($wheels as $wheel_count) { echo $wheel_count; } // Prints "24" echo "\n"; -// You can iterate over the keys as well as the values +// 値と同じ様に、keyも反復処理できます foreach ($wheels as $vehicle => $wheel_count) { echo "A $vehicle has $wheel_count wheels"; } @@ -382,20 +382,20 @@ for ($i = 0; $i < 5; $i++) { /******************************** - * Functions + * 関数 */ -// Define a function with "function": +// 関数を"function"で定義します function my_function () { return 'Hello'; } echo my_function(); // => "Hello" -// A valid function name starts with a letter or underscore, followed by any -// number of letters, numbers, or underscores. +// 有効な関数名は、文字またはアンダースコアで始めます。それ以降は +// どれだけ長い文字、数値、アンダースコアを続けても構いません -function add ($x, $y = 1) { // $y is optional and defaults to 1 +function add ($x, $y = 1) { // $yはオプショナルな値であり、デフォルトで 1 です $result = $x + $y; return $result; } @@ -403,10 +403,10 @@ function add ($x, $y = 1) { // $y is optional and defaults to 1 echo add(4); // => 5 echo add(4, 2); // => 6 -// $result is not accessible outside the function -// print $result; // Gives a warning. +// $result には、関数の外からアクセス出来ません +// print $result; // エラーになります -// Since PHP 5.3 you can declare anonymous functions; +// PHP 5.3 から、無名関数が使えます $inc = function ($x) { return $x + 1; }; @@ -417,9 +417,9 @@ function foo ($x, $y, $z) { echo "$x - $y - $z"; } -// Functions can return functions +// 関数は、関数を返すことができます function bar ($x, $y) { - // Use 'use' to bring in outside variables + // 関数外の変数を利用したいときは、'use'を使います return function ($z) use ($x, $y) { foo($x, $y, $z); }; @@ -428,14 +428,15 @@ function bar ($x, $y) { $bar = bar('A', 'B'); $bar('C'); // Prints "A - B - C" -// You can call named functions using strings +// 文字列を使って、定義済みの関数を呼び出すことができます $function_name = 'add'; echo $function_name(1, 2); // => 3 -// Useful for programatically determining which function to run. -// Or, use call_user_func(callable $callback [, $parameter [, ... ]]); +// プログラミング中に、動的に動かす関数を決める場合に便利です。 +// もしくは、call_user_func(callable $callback [, $parameter [, ... ]]) を使っても同じことができます -// You can get the all the parameters passed to a function + +// 特に指定しなくても、渡された引数を受け取ることもできます function parameters() { $numargs = func_num_args(); if ($numargs > 0) { @@ -450,38 +451,39 @@ function parameters() { parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | /******************************** - * Includes + * ファイルの読み込み */ Date: Sun, 17 Jan 2016 16:18:48 +0900 Subject: translate all --- ja-jp/php.html.markdown | 118 +++++++++++++++++++++++++----------------------- 1 file changed, 61 insertions(+), 57 deletions(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index 96d45f08..a5b48120 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -487,51 +487,52 @@ $value = include 'my-include.php'; /* */ /******************************** - * Classes + * クラス */ -// Classes are defined with the class keyword +// クラスはclassキーワードで定義します class MyClass { - const MY_CONST = 'value'; // A constant + const MY_CONST = 'value'; // クラス定数です static $staticVar = 'static'; - // Static variables and their visibility + // スタティック変数とアクセス制限 public static $publicStaticVar = 'publicStatic'; - // Accessible within the class only + // クラス内でのみアクセス可能 private static $privateStaticVar = 'privateStatic'; - // Accessible from the class and subclasses + // そのクラスと子クラスで参照可能 protected static $protectedStaticVar = 'protectedStatic'; - // Properties must declare their visibility + // プロパティはアクセス制限を宣言する必要があります public $property = 'public'; public $instanceProp; - protected $prot = 'protected'; // Accessible from the class and subclasses - private $priv = 'private'; // Accessible within the class only + protected $prot = 'protected'; // そのクラスと子クラスで参照可能 + private $priv = 'private'; // クラス内でのみアクセス可能 - // Create a constructor with __construct + // __constructでコンストラクターを生成します public function __construct($instanceProp) { - // Access instance variables with $this + // $thisでインスタンス変数にアクセスします $this->instanceProp = $instanceProp; } - // Methods are declared as functions inside a class + // メソッドはクラス内で関数として定義されます public function myMethod() { print 'MyClass'; } - //final keyword would make a function unoverridable + // finalキーワードは関数の上書きを禁止します final function youCannotOverrideMe() { } /* - * Declaring class properties or methods as static makes them accessible without - * needing an instantiation of the class. A property declared as static can not - * be accessed with an instantiated class object (though a static method can). + * クラスプロパティまたはメソッドをstaticとして作成すれば、 + * クラスをインスタンス化(newすること)しなくてもアクセスできます。 + * プロパティをstaticとして定義すると、 + * インスタンス化されたクラスオブジェクトを通してのアクセスはできなくなります。 */ public static function myStaticMethod() @@ -540,23 +541,23 @@ class MyClass } } -// Class constants can always be accessed statically +// クラス定数は、いつでも静的にアクセスできます。 echo MyClass::MY_CONST; // Outputs 'value'; echo MyClass::$staticVar; // Outputs 'static'; MyClass::myStaticMethod(); // Outputs 'I am static'; -// Instantiate classes using new +// クラスをインスタンス化するには、newを使います。 $my_class = new MyClass('An instance property'); -// The parentheses are optional if not passing in an argument. +// 括弧はもし引数を渡す必要がなければ省略可能です。 -// Access class members using -> +// ->を使ってクラスのメンバにアクセスします。 echo $my_class->property; // => "public" echo $my_class->instanceProp; // => "An instance property" $my_class->myMethod(); // => "MyClass" -// Extend classes using "extends" +// extendsを使用してクラスを継承します。 class MyOtherClass extends MyClass { function printProtectedProperty() @@ -564,7 +565,7 @@ class MyOtherClass extends MyClass echo $this->prot; } - // Override a method + // メソッドを上書きします。 function myMethod() { parent::myMethod(); @@ -580,7 +581,7 @@ final class YouCannotExtendMe { } -// You can use "magic methods" to create getters and setters +// 「マジックメソッド」を使ってゲッターとセッターを生成できます。 class MyMapClass { private $property; @@ -597,12 +598,12 @@ class MyMapClass } $x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +echo $x->property; // __get() メソッドを使用します +$x->property = 'Something'; // __set() メソッドを使用します -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// クラスは抽象クラスにもできます(abstractキーワードを使用します)し、 +// インターフェースを実装することもできます(implementsキーワードを使用します)。 +// インターフェースはinterfaceキーワードで定義します。 interface InterfaceOne { @@ -614,7 +615,7 @@ interface InterfaceTwo public function doSomethingElse(); } -// interfaces can be extended +// インターフェースは継承することができます interface InterfaceThree extends InterfaceTwo { public function doAnotherContract(); @@ -639,7 +640,7 @@ class MyConcreteClass extends MyAbstractClass implements InterfaceTwo } -// Classes can implement more than one interface +// クラスは1つ以上のインターフェースを実装できます。 class SomeOtherClass implements InterfaceOne, InterfaceTwo { public function doSomething() @@ -655,10 +656,10 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo /******************************** - * Traits + * トレイト */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// トレイトはPHP 5.4.0 以上で使用可能で、traitキーワードで定義します。 trait MyTrait { @@ -678,39 +679,40 @@ $cls->myTraitMethod(); // Prints "I have MyTrait" /******************************** - * Namespaces + * 名前空間 */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// このセクションは名前空間の定義はファイルの先頭で宣言される必要があるため、 +// 独立しています。 +// そのケースには当てはまらないふりをして続けましょう。 Date: Sun, 17 Jan 2016 16:21:04 +0900 Subject: fix typo --- ja-jp/php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja-jp/php.html.markdown b/ja-jp/php.html.markdown index a5b48120..b07dfb2f 100644 --- a/ja-jp/php.html.markdown +++ b/ja-jp/php.html.markdown @@ -277,7 +277,7 @@ if (false) { print 'Does'; } -// 参考演算子 +// 三項演算子 print (false ? 'Does not get printed' : 'Does'); // PHP 5.3から、三項演算子の短縮形が使用できます -- cgit v1.2.3 From 0bd64705a8096ed1ad808653bd88f1372533dd47 Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Sun, 17 Jan 2016 03:55:54 -0500 Subject: Update asciidoc.markdown --- asciidoc.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/asciidoc.markdown b/asciidoc.markdown index d6cfeca0..b98d0fa9 100644 --- a/asciidoc.markdown +++ b/asciidoc.markdown @@ -45,22 +45,22 @@ v1.0, 2016-01-13 This article about chips is going to be fun. ``` -Section Titles +Section Titles ```asciidoc = Level 0 (may only be used in document's header) -== Level 1

+== Same as

-=== Level 2

+=== Same as

-==== Level 3

+==== Same as

-===== Level 4

+===== Same as
-====== Level 5
+====== Same as
-======= Level 6 +======= Same as ``` -- cgit v1.2.3 From b253b8e4cba10dc28023e613498473f78e3a17ad Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Sun, 17 Jan 2016 04:04:41 -0500 Subject: Rename asciidoc.markdown to asciidoc.html.markdown --- asciidoc.html.markdown | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++ asciidoc.markdown | 66 -------------------------------------------------- 2 files changed, 66 insertions(+), 66 deletions(-) create mode 100644 asciidoc.html.markdown delete mode 100644 asciidoc.markdown diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown new file mode 100644 index 00000000..b98d0fa9 --- /dev/null +++ b/asciidoc.html.markdown @@ -0,0 +1,66 @@ +--- +language: asciidoc +contributors: + - ["Ryan Mavilia", "http://unoriginality.rocks/:] +filename: asciidoc.md +--- + +AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization. + +Document Header + +Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line. + +Title Only + +```asciidoc += Document Title + +First sentence of document. +``` + +Title and Author + +```asciidoc += Document Title +First Last + +Start of this document. +``` + +Multiple Authors +```asciidoc += Document Title +John Doe ; Jane Doe; Black Beard + +Start of a doc with multiple authors. +``` + +Revision Line (requires an author line) +```asciidoc += Doc Title V1 +Potato Man +v1.0, 2016-01-13 + +This article about chips is going to be fun. +``` + +Section Titles + +```asciidoc += Level 0 (may only be used in document's header) + +== Same as

+ +=== Same as

+ +==== Same as

+ +===== Same as

+ +====== Same as
+ +======= Same as + +``` + diff --git a/asciidoc.markdown b/asciidoc.markdown deleted file mode 100644 index b98d0fa9..00000000 --- a/asciidoc.markdown +++ /dev/null @@ -1,66 +0,0 @@ ---- -language: asciidoc -contributors: - - ["Ryan Mavilia", "http://unoriginality.rocks/:] -filename: asciidoc.md ---- - -AsciiDoc is a markup language similar to Markdown and it can be used for anything from books to blogs. Created in 2002 by Stuart Rackham the language is simple but it allows for a great amount of customization. - -Document Header - -Headers are optional and can't contain blank lines. It must be offset from content by at least one blank line. - -Title Only - -```asciidoc -= Document Title - -First sentence of document. -``` - -Title and Author - -```asciidoc -= Document Title -First Last - -Start of this document. -``` - -Multiple Authors -```asciidoc -= Document Title -John Doe ; Jane Doe; Black Beard - -Start of a doc with multiple authors. -``` - -Revision Line (requires an author line) -```asciidoc -= Doc Title V1 -Potato Man -v1.0, 2016-01-13 - -This article about chips is going to be fun. -``` - -Section Titles - -```asciidoc -= Level 0 (may only be used in document's header) - -== Same as

- -=== Same as

- -==== Same as

- -===== Same as

- -====== Same as
- -======= Same as - -``` - -- cgit v1.2.3 From e91cb98abedd979f67acdc08dd7cb81b75f317cc Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 19:38:14 +0100 Subject: Translated Wolfram tutorial to french --- fr-fr/wolfram-fr.html.markdown | 166 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 fr-fr/wolfram-fr.html.markdown diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown new file mode 100644 index 00000000..d297bd74 --- /dev/null +++ b/fr-fr/wolfram-fr.html.markdown @@ -0,0 +1,166 @@ +--- +language: wolfram +contributors: + - ["hyphz", "http://github.com/hyphz/"] + - ["altaris", "http://github.com/altaris/"] +filename: learnwolfram.nb +--- + +Le langage Wolfram est utilisé dans les programmes suivants : +* La ligne de commandes interactive noyau du Raspberry Pi, mais elle ne peut pas +gérer des éléments graphiques. +* _Mathematica_, un éditeur de texte riche spécialisé pour les mathématiques : +appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule +contenant le résultat. +* _Wolfram Wokbench_, une variante d'Eclipse spécialisée pour le langage +Wolfram. + +Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant, le +copier-coller directement dans Mathematica peut causer des problèmes de +formatage, car il ne contient aucune information de mise en page. + +``` +(* Ceci est un commentaire *) + +(* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des + cellules de texte et insérer de jolies images *) + +(* Saisissez une opération et appuyez sur Shift + Entrée pour obtenir le + résultat *) +2*2 (* 4 *) +5+8 (* 13 *) + +(* Appels de fonction *) +(* Le langage Wolfram est sensible à la casse *) +Sin[Pi/2] (* 1 *) + +(* Syntaxe alternative pour les appels de fonction à 1 paramètre *) +Sin@(Pi/2) (* 1 *) +(Pi/2) // Sin (* 1 *) + +(* Dans le langage Wolfram, toutes les expressions sont en réalité des appels de + fonction *) +Times[2, 2] (* 4 *) +Plus[5, 8] (* 13 *) + +(* Utiliser une variable pour la première fois la déclare globalement *) +x = 5 (* 5 *) +x == 5 (* True, l'assignation et le test d'égalité est écrit comme + dans le C *) +x (* 5 *) +x = x + 5 (* 10 *) +x (* 10 *) +Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *) +x (* 20 *) + +(* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des + variables non déclarées n'est pas illégal *) +cow + 5 (* 5 + cow, comme cow n'est pas déclarée, l'évaluation + s'arrête là *) +cow + 5 + 10 (* 15 + cow, on évalue ce qu'on peut... *) +% (* 15 + cow, % représente le dernier résultat *) +% - cow (* 15, les variables non déclarées peuvent quand même + s'annuler *) +moo = cow + 5 (* Attention : moo est ici une expression et non un nombre *) + +(* Déclaration d'une fonction *) +Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme + à droite *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets + fermants si moches *) +(Pi/2) // Sin // Double(* 2, Utiliser // permet d'écrire les fonctions dans + l'ordre d'appel *) + +(* Pour la programmation impérative, utiliser ; pour séparer les expressions *) +MyFirst[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires + car ; est prioritaire sur := *) +MyFirst[] (* Hello World *) + +(* Boucles For à la C *) +PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Crée une table associative *) +myHash[["Green"]] (* 2, l'utilise *) +myHash[["Green"]] := 5 (* 5, la modifie *) +myHash[["Puce"]] := 3.5 (* 3.5, l'étend *) +KeyDropFrom[myHash, "Green"] (* Supprime la clé "Green" *) +Keys[myHash] (* {Red} *) +Values[myHash] (* {1} *) + +(* Pour finir, toute bonne démonstration du langage Wolfram contient un + Manipulate ! *) +Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui + affiche y^2, permettant à l'utilisateur de + modifier la valeur de y grâce à un contrôle + allant de 0 à 20. Ne fonctionne que si le + logiciel utilisé gère les éléments graphique. *) +``` + +## Envie d'aller plus loin ? + +* [Documentation du langage Wolfram (en anglais)] +(http://reference.wolfram.com/language/) \ No newline at end of file -- cgit v1.2.3 From c70f53aabea745d4450aa51abdc33aa1ac51bdd2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 21:53:21 +0100 Subject: Translated make tutorial to french --- fr-fr/make-fr.html.markdown | 266 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100644 fr-fr/make-fr.html.markdown diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown new file mode 100644 index 00000000..8643ba45 --- /dev/null +++ b/fr-fr/make-fr.html.markdown @@ -0,0 +1,266 @@ +--- +language: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["altaris", "https://github.com/altaris"] +filename: Makefile +--- + +Un makefile est un fichier qui définit un ensemble de règles liées entre elles +pour créer une ou plusieurs cibles. L'idée est d'effectuer le moins de travail +possible afin de mettre à jour la ou les cibles en fonction des dépendances. + +Écrit en un week-end par Stuart Feldman en 1976, le make et les +makefiles sont encore très utilisés (principalement dans les systèmes Unix), +malgré la concurrence et les critiques faites à son égard. + +Le programme make a plusieurs variantes. Dans ce tutoriel, nous utiliserons +l'implémentation standard : GNU make. + +```make + +# Ceci est un commentaire. + +# Un makefile devrait être nommé "Makefile" (avec ou sans la +# majuscule). Il peut alors être exécuté par `make `. +# Ce nommage n'est toutefois pas obligatoire : utiliser +# `make -f "fichier" `. + +# ATTENTION : l'indentation est quant à elle obligatoire, et se fait avec des +# tabulations, pas avec des espaces ! + +#----------------------------------------------------------------------- +# Les basiques +#----------------------------------------------------------------------- + +# Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. +file0.txt: + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. + +# Cette règle ne sera exécutée que si fichier0.txt est plus récent que +# fichier1.txt. +file1.txt: fichier0.txt + cat fichier0.txt > fichier1.txt + # Utiliser les même guillemets que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à être exécutée si cette + # commande échoue. + +# Un règle peut avoir plusieurs cibles et plusieurs dépendances. +file2.txt fichier3.txt: fichier0.txt fichier1.txt + touch fichier2.txt + touch fichier3.txt + +# Make affichera un avertissement si le makefile comporte plusieurs règles pour +# une même cible. Cependant les règles vides ne comptent pas, et peuvent être +# utilisées pour ajouter des dépendances plus facilement. + +#----------------------------------------------------------------------- +# Fausses règles +#----------------------------------------------------------------------- + +# Une fausse règle est un règle qui ne correspond pas à un fichier. +# Par définition, elle ne peut pas être à jour, et donc make l’exécutera à +# chaque demande. +all: maker process + +# La déclaration des règles peut être faite dans n'importe quel ordre. +maker: + touch ex0.txt ex1.txt + +# On peut transformer une règle en fausse règle grâce à la cible spéciale +# suivante : +.PHONY: all maker process + +# Un règle dépendante d'une fausse règle sera toujours exécutée. +ex0.txt ex1.txt: maker + +# Voici quelques exemples fréquents de fausses règles : all, make, clean, +# install... + +#----------------------------------------------------------------------- +# Variables automatiques et wildcards +#----------------------------------------------------------------------- + +# Utilise un wildcard pour des noms de fichier +process: fichier*.txt + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. + +# Même si la définition de la règle est scindée en plusieurs morceaux, $^ +# listera toutes les dépendances indiquées. +process: ex1.txt fichier0.txt +# Ici, fichier0.txt est un duplicata dans $+. + +#----------------------------------------------------------------------- +# Pattern matching +#----------------------------------------------------------------------- + +# En utilisant le pattern matching, on peut par exemple créer des règles pour +# convertir les fichiers d'un certain format dans un autre. +%.png: %.svg + inkscape --export-png $^ + +# Make exécute une règle même si le fichier correspondant est situé dans un sous +# dossier. En cas de conflit, la règle avec la meilleure correspondance est +# choisie. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# Dans ce type de conflit (même cible, même dépendances), make exécutera la +# dernière règle déclarée... +%.png: %.svg + @echo cette règle est choisie + +# Dans ce type de conflit (même cible mais pas les mêmes dépendances), make +# exécutera la première règle pouvant être exécutée. +%.png: %.ps + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + +# Make a des règles pré établies. Par exemple, il sait comment créer la cible +# *.o à partir de *.c. + +# Les makefiles plus vieux utilisent un matching par extension de fichier. +.png.ps: + @echo cette règle est similaire à une règle par pattern matching + +# Utiliser cette syntaxe pour déclarer une règle comme règle avec matching par +# extension de fichier. +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables, ou macros +#----------------------------------------------------------------------- + +# Les variables sont des chaînes de caractères. + +variable = Ted +variable2="Sarah" + +echo: + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + +# Les variables sont déclarées de 4 manières, de la plus grande priorité à la +# plus faible : +# 1 : dans la ligne de commande qui invoque make, +# 2 : dans le makefile, +# 3 : dans les variables d’environnement du terminal qui invoque make, +# 4 : les variables prédéfinies. + +# Assigne la variable si une variable d’environnement du même nom n'existe pas +# déjà. +variable4 ?= Jean + +# Empêche cette variable d'être modifiée par la ligne de commande. +override variable5 = David + +# Concatène à une variable (avec un espace avant). +variable4 +=gris + +# Assignations de variable pour les règles correspondant à un pattern +# (spécifique à GNU make). +*.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous + # leurs descendants, la variable variable2 vaudra + # "Sara". +# Si le jeux des dépendances et descendances devient vraiment trop compliqué, +# des inconsistances peuvent survenir. + +# Certaines variables sont prédéfinies par make : +affiche_predefinies: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables : le retour +#----------------------------------------------------------------------- + +# Les variables sont évaluées à chaque instance, ce qui peut être coûteux en +# calculs. Pour parer à ce problème, il existe dans GNU make une seconde +# manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule +# fois seulement. + +var := wesh +var2 ::= $(var) mec # := et ::= sont équivalents. + +# Ces variables sont évaluées procéduralement (i.e. dans leur ordre +# d'apparition), contrairement au règles par exemple ! + +# Ceci ne fonctionne pas. +var3 ::= $(var4) et fais de beaux rêves +var4 ::= bonne nuit + +#----------------------------------------------------------------------- +# Fonctions +#----------------------------------------------------------------------- + +# Make a une multitude de fonctions. La syntaxe générale est +# $(fonction arg0,arg1,arg2...). + +# Quelques exemples : + +fichiers_source = $(wildcard *.c */*.c) +fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) + +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# Inclut d'autres makefiles. +include meuh.mk + +# Branchements conditionnels. +sport = tennis +report: +ifeq ($(sport),tennis) # Il y a aussi ifneq. + @echo 'jeu, set et match' +else + @echo "C'est pas ici Wimbledon ?" +endif + +truc = true +ifdef $(truc) # Il y a aussi ifndef. + machin = 'salut' +endif +``` + +## Quelques références + +### En français + ++ [Introduction à Makefile (developpez.com)] +(http://gl.developpez.com/tutoriel/outil/makefile/), ++ [Compilez sous GNU/Linux ! (openclassrooms)] +(https://openclassrooms.com/courses/compilez-sous-gnu-linux). + +### En anglais + ++ [Documentation de GNU make](https://www.gnu.org/software/make/manual/), ++ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/), ++ Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) +[ex28](http://c.learncodethehardway.org/book/ex28.html). \ No newline at end of file -- cgit v1.2.3 From 5c4eba5ef34593a0c6425da64f6a0d7688fca3d2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sun, 17 Jan 2016 21:54:51 +0100 Subject: Removed tabs in header --- fr-fr/make-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 8643ba45..405c47cd 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,8 +1,8 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["altaris", "https://github.com/altaris"] + - ["Robert Steed", "https://github.com/robochat"] + - ["altaris", "https://github.com/altaris"] filename: Makefile --- -- cgit v1.2.3 From a4e4b76afdb538fa577db8823bb7349ff7872722 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:07:20 +0100 Subject: Corrections to make-fr ... according to pull request comments: - completed header; - some typos; - finished translating target names. --- fr-fr/make-fr.html.markdown | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 405c47cd..b8255ce7 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -3,7 +3,8 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] - ["altaris", "https://github.com/altaris"] -filename: Makefile +filename: Makefile-fr +lang: fr-fr --- Un makefile est un fichier qui définit un ensemble de règles liées entre elles @@ -34,23 +35,23 @@ l'implémentation standard : GNU make. #----------------------------------------------------------------------- # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. -file0.txt: +fichier0.txt: echo "truc" > fichier0.txt # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. -file1.txt: fichier0.txt +fichier1.txt: fichier0.txt cat fichier0.txt > fichier1.txt - # Utiliser les même guillemets que dans un terminal. + # Utiliser la même syntaxe que dans un terminal. @cat fichier0.txt >> fichier1.txt # @ empêche l'affichage de la sortie texte d'une commande. -@echo 'hello' - # - signifie que la règle devrait continuer à être exécutée si cette - # commande échoue. + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. -# Un règle peut avoir plusieurs cibles et plusieurs dépendances. -file2.txt fichier3.txt: fichier0.txt fichier1.txt +# Une règle peut avoir plusieurs cibles et plusieurs dépendances. +fichier2.txt fichier3.txt: fichier0.txt fichier1.txt touch fichier2.txt touch fichier3.txt @@ -62,7 +63,7 @@ file2.txt fichier3.txt: fichier0.txt fichier1.txt # Fausses règles #----------------------------------------------------------------------- -# Une fausse règle est un règle qui ne correspond pas à un fichier. +# Une fausse règle est une règle qui ne correspond pas à un fichier. # Par définition, elle ne peut pas être à jour, et donc make l’exécutera à # chaque demande. all: maker process @@ -75,7 +76,7 @@ maker: # suivante : .PHONY: all maker process -# Un règle dépendante d'une fausse règle sera toujours exécutée. +# Une règle dépendante d'une fausse règle sera toujours exécutée. ex0.txt ex1.txt: maker # Voici quelques exemples fréquents de fausses règles : all, make, clean, -- cgit v1.2.3 From 8cff05396eeb7059904c52c3c2e62440d6c975b6 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:16:37 +0100 Subject: Corrected header Added myself as translator. --- fr-fr/make-fr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index b8255ce7..993eccba 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] +translators: - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr @@ -264,4 +265,4 @@ endif + [Documentation de GNU make](https://www.gnu.org/software/make/manual/), + [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/), + Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) -[ex28](http://c.learncodethehardway.org/book/ex28.html). \ No newline at end of file +[ex28](http://c.learncodethehardway.org/book/ex28.html). -- cgit v1.2.3 From db99c9966ce21789dfa4d6618998ea288756d0ae Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Mon, 18 Jan 2016 12:17:50 +0100 Subject: Corrected header - Added muself as translator; - set lang field; - corrected filename field. --- fr-fr/wolfram-fr.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index d297bd74..3a69e1d8 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -2,8 +2,10 @@ language: wolfram contributors: - ["hyphz", "http://github.com/hyphz/"] +translators: - ["altaris", "http://github.com/altaris/"] -filename: learnwolfram.nb +filename: learnwolfram-fr.nb +lang: fr-fr --- Le langage Wolfram est utilisé dans les programmes suivants : @@ -163,4 +165,4 @@ Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui ## Envie d'aller plus loin ? * [Documentation du langage Wolfram (en anglais)] -(http://reference.wolfram.com/language/) \ No newline at end of file +(http://reference.wolfram.com/language/) -- cgit v1.2.3 From ee88bcd13cf4b89843dde2cf530b832d314d1da7 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Tue, 19 Jan 2016 11:07:22 +0800 Subject: [xml/id-id] update changes --- id-id/xml-id.html.markdown | 79 +++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown index 8b8d72ae..fedba711 100644 --- a/id-id/xml-id.html.markdown +++ b/id-id/xml-id.html.markdown @@ -5,19 +5,76 @@ contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rizky Luthfianto", "https://github.com/rilut"] + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] lang: id-id --- -XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. +XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. XML mudah dibaca oleh manusia dan mesin. Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya. -* Sintaks XML +Terdapat perbedaan antara **konten** dan **markup**. Singkatnya, konten dapat berupa apapun dan markup adalah sebagai penentu. + +## Definisi dan Pendahuluan + +Dokumen XML pada dasarnya disusun oleh *elemen* yang dapat memiliki *atribut* untuk menjelaskan elemen tersebut dan dapat memiliki beberapa konten tekstual atau beberapa elemen sebagai anak-nya. Setiap dokumen XML hendaknya memiliki satu elemen akar, yang menjadi induk dari semua elemen dalam dokumen XML. + +Pengurai XML dirancang menjadi sangat ketat, dan akan berhenti melakukan penguraian terhadap dokumen yang cacat. Oleh karena itu semua dokumen XML harus mengikuti [Aturan Sintaks XML](http://www.w3schools.com/xml/xml_syntax.asp). ```xml - + + + + + + + +Konten + + + + + + + + + + + + + + + + + + + + + + + Teks + + + + + + + Teks + + +Teks +``` + + +## Dokumen XML +```xml + Everyday Italian @@ -65,7 +122,7 @@ Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, ``` -* Dokumen yang well-formated & Validasi +## Dokumen yang well-formated & Validasi Sebuah dokumen XML disebut well-formated jika sintaksisnya benar. Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen, @@ -128,3 +185,17 @@ Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi. ``` +## Kompatibilitas DTD dan Definisi Skema XML + +Dukungan untuk DTD dapat ditemukan dimana-mana karena sudah sangat lama. Namun sayangnya, fitur XML terkini seperti *namespaces* tidak didukung oleh DTD. XML Xchema Definitions (XSDs) bertujuan untuk mengganti DTD dalam mendefinisikan tatabahasa dokumen XML. + +## Sumber + +* [Validasi dokumen XML](http://www.xmlvalidation.com) + +## Bacaan lainnya + +* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/) +* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp) +* [XML Tutorial](http://www.w3schools.com/xml/default.asp) +* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp) -- cgit v1.2.3 From 0fe63187a9d61a0daa789ff59fc130b5dc678a34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric?= Date: Tue, 19 Jan 2016 11:53:13 +0100 Subject: Corrected typos in wolfram-fr --- fr-fr/wolfram-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 3a69e1d8..b9fe986f 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -110,7 +110,7 @@ BetterPrintTo[x_] := Module[{y}, (For[y=0, y Date: Tue, 19 Jan 2016 12:36:33 +0100 Subject: More typos --- fr-fr/make-fr.html.markdown | 110 ++++++++++++++++++++++---------------------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 993eccba..b404e1a1 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -37,24 +37,24 @@ l'implémentation standard : GNU make. # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. fichier0.txt: - echo "truc" > fichier0.txt - # Même les commentaires sont transférés dans le terminal. + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. fichier1.txt: fichier0.txt - cat fichier0.txt > fichier1.txt - # Utiliser la même syntaxe que dans un terminal. - @cat fichier0.txt >> fichier1.txt - # @ empêche l'affichage de la sortie texte d'une commande. - -@echo 'hello' - # - signifie que la règle devrait continuer à s'exécuter si cette commande - # échoue. + cat fichier0.txt > fichier1.txt + # Utiliser la même syntaxe que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. # Une règle peut avoir plusieurs cibles et plusieurs dépendances. fichier2.txt fichier3.txt: fichier0.txt fichier1.txt - touch fichier2.txt - touch fichier3.txt + touch fichier2.txt + touch fichier3.txt # Make affichera un avertissement si le makefile comporte plusieurs règles pour # une même cible. Cependant les règles vides ne comptent pas, et peuvent être @@ -71,7 +71,7 @@ all: maker process # La déclaration des règles peut être faite dans n'importe quel ordre. maker: - touch ex0.txt ex1.txt + touch ex0.txt ex1.txt # On peut transformer une règle en fausse règle grâce à la cible spéciale # suivante : @@ -89,17 +89,17 @@ ex0.txt ex1.txt: maker # Utilise un wildcard pour des noms de fichier process: fichier*.txt - @echo $^ # $^ est une variable contenant la liste des dépendances de la - # cible actuelle. - @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles - # multiples, $@ est le nom de la cible ayant causé l'exécution - # de cette règle. - @echo $< # $< contient la première dépendance. - @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. - @echo $+ # $+ contient la liste des dépendances avec d'éventuels - # duplicatas, contrairement à $^. - @echo $| # $| contient la liste des cibles ayant préséance sur la cible - # actuelle. + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. # Même si la définition de la règle est scindée en plusieurs morceaux, $^ # listera toutes les dépendances indiquées. @@ -113,33 +113,33 @@ process: ex1.txt fichier0.txt # En utilisant le pattern matching, on peut par exemple créer des règles pour # convertir les fichiers d'un certain format dans un autre. %.png: %.svg - inkscape --export-png $^ + inkscape --export-png $^ # Make exécute une règle même si le fichier correspondant est situé dans un sous # dossier. En cas de conflit, la règle avec la meilleure correspondance est # choisie. small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ + inkscape --export-png --export-dpi 30 $^ # Dans ce type de conflit (même cible, même dépendances), make exécutera la # dernière règle déclarée... %.png: %.svg - @echo cette règle est choisie + @echo cette règle est choisie # Dans ce type de conflit (même cible mais pas les mêmes dépendances), make # exécutera la première règle pouvant être exécutée. %.png: %.ps - @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents # Make a des règles pré établies. Par exemple, il sait comment créer la cible # *.o à partir de *.c. # Les makefiles plus vieux utilisent un matching par extension de fichier. .png.ps: - @echo cette règle est similaire à une règle par pattern matching + @echo cette règle est similaire à une règle par pattern matching -# Utiliser cette syntaxe pour déclarer une règle comme règle avec matching par -# extension de fichier. +# Utiliser cette règle spéciale pour déclarer une règle comme ayant un +# matching par extension de fichier. .SUFFIXES: .png #----------------------------------------------------------------------- @@ -152,10 +152,10 @@ variable = Ted variable2="Sarah" echo: - @echo $(variable) - @echo ${variable2} - @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! - @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). # Les variables sont déclarées de 4 manières, de la plus grande priorité à la # plus faible : @@ -177,21 +177,21 @@ variable4 +=gris # Assignations de variable pour les règles correspondant à un pattern # (spécifique à GNU make). *.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous - # leurs descendants, la variable variable2 vaudra - # "Sara". + # leurs descendants, la variable variable2 vaudra + # "Sara". # Si le jeux des dépendances et descendances devient vraiment trop compliqué, -# des inconsistances peuvent survenir. +# des incohérences peuvent survenir. # Certaines variables sont prédéfinies par make : affiche_predefinies: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} #----------------------------------------------------------------------- # Variables : le retour @@ -202,11 +202,11 @@ affiche_predefinies: # manière d'assigner des variables pour qu'elles ne soient évaluées qu'une seule # fois seulement. -var := wesh -var2 ::= $(var) mec # := et ::= sont équivalents. +var := A B C +var2 ::= $(var) D E F # := et ::= sont équivalents. # Ces variables sont évaluées procéduralement (i.e. dans leur ordre -# d'apparition), contrairement au règles par exemple ! +# d'apparition), contrairement aux règles par exemple ! # Ceci ne fonctionne pas. var3 ::= $(var4) et fais de beaux rêves @@ -225,9 +225,9 @@ fichiers_source = $(wildcard *.c */*.c) fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) #----------------------------------------------------------------------- # Directives @@ -240,14 +240,14 @@ include meuh.mk sport = tennis report: ifeq ($(sport),tennis) # Il y a aussi ifneq. - @echo 'jeu, set et match' + @echo 'jeu, set et match' else - @echo "C'est pas ici Wimbledon ?" + @echo "C'est pas ici Wimbledon ?" endif truc = true -ifdef $(truc) # Il y a aussi ifndef. - machin = 'salut' +ifdef $(truc) # Il y a aussi ifndef. + machin = 'salut' endif ``` -- cgit v1.2.3 From 43c93e3449c2b82bf71529a901034b38077cbcc1 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Tue, 19 Jan 2016 12:38:39 +0100 Subject: Changed indentation to tabs They were converted to spaces by error in previous commit. oups. --- fr-fr/make-fr.html.markdown | 100 ++++++++++++++++++++++---------------------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index b404e1a1..5a1e03e7 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,9 +1,9 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] + - ["Robert Steed", "https://github.com/robochat"] translators: - - ["altaris", "https://github.com/altaris"] + - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr --- @@ -37,24 +37,24 @@ l'implémentation standard : GNU make. # Une règle. Elle ne sera exécutée que si fichier0.txt n'existe pas. fichier0.txt: - echo "truc" > fichier0.txt - # Même les commentaires sont transférés dans le terminal. + echo "truc" > fichier0.txt + # Même les commentaires sont transférés dans le terminal. # Cette règle ne sera exécutée que si fichier0.txt est plus récent que # fichier1.txt. fichier1.txt: fichier0.txt - cat fichier0.txt > fichier1.txt - # Utiliser la même syntaxe que dans un terminal. - @cat fichier0.txt >> fichier1.txt - # @ empêche l'affichage de la sortie texte d'une commande. - -@echo 'hello' - # - signifie que la règle devrait continuer à s'exécuter si cette commande - # échoue. + cat fichier0.txt > fichier1.txt + # Utiliser la même syntaxe que dans un terminal. + @cat fichier0.txt >> fichier1.txt + # @ empêche l'affichage de la sortie texte d'une commande. + -@echo 'hello' + # - signifie que la règle devrait continuer à s'exécuter si cette commande + # échoue. # Une règle peut avoir plusieurs cibles et plusieurs dépendances. fichier2.txt fichier3.txt: fichier0.txt fichier1.txt - touch fichier2.txt - touch fichier3.txt + touch fichier2.txt + touch fichier3.txt # Make affichera un avertissement si le makefile comporte plusieurs règles pour # une même cible. Cependant les règles vides ne comptent pas, et peuvent être @@ -71,7 +71,7 @@ all: maker process # La déclaration des règles peut être faite dans n'importe quel ordre. maker: - touch ex0.txt ex1.txt + touch ex0.txt ex1.txt # On peut transformer une règle en fausse règle grâce à la cible spéciale # suivante : @@ -89,17 +89,17 @@ ex0.txt ex1.txt: maker # Utilise un wildcard pour des noms de fichier process: fichier*.txt - @echo $^ # $^ est une variable contenant la liste des dépendances de la - # cible actuelle. - @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles - # multiples, $@ est le nom de la cible ayant causé l'exécution - # de cette règle. - @echo $< # $< contient la première dépendance. - @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. - @echo $+ # $+ contient la liste des dépendances avec d'éventuels - # duplicatas, contrairement à $^. - @echo $| # $| contient la liste des cibles ayant préséance sur la cible - # actuelle. + @echo $^ # $^ est une variable contenant la liste des dépendances de la + # cible actuelle. + @echo $@ # $@ est le nom de la cible actuelle. En cas de cibles + # multiples, $@ est le nom de la cible ayant causé l'exécution + # de cette règle. + @echo $< # $< contient la première dépendance. + @echo $? # $? contient la liste des dépendances qui ne sont pas à jour. + @echo $+ # $+ contient la liste des dépendances avec d'éventuels + # duplicatas, contrairement à $^. + @echo $| # $| contient la liste des cibles ayant préséance sur la cible + # actuelle. # Même si la définition de la règle est scindée en plusieurs morceaux, $^ # listera toutes les dépendances indiquées. @@ -113,30 +113,30 @@ process: ex1.txt fichier0.txt # En utilisant le pattern matching, on peut par exemple créer des règles pour # convertir les fichiers d'un certain format dans un autre. %.png: %.svg - inkscape --export-png $^ + inkscape --export-png $^ # Make exécute une règle même si le fichier correspondant est situé dans un sous # dossier. En cas de conflit, la règle avec la meilleure correspondance est # choisie. small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ + inkscape --export-png --export-dpi 30 $^ # Dans ce type de conflit (même cible, même dépendances), make exécutera la # dernière règle déclarée... %.png: %.svg - @echo cette règle est choisie + @echo cette règle est choisie # Dans ce type de conflit (même cible mais pas les mêmes dépendances), make # exécutera la première règle pouvant être exécutée. %.png: %.ps - @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents + @echo cette règle n\'est pas choisie si *.svg et *.ps sont présents # Make a des règles pré établies. Par exemple, il sait comment créer la cible # *.o à partir de *.c. # Les makefiles plus vieux utilisent un matching par extension de fichier. .png.ps: - @echo cette règle est similaire à une règle par pattern matching + @echo cette règle est similaire à une règle par pattern matching # Utiliser cette règle spéciale pour déclarer une règle comme ayant un # matching par extension de fichier. @@ -152,10 +152,10 @@ variable = Ted variable2="Sarah" echo: - @echo $(variable) - @echo ${variable2} - @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! - @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). + @echo $(variable) + @echo ${variable2} + @echo $variable # Cette syntaxe signifie $(n)ame et non pas $(variable) ! + @echo $(variable3) # Les variables non déclarées valent "" (chaîne vide). # Les variables sont déclarées de 4 manières, de la plus grande priorité à la # plus faible : @@ -177,21 +177,21 @@ variable4 +=gris # Assignations de variable pour les règles correspondant à un pattern # (spécifique à GNU make). *.png: variable2 = Sara # Pour toutes les règles correspondant à *.png, et tous - # leurs descendants, la variable variable2 vaudra - # "Sara". + # leurs descendants, la variable variable2 vaudra + # "Sara". # Si le jeux des dépendances et descendances devient vraiment trop compliqué, # des incohérences peuvent survenir. # Certaines variables sont prédéfinies par make : affiche_predefinies: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} #----------------------------------------------------------------------- # Variables : le retour @@ -225,9 +225,9 @@ fichiers_source = $(wildcard *.c */*.c) fichiers_objet = $(patsubst %.c,%.o,$(fichiers_source)) ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) #----------------------------------------------------------------------- # Directives @@ -240,14 +240,14 @@ include meuh.mk sport = tennis report: ifeq ($(sport),tennis) # Il y a aussi ifneq. - @echo 'jeu, set et match' + @echo 'jeu, set et match' else - @echo "C'est pas ici Wimbledon ?" + @echo "C'est pas ici Wimbledon ?" endif truc = true ifdef $(truc) # Il y a aussi ifndef. - machin = 'salut' + machin = 'salut' endif ``` -- cgit v1.2.3 From e3346920d211f19ac651fc6c1618db35f81067ff Mon Sep 17 00:00:00 2001 From: krikmo <616c6c@gmail.com> Date: Tue, 19 Jan 2016 20:54:37 -0200 Subject: [javascript pt-br]: Use articles translated to portuguese --- pt-br/javascript-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 6424214e..59c6890e 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -519,13 +519,13 @@ if (Object.create === undefined){ // Não o sobrescreve se já existir ## Leitura Adicional O [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma +Network](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript) dispõe de uma excelente documentação sobre Javascript e seu uso nos browsers. E mais, é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando os outros compartilhando do seu conhecimento. [Uma re-introdução do JavaScript pela MDN] -(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala somente sobre a linguagem JavaScript em si; se você quiser aprender mais sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre @@ -542,5 +542,5 @@ profundo de todas as partes do JavaScript. / livro de referência. Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está -nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +nesse site e do [Tutorial de JS](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) da Mozilla Developer Network. -- cgit v1.2.3 From 39825e459f11f8c59d0f39afa6418ad1332ec3a4 Mon Sep 17 00:00:00 2001 From: Hanlei Qin Date: Wed, 20 Jan 2016 22:59:48 +0800 Subject: Update lua-cn.html.markdown local variables will better. --- zh-cn/lua-cn.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 098d0ab5..fc0375f5 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -210,7 +210,7 @@ f2 = {a = 2, b = 3} metafraction = {} function metafraction.__add(f1, f2) - sum = {} + local sum = {} sum.b = f1.b * f2.b sum.a = f1.a * f2.b + f2.a * f1.b return sum @@ -273,7 +273,7 @@ eatenBy = myFavs.animal -- 可以工作!感谢元表 Dog = {} -- 1. function Dog:new() -- 2. - newObj = {sound = 'woof'} -- 3. + local newObj = {sound = 'woof'} -- 3. self.__index = self -- 4. return setmetatable(newObj, self) -- 5. end @@ -307,7 +307,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. LoudDog = Dog:new() -- 1. function LoudDog:makeSound() - s = self.sound .. ' ' -- 2. + local s = self.sound .. ' ' -- 2. print(s .. s .. s) end -- cgit v1.2.3 From 5edee6c0d2afac2ab2690af4da1ebb88f06d2ca4 Mon Sep 17 00:00:00 2001 From: Oliver Vartiainen Date: Wed, 20 Jan 2016 22:15:20 +0200 Subject: Translate Ruby docs to Finnish --- fi-fi/ruby-fi.html.markdown | 607 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 607 insertions(+) create mode 100644 fi-fi/ruby-fi.html.markdown diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown new file mode 100644 index 00000000..b4f7583d --- /dev/null +++ b/fi-fi/ruby-fi.html.markdown @@ -0,0 +1,607 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] +translators: + - ["Oliver Vartiainen", "https://github.com/firoxer"] +--- + +```ruby +# Tässä yhden rivin kommentti + +=begin +Tässä usean rivin kommentti +Näitä ei kylläkään käytetä +Joten käytetään vastedes vain yksirivisiä +=end + +# Tärkeintä on muistaa, että Rubyssa kaikki pohjautuu olioihin. + +# Luvutkin ovat olioita: + +3.class #=> Fixnum + +3.to_s #=> "3" + +# Peruslaskutoimituksia: +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 + +# Bittioperaatioita: +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# Laskutoimitukset ovat vain syntaksisokeria lukuolion laskumetodin kutsulle: +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Erityisarvotkin ovat olioita: + +nil # vastaa joidenkin kielten "null"-arvoa +true # tosi +false # epätosi + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Samanvertaisuuden testaus: +1 == 1 #=> true +2 == 1 #=> false + +# ...ja sama eriarvoisuudelle: +1 != 1 #=> false +2 != 1 #=> true + +# "nil" ja "false" ovat ainoat epätodet arvot; kaikki muu ymmärretään todeksi: +!nil #=> true +!false #=> true +!0 #=> false + +# Lisää vertailuoperaatioita: +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Kahdensuuntainen vertailuoperaattori: +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Logiikkaoperaattorit: +true && false #=> false +true || false #=> true +!true #=> false + +# Merkkipohjaisten logiikkaoperaattorien vaihtoehtona on sanalliset muodot, +# joilla on hyvin matala presedenssi. Niillä voi muokata ohjelman kulkua +# esimerkiksi väitelausekkeita ketjuttaen. + +# Metodia `do_something_else` kutsutaan vain, jos `do_something` onnistuu: +do_something() and do_something_else() +# Metodia `log_error` kutsutaan vain, jos `do_something` epäonnistuu: +do_something() or log_error() + +# Merkkijonot ovat olioita: + +'Tässä on merkkijono'.class #=> String +"Rajaavat lainausmerkit voivat olla yksin- tai kaksinkertaisia".class #=> String + +täyte = 'sisällyttää muita merkkijonoja' +"Kaksinkertaisilla lainausmerkeillä voi #{täyte}" +#=> "Kaksinkertaisilla lainausmerkeillä voi sisällyttää muita merkkijonoja" + +# Yksinkertaisia lainausmerkkejä kannattaa silti suosia, sillä kaksinkertaiset +# merkit saattavat aiheuttaa turhia kielensisäisiä tarkistuksia. + +# Merkkijonoja voi yhdistellä toisiinsa: +'hello ' + 'world' #=> "hello world" + +# ...mutta luvut vaativat ensin tyyppimuunnoksen: +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Merkkijonoja voi soveltaa laskutoimituksiin... odotettavin seurauksin: +'hello ' * 3 #=> "hello hello hello " + +# Merkkijonoa voi jatkaa toisella: +'hello' << ' world' #=> "hello world" + +# Tulosteen luonti kera rivinvaihdon: +puts "I'm printing!" +#=> I'm printing! +#=> nil + +# ...ja ilman rivinvaihtoa: +print "I'm printing!" +#=> I'm printing! => nil + +# Muuttujien määrittely: +x = 25 #=> 25 +x #=> 25 + +# Arvon asettaminen palauttaa arvon itsensä, joten usean muuttujan arvon +# yhtäaikainen määrittely käy vaivatta: +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Muuttujien sanaerottimena käytetään alaviivaa: +snake_case = true + +# Lisäksi Rubyssa suositaan ytimekkäitä nimiä: +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Symbolit + +# Symbolit ovat muuttumattomia, uudelleenkäytettäviä vakioita. +# Niitä käytetään merkkijonojen sijaan, kun tarkoitus on viitata arvoon, +# jolla on tietty, pysyvä merkitys: + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Taulukot + +# Tässä taulukko: +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Taulukko saa koostua erityyppisistä arvoista: +[1, 'hello', false] #=> [1, "hello", false] + +# Taulukon alkioihin voi viitata järjestysnumerolla nollasta alkaen: +array[0] #=> 1 +array.first #=> 1 +array[12] #=> nil + +# Kuten laskutoimituksissa nähty syntaksisokeri on myös taulukon alkioiden haku +# pohjimmiltaan vain taulukko-olioon kuuluvan "[]"-metodin kutsu: +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Haku käy myös lopustapäin: +array[-1] #=> 5 +array.last #=> 5 + +# Alitaulukon haku käy indeksiparilla... +array[2, 3] #=> [3, 4, 5] + +# ...tai määrittelemällä väli: +array[1..3] #=> [2, 3, 4] + +# Taulukon voi kääntää: +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Ja sitä voi jatkaa näin... +array << 6 #=> [1, 2, 3, 4, 5, 6] + +# ...tai näin: +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Alkion olemassaolon tarkistus: +array.include?(1) #=> true + +# Hashit eli assosiaatiotaulut ovat Rubyn tärkein avain-/arvoparirakenne. +# Hash luodaan aaltosulkeilla: +hash = { 'color' => 'green', 'number' => 5 } + +hash.keys #=> ['color', 'number'] + +# Hash toimii erityisen nopeasti, kun haetaan arvoa avaimen perusteella: +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Jos hashistä ei löyty avainta vastaavaa arvoa, palautetaan nil-arvo: +hash['nothing here'] #=> nil + +# Symbolihashin määrittelylle on oma syntaksinsa (alkaen Rubyn versiosta 1.9): +new_hash = { defcon: 3, action: true } +new_hash.keys #=> [:defcon, :action] + +# Hashin avaimen ja arvon olemassaolon tarkistus: +new_hash.key?(:defcon) #=> true +new_hash.value?(3) #=> true + +# Vinkki! Sekä taulukot että hashit sisältävät Enumerable-moduulin, +# johon kuuluu useita hyödyllisiä iterointimetodeja kuten .each, .map, +# .reduce ja .count + +# Rakenteita + +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# HUOMAA, että for-rakennetta kannattaa välttää, sillä Rubyssa suosittu +# each-metodi ajaa saman asian idiomaattisemmin. Each-metodi ottaa ainoana +# argumenttinaan lohkon. Lohkot toimivat pitkälti samoin kuin muiden kielten +# anonyymit funktiot, lambdat tai sulkeumat. + +# Lukuvälit vastaavat each-metodiin, jolloin sille annettu lohko ajetaan +# kerran jokaiselle välin kokonaisluvulle. +# Lukuvälin each-rakenne lohkoineen näyttää tältä: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Lohkoa ympäröivät do/end-avainsanat voi korvata myös aaltosulkeilla: +(1..5).each { |counter| puts "iteration #{counter}" } + +# Lukuvälien lisäksi myös tietorakenteita voidaan iteroida each-metodilla: +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +# Taulukoita voi iteroida metodilla each_with_index, jolloin lohko saa +# argumenteikseen sekä alkion että indeksin: +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Each-metodin lisäksi Rubyssa on useita muita iterointimetodeja kuten +# "map" ja "reduce". Näistä "map" kutsuttuna taulukolla ottaa argumentikseen +# lohkon, suorittaa sen kerran jokaiselle rakenteen jäsenelle, ja lopuksi +# palauttaa uuden taulukon, jonka jäsenet ovat lohkon suorituksen tuloksia. + +array = [1, 2, 3, 4, 5] +doubled = array.map do |element| + element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + +# Case-rakenne siirtää ohjelman kulun yhdelle monista määritellyistä poluista: + +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# Case-rakenteessa voidaan hyödyntää lukuvälejä: +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Virheidenkäsittely: +begin + # Seuraava koodinpätkä aiheuttaa NoMemoryError-poikkeuksen + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end + +# Ylimmän näkyvyysalueen metodi näyttää itsenäiseltä funktiolta: +def double(x) + x * 2 +end + +# Funktiot (ja lohkot) palauttavat implisiittisesti +# viimeiseksi ajamansa lausekkeen arvon: +double(2) #=> 4 + +# Metodikutsun argumentteja ympäröivät kaarisulkeet voi jättää pois, +# kunhan koodi ei muutu monitulkintaiseksi: + +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Argumentit erotetaan pilkuilla: + +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# Kaikilla metodeilla on implisiittinen lohkoparametri, +# joka voidaan suorittaa yield-avainsanalla: + +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + +# Metodille annetun lohkon voi nimetä parametrilistassa &-merkin avulla, +# minkä jälkeen se suoritetaan call-metodilla: +def guests(&block) + block.call 'some_argument' +end + +# Metodille voi antaa vaihtelevan määrän muuttujia. Ne siirretään taulukkoon, +# jolle annetaan parametrilistassa nimi \*-merkin avulla +def guests(*array) + array.each { |guest| puts guest } +end + +# Luokan määritys aloitetaan class-avainsanalla: + +class Human + + # Tässä luokkamuuttuja, joka on yhteinen kaikille luokan olioille: + @@species = 'H. sapiens' + + # Alustusmetodin määrittely: + def initialize(name, age = 0) + # name-oliomuuttujan arvon asetus metodille annetun name-muuttujan mukaan: + @name = name + + # Jos tätä metodia kutsuessa jätetään toinen argumentti (age) antamatta, + # saa se parametriluettelossa määritetyn arvon 0: + @age = age + end + + # Tyypillinen oliomuuttujan arvon asettava metodi: + def name=(name) + @name = name + end + + # Tyypillinen oliomuuttujan arvon palauttava metodi: + def name + @name + end + + # Edelliset kaksi metodia voi ilmaista idiomaattisemmin myös näin: + attr_accessor :name + + # Lisäksi arvon palauttavan ja asettavan metodin voi määritellä erikseen: + attr_reader :name + attr_writer :name + + # Luokkametodeissa käytetään avainsanaa self erotuksena oliometodeista. + # Luokkametodia voi kutsua vain luokalla itsellään, ei olioilla: + def self.say(msg) + puts msg + end + + def species + @@species + end +end + +# Olion luonti: + +jim = Human.new('Jim Halpert') + +dwight = Human.new('Dwight K. Schrute') + +# Olion metodien kutsuja: +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Luokkametodin kutsu: +Human.say('Hi') #=> "Hi" + +# Muuttujan näkyvyysalueen voi määritellä etuliitteellä. + +# $-alkuiset muuttujat ovat globaaleja: +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# @-alkuiset muuttujat kuuluvat oliolle, +# jonka näkyvyysalueella määrittely tehdään: +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# @@-alkuiset muuttujat kuuluvat vastaavasti näkyvyysalueensa luokalle: +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Isolla alkukirjaimella nimetyt muuttujat ovatkin vakioita: +Var = "I'm a constant" +defined? Var #=> "constant" + +# Kuten odottaa saattaa, myös luokat itsessään ovat olioita. +# Siksi niille voi määritellä muuttujia, jotka ovat yhteisiä kaikille +# luokan ilmentymille ja perillisille. + +# Tavallisen luokan määrittely: + +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Perillisluokan määrittely: + +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Oliomuuttuja on kuitenkin olion oma eikä periydy: + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +module ModuleExample + def foo + 'foo' + end +end + +# Moduulien lisääminen luokkaan "include"-avainsanalla siirtää moduulin metodit +# luokan ilmentymille, kun taas "extend" avainsana siirtää metodit +# luokalle itselleen: + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Callback-tyyppiset metodit suoritetaan moduulia sisällyttäessä: + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Lisämateriaalia englanniksi + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Selaimessa tehtäviä harjoituksia tämän dokumentin hengessä +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - Virallinen dokumentaatio +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Vanhempi, mutta [ilmainen painos](http://ruby-doc.com/docs/ProgrammingRuby/) on luettavissa netissä +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Yhteisön luoma Ruby-tyyliopas +- [Try Ruby](http://tryruby.org) - Rubyn perusteet interaktiivisesti -- cgit v1.2.3 From f39e2fcab76fa0d111195c3b4660b87a101f2032 Mon Sep 17 00:00:00 2001 From: qinhanlei Date: Thu, 21 Jan 2016 16:55:20 +0800 Subject: synchronized with EN version. --- zh-cn/lua-cn.html.markdown | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index fc0375f5..a0acce05 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -91,10 +91,10 @@ until num == 0 -- 2. 函数。 ---------------------------------------------------- -function fib(n) - if n < 2 then return 1 end - return fib(n - 2) + fib(n - 1) -end +function fib(n) + if n < 2 then return n end + return fib(n - 2) + fib(n - 1) +end -- 支持闭包及匿名函数: function adder(x) @@ -129,9 +129,11 @@ function f(x) return x * x end f = function (x) return x * x end -- 这些也是等价的: -local function g(x) return math.sin(x) end -local g; g = function (x) return math.sin(x) end --- 'local g'使得g可以自引用。 +local function g(x) return math.sin(x) end +local g; g = function (x) return math.sin(x) end +-- 以上均因'local g',使得g可以自引用。 +local g = function(x) return math.sin(x) end +-- 等价于 local function g(x)..., 但函数体中g不可自引用 -- 顺便提下,三角函数以弧度为单位。 @@ -328,7 +330,7 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- 如果有必要,子类也可以有new(),与基类相似: function LoudDog:new() - newObj = {} + local newObj = {} -- 初始化newObj self.__index = self return setmetatable(newObj, self) @@ -340,7 +342,9 @@ end --[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 +``` +```lua -- 假设文件mod.lua的内容类似这样: local M = {} @@ -411,4 +415,9 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us * io library * os library +顺便说一下,整个文件是可运行的Lua; +保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! + +本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 github gist 版. + 使用Lua,欢乐常在! -- cgit v1.2.3 From def04721be506f1c7ff5ddf407f2333999570a89 Mon Sep 17 00:00:00 2001 From: Mark Green Date: Fri, 22 Jan 2016 00:54:44 +0000 Subject: Add a try at an Inform 7 tutorial. Obscure, but really interesting. --- inform7.html.markdown | 195 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 inform7.html.markdown diff --git a/inform7.html.markdown b/inform7.html.markdown new file mode 100644 index 00000000..7f1da0e0 --- /dev/null +++ b/inform7.html.markdown @@ -0,0 +1,195 @@ +--- +language: Inform7 +contributors: + - ["Hyphz", "http://github.com/hyphz/"] +filename: LearnInform.Inform +--- +Inform 7 is a natural language based language created by Graham Nelson and Emily Short for writing text adventures, but also potentially usable for other text based applications, especially data backed ones. + +``` +"LearnInform" by Hyphz + +[This is a comment.] + +[Inform 7 is a language designed for building text adventures. +It can be used for other purposes too, although the default +library builds a text adventure. Inform 7 is object oriented.] + +[This creates a class by subclassing. "Value" is the universal subclass, +but "object" is the most basic that behaves like an OO object.] +A datablock is a kind of object. + +[Classes can have properties.] +A datablock can be broken. [This creates a boolean property.] +A datablock is usually not broken. [This sets its default value.] +A datablock can be big or small. [This creates an enumerated property.] +A datablock is usually small. [This sets its default value.] +A datablock has a number called the sequence number. [This creates a typed property.] +A datablock has some text called the name. ["Some text" means a string.] +A datablock has a datablock called the chain. [Declared classes become types.] + +[This creates a global named instance.] +Block1 is a datablock. +The sequence number of Block1 is 1. +The name of Block1 is "Block One." + +[Functions and procedures are defined as "phrases".] +To do the thing everyone does with their first program: + say "Hello World.". [Full stop indicates the end, indent indicates the scope.] + +To dump (the block - a datablock): [That's how we create a parameter.] + say the sequence number of the block; + say the name of the block; + if the block is broken, say "(Broken)". + +To toggle (the block - a datablock): + if the block is broken: [Conditional.] + now the block is not broken; [Updating a property.] + else: + now the block is broken. + +[Multiple parameters.] +To fix (the broken block - a datablock) using (the repair block - a datablock): + if the broken block is not broken, stop; [Comma for a non indented single command.] + if the repair block is broken, stop; + now the sequence number of the broken block is the sequence number of the repair block; + now the broken block is not broken. + +[Because of its text adventure origins, Inform 7 doesn't generally allow objects +to be created dynamically, although there's a language extension that enables it.] +Block2 is a datablock. +Block2 is broken. +The sequence number of Block2 is 2. +The name of Block2 is "Block two." + +To demonstrate calling a phrase with two parameters: + Let the second block be block2; [Local pointer variable.] + fix the second block using Block1; + say the sequence number of the second block. [1.] + +[Lists.] +To show how to use list types: + let the list be a list of datablocks; + add Block1 to the list; + add Block2 to the list; + say the list; ["Block1 and Block2"] + [Membership.] + if Block1 is listed in the list: + say "Block1 is there."; + [Loop.] + repeat with the block running through the list: + dump the block; [1 Block One. 1 Block Two.] + [Remember block two's sequence number was changed above.] + let X be entry 2 of the list; [Counting starts at 1.] + dump X; ["1 Block two."] + remove X from the list; + say the list. [Block1] + +[Here's how we define a function and do arithmetic.] + +To decide which number is the sum of all numbers up to (X - a number) (this is summing up): + let the total so far be a number; + repeat with the current number running from 1 to X: + now the total so far is the total so far + the current number; + decide on the total so far. [This is the return statement.] + +[ We have higher order functions too. ] + +To demonstrate a higher order function: + say summing up applied to {1, 2, 3, 4}. + +To decide which number is the result of applying (phrase - phrase A -> A) twice to (B - a value of kind A): + let b1 be phrase applied to B; + let b2 be phrase applied to b1; + decide on b2. + +To demonstrate defining a higher order function: + let X be 5; + say the result of applying summing up twice to X. + +[ Rulebooks allow a number of functions which apply to the same type under different conditions to be stacked. ] + +Datablock validation rules is a datablock based rulebook. + +A datablock validation rule for a broken datablock: rule fails. +A datablock validation rule for a datablock (called the block): + dump the block; + rule succeeds. + +To demonstrate invoking a rulebook: + follow datablock validation rules for Block1; + follow datablock validation rules for Block2. + +[ Objects can also have relations, which resemble those in a relational database. ] +A dog is a kind of thing. +Rover is a dog. +The kennel is a container. [This is a built in base class.] +Rover is in the kennel. [This creates an inbuilt relation called "containment".] + +[We can create relations by declaring their type.] + +Guide dog ownership relates one dog to one person. [One-to-one.] +Property ownership relates various things to one person. [Many-to-one.] +Friendship relates various people to various people. [Many-to-many.] + +[To actually use them we must assign verbs or prepositions to them.] + +The verb to own means the property ownership relation. +The verb to be the guide dog of means the guide dog ownership relation. +The verb to be guided by means the reversed guide dog ownership relation. +The verb to be friends with means the friendship relation. + +Edward is a person. A person can be blind. Edward is blind. +Edward is guided by Rover. +Benny is a person. Edward is friends with Benny. + +To demonstrate looking something up with a relation: + repeat with the dog running through things that are the guide dog of Edward: + say the dog; + repeat with the friend running through things that are friends with Edward: + say the friend. + +[We can also define relations that exist procedurally.] + +Helpfulness relates a person (called the helper) to a person (called the helpee) when the helpee is blind and the helper is not blind. +The verb to be helpful to means the helpfulness relation. +To demonstrate using a procedural relation: + repeat with the helper running through people that are helpful to Edward: + say the helper. + + +[ Interface to the text adventure harness to allow the above code to be run. ] +Tutorial room is a room. +"A rather strange room full of buttons. Push them to run the exercises, or turn on the robot to run them all." +A button is a kind of thing. A button is fixed in place. + +The red button is a button in tutorial room. +Instead of pushing the red button, do the thing everyone does with their first program. +The green button is a button in tutorial room. +Instead of pushing the green button, demonstrate calling a phrase with two parameters. +The blue button is a button in tutorial room. +Instead of pushing the blue button, show how to use list types. +The cyan button is a button in tutorial room. +Instead of pushing the cyan button, say the sum of all numbers up to 5. +The purple button is a button in tutorial room. +Instead of pushing the purple button, demonstrate a higher order function. +The black button is a button in tutorial room. +Instead of pushing the black button, demonstrate defining a higher order function. +The white button is a button in tutorial room. +Instead of pushing the white button, demonstrate invoking a rulebook. +The puce button is a button in tutorial room. +Instead of pushing the puce button, demonstrate looking something up with a relation. +The orange button is a button in tutorial room. +Instead of pushing the orange button, demonstrate using a procedural relation. + +The robot is an object in tutorial room. +Instead of switching on the robot: + say "The robot begins to frantically flail its arms about."; + repeat with button running through buttons in the tutorial room: + say "The robot randomly hits [the button]."; + try pushing button. +``` + +##Ready For More? + +* [Inform 7](http://www.inform7.com/) -- cgit v1.2.3 From 4d1b90826f7625fc5fb438b3581866e2d33f7e99 Mon Sep 17 00:00:00 2001 From: Hanlei Qin Date: Fri, 22 Jan 2016 11:01:28 +0800 Subject: Update lua-cn.html.markdown change link to Markdown style. --- zh-cn/lua-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index a0acce05..f7065445 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -418,6 +418,6 @@ lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/us 顺便说一下,整个文件是可运行的Lua; 保存为 learn-cn.lua 用命令 `lua learn.lua` 启动吧! -本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 github gist 版. +本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [github gist](https://gist.github.com/tylerneylon/5853042) 版. 使用Lua,欢乐常在! -- cgit v1.2.3 From a3e68ea324716f1f018888782b357812be3865a2 Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:31:17 +0100 Subject: Transleted code variables and strings to french --- fr-fr/wolfram-fr.html.markdown | 116 ++++++++++++++++++++--------------------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index b9fe986f..ea07aae5 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -57,101 +57,101 @@ x (* 20 *) (* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des variables non déclarées n'est pas illégal *) -cow + 5 (* 5 + cow, comme cow n'est pas déclarée, l'évaluation +truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation s'arrête là *) -cow + 5 + 10 (* 15 + cow, on évalue ce qu'on peut... *) -% (* 15 + cow, % représente le dernier résultat *) -% - cow (* 15, les variables non déclarées peuvent quand même +truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *) +% (* 15 + truc, % représente le dernier résultat *) +% - truc (* 15, les variables non déclarées peuvent quand même s'annuler *) -moo = cow + 5 (* Attention : moo est ici une expression et non un nombre *) +chose = truc + 5 (* Attention : chose est ici une expression et non un nombre *) (* Déclaration d'une fonction *) -Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme - à droite *) -Double[10] (* 20 *) -Double[Sin[Pi/2]] (* 2 *) -Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets - fermants si moches *) -(Pi/2) // Sin // Double(* 2, Utiliser // permet d'écrire les fonctions dans - l'ordre d'appel *) +Double[x_] := x * 2 (* Le symbole := empêche l'évaluation immédiate du terme + à droite *) +Double[10] (* 20 *) +Double[Sin[Pi/2]] (* 2 *) +Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets + fermants si moches *) +(Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans + l'ordre d'appel *) (* Pour la programmation impérative, utiliser ; pour séparer les expressions *) -MyFirst[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires - car ; est prioritaire sur := *) -MyFirst[] (* Hello World *) +Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires + car ; est prioritaire sur := *) +Salut[] (* Hello World *) (* Boucles For à la C *) -PrintTo[x_] := For[y=0, y 2, "Red" -> 1|> (* Crée une table associative *) -myHash[["Green"]] (* 2, l'utilise *) -myHash[["Green"]] := 5 (* 5, la modifie *) -myHash[["Puce"]] := 3.5 (* 3.5, l'étend *) -KeyDropFrom[myHash, "Green"] (* Supprime la clé "Green" *) -Keys[myHash] (* {Red} *) -Values[myHash] (* {1} *) +table = <|"Vert" -> 2, "Rouge" -> 1|> (* Crée une table associative *) +table[["Vert"]] (* 2, l'utilise *) +table[["Vert"]] := 5 (* 5, la modifie *) +table[["Bleu"]] := 3.5 (* 3.5, l'étend *) +KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *) +Keys[table] (* {Rouge} *) +Values[table] (* {1} *) (* Pour finir, toute bonne démonstration du langage Wolfram contient un Manipulate ! *) -- cgit v1.2.3 From 3ea060e936b4260ab57abfee6de9dabc3232d6fd Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:32:02 +0100 Subject: Corrected code results in comments In subsection on hash tables. --- fr-fr/wolfram-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index ea07aae5..9cdbabcc 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -150,8 +150,8 @@ table[["Vert"]] (* 2, l'utilise *) table[["Vert"]] := 5 (* 5, la modifie *) table[["Bleu"]] := 3.5 (* 3.5, l'étend *) KeyDropFrom[table, "Vert"] (* Supprime la clé "Vert" *) -Keys[table] (* {Rouge} *) -Values[table] (* {1} *) +Keys[table] (* {Rouge, Bleu} *) +Values[table] (* {1, 3.5} *) (* Pour finir, toute bonne démonstration du langage Wolfram contient un Manipulate ! *) -- cgit v1.2.3 From 2b3d1e524d483e647fd6a193d6b17808d67af5ab Mon Sep 17 00:00:00 2001 From: Cedric HT Date: Sat, 23 Jan 2016 11:37:15 +0100 Subject: Some improvments in comments --- fr-fr/wolfram-fr.html.markdown | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 9cdbabcc..7b446259 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -33,22 +33,21 @@ formatage, car il ne contient aucune information de mise en page. 5+8 (* 13 *) (* Appels de fonction *) -(* Le langage Wolfram est sensible à la casse *) Sin[Pi/2] (* 1 *) - (* Syntaxe alternative pour les appels de fonction à 1 paramètre *) Sin@(Pi/2) (* 1 *) (Pi/2) // Sin (* 1 *) -(* Dans le langage Wolfram, toutes les expressions sont en réalité des appels de - fonction *) +(* Attention : le langage est sensible à la casse ! *) + +(* Toutes les expressions sont en réalité des appels de fonction *) Times[2, 2] (* 4 *) Plus[5, 8] (* 13 *) (* Utiliser une variable pour la première fois la déclare globalement *) x = 5 (* 5 *) x == 5 (* True, l'assignation et le test d'égalité est écrit comme - dans le C *) + en C *) x (* 5 *) x = x + 5 (* 10 *) x (* 10 *) @@ -56,7 +55,7 @@ Set[x, 20] (* TOUT est un appel de fonction, TOUUUUUUUUT *) x (* 20 *) (* Le langage Wolfram effectue des manipulations symboliques, donc utiliser des - variables non déclarées n'est pas illégal *) + variables non déclarées est légal *) truc + 5 (* 5 + truc, comme truc n'est pas déclarée, l'évaluation s'arrête là *) truc + 5 + 10 (* 15 + truc, on évalue ce qu'on peut... *) @@ -75,18 +74,18 @@ Double @ Sin @ (Pi/2) (* 2, Utiliser @ évite les paquets de crochets (Pi/2) // Sin // Double (* 2, Utiliser // permet d'écrire les fonctions dans l'ordre d'appel *) -(* Pour la programmation impérative, utiliser ; pour séparer les expressions *) +(* En programmation impérative, utiliser ; pour séparer les expressions *) Salut[] := (Print@"Hello"; Print@"World") (* Les parenthèses sont nécessaires car ; est prioritaire sur := *) Salut[] (* Hello World *) (* Boucles For à la C *) Compter[x_] := For[y=0, y Date: Mon, 25 Jan 2016 12:21:51 +0200 Subject: Fix file metadata --- fi-fi/ruby-fi.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fi-fi/ruby-fi.html.markdown b/fi-fi/ruby-fi.html.markdown index b4f7583d..52c60182 100644 --- a/fi-fi/ruby-fi.html.markdown +++ b/fi-fi/ruby-fi.html.markdown @@ -1,6 +1,6 @@ --- language: ruby -filename: learnruby.rb +filename: learnruby-fi.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] @@ -17,6 +17,7 @@ contributors: - ["Jake Faris", "https://github.com/farisj"] translators: - ["Oliver Vartiainen", "https://github.com/firoxer"] +lang: fi-fi --- ```ruby -- cgit v1.2.3 From 39c83718b14a768ed62a6644ed633c9a032ff9f6 Mon Sep 17 00:00:00 2001 From: sarthfrey Date: Mon, 25 Jan 2016 18:34:25 -0500 Subject: removed merge stuff --- python.html.markdown | 3 --- 1 file changed, 3 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 70f7f73f..2e7fd8be 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -726,11 +726,8 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) -<<<<<<< HEAD * [LearnPython](http://www.learnpython.org/) -======= * [Fullstack Python](https://www.fullstackpython.com/) ->>>>>>> adambard/master ### Dead Tree -- cgit v1.2.3 From 82cb669cd77e0b394be0161ea8c688aa78f955d6 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:44:47 +1100 Subject: Fix typo --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 3eed2d3c..24dd788a 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -285,7 +285,7 @@ hash.each do |key, value| puts "#{key} is #{value}" end -# If you still need and index you can use "each_with_index" and define an index +# If you still need an index you can use "each_with_index" and define an index # variable array.each_with_index do |element, index| puts "#{element} is number #{index} in the array" -- cgit v1.2.3 From 0f5c74a79f328aa1b385a2dae3389d48faa47ce5 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:52:06 +1100 Subject: Add note on destructuring assignment --- ruby.html.markdown | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 24dd788a..6743de6b 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -411,6 +411,15 @@ def guests(*array) array.each { |guest| puts guest } end +# If a method returns an array, you can use destructuring assignment +def foods + ['pancake', 'sandwich', 'quesadilla'] +end +breakfast, lunch, dinner = foods +breakfast # 'pancake' +dinner # 'quesadilla' + + # Define a class with the class keyword class Human -- cgit v1.2.3 From b9c1502cab19360bda496df5a2503a198f7c4f50 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:58:46 +1100 Subject: Add note on method naming conventions --- ruby.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 6743de6b..bdad4d06 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -419,6 +419,19 @@ breakfast, lunch, dinner = foods breakfast # 'pancake' dinner # 'quesadilla' +# By convention, all methods that return booleans end with a question mark +5.even? # false +5.odd? # true + +# And if a method ends with an exclamation mark, it does something destructive +# like mutate the receiver. Many methods have a ! version to make a change, and +# a non-! version to just return a new changed version +company_name = "Dunder Mifflin" +company_name.upcase #=> "DUNDER MIFFLIN" +company_name #=> "Dunder Mifflin" +company_name.upcase! # we're mutating company_name this time! +company_name #=> "DUNDER MIFFLIN" + # Define a class with the class keyword class Human -- cgit v1.2.3 From 236cc1c14c71e561d9ab715079f6974a86fad271 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 26 Jan 2016 11:59:08 +1100 Subject: Fix formatting on comments --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index bdad4d06..adf5ce81 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -416,8 +416,8 @@ def foods ['pancake', 'sandwich', 'quesadilla'] end breakfast, lunch, dinner = foods -breakfast # 'pancake' -dinner # 'quesadilla' +breakfast #=> 'pancake' +dinner #=> 'quesadilla' # By convention, all methods that return booleans end with a question mark 5.even? # false -- cgit v1.2.3 From f60cb8316e21197e369311df91a1f9576878785d Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Tue, 26 Jan 2016 03:27:17 -0500 Subject: Added paragraphs, lists, and formatted text. --- asciidoc.html.markdown | 66 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 60 insertions(+), 6 deletions(-) diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index b98d0fa9..4196e424 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -44,23 +44,77 @@ v1.0, 2016-01-13 This article about chips is going to be fun. ``` +Paragraphs + +```asciidoc +You don't need anything special for paragraphs. + +Add a blank line between paragraphs to seperate them. + +To create a line blank add a + +and you will recieve a line break! +``` + +Formatting Text + +```asciidoc +_underscore creates italics_ +*asterisks for bold* +*_combine for extra fun_* +`use ticks to signify monospace` +`*bolded monospace*` +``` Section Titles ```asciidoc = Level 0 (may only be used in document's header) -== Same as

+== Level 1

-=== Same as

+=== Level 2

-==== Same as

+==== Level 3

-===== Same as

+===== Level 4
-====== Same as
+====== Level 5
-======= Same as +======= Level 6 ``` +Lists + +To create a bulleted list use asterisks. +```asciidoc +* foo +* bar +* baz +``` + +To create a numbered list use periods. +```asciidoc +. item 1 +. item 2 +. item 3 +``` + +You can nest lists by adding extra asterisks or periods up to five times. +```asciidoc +* foo 1 +** foo 2 +*** foo 3 +**** foo 4 +***** foo 5 +``` +```asciidoc +. foo 1 +.. foo 2 +... foo 3 +.... foo 4 +..... foo 5 +``` + + + -- cgit v1.2.3 From 083aa4fa4c462cbd9b5f9b3c671969d7d3d6976c Mon Sep 17 00:00:00 2001 From: Ryan Mavilia Date: Tue, 26 Jan 2016 03:32:28 -0500 Subject: Edit my website! --- asciidoc.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index 4196e424..f9ca8e21 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -1,7 +1,7 @@ --- language: asciidoc contributors: - - ["Ryan Mavilia", "http://unoriginality.rocks/:] + - ["Ryan Mavilia", "http://unoriginality.rocks/"] filename: asciidoc.md --- -- cgit v1.2.3 From 92beb9c37ca76d9ff0ea8b8c25cfe191accb6977 Mon Sep 17 00:00:00 2001 From: Tomy Date: Tue, 26 Jan 2016 19:53:14 +0900 Subject: feedback --- ja-jp/php-jp.html.markdown | 777 +++++++++++++++++++++++++++++++++++++++++++++ ja-jp/php.html.markdown | 776 -------------------------------------------- 2 files changed, 777 insertions(+), 776 deletions(-) create mode 100644 ja-jp/php-jp.html.markdown delete mode 100644 ja-jp/php.html.markdown diff --git a/ja-jp/php-jp.html.markdown b/ja-jp/php-jp.html.markdown new file mode 100644 index 00000000..2ca17179 --- /dev/null +++ b/ja-jp/php-jp.html.markdown @@ -0,0 +1,777 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Kazushige Tominaga", "https://github.com/kazu9su"] +filename: learnphp.php +lang: ja-jp +--- + +このドキュメントでは、 PHP 5+ について説明します。 + +```php + +Hello World Again! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (先頭の0は8進法を示す) +$int4 = 0x0F; // => 15 (先頭の0xは16進法を示す) + +// floats(浮動小数) (別名double) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// 変数の削除 +unset($int1); + +// 計算式 +$sum = 1 + 1; // 2 +$difference = 2 - 1; // 1 +$product = 2 * 2; // 4 +$quotient = 2 / 1; // 2 + +// 式の省略 +$number = 0; +$number += 1; // $numberに1加算Increment $number by 1 +echo $number++; // 1 がプリントされる(式の評価の後に加算される) +echo ++$number; // 3 がプリントされる(式の評価の前に加算される) +$number /= $float; // 割り算した結果の商を$numberに割り当てる + +// 文字列はシングルクォートで囲むのが望ましいです +$sgl_quotes = '$String'; // => '$String' + +// 文字列中に、他の変数を埋め込みたい場合以外は、ダブルクォートを使用するのはやめましょう +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Special characters are only escaped in double quotes +// 特殊文字はダブルクォートによってのみ、エスケープされます +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// 必要があれば、変数を波括弧で囲みます +$money = "I have $${number} in the bank."; + +// PHP 5.3から、nowdocs形式が変数の挿入をしない複数行の文字列の定義に使用できます +$nowdoc = <<<'END' +Multi line +string +END; + +// ヒアドキュメント形式なら、文字列中に変数の挿入を行えます。 +$heredoc = << 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 から、新しいシンタックスが導入されました +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // 1とプリントされます + +// キーを指定しないシンプルな配列にも、自動的に数値キーが振られます +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// 配列の最後に要素を追加する +$array[] = 'Four'; +// または、次のようにも書けます +array_push($array, 'Five'); + +// 配列から要素を削除 +unset($array[3]); + +/******************************** + * 出力 + */ + +echo('Hello World!'); +// 標準出力にHello World! とプリントします +// 標準出力はブラウザーで実行していればWebページに出力されます +// Stdout is the web page if running in a browser. + +print('Hello World!'); // echoの結果と同じです + +// echo は言語自体の構成要素であり、括弧なしで呼び出せます +// echo is actually a language construct, so you can drop the parentheses. +echo 'Hello World!'; +print 'Hello World!'; // printも同様です + +$paragraph = 'paragraph'; + +echo 100; // スカラー数値を直接出力します +echo $paragraph; // 変数も使用できます + +// PHPタグの短縮型が設定されているか、使用しているPHPのバージョンが +// 5.4.0 以上であれば、短縮echoシンタックスを使用できます +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// 変数の型と値を標準出力へダンプします +var_dump($z); // int(0) と出力されます + +// 人間が読めるフォーマットで変数を標準出力にプリントします +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * ロジック + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assertは引数がfalseの場合、Exceptionを投げます + +//これらの比較は型が違ったとしても、常に真です。 +assert($a == $b); // equality +assert($c != $a); // inequality +assert($c <> $a); // alternative inequality +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// 次の比較は値が等しく、かつ同じ型である場合のみ真です +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// spaceship演算子はPHP7から使用可能です +$a = 100; +$b = 1000; + +echo $a <=> $a; // 等しいので0になります +echo $a <=> $b; // $a < $b なので -1 です +echo $b <=> $a; // $b > $a なので 1 です + +// 変数は使用するコンテキストによって、変換されます + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (文字列は強制的に数値として処理されます) + +$string = 'one'; +echo $string + $string; // => 0 +// '+'演算子は文字列'one'を数値にキャストできないので、0と出力されます + +// 型のキャスティングによって、変数を指定したもう一つの型として扱うことができます +// Type casting can be used to treat a variable as another type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// 型をキャストするため専用の関数も存在します +$integer = 5; +$string = strval($integer); + +$var = null; // Null値 + + +/******************************** + * 制御構造 + */ + +if (true) { + print 'I get printed'; +} + +if (false) { + print 'I don\'t'; +} else { + print 'I get printed'; +} + +if (false) { + print 'Does not get printed'; +} elseif(true) { + print 'Does'; +} + +// 三項演算子 +print (false ? 'Does not get printed' : 'Does'); + +// PHP 5.3から、三項演算子の短縮形が使用できます +// $x ? $x : 'Does'と同義です +$x = false; +print($x ?: 'Does'); + +// null合体演算子はPHP 7から使用できます +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + +$x = 0; +if ($x === '0') { + print 'Does not print'; +} elseif($x == '1') { + print 'Does not print'; +} else { + print 'Does print'; +} + + + +// :を用いる別の構文はテンプレートで有用です +?> + + +この部分はifが真のとき表示されます + +それ以外の場合は、この部分が表示されます + + + 2, 'car' => 4]; + +//Foreachループによって、 配列を反復処理できます +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Prints "24" + +echo "\n"; + +// 値と同じ様に、keyも反復処理できます +foreach ($wheels as $vehicle => $wheel_count) { + echo "A $vehicle has $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Exit out of the while loop + } + echo $i++; +} // Prints "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Skip this iteration of the loop + } + echo $i; +} // Prints "0124" + + +/******************************** + * 関数 + */ + +// 関数を"function"で定義します +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + +// 有効な関数名は、文字またはアンダースコアで始めます。それ以降は +// どれだけ長い文字、数値、アンダースコアを続けても構いません + +function add ($x, $y = 1) { // $yはオプショナルな値であり、デフォルトで 1 です + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result には、関数の外からアクセス出来ません +// print $result; // エラーになります + +// PHP 5.3 から、無名関数が使えます +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// 関数は、関数を返すことができます +function bar ($x, $y) { + // 関数外の変数を利用したいときは、'use'を使います + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Prints "A - B - C" + +// 文字列を使って、定義済みの関数を呼び出すことができます +$function_name = 'add'; +echo $function_name(1, 2); // => 3 + +// プログラミング中に、動的に動かす関数を決める場合に便利です。 +// もしくは、call_user_func(callable $callback [, $parameter [, ... ]]) を使っても同じことができます + + +// 特に指定しなくても、渡された引数を受け取ることもできます +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +/******************************** + * ファイルの読み込み + */ + +instanceProp = $instanceProp; + } + + // メソッドはクラス内で関数として定義されます + public function myMethod() + { + print 'MyClass'; + } + + // finalキーワードは関数の上書きを禁止します + final function youCannotOverrideMe() + { + } + +/* + * クラスプロパティまたはメソッドをstaticとして作成すれば、 + * クラスをインスタンス化(newすること)しなくてもアクセスできます。 + * プロパティをstaticとして定義すると、 + * インスタンス化されたクラスオブジェクトを通してのアクセスはできなくなります。 + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// クラス定数は、いつでも静的にアクセスできます。 +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Outputs 'static'; +MyClass::myStaticMethod(); // Outputs 'I am static'; + +// クラスをインスタンス化するには、newを使います。 +$my_class = new MyClass('An instance property'); +// 括弧はもし引数を渡す必要がなければ省略可能です。 + +// ->を使ってクラスのメンバにアクセスします。 +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// extendsを使用してクラスを継承します。 +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // メソッドを上書きします。 + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// 「マジックメソッド」を使ってゲッターとセッターを生成できます。 +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // __get() メソッドを使用します +$x->property = 'Something'; // __set() メソッドを使用します + +// クラスは抽象クラスにもできます(abstractキーワードを使用します)し、 +// インターフェースを実装することもできます(implementsキーワードを使用します)。 +// インターフェースはinterfaceキーワードで定義します。 + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// インターフェースは継承することができます +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// クラスは1つ以上のインターフェースを実装できます。 +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * トレイト + */ + +// トレイトはPHP 5.4.0 以上で使用可能で、traitキーワードで定義します。 + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * 名前空間 + */ + +// このセクションは名前空間の定義はファイルの先頭で宣言される必要があるため、 +// 独立しています。 +// そのケースには当てはまらないふりをして続けましょう。 + + -Hello World Again! - 12 -$int2 = -12; // => -12 -$int3 = 012; // => 10 (先頭の0は8進法を示す) -$int4 = 0x0F; // => 15 (先頭の0xは16進法を示す) - -// floats(浮動小数) (別名double) -$float = 1.234; -$float = 1.2e3; -$float = 7E-10; - -// 変数の削除 -unset($int1); - -// 計算式 -$sum = 1 + 1; // 2 -$difference = 2 - 1; // 1 -$product = 2 * 2; // 4 -$quotient = 2 / 1; // 2 - -// 式の省略 -$number = 0; -$number += 1; // $numberに1加算Increment $number by 1 -echo $number++; // 1 がプリントされる(式の評価の後に加算される) -echo ++$number; // 3 がプリントされる(式の評価の前に加算される) -$number /= $float; // 割り算した結果の商を$numberに割り当てる - -// 文字列はシングルクォートで囲むのが望ましいです -$sgl_quotes = '$String'; // => '$String' - -// 文字列中に、他の変数を埋め込みたい場合以外は、ダブルクォートを使用するのはやめましょう -$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' - -// Special characters are only escaped in double quotes -// 特殊文字はダブルクォートによってのみ、エスケープされます -$escaped = "This contains a \t tab character."; -$unescaped = 'This just contains a slash and a t: \t'; - -// 必要があれば、変数を波括弧で囲みます -$money = "I have $${number} in the bank."; - -// PHP 5.3から、nowdocs形式が変数の挿入をしない複数行の文字列の定義に使用できます -$nowdoc = <<<'END' -Multi line -string -END; - -// ヒアドキュメント形式なら、文字列中に変数の挿入を行えます。 -$heredoc = << 1, 'Two' => 2, 'Three' => 3); - -// PHP 5.4 から、新しいシンタックスが導入されました -$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; - -echo $associative['One']; // 1とプリントされます - -// キーを指定しないシンプルな配列にも、自動的に数値キーが振られます -$array = ['One', 'Two', 'Three']; -echo $array[0]; // => "One" - -// 配列の最後に要素を追加する -$array[] = 'Four'; -// または、次のようにも書けます -array_push($array, 'Five'); - -// 配列から要素を削除 -unset($array[3]); - -/******************************** - * 出力 - */ - -echo('Hello World!'); -// 標準出力にHello World! とプリントします -// 標準出力はブラウザーで実行していればWebページに出力されます -// Stdout is the web page if running in a browser. - -print('Hello World!'); // echoの結果と同じです - -// echo は言語自体の構成要素であり、括弧なしで呼び出せます -// echo is actually a language construct, so you can drop the parentheses. -echo 'Hello World!'; -print 'Hello World!'; // printも同様です - -$paragraph = 'paragraph'; - -echo 100; // スカラー数値を直接出力します -echo $paragraph; // 変数も使用できます - -// PHPタグの短縮型が設定されているか、使用しているPHPのバージョンが -// 5.4.0 以上であれば、短縮echoシンタックスを使用できます -?> -

- 2 -echo $z; // => 2 -$y = 0; -echo $x; // => 2 -echo $z; // => 0 - -// 変数の型と値を標準出力へダンプします -var_dump($z); // int(0) と出力されます - -// 人間が読めるフォーマットで変数を標準出力にプリントします -print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) - -/******************************** - * ロジック - */ -$a = 0; -$b = '0'; -$c = '1'; -$d = '1'; - -// assertは引数がfalseの場合、Exceptionを投げます - -//これらの比較は型が違ったとしても、常に真です。 -assert($a == $b); // equality -assert($c != $a); // inequality -assert($c <> $a); // alternative inequality -assert($a < $c); -assert($c > $b); -assert($a <= $b); -assert($c >= $d); - -// 次の比較は値が等しく、かつ同じ型である場合のみ真です -assert($c === $d); -assert($a !== $d); -assert(1 === '1'); -assert(1 !== '1'); - -// spaceship演算子はPHP7から使用可能です -$a = 100; -$b = 1000; - -echo $a <=> $a; // 等しいので0になります -echo $a <=> $b; // $a < $b なので -1 です -echo $b <=> $a; // $b > $a なので 1 です - -// 変数は使用するコンテキストによって、変換されます - -$integer = 1; -echo $integer + $integer; // => 2 - -$string = '1'; -echo $string + $string; // => 2 (文字列は強制的に数値として処理されます) - -$string = 'one'; -echo $string + $string; // => 0 -// '+'演算子は文字列'one'を数値にキャストできないので、0と出力されます - -// 型のキャスティングによって、変数を指定したもう一つの型として扱うことができます -// Type casting can be used to treat a variable as another type - -$boolean = (boolean) 1; // => true - -$zero = 0; -$boolean = (boolean) $zero; // => false - -// 型をキャストするため専用の関数も存在します -$integer = 5; -$string = strval($integer); - -$var = null; // Null値 - - -/******************************** - * 制御構造 - */ - -if (true) { - print 'I get printed'; -} - -if (false) { - print 'I don\'t'; -} else { - print 'I get printed'; -} - -if (false) { - print 'Does not get printed'; -} elseif(true) { - print 'Does'; -} - -// 三項演算子 -print (false ? 'Does not get printed' : 'Does'); - -// PHP 5.3から、三項演算子の短縮形が使用できます -// $x ? $x : 'Does'と同義です -$x = false; -print($x ?: 'Does'); - -// null合体演算子はPHP 7から使用できます -$a = null; -$b = 'Does print'; -echo $a ?? 'a is not set'; // prints 'a is not set' -echo $b ?? 'b is not set'; // prints 'Does print' - - -$x = 0; -if ($x === '0') { - print 'Does not print'; -} elseif($x == '1') { - print 'Does not print'; -} else { - print 'Does print'; -} - - - -// :を用いる別の構文はテンプレートで有用です -?> - - -この部分はifが真のとき表示されます - -それ以外の場合は、この部分が表示されます - - - 2, 'car' => 4]; - -//Foreachループによって、 配列を反復処理できます -foreach ($wheels as $wheel_count) { - echo $wheel_count; -} // Prints "24" - -echo "\n"; - -// 値と同じ様に、keyも反復処理できます -foreach ($wheels as $vehicle => $wheel_count) { - echo "A $vehicle has $wheel_count wheels"; -} - -echo "\n"; - -$i = 0; -while ($i < 5) { - if ($i === 3) { - break; // Exit out of the while loop - } - echo $i++; -} // Prints "012" - -for ($i = 0; $i < 5; $i++) { - if ($i === 3) { - continue; // Skip this iteration of the loop - } - echo $i; -} // Prints "0124" - - -/******************************** - * 関数 - */ - -// 関数を"function"で定義します -function my_function () { - return 'Hello'; -} - -echo my_function(); // => "Hello" - -// 有効な関数名は、文字またはアンダースコアで始めます。それ以降は -// どれだけ長い文字、数値、アンダースコアを続けても構いません - -function add ($x, $y = 1) { // $yはオプショナルな値であり、デフォルトで 1 です - $result = $x + $y; - return $result; -} - -echo add(4); // => 5 -echo add(4, 2); // => 6 - -// $result には、関数の外からアクセス出来ません -// print $result; // エラーになります - -// PHP 5.3 から、無名関数が使えます -$inc = function ($x) { - return $x + 1; -}; - -echo $inc(2); // => 3 - -function foo ($x, $y, $z) { - echo "$x - $y - $z"; -} - -// 関数は、関数を返すことができます -function bar ($x, $y) { - // 関数外の変数を利用したいときは、'use'を使います - return function ($z) use ($x, $y) { - foo($x, $y, $z); - }; -} - -$bar = bar('A', 'B'); -$bar('C'); // Prints "A - B - C" - -// 文字列を使って、定義済みの関数を呼び出すことができます -$function_name = 'add'; -echo $function_name(1, 2); // => 3 - -// プログラミング中に、動的に動かす関数を決める場合に便利です。 -// もしくは、call_user_func(callable $callback [, $parameter [, ... ]]) を使っても同じことができます - - -// 特に指定しなくても、渡された引数を受け取ることもできます -function parameters() { - $numargs = func_num_args(); - if ($numargs > 0) { - echo func_get_arg(0) . ' | '; - } - $args_array = func_get_args(); - foreach ($args_array as $key => $arg) { - echo $key . ' - ' . $arg . ' | '; - } -} - -parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | - -/******************************** - * ファイルの読み込み - */ - -instanceProp = $instanceProp; - } - - // メソッドはクラス内で関数として定義されます - public function myMethod() - { - print 'MyClass'; - } - - // finalキーワードは関数の上書きを禁止します - final function youCannotOverrideMe() - { - } - -/* - * クラスプロパティまたはメソッドをstaticとして作成すれば、 - * クラスをインスタンス化(newすること)しなくてもアクセスできます。 - * プロパティをstaticとして定義すると、 - * インスタンス化されたクラスオブジェクトを通してのアクセスはできなくなります。 - */ - - public static function myStaticMethod() - { - print 'I am static'; - } -} - -// クラス定数は、いつでも静的にアクセスできます。 -echo MyClass::MY_CONST; // Outputs 'value'; - -echo MyClass::$staticVar; // Outputs 'static'; -MyClass::myStaticMethod(); // Outputs 'I am static'; - -// クラスをインスタンス化するには、newを使います。 -$my_class = new MyClass('An instance property'); -// 括弧はもし引数を渡す必要がなければ省略可能です。 - -// ->を使ってクラスのメンバにアクセスします。 -echo $my_class->property; // => "public" -echo $my_class->instanceProp; // => "An instance property" -$my_class->myMethod(); // => "MyClass" - - -// extendsを使用してクラスを継承します。 -class MyOtherClass extends MyClass -{ - function printProtectedProperty() - { - echo $this->prot; - } - - // メソッドを上書きします。 - function myMethod() - { - parent::myMethod(); - print ' > MyOtherClass'; - } -} - -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" - -final class YouCannotExtendMe -{ -} - -// 「マジックメソッド」を使ってゲッターとセッターを生成できます。 -class MyMapClass -{ - private $property; - - public function __get($key) - { - return $this->$key; - } - - public function __set($key, $value) - { - $this->$key = $value; - } -} - -$x = new MyMapClass(); -echo $x->property; // __get() メソッドを使用します -$x->property = 'Something'; // __set() メソッドを使用します - -// クラスは抽象クラスにもできます(abstractキーワードを使用します)し、 -// インターフェースを実装することもできます(implementsキーワードを使用します)。 -// インターフェースはinterfaceキーワードで定義します。 - -interface InterfaceOne -{ - public function doSomething(); -} - -interface InterfaceTwo -{ - public function doSomethingElse(); -} - -// インターフェースは継承することができます -interface InterfaceThree extends InterfaceTwo -{ - public function doAnotherContract(); -} - -abstract class MyAbstractClass implements InterfaceOne -{ - public $x = 'doSomething'; -} - -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo -{ - public function doSomething() - { - echo $x; - } - - public function doSomethingElse() - { - echo 'doSomethingElse'; - } -} - - -// クラスは1つ以上のインターフェースを実装できます。 -class SomeOtherClass implements InterfaceOne, InterfaceTwo -{ - public function doSomething() - { - echo 'doSomething'; - } - - public function doSomethingElse() - { - echo 'doSomethingElse'; - } -} - - -/******************************** - * トレイト - */ - -// トレイトはPHP 5.4.0 以上で使用可能で、traitキーワードで定義します。 - -trait MyTrait -{ - public function myTraitMethod() - { - print 'I have MyTrait'; - } -} - -class MyTraitfulClass -{ - use MyTrait; -} - -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" - - -/******************************** - * 名前空間 - */ - -// このセクションは名前空間の定義はファイルの先頭で宣言される必要があるため、 -// 独立しています。 -// そのケースには当てはまらないふりをして続けましょう。 - - Date: Tue, 26 Jan 2016 19:56:15 +0900 Subject: update filename --- ja-jp/php-jp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ja-jp/php-jp.html.markdown b/ja-jp/php-jp.html.markdown index 2ca17179..112916f4 100644 --- a/ja-jp/php-jp.html.markdown +++ b/ja-jp/php-jp.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["Kazushige Tominaga", "https://github.com/kazu9su"] -filename: learnphp.php +filename: learnphp-jp.php lang: ja-jp --- -- cgit v1.2.3 From 32f18cd992b5b6988a3b37eaa533f8215d83fe2e Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 10:38:51 +0530 Subject: Added Tuple --- c++.html.markdown | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index 44cad665..b8ab656c 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -955,6 +955,54 @@ v.push_back(Foo()); // New value is copied into the first Foo we inserted // explanation of why this works. v.swap(vector()); + +/////////////////////////////////////// +// Tuples (C++11 and above) +/////////////////////////////////////// + +#include + +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// its elements are accessed by their order in the tuple. + +// We start with constructing a tuple. +// +// Packing values into tuple +auto first = make_tuple ( 10 , 'A' ) ; +const int maxN = 1e9; +int maxL = 15; +auto second = make_tuple ( maxN , maxL ) ; + +// printing elements of 'first' tuple +cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A + +// printing elements of 'second' tuple +cout << get<0>(second)<< " " << get<1>(second) << "\n"; // prints: 1000000000 15 + + +// Unpacking tuple into variables + +int first_int; +char first_char; +tie (first_int , first_char ) = first; +cout << first_int << " " << first_char << "\n"; // prints : 10 A + +// We can also create tuple like this. + +tuple third ( 11 ,'A' , 3.14141); +// tuple_size returns number of elements in a tuple (as a constexpr) + +cout << tuple_size< decltype(third)>::value << "\n"; // prints: 3 + +// tuple_cat concatenates the elements of all the tuples in the same order. + +auto concatenated_tuple = tuple_cat( first, second ,third); +// concatenated_tuple becomes = (10 , 'A' , 1e9 , 15 , 11 , 'A' , 3.14141 ) + +cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 +cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 +cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' + ``` Further Reading: -- cgit v1.2.3 From a931cd772de4f5debc2dc379c0e8125ef9338d13 Mon Sep 17 00:00:00 2001 From: can Date: Thu, 28 Jan 2016 16:45:24 +0800 Subject: Remove junk string `450635425` --- zh-cn/java-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index a8fd2a4c..1e9c38f6 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -302,7 +302,7 @@ class Bicycle { // 构造函数是初始化一个对象的方式 // 以下是一个默认构造函数 - public Bi450635425cycle() { + public Bicycle() { gear = 1; cadence = 50; speed = 5; @@ -328,7 +328,7 @@ class Bicycle { return cadence; } - // void返450635425回值函数没有返回值 + // void返回值函数没有返回值 public void setCadence(int newValue) { cadence = newValue; } -- cgit v1.2.3 From c805148618f5b2679d6581ff41885abc7140fd4d Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 15:26:35 +0530 Subject: [C++/en] Tuples in C++ --- c++.html.markdown | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index b8ab656c..594cf15f 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -966,25 +966,24 @@ v.swap(vector()); // its elements are accessed by their order in the tuple. // We start with constructing a tuple. -// // Packing values into tuple -auto first = make_tuple ( 10 , 'A' ) ; +auto first = make_tuple( 10 , 'A' ) ; const int maxN = 1e9; -int maxL = 15; -auto second = make_tuple ( maxN , maxL ) ; +const int maxL = 15; +auto second = make_tuple( maxN , maxL ) ; // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A // printing elements of 'second' tuple -cout << get<0>(second)<< " " << get<1>(second) << "\n"; // prints: 1000000000 15 +cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 // Unpacking tuple into variables int first_int; char first_char; -tie (first_int , first_char ) = first; +tie(first_int , first_char ) = first; cout << first_int << " " << first_char << "\n"; // prints : 10 A // We can also create tuple like this. @@ -992,7 +991,7 @@ cout << first_int << " " << first_char << "\n"; // prints : 10 A tuple third ( 11 ,'A' , 3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) -cout << tuple_size< decltype(third)>::value << "\n"; // prints: 3 +cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. -- cgit v1.2.3 From 4a1a6857ce30f19f8c04dcca4571bb27f7dc36d0 Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 17:15:44 +0530 Subject: [C++/en] Tuple , updated --- c++.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 594cf15f..ea6ef034 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -967,10 +967,10 @@ v.swap(vector()); // We start with constructing a tuple. // Packing values into tuple -auto first = make_tuple( 10 , 'A' ) ; +auto first = make_tuple(10,'A') ; const int maxN = 1e9; const int maxL = 15; -auto second = make_tuple( maxN , maxL ) ; +auto second = make_tuple(maxN,maxL) ; // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A @@ -983,12 +983,12 @@ cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 1 int first_int; char first_char; -tie(first_int , first_char ) = first; +tie(first_int,first_char) = first; cout << first_int << " " << first_char << "\n"; // prints : 10 A // We can also create tuple like this. -tuple third ( 11 ,'A' , 3.14141); +tuple third (11,'A',3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 @@ -996,7 +996,7 @@ cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. auto concatenated_tuple = tuple_cat( first, second ,third); -// concatenated_tuple becomes = (10 , 'A' , 1e9 , 15 , 11 , 'A' , 3.14141 ) +// concatenated_tuple becomes = (10,'A',1e9,15,11,'A',3.14141) cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 -- cgit v1.2.3 From fa2b171008061bc82cf9b35e0470eebeaecb4a26 Mon Sep 17 00:00:00 2001 From: Jaskamal Kainth Date: Thu, 28 Jan 2016 18:22:11 +0530 Subject: [C++/en] Tuple , Updated --- c++.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index ea6ef034..1065b9e8 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -967,10 +967,10 @@ v.swap(vector()); // We start with constructing a tuple. // Packing values into tuple -auto first = make_tuple(10,'A') ; +auto first = make_tuple(10,'A'); const int maxN = 1e9; const int maxL = 15; -auto second = make_tuple(maxN,maxL) ; +auto second = make_tuple(maxN,maxL); // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A @@ -978,7 +978,6 @@ cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A // printing elements of 'second' tuple cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 - // Unpacking tuple into variables int first_int; -- cgit v1.2.3 From e1016455d5e4472e7a533c8cdd6df8ae4f2e7854 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 28 Jan 2016 14:04:41 +0100 Subject: #2119 fixups --- c++.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 1065b9e8..82662b15 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -967,10 +967,10 @@ v.swap(vector()); // We start with constructing a tuple. // Packing values into tuple -auto first = make_tuple(10,'A'); +auto first = make_tuple(10, 'A'); const int maxN = 1e9; const int maxL = 15; -auto second = make_tuple(maxN,maxL); +auto second = make_tuple(maxN, maxL); // printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A @@ -982,20 +982,20 @@ cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 1 int first_int; char first_char; -tie(first_int,first_char) = first; +tie(first_int, first_char) = first; cout << first_int << " " << first_char << "\n"; // prints : 10 A // We can also create tuple like this. -tuple third (11,'A',3.14141); +tuple third(11, 'A', 3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) -cout << tuple_size < decltype(third) >::value << "\n"; // prints: 3 +cout << tuple_size::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. -auto concatenated_tuple = tuple_cat( first, second ,third); -// concatenated_tuple becomes = (10,'A',1e9,15,11,'A',3.14141) +auto concatenated_tuple = tuple_cat(first, second, third); +// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141) cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 -- cgit v1.2.3 From fc1dd9d6af6f1e99c29655a766fda19d78440ee3 Mon Sep 17 00:00:00 2001 From: Rajat Gupta Date: Fri, 29 Jan 2016 11:34:28 +0530 Subject: Update css.html.markdown Updated CSS for clarity. --- css.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/css.html.markdown b/css.html.markdown index 8ee4f4b9..01fdbf4f 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] - ["Tyler Mumford", "https://tylermumford.com"] + - ["Rajat Gupta","httpd://github.com/rajat-explorer"] filename: learncss.css --- @@ -195,7 +196,7 @@ Save a CSS stylesheet with the extension `.css`. ## Precedence or Cascade -An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one (which also means that if two different linked stylesheets contain rules for a block and if the rules below don't differentiate them, then order of linking would take precedence and the sheet linked latest would govern styling) . This process is called cascading, hence the name Cascading Style Sheets. -- cgit v1.2.3 From b29ef73fd81c3d89784c0ca9fe1f90d875cbd223 Mon Sep 17 00:00:00 2001 From: oburdin Date: Fri, 29 Jan 2016 14:34:53 +0200 Subject: Update json-ua.html.markdown --- uk-ua/json-ua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uk-ua/json-ua.html.markdown b/uk-ua/json-ua.html.markdown index 120fb410..a860e9a7 100644 --- a/uk-ua/json-ua.html.markdown +++ b/uk-ua/json-ua.html.markdown @@ -22,7 +22,7 @@ JSON - це надзвичайно простий формат обміну да "ключі": "завжди мають бути обгорнуті в подвійні лапки", "числа": 0, - "рядки": "Пρивіт, світ. Допускаються всі unicode-символи разом із \"екрануванням\".", + "рядки": "Пρивіт, світe. Допускаються всі unicode-символи разом із \"екрануванням\".", "логічний тип": true, "нічого": null, -- cgit v1.2.3 From 89f24b7c255686723a8e7e89a3c820fc203c0243 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Sat, 30 Jan 2016 12:07:45 +0700 Subject: [php/id-id] add ID translation --- id-id/php-id.html.markdown | 851 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 851 insertions(+) create mode 100644 id-id/php-id.html.markdown diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown new file mode 100644 index 00000000..491a190e --- /dev/null +++ b/id-id/php-id.html.markdown @@ -0,0 +1,851 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp-id.php +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Dokumen ini menjelaskan tentang PHP5 keatas. + +```php + +Halo Dunia, lagi! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal) +$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal) +// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0. +$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner) + +// Nilai Floats (dikenal juga sebagai Doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Menghapus variable +unset($int1); + +// Aritmatika +$jumlah = 1 + 1; // 2 +$selisih = 2 - 1; // 1 +$perkalian = 2 * 2; // 4 +$pembagian = 2 / 1; // 2 + +// Aritmatika singkat +$angka = 0; +$angka += 1; // Menjumlahkan $angka dengan 1 +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; + +// String biasanya diawali dan ditutup dengan petik satu. +$sgl_quotes = '$String'; // => '$String' + +// Hindari menggunakan petik dua kecuali menyertakan variabel lain +$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' + +// Karakter khusus hanya berlaku pada petik dua +$berfungsi = "Ini mengandung \t karakter tab."; +$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t'; + +// Batasi variabel dengan kurung kurawal jika diperlukan +$uang = "Saya memiliki $${angka} di Bank."; + +// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris +$nowdoc = <<<'END' +Banyak baris +string +END; + +// Heredocs akan melakukan interpolasi +$heredoc = << 1, 'Dua' => 2, 'Tiga' => 3); + +// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru +$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3]; + +echo $asosiatif['Satu']; // menampilkan 1 + +// Daftar literal secara tidak langsung ditentukan oleh kunci integer +$larik = ['Satu', 'Dua', 'Tiga']; +echo $larik[0]; // => "Satu" + +// Menambahkan sebuah elemen pada akhir larik +$larik[] = 'Empat'; +// atau +array_push($larik, 'Lima'); + +// Menghapus elemen dari larik +unset($larik[3]); + +/******************************** + * Keluaran + */ + +echo('Halo Dunia!'); +// Menampilkan Halo Dunia! ke "stdout". +// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser). + +print('Halo Dunia!'); // Sama seperti "echo" + +// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan +echo 'Halo Dunia!'; +print 'Halo Dunia!'; + +$paragraf = 'paragraf'; + +echo 100; // Menampilkan variabel skalar secara langsung +echo $paragraf; // atau sebuat variabel + +// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan +// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat + +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Menampilkan tipe dan nilai dari variabel ke "stdout" +var_dump($z); // prints int(0) + +// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca +print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga ) + +/******************************** + * Logika + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar + +// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. +assert($a == $b); // kesamaan +assert($c != $a); // ketidak-samaan +assert($c <> $a); // versi lain dari ketidak-samaan +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operator 'Spaceship' (sejak PHP 7) +// Mengembalikan 0 jika nilai pada kedua sisi adalah sama +// Mengembalikan 1 jika nilai pada sisi kiri lebih besar +// Mengembalikan -1 jika nilai pada sisi kanan lebih besar + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 karena keduanya sama +echo $a <=> $b; // -1 karena $a < $b +echo $b <=> $a; // 1 karena $b > $a + +// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (string dipaksa menjadi integer) + +$string = 'satu'; +echo $string + $string; // => 0 +// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer + +// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya + +$boolean = (boolean) 1; // => true + +$nol = 0; +$boolean = (boolean) $nol; // => false + +// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe +$integer = 5; +$string = strval($integer); + +$var = null; // Nilai Null + + +/******************************** + * Struktur Kontrol + */ + +if (true) { + print 'Saya tampil'; +} + +if (false) { + print 'Saya tidak tampil'; +} else { + print 'Saya tampil'; +} + +if (false) { + print 'Tidak tampil'; +} elseif(true) { + print 'Tampil'; +} + +// operator ternary +print (false ? 'Tidak tampil' : 'Tampil'); + +// cara pintas operator ternary mulai dirilis sejak PHP 5.3 +// persamaan dari "$x ? $x : 'Kerjakan'" +$x = false; +print($x ?: 'Kerjakan'); + +// operator null coalesce sejak PHP 7 +$a = null; +$b = 'Ditampilkan'; +echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set' +echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan' + + +$x = 0; +if ($x === '0') { + print 'Tidak ditampilkan'; +} elseif($x == '1') { + print 'Tidak ditampilkan'; +} else { + print 'Tampil'; +} + + +// Alternatif sintaks untuk kebutuhan templat: +?> + + +Ini ditampilkan jika pengujian benar. + +Selain tersebut ini yang akan ditampilkan. + + + 2, 'mobil' => 4]; + +// Perulangan "foreach" dapat melakukan iterasi pada larik (array) +foreach ($roda as $jumlah_roda) { + echo $jumlah_roda; +} // Menampilkan "24" + +echo "\n"; + +// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai) +foreach ($roda as $mesin => $jumlah_roda) { + echo "$mesin memiliki $jumlah_roda buah roda"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Menghentikan proses perulangan + } + echo $i++; +} // Menampilkan "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Melewati tahapan iterasi saat ini + } + echo $i; +} // Menampilkan "0124" + + +/******************************** + * Fungsi + */ + +// Fungsi didefinisikan dengan "function": +function fungsi_saya () { + return 'Halo'; +} + +echo fungsi_saya(); // => "Halo" + +// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh +// beberapa huruf, angka, atau garis-bawah. + +function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1 + $hasil = $x + $y; + return $hasil; +} + +echo jumlah(4); // => 5 +echo jumlah(4, 2); // => 6 + +// $hasil tidak dapat diakses dari luar fungsi +// print $hasil; // Akan menghasilkan sebuah "warning". + +// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous); +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fungsi dapat mengembalikan fungsi juga +function bar ($x, $y) { + // Gunakan "use" untuk mengakses variabel diluar fungsi + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Menampilkan "A - B - C" + +// Fungsi uang memiliki nama dapat dipanggil berdasarkan string +$nama_fungsi = 'jumlah'; +echo $nama_fungsi(1, 2); // => 3 +// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis. +// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]); + +// Akses semua parameter yang dikirim ke sebuah fungsi +function parameter() { + $jumlah_param = func_num_args(); + if( $jumlah_param > 0 ) { + echo func_get_arg(0) . ' | '; + } + $daftar_param = func_get_args(); + foreach( $daftar_param as $kunci => $param ) { + echo $kunci . ' - ' . $param . ' | '; + } +} + +parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia | + +// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter +function variabel($kata, ...$daftar) { + echo $kata . " || "; + foreach ($daftar as $item) { + echo $item . ' | '; + } +} + +variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia | + +/******************************** + * Penyertaan ("include") + */ + +PropertiInstansi = $PropertiInstansi; + } + + // Method dideklarasikan sebagai fungsi didalam kelas + public function methodSaya() + { + print 'KelasSaya'; + } + + // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya + final function tidakDapatDiOverride() + { + } + +/* + * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut + * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui + * objek kelas yang hasil instansiasi, sedangkan method statis bisa. + */ + + public static function methodStatisSaya() + { + print 'Saya adalah statis'; + } +} + +// Konstan pada kelas dapat diakses secara statis +echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai' + +echo KelasSaya::$nilaiStatis; // Menampilkan 'statis' +KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis' + +// Instansi kelas menggunakan perintah "new" +$kelas_saya = new KelasSaya('Sebuah properti instansiasi'); +// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen. + +// Akses anggota kelas menggunakan -> +echo $kelas_saya->properti; // => "publik" +echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" +$kelas_saya->methodSaya(); // => "KelasSaya" + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Sun, 31 Jan 2016 16:08:28 +0100 Subject: Update c++.html.markdown v.empty() queries if v is empty while v.clear() actually clears it (or rather sets size to 0). --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 82662b15..a59b4db8 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -948,7 +948,7 @@ for (int i = 0; i < 10; ++i) // Following line sets size of v to 0, but destructors don't get called // and resources aren't released! -v.empty(); +v.clear(); v.push_back(Foo()); // New value is copied into the first Foo we inserted // Truly destroys all values in v. See section about temporary objects for -- cgit v1.2.3 From 600f8ccdd967252195dce4af3f831193e32c79a8 Mon Sep 17 00:00:00 2001 From: Petru Dimitriu Date: Mon, 1 Feb 2016 14:03:18 +0200 Subject: Add Brainf*ck and LaTeX Romanian translations --- ro-ro/brainfuck-ro.html.markdown | 91 ++++++++++++++ ro-ro/latex.html.markdown | 258 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 349 insertions(+) create mode 100644 ro-ro/brainfuck-ro.html.markdown create mode 100644 ro-ro/latex.html.markdown diff --git a/ro-ro/brainfuck-ro.html.markdown b/ro-ro/brainfuck-ro.html.markdown new file mode 100644 index 00000000..c67747c4 --- /dev/null +++ b/ro-ro/brainfuck-ro.html.markdown @@ -0,0 +1,91 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +filename: brainfuck-ro.clj +lang: ro-ro +--- + +Brainfuck (un nume propriu care nu primește majusculă inițială decât la începutul +propoziției) este un limbaj de programare Turing-comple extrem de minimalist cu +doar 8 instrucțiuni. + +Puteți încerca brainfuck în navigatorul dvs cu [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Orice caracter in afara de "><+-.,[]" (fara ghilimele) este ignorat. + +Brainfuck se reprezinta ca un vector de 30 000 de celule initializate cu zero +si un pointer de date care trimite spre celula curenta. + +Exista opt comenzi: ++ : Incrementeaza valoarea celulei curente cu 1. +- : Decrementeaza valoarea celulei curente cu 1. +> : Muta pointerul de date la urmatoarea celula (o celula la dreapta). +< : Muta pointerul de date la celula precedenta (o celula la stanga). +. : Afiseaza valoarea caracterului ASCII din celul caurenta (ex. 65 = 'A'). +, : Citeste un singur caracter si plaseaza valoarea lui in celula curenta. +[ : Daca valoarea in celula curenta este zero, sare la urmatorul caracter ] . + Altfel, merge la urmatoarea instructiune. +] : Daca valoarea in celula curenta este zero, sare la urmatoarea + instructiune. + Altfel, se intoarce la instructiunea de dupa caracterul [ precedent . + +[ and ] formeaza un ciclu. Evident, trebuie ca parantezarea sa fie corecta. + +Sa privim cateva programe brainfuck simple. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Acest program afiseaza litera 'A'. Mai intai, incrementeaza celula #1 pana +la valoarea 6. Celula #1 va fi folosita pentru ciclare. Apoi, intra in ciclu +([) si muta pointerul la celula #2. Incrementeaza celula #2 de 10 ori, +muta pointerul la celula #1 si decrementeaza celula #1. Acest ciclu parcurge +6 iteratii (este nevoie de 6 decrementari pentru ca celula #1 sa ajunga la 0), +iar dupa aceea se trece la caracterul ] corespunzator si se continua executia. + +In acest moment, ne aflam in celula #1, care are valoarea 0, in timp ce celula +#2 are valoarea 60. Ne mutam pe celula #2, incrementam de 5 ori, pentru a +obtine valoarea 65, si apoi afisam valoarea celulei #2. 65 este codul ASCII +pentru 'A', deci se afiseaza 'A' in terminal. + +, [ > + < - ] > . + +Acest program citeste un caracter de la intrarea utilizator si copiaza caracterul +in celula #1. Apoi incepem un ciclu. Se muta pointerul in celula #2, se +incremneteaza valoarea de la celula #2, se muta inapoi la celula #1, se +decrementeaza valoarea de la celula #1. Aceasta continua pana cand celula #1 este +0 iar celula #2 retine vechea valoare a celulei #1. Deoarece ne aflam in celula +#1 la sfarsitul ciclului, ne mutam pe celula #2 si afisam simbolul corespunzator +in ASCII. + +Aveti in vedere ca spatiile sunt doar pentru usurinta citirii. La fel de bine +programul ar fi putut fi scris astfel: + +,[>+<-]>. + +Incercati sa va dati seama ce face acest program: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Acest program citeste doua numere ca intrare si le inmulteste. + +Pe scurt, programul citeste doua date de intrare, apoi incepe ciclul +mare, a carui conditie se afla in celula #1; apoi se muta la celula #2 +si incepe un ciclu imbricat a carui conditie de reluare se afla in +celula #2, si care incrementeaza celula #3. Totusi aici intervine o +problema: La sfarsitul ciclului imbricat, celula #2 este zero. In +acest caz, celula ciclul imbricat nu va mai functiona data viitoare. +Pentru a rezolva aceasta problema, incrementam celula si #4, si +recopiem celula #4 in celula #2. In final, celula #3 este rezultatul. + +``` + +Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru +amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți +scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul +este destul de ușor de implementat, dar dacă sunteți masochist, încercați +să implementați un interpretor de brainfuck… în brainfuck. \ No newline at end of file diff --git a/ro-ro/latex.html.markdown b/ro-ro/latex.html.markdown new file mode 100644 index 00000000..35651e28 --- /dev/null +++ b/ro-ro/latex.html.markdown @@ -0,0 +1,258 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] + - ["Ramanan Balakrishnan", "https://github.com/ramananbalakrishnan"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +filename: brainfuck-ro.clj +filename: learn-latex-ro.tex +lang: ro-ro +--- + +```tex +% Toate comentariile încep cu % +% Nu există comentarii multi-linie + +% LaTeX NU este un program software de procesare text de tipul +% "What You See Is What You Get" +% precum MS Word, sau OpenOffice Writer + +% Toate comenzile LaTeX încep cu backslash. (\) + +% Documentele LaTeX încep cu o linie care definește tipul documentului +% care urmează a fi compilat. Alte tipuri de documente sunt book (carte), +% presentation (prezentare), etc. Opțiunile pentru document apar +% între paranteze drepte. În acest caz, specificăm că vrem să folosim +% un corp de text (font) de 12 puncte. +\documentclass[12pt]{article} + +% Mai apoi definim pachetele pe care documentul le folosește. +% Dacă vreți să includeți grafice, text colorat sau +% cod sursă din alt fișier în documentul dumneavoastră, +% trebuie să îmbogățiți capabilitățile LaTeX. Aceasta se realizează +% adăugând pachete. Voi include pachetele float și caption pentru +% imagini. +\usepackage{caption} +\usepackage{float} +% această comandă este necesară atunci când vreți să scrieți codul +% sursă folosind diacrtice! (cum e cazul aici, unde translatorul +% a vrut să scrie neapărat folosind diacriticele românești) +\usepackage[utf8]{inputenc} + +% De asemenea, putem defini și alte proprietăți pentru documente. +% We can define some other document properties too! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu \\ Traducere de Petru Dimitriu} +\date{\today} +\title{Învățați LaTeX în Y minute!} + +% Suntem gata să începem documentul. +% Tot ce se află înaintea acestei linii se numește "Preambul" +\begin{document} +% dacă am setat autorul, data și titlul, putem cere LaTeX să +% creeze o pagină de titlu +\maketitle + +% Cele mai multe documente științifice au un abstract; puteți folosi comenzile +% predefinite pentru acesta. Acesta ar trebui să apară, așa cum ar fi logic, +% după titlu, dar înainte de secțiunile principale ale corpului. +% Această comandă este disponibilă în clasele de document article și report. +\begin{abstract} + Documentațue LaTeX scrisă în LaTeX. O idee nicidecum nouă și nicidecum a mea! +\end{abstract} + +% Comenzile pentru secțiuni sunt intuitive. +% Toate titlurile secțiunilor sunt adăugate automat la tabla de materii (cuprins). +\section{Introducere} +Salut, mă numesc Petru. Astăzi vom învăța împreună LaTeX! + +\section{Altă secțiune} +Acesta este textul pentru altă secțiune. Vom face o subsecțiune. + +\subsection{Aceasta este o subsecțiune} % Subsecțiunile sunt și ele intuitive. +Și încă una. + +\subsubsection{Pitagora} +Mult mai bine. +\label{subsec:pitagora} + +% Folosind asteriscul putem suprima numărătoarea automată a LaTeX. +% Aceasta funcționează și pentru alte comenzi LaTeX. +\section*{Secțiune fără numerotare} +Totuși nu toate secțiunile trebuie să fie nenumerotate! + +\section{Note despre text} +În general LaTeX se pricepe să pună textul unde trebuie. Dacă o linie are \\ +nevoie \\ să \\ fie \\ întreruptă, puteți adăuga două caractere backslash +la codul sursă. + +\section{Liste} +Listele sunt printre cel mai simplu de făcut lucruri în LaTeX! Mâine merg la +cumpărături așa că fac o listă: +\begin{enumerate} % Aceasta creează un mediu "enumerate" + % \item spune mediului "enumerate" să incrementeze + \item salată + \item 27 pepeni + \item un singur iepuroi + % putem suprascrie numărul elementului folosind [] + \item[câte?] conserve de ton + + Nu este un element din listă, dar încă face parte din "enumerate". + +\end{enumerate} % All environments must have an end. + +\section{Matematică} + +Una dintre principalele întrebuințări ale LaTeX este realizarea +articolelor academice sau a foilor tehnice, de obicei aflate în +universul matematicii și științelor exacte. Astfel, trebuie să putem +adăuga simboluri speciale în documentului nostru! \\ + +Matematica are multe simboluri, mult mai multe decât se găsesc +pe o tastatură - printre ele, simboluri pentru mulțimi și relații, +săgeți, operatori și litere grecești.\\ + +Mulțimile și relațiile sunt de bază în lucrările științifce matematice. +Iată cum se scrie: toți y aparținând lui X.\\ +$\forall$ x $\in$ X. \\ + +% Observați cum am avut nevoie să pun semnul $ înainte și după simboluri. +% Aceasta pentru că atunci când scriem, suntem în modul text (text-mode). +% Totuși simbolurile matematice există numai în modul matematic (math-mode). +% Când ne aflăm în text-mode, putem scrie texte în math-mode punând $ înainte +% și după simboluri. La fel și viceversa. Și variabilele pot fi redate +% în math-mode. Putem intra în math-mode și scriind \[\]. + +\[a^2 + b^2 = c^2 \] + +Litera mea grecească este $\xi$. De asemenea îmi plac $\beta$, $\gamma$ și +$\sigma$. Nu există nicio literă grecească necunoscută pentru LaTeX! + +Operatorii sunt exențiali într-un document matematic! +funcțiile trigonometrice ($\sin$, $\cos$, $\tan$), +logaritmii și exponențialele ($\log$, $\exp$), +limitele ($\lim$), etc. +au comenzi definite în LaTeX pentru fiecare. +Să vedem cum scriem o ecuație: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fracțiile (numărător - numitor) pot fi scrise astfel: +% 10 / 7 +$^{10}/_{7}$ \\ + +% Fracții relativ complexe pot fi scrie ca +% \frac{numărător}{numitor} +$\frac{n!}{k!(n - k)!}$ \\ + +Putem insera ecuații și într-un "mediu pentru ecuații". + +% Afișează text matematic într-un mediu pentru ecuații. +\begin{equation} % intră în math-mode + c^2 = a^2 + b^2. + \label{eq:pitagora} % pentru referențiere +\end{equation} +% toate instrucțiunile cu \begin trebuie să fie cuplate cu o instrucțiune cu \end + +Putem referenția noua nosatră ecuație! +~\ref{eq:pitagora} este cunoscută și ca Teorema lui Pitagora, despre care vorbim și la Sec.~\ref{subsec:pitagora}. Multe lucruri prot fi etichetate: +figuri, ecuații, secțiuni, etc. + +Sumele discrete și integralele se scriu cu comenzile sum și int. + +% Unele compilatoare LaTeX nu acceptă să există linii goala +% într-un mediu pentru ecuații. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figuri} + +Să inserăm o figură. Așezarea figurilor poate fi ușor dificilă. +Eu trebuie să mă uit peste opțiunile de așezare de fiecare dată. + +\begin{figure}[H] % H denumește opțiunle de așezare + \centering % centrează figura pe pagină + % Inserează o figură scalată la 0.8 din lățimea paginii. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Comentat pentru a nu împiedica fișierul să compileze. + \caption{Triunghi dreptunghic cu laturile $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabel} +Putem insera tabele la fel cum inserăm figuri. + +\begin{table}[H] + \caption{Descriere pentru tabel} + % argumentele {} controlează cum vor fi afișate coloanele + \begin{tabular}{c|cc} + Număr & Nume & Prenume \\ % Numele coloanelor sunt separate prin $ + \hline % a linie orizonală + 1 & Popescu & Ion \\ + 2 & Sima & Felix + \end{tabular} +\end{table} + +% \section{Hyperlinkuri} % În curând + +\section{Cum facem ca LaTeX să nu compileze ceva (de exemplu cod sursă)} +Să zicem că vrem să includem niște cod în documentul nostru LaTeX. +Vom avea nevoie ca LaTeX să nu încerce să interpreteze acel cod, +ci doar să îl redea în document. Vom face asta cu un mediu verbatim. + +% Există și alte pachete (i.e. minty, lstlisting, etc.) +% dar verbatim este pachetul cel mai simplu. +\begin{verbatim} + print("Salut lume!") + a%b; % hei! putem folosi % în verbatim + random = 4; +\end{verbatim} + +\section{Compilarea} +Acum vă întrebați cum se compilează acest document minunat și să vă +minunați de rezultatul, un PDF LaTeX. (da, documentul acesta chiar +compilează). \\ +Realizarea documentului cu LaTeX va parcurge următorii pași: + \begin{enumerate} + \item Se scrie documentul în text simplu. (codul sursă) + \item Se compilează documentul pentru a produce un PDF. + Compilarea arată cam așa în Linux:\\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Anumiți editor pentru LaTeX combină pașii 1 și 2 în același produs software. +Așadar, dacă vreți să vedeți realizați pasul 1 dar nu și pasul 2, el se poate +realiza "în spate". + +Scrieți toate informațiile de formatare în pasul 1. Compilarea din pasul 2 +se ocupă de producerea documentului în formatul definit în pasul 1. + +\section{Final} + +Asta e tot pentru moment! + +% De multe ori veți vrea să aveți o secțiune cu bibliografie în document. +% Cea mai ușoară modalitate este folosind mediul thebibliography. +\begin{thebibliography}{1} + % Similar celorlalte liste, comanda \bibitem e folosită pentru a înșirui + % elemente; fiecare element poate fi citat în interiorul textului + \bibitem{latexwiki} Uimitoarea carte wiki LaTeX: {\em https://en.wikibooks.org/wiki/LaTeX} + \bibitem{latextutorial} Un tutorial propriu-zis: {\em http://www.latex-tutorial.com} +\end{thebibliography} + +% încheie documentul +\end{document} +``` + +## Mai multe despre LaTeX + +* Uimitoarea carte wiki LaTeX: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* Un tutorial propriu-zis: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) -- cgit v1.2.3 From 93c92ac2361244a3ba78e523309517499950212a Mon Sep 17 00:00:00 2001 From: Petru Dimitriu Date: Mon, 1 Feb 2016 14:04:10 +0200 Subject: Fix tiny typo in LaTeX doc --- latex.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/latex.html.markdown b/latex.html.markdown index 2492f226..d41f6b2f 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -205,7 +205,7 @@ environment. By now you're probably wondering how to compile this fabulous document and look at the glorious glory that is a LaTeX pdf. -(yes, this document actually does compiles). \\ +(yes, this document actually does compile). \\ Getting to the final document using LaTeX consists of the following steps: \begin{enumerate} \item Write the document in plain text (the "source code"). -- cgit v1.2.3 From 528a761ca68b5d30fac6aed9686104a483467be6 Mon Sep 17 00:00:00 2001 From: Petru Dimitriu Date: Mon, 1 Feb 2016 14:07:58 +0200 Subject: Fix another tiny typo --- ro-ro/brainfuck-ro.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/ro-ro/brainfuck-ro.html.markdown b/ro-ro/brainfuck-ro.html.markdown index c67747c4..19209c2e 100644 --- a/ro-ro/brainfuck-ro.html.markdown +++ b/ro-ro/brainfuck-ro.html.markdown @@ -5,7 +5,6 @@ contributors: - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] -filename: brainfuck-ro.clj lang: ro-ro --- -- cgit v1.2.3 From b7e166dc45edd2d5cc6dd271749cd49ef003b8ae Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Tue, 2 Feb 2016 07:34:19 +0700 Subject: [php/id-id] updates for ID translation --- id-id/php-id.html.markdown | 239 ++++++++++++++++++++++----------------------- 1 file changed, 118 insertions(+), 121 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 491a190e..34d6e5f5 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -567,34 +567,34 @@ echo $kelas_saya->properti; // => "publik" echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" $kelas_saya->methodSaya(); // => "KelasSaya" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Menurunkan kelas menggunakan kata kunci "extends" +class KelasSayaLainnya extends KelasSaya { - function printProtectedProperty() + function tampilkanPropertiTerlindungi() { - echo $this->prot; + echo $this->properti; } - // Override a method - function myMethod() + // "override" terhadap sebuah method + function methodSaya() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::methodSaya(); + print ' > KelasSayaLainnya'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti'); +$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi" +$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya" -final class YouCannotExtendMe +final class SayaTidakBisaDiturunkan { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters" +class PetaKelasSaya { - private $property; + private $properti; public function __get($key) { @@ -607,127 +607,125 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new PetaKelasSaya(); +echo $x->properti; // akan memanggil method __get() +$x->properti = 'Sesuatu'; // akan memanggil method __set(); -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau +// meng-implementasikan interfaces (menggunakan kata kunci "implements"). +// Sebuah interface dideklarasikan dengan perintah "interface". -interface InterfaceOne +interface InterfaceSatu { - public function doSomething(); + public function kerjakanSesuatu(); } -interface InterfaceTwo +interface InterfaceDua { - public function doSomethingElse(); + public function kerjakanYangLain(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// interface dapat diturunkan +interface InterfaceTiga extends InterfaceDua { - public function doAnotherContract(); + public function kerjakanYangBerbeda(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class KelasAbstrakSaya implements InterfaceSatu { - public $x = 'doSomething'; + public $x = 'kerjakanSesuatu'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo { - public function doSomething() + public function kerjakanSesuatu() { echo $x; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } - -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Kelas dapat diimplementasikan pada banyak interface +class KelasLainnya implements InterfaceSatu, InterfaceDua { - public function doSomething() + public function kerjakanSesuatu() { - echo 'doSomething'; + echo 'kerjakanSesuatu'; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } /******************************** - * Traits + * Sifat (Traits) */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait" -trait MyTrait +trait TraitSaya { - public function myTraitMethod() + public function methodTraitSaya() { - print 'I have MyTrait'; + print 'Saya menggunakan Trait'; } } -class MyTraitfulClass +class KelasTraitSaya { - use MyTrait; + use TraitSaya; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$kls = new KelasTraitSaya(); +$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Bagian ini telah dibatasi, karena deklarasi "namespace" +// karena harus ditempatkan diawal dokumen. Date: Sat, 30 Jan 2016 12:07:45 +0700 Subject: [php/id-id] add ID translation --- id-id/php-id.html.markdown | 851 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 851 insertions(+) create mode 100644 id-id/php-id.html.markdown diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown new file mode 100644 index 00000000..491a190e --- /dev/null +++ b/id-id/php-id.html.markdown @@ -0,0 +1,851 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +filename: learnphp-id.php +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Dokumen ini menjelaskan tentang PHP5 keatas. + +```php + +Halo Dunia, lagi! + 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (awalan 0 menandakan bilangan Oktal) +$int4 = 0x0F; // => 15 (awalan 0x menandakan bilangan Heksadesimal) +// Bilangan Biner Integer tersedia mulai dari PHP 5.4.0. +$int5 = 0b11111111; // 255 (awalan 0b menandakan bilangan Biner) + +// Nilai Floats (dikenal juga sebagai Doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Menghapus variable +unset($int1); + +// Aritmatika +$jumlah = 1 + 1; // 2 +$selisih = 2 - 1; // 1 +$perkalian = 2 * 2; // 4 +$pembagian = 2 / 1; // 2 + +// Aritmatika singkat +$angka = 0; +$angka += 1; // Menjumlahkan $angka dengan 1 +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +$angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; + +// String biasanya diawali dan ditutup dengan petik satu. +$sgl_quotes = '$String'; // => '$String' + +// Hindari menggunakan petik dua kecuali menyertakan variabel lain +$dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' + +// Karakter khusus hanya berlaku pada petik dua +$berfungsi = "Ini mengandung \t karakter tab."; +$tidak_berfungsi = 'Ini hanya mengandung garis miring dan huruf t: \t'; + +// Batasi variabel dengan kurung kurawal jika diperlukan +$uang = "Saya memiliki $${angka} di Bank."; + +// Sejak PHP 5.3, nowdocs dapat digunakan untuk tak-terinterpolasi banyak-baris +$nowdoc = <<<'END' +Banyak baris +string +END; + +// Heredocs akan melakukan interpolasi +$heredoc = << 1, 'Dua' => 2, 'Tiga' => 3); + +// Pada PHP 5.4 diperkenalkan cara penulisan (sintaks) baru +$asosiatif = ['Satu' => 1, 'Dua' => 2, 'Tiga' => 3]; + +echo $asosiatif['Satu']; // menampilkan 1 + +// Daftar literal secara tidak langsung ditentukan oleh kunci integer +$larik = ['Satu', 'Dua', 'Tiga']; +echo $larik[0]; // => "Satu" + +// Menambahkan sebuah elemen pada akhir larik +$larik[] = 'Empat'; +// atau +array_push($larik, 'Lima'); + +// Menghapus elemen dari larik +unset($larik[3]); + +/******************************** + * Keluaran + */ + +echo('Halo Dunia!'); +// Menampilkan Halo Dunia! ke "stdout". +// "stdout" adalah sebuah halaman web ketika dijalankan dalam peramban (browser). + +print('Halo Dunia!'); // Sama seperti "echo" + +// "echo" dan "print" merupakan bahasa konstruksi, jadi tanda kurung dapat dihilangkan +echo 'Halo Dunia!'; +print 'Halo Dunia!'; + +$paragraf = 'paragraf'; + +echo 100; // Menampilkan variabel skalar secara langsung +echo $paragraf; // atau sebuat variabel + +// Jika PHP tag-singkat telah dikonfigurasi, atau versi PHP yang digunakan +// adalah 5.4.0 keatas, dapat digunakan sintaks "echo" singkat + +?> +

+ 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Menampilkan tipe dan nilai dari variabel ke "stdout" +var_dump($z); // prints int(0) + +// Menampilkan variabel ke "stdout" dalam format yang mudah dibaca +print_r($larik); // menampilkan: Array ( [0] => Satu [1] => Dua [2] => Tiga ) + +/******************************** + * Logika + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar + +// Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. +assert($a == $b); // kesamaan +assert($c != $a); // ketidak-samaan +assert($c <> $a); // versi lain dari ketidak-samaan +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Dibawah ini hanya akan bernilai benar jika nilainya memiliki tipe yang sama. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Operator 'Spaceship' (sejak PHP 7) +// Mengembalikan 0 jika nilai pada kedua sisi adalah sama +// Mengembalikan 1 jika nilai pada sisi kiri lebih besar +// Mengembalikan -1 jika nilai pada sisi kanan lebih besar + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 karena keduanya sama +echo $a <=> $b; // -1 karena $a < $b +echo $b <=> $a; // 1 karena $b > $a + +// Variabel dapat dikonversi menjadi tipe lain, sesuai penggunaannya. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 (string dipaksa menjadi integer) + +$string = 'satu'; +echo $string + $string; // => 0 +// Menghasilkan 0 karena operator (+) tidak dapat memaksa string 'satu' menjadi sebuah integer + +// Perubahan tipe dapat dimanfaatkan untuk diperlakukan sebagai tipe lainnya + +$boolean = (boolean) 1; // => true + +$nol = 0; +$boolean = (boolean) $nol; // => false + +// Terdapat juga fungsi khusus untuk melakukan perubahan terhadap beberapa tipe +$integer = 5; +$string = strval($integer); + +$var = null; // Nilai Null + + +/******************************** + * Struktur Kontrol + */ + +if (true) { + print 'Saya tampil'; +} + +if (false) { + print 'Saya tidak tampil'; +} else { + print 'Saya tampil'; +} + +if (false) { + print 'Tidak tampil'; +} elseif(true) { + print 'Tampil'; +} + +// operator ternary +print (false ? 'Tidak tampil' : 'Tampil'); + +// cara pintas operator ternary mulai dirilis sejak PHP 5.3 +// persamaan dari "$x ? $x : 'Kerjakan'" +$x = false; +print($x ?: 'Kerjakan'); + +// operator null coalesce sejak PHP 7 +$a = null; +$b = 'Ditampilkan'; +echo $a ?? 'a belum di-set'; // menampilkan 'a belum di-set' +echo $b ?? 'b belum di-set'; // menampilkan 'Ditampilkan' + + +$x = 0; +if ($x === '0') { + print 'Tidak ditampilkan'; +} elseif($x == '1') { + print 'Tidak ditampilkan'; +} else { + print 'Tampil'; +} + + +// Alternatif sintaks untuk kebutuhan templat: +?> + + +Ini ditampilkan jika pengujian benar. + +Selain tersebut ini yang akan ditampilkan. + + + 2, 'mobil' => 4]; + +// Perulangan "foreach" dapat melakukan iterasi pada larik (array) +foreach ($roda as $jumlah_roda) { + echo $jumlah_roda; +} // Menampilkan "24" + +echo "\n"; + +// Iterasi dapat dilakukan terhadap "key" (kunci) dan "value" (nilai) +foreach ($roda as $mesin => $jumlah_roda) { + echo "$mesin memiliki $jumlah_roda buah roda"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Menghentikan proses perulangan + } + echo $i++; +} // Menampilkan "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Melewati tahapan iterasi saat ini + } + echo $i; +} // Menampilkan "0124" + + +/******************************** + * Fungsi + */ + +// Fungsi didefinisikan dengan "function": +function fungsi_saya () { + return 'Halo'; +} + +echo fungsi_saya(); // => "Halo" + +// Nama fungsi yang baik dan benar diawali dengan sebuah huruf atau garis-bawah, diikuti oleh +// beberapa huruf, angka, atau garis-bawah. + +function jumlah ($x, $y = 1) { // $y merupakan opsional, jika tidak ditentukan akan bernilai 1 + $hasil = $x + $y; + return $hasil; +} + +echo jumlah(4); // => 5 +echo jumlah(4, 2); // => 6 + +// $hasil tidak dapat diakses dari luar fungsi +// print $hasil; // Akan menghasilkan sebuah "warning". + +// Sejak PHP 5.3 fungsi dapat dideklarasikan menjadi tanpa-nama (anonymous); +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Fungsi dapat mengembalikan fungsi juga +function bar ($x, $y) { + // Gunakan "use" untuk mengakses variabel diluar fungsi + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Menampilkan "A - B - C" + +// Fungsi uang memiliki nama dapat dipanggil berdasarkan string +$nama_fungsi = 'jumlah'; +echo $nama_fungsi(1, 2); // => 3 +// Bermanfaat untuk menentukan fungsi mana yang akan dipanggil secara dinamis. +// Atau, dapat juga menggunakan fungsi call_user_func(callable $callback [, $parameter [, ... ]]); + +// Akses semua parameter yang dikirim ke sebuah fungsi +function parameter() { + $jumlah_param = func_num_args(); + if( $jumlah_param > 0 ) { + echo func_get_arg(0) . ' | '; + } + $daftar_param = func_get_args(); + foreach( $daftar_param as $kunci => $param ) { + echo $kunci . ' - ' . $param . ' | '; + } +} + +parameter('Halo', 'Dunia'); // Halo | 0 - Halo | 1 - Dunia | + +// Sejak PHP 5.6, mendapatkan jumlah variabel yang ada pada parameter +function variabel($kata, ...$daftar) { + echo $kata . " || "; + foreach ($daftar as $item) { + echo $item . ' | '; + } +} + +variable("Pemisah", "Halo", "Dunia") // Pemisah || Halo | Dunia | + +/******************************** + * Penyertaan ("include") + */ + +PropertiInstansi = $PropertiInstansi; + } + + // Method dideklarasikan sebagai fungsi didalam kelas + public function methodSaya() + { + print 'KelasSaya'; + } + + // Perintah "final" membuat sebuah fungsi tidak dapat di-override oleh kelas turunannya + final function tidakDapatDiOverride() + { + } + +/* + * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut + * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui + * objek kelas yang hasil instansiasi, sedangkan method statis bisa. + */ + + public static function methodStatisSaya() + { + print 'Saya adalah statis'; + } +} + +// Konstan pada kelas dapat diakses secara statis +echo KelasSaya::NILAI_KONSTAN; // Menampilkan 'nilai' + +echo KelasSaya::$nilaiStatis; // Menampilkan 'statis' +KelasSaya::methodStatisSaya(); // Menampilkan 'Saya adalah statis' + +// Instansi kelas menggunakan perintah "new" +$kelas_saya = new KelasSaya('Sebuah properti instansiasi'); +// Tanda kurung adalah opsional jika tidak ingin menggunakan argumen. + +// Akses anggota kelas menggunakan -> +echo $kelas_saya->properti; // => "publik" +echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" +$kelas_saya->methodSaya(); // => "KelasSaya" + +// Extend classes using "extends" +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Override a method + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Prints "protected" +$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" + +final class YouCannotExtendMe +{ +} + +// You can use "magic methods" to create getters and setters +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Will use the __get() method +$x->property = 'Something'; // Will use the __set() method + +// Classes can be abstract (using the abstract keyword) or +// implement interfaces (using the implements keyword). +// An interface is declared with the interface keyword. + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// interfaces can be extended +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Classes can implement more than one interface +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +/******************************** + * Traits + */ + +// Traits are available from PHP 5.4.0 and are declared using "trait" + +trait MyTrait +{ + public function myTraitMethod() + { + print 'I have MyTrait'; + } +} + +class MyTraitfulClass +{ + use MyTrait; +} + +$cls = new MyTraitfulClass(); +$cls->myTraitMethod(); // Prints "I have MyTrait" + + +/******************************** + * Namespaces + */ + +// This section is separate, because a namespace declaration +// must be the first statement in a file. Let's pretend that is not the case + + Date: Tue, 2 Feb 2016 07:34:19 +0700 Subject: [php/id-id] updates for ID translation --- id-id/php-id.html.markdown | 239 ++++++++++++++++++++++----------------------- 1 file changed, 118 insertions(+), 121 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 491a190e..34d6e5f5 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -567,34 +567,34 @@ echo $kelas_saya->properti; // => "publik" echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" $kelas_saya->methodSaya(); // => "KelasSaya" -// Extend classes using "extends" -class MyOtherClass extends MyClass +// Menurunkan kelas menggunakan kata kunci "extends" +class KelasSayaLainnya extends KelasSaya { - function printProtectedProperty() + function tampilkanPropertiTerlindungi() { - echo $this->prot; + echo $this->properti; } - // Override a method - function myMethod() + // "override" terhadap sebuah method + function methodSaya() { - parent::myMethod(); - print ' > MyOtherClass'; + parent::methodSaya(); + print ' > KelasSayaLainnya'; } } -$my_other_class = new MyOtherClass('Instance prop'); -$my_other_class->printProtectedProperty(); // => Prints "protected" -$my_other_class->myMethod(); // Prints "MyClass > MyOtherClass" +$kelas_saya_lainnya = new KelasSayaLainnya('Instansiasi properti'); +$kelas_saya_lainnya->tampilkanPropertiTerlindung(); // => Menampilkan "terlindungi" +$kelas_saya_lainnya->methodSaya(); // Menampilkan "KelasSaya > KelasSayaLainnya" -final class YouCannotExtendMe +final class SayaTidakBisaDiturunkan { } -// You can use "magic methods" to create getters and setters -class MyMapClass +// Gunakan method ajaib (magic method) untuk membuat fungsi "getters" dan "setters" +class PetaKelasSaya { - private $property; + private $properti; public function __get($key) { @@ -607,127 +607,125 @@ class MyMapClass } } -$x = new MyMapClass(); -echo $x->property; // Will use the __get() method -$x->property = 'Something'; // Will use the __set() method +$x = new PetaKelasSaya(); +echo $x->properti; // akan memanggil method __get() +$x->properti = 'Sesuatu'; // akan memanggil method __set(); -// Classes can be abstract (using the abstract keyword) or -// implement interfaces (using the implements keyword). -// An interface is declared with the interface keyword. +// Kelas dapat dijadikan abstrak (menggunakan kata kunci "abstract"), atau +// meng-implementasikan interfaces (menggunakan kata kunci "implements"). +// Sebuah interface dideklarasikan dengan perintah "interface". -interface InterfaceOne +interface InterfaceSatu { - public function doSomething(); + public function kerjakanSesuatu(); } -interface InterfaceTwo +interface InterfaceDua { - public function doSomethingElse(); + public function kerjakanYangLain(); } -// interfaces can be extended -interface InterfaceThree extends InterfaceTwo +// interface dapat diturunkan +interface InterfaceTiga extends InterfaceDua { - public function doAnotherContract(); + public function kerjakanYangBerbeda(); } -abstract class MyAbstractClass implements InterfaceOne +abstract class KelasAbstrakSaya implements InterfaceSatu { - public $x = 'doSomething'; + public $x = 'kerjakanSesuatu'; } -class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +class KelasKongkritSaya extends KelasAbstrakSaya implements InterfaceTwo { - public function doSomething() + public function kerjakanSesuatu() { echo $x; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } - -// Classes can implement more than one interface -class SomeOtherClass implements InterfaceOne, InterfaceTwo +// Kelas dapat diimplementasikan pada banyak interface +class KelasLainnya implements InterfaceSatu, InterfaceDua { - public function doSomething() + public function kerjakanSesuatu() { - echo 'doSomething'; + echo 'kerjakanSesuatu'; } - public function doSomethingElse() + public function kerjakanYangLain() { - echo 'doSomethingElse'; + echo 'kerjakanYangLain'; } } /******************************** - * Traits + * Sifat (Traits) */ -// Traits are available from PHP 5.4.0 and are declared using "trait" +// Traits mulai tersedia sejak PHP 5.4.0 dan dideklarasikan menggunakan kata kunci "trait" -trait MyTrait +trait TraitSaya { - public function myTraitMethod() + public function methodTraitSaya() { - print 'I have MyTrait'; + print 'Saya menggunakan Trait'; } } -class MyTraitfulClass +class KelasTraitSaya { - use MyTrait; + use TraitSaya; } -$cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$kls = new KelasTraitSaya(); +$kls->methodTraitSaya(); // menampilkan "Saya menggunakan Trait" /******************************** * Namespaces */ -// This section is separate, because a namespace declaration -// must be the first statement in a file. Let's pretend that is not the case +// Bagian ini telah dibatasi, karena deklarasi "namespace" +// karena harus ditempatkan diawal dokumen. Date: Fri, 5 Feb 2016 13:44:40 +0530 Subject: Update css.html.markdown --- css.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index 01fdbf4f..4ec95f8b 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -7,7 +7,7 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] - ["Tyler Mumford", "https://tylermumford.com"] - - ["Rajat Gupta","httpd://github.com/rajat-explorer"] + filename: learncss.css --- @@ -196,7 +196,7 @@ Save a CSS stylesheet with the extension `.css`. ## Precedence or Cascade -An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one (which also means that if two different linked stylesheets contain rules for a block and if the rules below don't differentiate them, then order of linking would take precedence and the sheet linked latest would govern styling) . +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one (which also means that if two different linked stylesheets contain rules for an element and if the rules are of the same specificity, then order of linking would take precedence and the sheet linked latest would govern styling) . This process is called cascading, hence the name Cascading Style Sheets. -- cgit v1.2.3 From 71e503325ec63ea16697ca74b8678f7148db7cc2 Mon Sep 17 00:00:00 2001 From: rajanand ilangovan Date: Sat, 6 Feb 2016 00:00:12 +0530 Subject: Removed ! --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index e82c1c36..745605ed 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -48,7 +48,7 @@ println(10) // Printing, without forcing a new line on next print print("Hello world") print(10) -// Hello world!10 +// Hello world10 // Declaring values is done using either var or val. // val declarations are immutable, whereas vars are mutable. Immutability is -- cgit v1.2.3 From 2b2951d0e0ae4de8f212ff4f9ee8c77db8e9458d Mon Sep 17 00:00:00 2001 From: oscarb-se Date: Mon, 8 Feb 2016 02:54:41 +0100 Subject: Fixed statement about many classes in one file Fixed statement on line 441 to say that it is _not_ good practice to keep many classes in the same file. --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 74140120..073135c9 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -438,7 +438,7 @@ public class LearnJava { // You can include other, non-public outer-level classes in a .java file, -// but it is good practice. Instead split classes into separate files. +// but it is not good practice. Instead split classes into separate files. // Class Declaration Syntax: -- cgit v1.2.3 From 39a6ab4d7a42bc76f14cd45882275f6754e4840d Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Fri, 12 Feb 2016 08:12:51 -0700 Subject: fix a typo --- zfs.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index 74487e35..de8c81f0 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -9,7 +9,7 @@ filename: LearnZfs.txt [ZFS](http://open-zfs.org/wiki/Main_Page) is a rethinking of the storage stack, combining traditional file systems as well as volume -managers into one cohesive tool. ZFS has some specific teminology that sets it appart from +managers into one cohesive tool. ZFS has some specific terminology that sets it appart from more traditional storage systems, however it has a great set of features with a focus on usability for systems administrators. -- cgit v1.2.3 From 85b4e2084e625ebbdfe8899b85bc207e9e5184f6 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Fri, 12 Feb 2016 08:15:27 -0700 Subject: fix a few more typos --- zfs.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index de8c81f0..39ff84cd 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -9,7 +9,7 @@ filename: LearnZfs.txt [ZFS](http://open-zfs.org/wiki/Main_Page) is a rethinking of the storage stack, combining traditional file systems as well as volume -managers into one cohesive tool. ZFS has some specific terminology that sets it appart from +managers into one cohesive tool. ZFS has some specific terminology that sets it apart from more traditional storage systems, however it has a great set of features with a focus on usability for systems administrators. @@ -23,7 +23,7 @@ types of VDEV's that offer various advantages, including redundancy and speed. VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. -Types of VDEV's +Types of VDEV's * stripe (a single disk, no redundancy) * mirror (n-way mirrors supported) * raidz @@ -39,13 +39,13 @@ increase your IOPS. ### Storage Pools ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow -you to separate the user visable file system from the physcal layout. +you to separate the user visible file system from the physical layout. ### ZFS Dataset -ZFS datasets are analagous to traditional filesystems but with many more features. They +ZFS datasets are analogous to traditional filesystems but with many more features. They provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) -snapshots, quota's, compression and deduplication. +snapshots, quota's, compression and de-duplication. ### Limits @@ -68,7 +68,7 @@ Actions: List zpools ```bash -# Create a raidz zpool +# Create a raidz zpool $ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 # List ZPools @@ -347,7 +347,7 @@ $ zfs promote tank/home/sarlalian_new ### Putting it all together -This following a script utilizing FreeBSD, jails and ZFS to automate +This following a script utilizing FreeBSD, jails and ZFS to automate provisioning a clean copy of a mysql staging database from a live replication slave. @@ -384,7 +384,7 @@ mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local echo "==== Starting the staging db server ====" jail -c staging -echo "==== Make sthe staging database not pull from the master ====" +echo "==== Makes the staging database not pull from the master ====" echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ``` -- cgit v1.2.3 From 5aa692f5f3bbfa7b79224748dcfd8ca5fba7a8bc Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 12 Feb 2016 11:42:25 -0800 Subject: brainfuck->bf --- bf.html.markdown | 81 ++++++++++++++++++++++++++++++++++ brainfuck.html.markdown | 81 ---------------------------------- es-es/bf-es.html.markdown | 89 ++++++++++++++++++++++++++++++++++++++ es-es/brainfuck-es.html.markdown | 89 -------------------------------------- fa-ir/bf-fa.html.markdown | 81 ++++++++++++++++++++++++++++++++++ fa-ir/brainfuck-fa.html.markdown | 81 ---------------------------------- fr-fr/bf-fr.html.markdown | 87 +++++++++++++++++++++++++++++++++++++ fr-fr/brainfuck-fr.html.markdown | 87 ------------------------------------- it-it/bf-it.html.markdown | 92 +++++++++++++++++++++++++++++++++++++++ it-it/brainfuck-it.html.markdown | 92 --------------------------------------- ko-kr/bf-kr.html.markdown | 84 ++++++++++++++++++++++++++++++++++++ ko-kr/brainfuck-kr.html.markdown | 84 ------------------------------------ nl-nl/bf.html.markdown | 86 +++++++++++++++++++++++++++++++++++++ nl-nl/brainfuck-nl.html.markdown | 86 ------------------------------------- pl-pl/bf-pl.html.markdown | 93 ++++++++++++++++++++++++++++++++++++++++ pl-pl/brainfuck-pl.html.markdown | 93 ---------------------------------------- pt-br/bf.html.markdown | 85 ++++++++++++++++++++++++++++++++++++ pt-br/brainfuck-pt.html.markdown | 85 ------------------------------------ pt-pt/bf.html.markdown | 84 ++++++++++++++++++++++++++++++++++++ pt-pt/brainfuck-pt.html.markdown | 84 ------------------------------------ ru-ru/bf.html.markdown | 85 ++++++++++++++++++++++++++++++++++++ ru-ru/brainfuck-ru.html.markdown | 85 ------------------------------------ tr-tr/bf-tr.html.markdown | 87 +++++++++++++++++++++++++++++++++++++ tr-tr/brainfuck-tr.html.markdown | 87 ------------------------------------- zh-cn/bf-cn.html.markdown | 70 ++++++++++++++++++++++++++++++ zh-cn/brainfuck-cn.html.markdown | 70 ------------------------------ 26 files changed, 1104 insertions(+), 1104 deletions(-) create mode 100644 bf.html.markdown delete mode 100644 brainfuck.html.markdown create mode 100644 es-es/bf-es.html.markdown delete mode 100644 es-es/brainfuck-es.html.markdown create mode 100644 fa-ir/bf-fa.html.markdown delete mode 100644 fa-ir/brainfuck-fa.html.markdown create mode 100644 fr-fr/bf-fr.html.markdown delete mode 100644 fr-fr/brainfuck-fr.html.markdown create mode 100644 it-it/bf-it.html.markdown delete mode 100644 it-it/brainfuck-it.html.markdown create mode 100644 ko-kr/bf-kr.html.markdown delete mode 100644 ko-kr/brainfuck-kr.html.markdown create mode 100644 nl-nl/bf.html.markdown delete mode 100644 nl-nl/brainfuck-nl.html.markdown create mode 100644 pl-pl/bf-pl.html.markdown delete mode 100644 pl-pl/brainfuck-pl.html.markdown create mode 100644 pt-br/bf.html.markdown delete mode 100644 pt-br/brainfuck-pt.html.markdown create mode 100644 pt-pt/bf.html.markdown delete mode 100644 pt-pt/brainfuck-pt.html.markdown create mode 100644 ru-ru/bf.html.markdown delete mode 100644 ru-ru/brainfuck-ru.html.markdown create mode 100644 tr-tr/bf-tr.html.markdown delete mode 100644 tr-tr/brainfuck-tr.html.markdown create mode 100644 zh-cn/bf-cn.html.markdown delete mode 100644 zh-cn/brainfuck-cn.html.markdown diff --git a/bf.html.markdown b/bf.html.markdown new file mode 100644 index 00000000..c8bbee61 --- /dev/null +++ b/bf.html.markdown @@ -0,0 +1,81 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +--- + +Brainfuck (not capitalized except at the start of a sentence) is an extremely +minimal Turing-complete programming language with just 8 commands. + +You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Any character not "><+-.,[]" (excluding quotation marks) is ignored. + +Brainfuck is represented by an array with 30,000 cells initialized to zero +and a data pointer pointing at the current cell. + +There are eight commands: ++ : Increments the value at the current cell by one. +- : Decrements the value at the current cell by one. +> : Moves the data pointer to the next cell (cell on the right). +< : Moves the data pointer to the previous cell (cell on the left). +. : Prints the ASCII value at the current cell (i.e. 65 = 'A'). +, : Reads a single input character into the current cell. +[ : If the value at the current cell is zero, skips to the corresponding ] . + Otherwise, move to the next instruction. +] : If the value at the current cell is zero, move to the next instruction. + Otherwise, move backwards in the instructions to the corresponding [ . + +[ and ] form a while loop. Obviously, they must be balanced. + +Let's look at some basic brainfuck programs. + +++++++ [ > ++++++++++ < - ] > +++++ . + +This program prints out the letter 'A'. First, it increments cell #1 to 6. +Cell #1 will be used for looping. Then, it enters the loop ([) and moves +to cell #2. It increments cell #2 10 times, moves back to cell #1, and +decrements cell #1. This loop happens 6 times (it takes 6 decrements for +cell #1 to reach 0, at which point it skips to the corresponding ] and +continues on). + +At this point, we're on cell #1, which has a value of 0, while cell #2 has a +value of 60. We move on cell #2, increment 5 times, for a value of 65, and then +print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal. + + +, [ > + < - ] > . + +This program reads a character from the user input and copies the character into +cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, +move back to cell #1, and decrement the value at cell #1. This continues on +until cell #1 is 0, and cell #2 holds cell #1's old value. Because we're on +cell #1 at the end of the loop, move to cell #2, and then print out the value +in ASCII. + +Also keep in mind that the spaces are purely for readability purposes. You +could just as easily write it as: + +,[>+<-]>. + +Try and figure out what this program does: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +This program takes two numbers for input, and multiplies them. + +The gist is it first reads in two inputs. Then it starts the outer loop, +conditioned on cell #1. Then it moves to cell #2, and starts the inner +loop conditioned on cell #2, incrementing cell #3. However, there comes a +problem: At the end of the inner loop, cell #2 is zero. In that case, +inner loop won't work anymore since next time. To solve this problem, +we also increment cell #4, and then recopy cell #4 into cell #2. +Then cell #3 is the result. +``` + +And that's brainfuck. Not that hard, eh? For fun, you can write your own +brainfuck programs, or you can write a brainfuck interpreter in another +language. The interpreter is fairly simple to implement, but if you're a +masochist, try writing a brainfuck interpreter… in brainfuck. diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown deleted file mode 100644 index a76169c8..00000000 --- a/brainfuck.html.markdown +++ /dev/null @@ -1,81 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] ---- - -Brainfuck (not capitalized except at the start of a sentence) is an extremely -minimal Turing-complete programming language with just 8 commands. - -You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Any character not "><+-.,[]" (excluding quotation marks) is ignored. - -Brainfuck is represented by an array with 30,000 cells initialized to zero -and a data pointer pointing at the current cell. - -There are eight commands: -+ : Increments the value at the current cell by one. -- : Decrements the value at the current cell by one. -> : Moves the data pointer to the next cell (cell on the right). -< : Moves the data pointer to the previous cell (cell on the left). -. : Prints the ASCII value at the current cell (i.e. 65 = 'A'). -, : Reads a single input character into the current cell. -[ : If the value at the current cell is zero, skips to the corresponding ] . - Otherwise, move to the next instruction. -] : If the value at the current cell is zero, move to the next instruction. - Otherwise, move backwards in the instructions to the corresponding [ . - -[ and ] form a while loop. Obviously, they must be balanced. - -Let's look at some basic brainfuck programs. - -++++++ [ > ++++++++++ < - ] > +++++ . - -This program prints out the letter 'A'. First, it increments cell #1 to 6. -Cell #1 will be used for looping. Then, it enters the loop ([) and moves -to cell #2. It increments cell #2 10 times, moves back to cell #1, and -decrements cell #1. This loop happens 6 times (it takes 6 decrements for -cell #1 to reach 0, at which point it skips to the corresponding ] and -continues on). - -At this point, we're on cell #1, which has a value of 0, while cell #2 has a -value of 60. We move on cell #2, increment 5 times, for a value of 65, and then -print cell #2's value. 65 is 'A' in ASCII, so 'A' is printed to the terminal. - - -, [ > + < - ] > . - -This program reads a character from the user input and copies the character into -cell #1. Then we start a loop. Move to cell #2, increment the value at cell #2, -move back to cell #1, and decrement the value at cell #1. This continues on -until cell #1 is 0, and cell #2 holds cell #1's old value. Because we're on -cell #1 at the end of the loop, move to cell #2, and then print out the value -in ASCII. - -Also keep in mind that the spaces are purely for readability purposes. You -could just as easily write it as: - -,[>+<-]>. - -Try and figure out what this program does: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -This program takes two numbers for input, and multiplies them. - -The gist is it first reads in two inputs. Then it starts the outer loop, -conditioned on cell #1. Then it moves to cell #2, and starts the inner -loop conditioned on cell #2, incrementing cell #3. However, there comes a -problem: At the end of the inner loop, cell #2 is zero. In that case, -inner loop won't work anymore since next time. To solve this problem, -we also increment cell #4, and then recopy cell #4 into cell #2. -Then cell #3 is the result. -``` - -And that's brainfuck. Not that hard, eh? For fun, you can write your own -brainfuck programs, or you can write a brainfuck interpreter in another -language. The interpreter is fairly simple to implement, but if you're a -masochist, try writing a brainfuck interpreter… in brainfuck. diff --git a/es-es/bf-es.html.markdown b/es-es/bf-es.html.markdown new file mode 100644 index 00000000..c93b8c3a --- /dev/null +++ b/es-es/bf-es.html.markdown @@ -0,0 +1,89 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +lang: es-es +--- + +Brainfuck (con mayúscula sólo al inicio de una oración) es un +lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos. + +Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + + +``` + +Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) +será ignorado. + +Brainfuck es representado por un arreglo de 30,000 celdas inicializadas +en cero y un puntero apuntando la celda actual. + +Existen ocho comandos: + ++ : Incrementa 1 al valor de la celda actual. +- : Decrementa 1 al valor de la celda actual. +> : Mueve el apuntador a la siguiente celda. (a la derecha) +< : Mueve el apuntador a la celda anterior. (a la izquierda) +. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A') +, : Lee un caracter como input y lo escribe en la celda actual. +[ : Si el valor en la celda actual es cero mueve el apuntador + hasta el primer ']' que encuentre. Si no es cero sigue a la + siguiente instrucción. +] : Si el valor en la celda actual es cero, entonces sigue con + la siguiente instrucción. Si no entonces mueve el apuntador + hacia atrás hasta encontrar el primer '['. + +[ y ] forman un while. Obviamente, deben estar balanceados. + +Estos son algunos ejemplos de programas escritos con brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime la letra 'A'. Primero, incrementa la celda #1 a +6. La celda #1 será usada para hacer los ciclos. Después entra al ciclo +([) y se mueve a la celda #2 (>). Después incrementa la celda #2 10 veces, +y se regresa a la celda #1 (<), para después decrementarla en 1 (-). +Este ciclo ocurre 6 veces (le toma 6 decrementos a la celda #1 volverse 0), +cuando esto pasa se salta a (]) y continúa. + +En este punto estamos en la celda #1, que tiene un valor de 0, mientras +que la celda #2 tiene un valor de 60. Nos movemos a la celda #2 (>), +la incrementamos 5 veces para tener un valor de 65 y luego imprimimos +el valor de la celda #2 (.). 65 es 'A' en ASCII así que la letra 'A' +se imprime. + +, [ > + < - ] > . + +Este programa lee un caracter del input y lo copia en la celda #2 (,). +Después empieza un ciclo. Nos movemos a la celda #2 (>) e incrementamos su +valor (+). Regresamos a la celda #1 y decrementamos su valor en 1 (-). +Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un +cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre +terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). + +Ten en cuenta que los espacios son sólo para fines de legibilidad. +Es lo mismo escribir el ejemplo de arriba que esto: +,[>+<-]>. + +Intenta descrifrar lo que hace este programa: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa toma dos números como input y los multiplica. + +Primero recibe dos números del usuario. Luego empieza el ciclo externo, +condicionado en la celda #1. Luego se mueve a la celda #2, comenzando +el ciclo interno condicionado en la celda #2 incrementando la celda #3. +Sin embargo viene un problema: El ciclo interior no funcionará nuevamente +hasta la próxima vez. Para resolver este problema también incrementamos la +celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene +el resultado. +``` +Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir +tu propio intérprete de brainfuck o tu propio programa en brainfuck. El +intérprete es relativamente sencillo de hacer, pero si eres masoquista, +puedes intentar construir tu propio intérprete de brainfuck... en brainfuck. diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown deleted file mode 100644 index 550511da..00000000 --- a/es-es/brainfuck-es.html.markdown +++ /dev/null @@ -1,89 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Daniel Zendejas", "https://github.com/DanielZendejas"] -lang: es-es ---- - -Brainfuck (con mayúscula sólo al inicio de una oración) es un -lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos. - -Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - - -``` - -Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) -será ignorado. - -Brainfuck es representado por un arreglo de 30,000 celdas inicializadas -en cero y un puntero apuntando la celda actual. - -Existen ocho comandos: - -+ : Incrementa 1 al valor de la celda actual. -- : Decrementa 1 al valor de la celda actual. -> : Mueve el apuntador a la siguiente celda. (a la derecha) -< : Mueve el apuntador a la celda anterior. (a la izquierda) -. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A') -, : Lee un caracter como input y lo escribe en la celda actual. -[ : Si el valor en la celda actual es cero mueve el apuntador - hasta el primer ']' que encuentre. Si no es cero sigue a la - siguiente instrucción. -] : Si el valor en la celda actual es cero, entonces sigue con - la siguiente instrucción. Si no entonces mueve el apuntador - hacia atrás hasta encontrar el primer '['. - -[ y ] forman un while. Obviamente, deben estar balanceados. - -Estos son algunos ejemplos de programas escritos con brainfuck. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime la letra 'A'. Primero, incrementa la celda #1 a -6. La celda #1 será usada para hacer los ciclos. Después entra al ciclo -([) y se mueve a la celda #2 (>). Después incrementa la celda #2 10 veces, -y se regresa a la celda #1 (<), para después decrementarla en 1 (-). -Este ciclo ocurre 6 veces (le toma 6 decrementos a la celda #1 volverse 0), -cuando esto pasa se salta a (]) y continúa. - -En este punto estamos en la celda #1, que tiene un valor de 0, mientras -que la celda #2 tiene un valor de 60. Nos movemos a la celda #2 (>), -la incrementamos 5 veces para tener un valor de 65 y luego imprimimos -el valor de la celda #2 (.). 65 es 'A' en ASCII así que la letra 'A' -se imprime. - -, [ > + < - ] > . - -Este programa lee un caracter del input y lo copia en la celda #2 (,). -Después empieza un ciclo. Nos movemos a la celda #2 (>) e incrementamos su -valor (+). Regresamos a la celda #1 y decrementamos su valor en 1 (-). -Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un -cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre -terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). - -Ten en cuenta que los espacios son sólo para fines de legibilidad. -Es lo mismo escribir el ejemplo de arriba que esto: -,[>+<-]>. - -Intenta descrifrar lo que hace este programa: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa toma dos números como input y los multiplica. - -Primero recibe dos números del usuario. Luego empieza el ciclo externo, -condicionado en la celda #1. Luego se mueve a la celda #2, comenzando -el ciclo interno condicionado en la celda #2 incrementando la celda #3. -Sin embargo viene un problema: El ciclo interior no funcionará nuevamente -hasta la próxima vez. Para resolver este problema también incrementamos la -celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene -el resultado. -``` -Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir -tu propio intérprete de brainfuck o tu propio programa en brainfuck. El -intérprete es relativamente sencillo de hacer, pero si eres masoquista, -puedes intentar construir tu propio intérprete de brainfuck... en brainfuck. diff --git a/fa-ir/bf-fa.html.markdown b/fa-ir/bf-fa.html.markdown new file mode 100644 index 00000000..bc5d8dc4 --- /dev/null +++ b/fa-ir/bf-fa.html.markdown @@ -0,0 +1,81 @@ +--- +language: bf +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] +lang: fa-ir +--- + +

برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت

+

دستور است.

+ +

هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود.

+ + +`>` `<` `+` `-` `.` `,` `[` `]` + +

برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند.

+

همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند.

+ +

در زیر هشت دستور این زبان شرح داده شده است:

+ +

`+` : یک عدد به خانه ی فعلی اضافه می کند. +

`-` : یک عدد از خانه ی فعلی کم می کند.

+

`>` : اشاره گر به خانه ی بعدی میرود -- به راست

+

`<` : اشاره گر به خانه ی قبلی میرود -- به چپ

+

`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A

+

`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند.

+

`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود.

+

در غیر این صورت به دستور بعدی میرود.

+

`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب

+ +

دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند.

+ +

در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید.

+ +``` +++++++ [ > ++++++++++ < - ] > +++++ . +``` + +

این برنامه کارکتر A را بر روی خروجی چاپ میکند.

+

در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A

+

ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار

+

تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند.

+

-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود

+

بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند.

+ +``` +, [ > + < - ] > . +``` + +

در این برنامه ابتدا یک کارکتر از ورودی خوانده می شود. سپس یک حلقه به تعداد بار مقدار

+

عددی کارکتر، یک عدد به خانه ی دوم اضافه می کند. با این کار در واقع برنامه مقدار ورودی را در خانه ی

+

دوم کپی می کند. و در نهایت آن را برروی خروجی چاپ می کند.

+ +

توجه داشته باشید که ردر بالا فواصل بین دستور ها فقط برای خوانایی بیشتر گذاشته شده اند.

+

در واقع برنامه بالا به شکل زیر صحیح می باشد.

+ +``` +,[>+<-]>. +``` + +

حال سعی کنید ببینید که برنامه ی زیر چه کاری انجام می دهد؟

+ +``` +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> +``` + +

این برنامه دو عدد را از ورودی خوانده و با هم ضرب می کند.

+ +

ابتدا دو عدد از ورودی خوانده می شوند. سپس حلقه ی بیرونی بر روی خانه شماره یک شروع میشود.

+

و درون آن حلقه ی دیگری بر روی خانه ی دوم شروع میشود که خانه ی 3 را زیاد میکند.

+

ولی مشکلی که در اینجا به وجود می آید اینست که در پایان حلقه ی دوم مقدار خانه ی 2 صفر شده

+

و مقدار اولیه ی آن از دست رفته است. برای حل این مشکل خانه ی شماره چهار هم زیاد میشود

+

و در پایان حلقه مقدار آن به خانه 2 کپی میشود.

+

در پایان خانه ی شماره 2 حاوی حاصلضرب خواهد بود.

+ +
+ +

و این همه ی برین فاک بود! خیلی ساده برای یادگیری ولی سنگین برای به کار بردن.

+

حال می توانید برای تفریح مشغول نوشتن برنامه ی های مختلف با آن شوید.

+

و یا یک اجرا کننده برین فاک را با یک زبان دیگر پیاده سازی کنید.

+

و یا اگر خیلی دوست داشتید یک اجرا کننده ی برین فاک با برین فاک بنویسید!!

diff --git a/fa-ir/brainfuck-fa.html.markdown b/fa-ir/brainfuck-fa.html.markdown deleted file mode 100644 index ef2bcba3..00000000 --- a/fa-ir/brainfuck-fa.html.markdown +++ /dev/null @@ -1,81 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Mohammad Valipour", "https://github.com/mvalipour"] -lang: fa-ir ---- - -

برین فاک زبان برنامه نویسی تورینگ کامل بی نهایت ساده ایست که دارای فقط هشت

-

دستور است.

- -

هر کارکتری به جر کارکتر های زیر در این زبان در نظر گرفته نمیشود.

- - -`>` `<` `+` `-` `.` `,` `[` `]` - -

برین فاک به صورت یک آرایه ی سی هزار خانه ای کار میکند که در ابتدا تمامی خانه های آن صفر هستند.

-

همچنین یک اشاره گر در این برنامه به خانه ی فعلی اشاره میکند.

- -

در زیر هشت دستور این زبان شرح داده شده است:

- -

`+` : یک عدد به خانه ی فعلی اضافه می کند. -

`-` : یک عدد از خانه ی فعلی کم می کند.

-

`>` : اشاره گر به خانه ی بعدی میرود -- به راست

-

`<` : اشاره گر به خانه ی قبلی میرود -- به چپ

-

`.` : کارکتر اسکی معادل مقدار خانه ی فعلی را چاپ میکند. -- به عنوان مثال 65 برای A

-

`,` : یک کارکتر را از ورودی خوانده و مقدار آن را در خانه ی فعلی زخیره میکند.

-

`[` : اگر مقدار خانه ی فعلی صفر باشد به محل بسته شدن کروشه جهش میکند. -- و از همه ی دستور های بین آن صرف نظر میشود.

-

در غیر این صورت به دستور بعدی میرود.

-

`]` : اگر مقدار خانه ی فعلی صفر باشد به خانه ی بعدی و در غیر این صورت به محل باز شدن کروشه جهش می کند. -- به عقب

- -

دو علامت کروشه امکان ایجاد حلقه را فراهم میکنند.

- -

در اینجا یک برنامه ی ساره برین فاک را مشاهده میکنید.

- -``` -++++++ [ > ++++++++++ < - ] > +++++ . -``` - -

این برنامه کارکتر A را بر روی خروجی چاپ میکند.

-

در این برنامه خانه ی اول به عنوان متغیر حلقه و خانه ی دوم برای مقدار عددی A

-

ابتدا عدد شش در خانه ی اول ایجاد شده. سپس برنامه وارد یک حلقه میشود که در هر بار

-

تکرار آن اشاره گر به خانه ی دوم رفته و ده بار به خانه ی فعلی اضافه می کند.

-

-- و در انتهای حلقه به خانه ی اول برگشته تا حلقه کنترل شود

-

بعد از اتمام حلقه به خانه ی دوم میرود و پنج بار به این خانه اضافه کرده و سپس آنرا چاپ میکند.

- -``` -, [ > + < - ] > . -``` - -

در این برنامه ابتدا یک کارکتر از ورودی خوانده می شود. سپس یک حلقه به تعداد بار مقدار

-

عددی کارکتر، یک عدد به خانه ی دوم اضافه می کند. با این کار در واقع برنامه مقدار ورودی را در خانه ی

-

دوم کپی می کند. و در نهایت آن را برروی خروجی چاپ می کند.

- -

توجه داشته باشید که ردر بالا فواصل بین دستور ها فقط برای خوانایی بیشتر گذاشته شده اند.

-

در واقع برنامه بالا به شکل زیر صحیح می باشد.

- -``` -,[>+<-]>. -``` - -

حال سعی کنید ببینید که برنامه ی زیر چه کاری انجام می دهد؟

- -``` -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -``` - -

این برنامه دو عدد را از ورودی خوانده و با هم ضرب می کند.

- -

ابتدا دو عدد از ورودی خوانده می شوند. سپس حلقه ی بیرونی بر روی خانه شماره یک شروع میشود.

-

و درون آن حلقه ی دیگری بر روی خانه ی دوم شروع میشود که خانه ی 3 را زیاد میکند.

-

ولی مشکلی که در اینجا به وجود می آید اینست که در پایان حلقه ی دوم مقدار خانه ی 2 صفر شده

-

و مقدار اولیه ی آن از دست رفته است. برای حل این مشکل خانه ی شماره چهار هم زیاد میشود

-

و در پایان حلقه مقدار آن به خانه 2 کپی میشود.

-

در پایان خانه ی شماره 2 حاوی حاصلضرب خواهد بود.

- -
- -

و این همه ی برین فاک بود! خیلی ساده برای یادگیری ولی سنگین برای به کار بردن.

-

حال می توانید برای تفریح مشغول نوشتن برنامه ی های مختلف با آن شوید.

-

و یا یک اجرا کننده برین فاک را با یک زبان دیگر پیاده سازی کنید.

-

و یا اگر خیلی دوست داشتید یک اجرا کننده ی برین فاک با برین فاک بنویسید!!

diff --git a/fr-fr/bf-fr.html.markdown b/fr-fr/bf-fr.html.markdown new file mode 100644 index 00000000..0fae6032 --- /dev/null +++ b/fr-fr/bf-fr.html.markdown @@ -0,0 +1,87 @@ +--- +language: bf +filename: learnbrainfuck-fr.bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Baptiste Fontaine", "http://bfontaine.net"] +lang: fr-fr +--- + +Brainfuck (sans majuscule à part au début d’une phrase) est un langage +Turing-complet extrêmement simple avec seulement 8 commandes. + +``` +Tout caractère en dehors de "><+-.,[]" (en dehors des guillemets) est ignoré. + +Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et +un pointeur de données pointant sur la cellule courante. + +Il y a huit commandes : ++ : Incrémente la valeur de la cellule courante de un. +- : Décrémente la valeur de la cellule courante de un. +> : Déplace le pointeur de données sur la cellule suivante (à droite). +< : Déplace le pointeur de données sur la cellule précédente (à gauche). +. : Affiche la valeur ASCII de la cellule courante (par ex. 65 = 'A'). +, : Lit un caractère et le place dans la cellule courante. +[ : Si la valeur dans la cellule courante vaut 0, saute au ] correspondant. + Sinon, continue avec la commande suivante. +] : Si la valeur dans la cellule courante vaut 0, continue avec la commande + suivante. Sinon, retourne au [ correspondant. + +[ et ] forment une boucle « tant que » (« while »). Ils doivent évidemment +aller par paires. + +Regardons quelques programmes simples en brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ce programme affiche la lettre 'A'. Il commence par incrémenter la première +cellule à 6. Il entre ensuite dans une boucle et se déplace sur la seconde +cellule. Il l’incrémente 10 fois, retourne sur la première cellule, et la +décrémente. Cette boucle est exécutée 6 fois (ce qui correspond aux 6 +décrémentations de la première cellule pour la faire atteindre 0, ce qui fait +sortir de la boucle). + +À ce moment-là, nous sommes sur la première cellule, qui a une valeur de 0, +tandis que la seconde cellule a une valeur de 60. Nous nous déplaçons sur +celle-ci, l’incrémentons 5 fois, pour une valeur de 65, et affichons sa valeur. +En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal. + +, [ > + < - ] > . + +Ce programme lit un caractère sur l’entrée standard et le copie dans la +première cellule. Il commence ensuite une boucle : il bouge sur la seconde +cellule, incrémente sa valeur, retourne sur la première et décrémente sa +valeur. Il continue jusqu’à ce que la valeur de la première cellule soit à 0, +et que la seconde cellule contienne l’ancienne valeur de la première. Comme +nous sommes sur la première cellule à la fin de la boucle, il bouge sur la +seconde et affiche sa valeur en ASCII. + +Souvenez-vous que les espaces sont uniquement là pour favoriser la lisibilité, +vous pourriez tout aussi aisément écrire le programme comme ceci : + +,[>+<-]>. + +Essayez et devinez ce que ce programme fait : + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ce programme prend deux nombres en entrée, et les multiplie. + +Il commence par lire deux entrées, puis commence une boucle externe, qui a une +condition sur la première cellule. Il bouge ensuite sur la seconde, et commence +une boucle interne sur celle-ci, en incrémentant la troisième cellule. Il y a +cependant un problème : à la fin de la boucle interne, la valeur de la seconde +cellule est à zéro. Dans ce cas, la boucle interne ne fonctionnera pas une +seconde fois. Pour régler le problème, nous incrémentons aussi la quatrième +cellule, puis recopions sa valeur dans la seconde cellule. +À la fin, la troisième cellule contient le résultat de la multiplication. +``` + +Et voilà ce qu’est le brainfuck. Pas très dur, hein ? Pour le fun, vous pouvez +écrire vos propres programmes en brainfuck, ou écrire un interpréteur brainfuck +dans un autre langage. L’interpréteur est relativement simple à implémenter, +mais si vous êtes un masochiste, essayez d’écrire un interpréteur brainfuck en… +brainfuck. diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/brainfuck-fr.html.markdown deleted file mode 100644 index 545e407e..00000000 --- a/fr-fr/brainfuck-fr.html.markdown +++ /dev/null @@ -1,87 +0,0 @@ ---- -language: brainfuck -filename: learnbrainfuck-fr.bf -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Baptiste Fontaine", "http://bfontaine.net"] -lang: fr-fr ---- - -Brainfuck (sans majuscule à part au début d’une phrase) est un langage -Turing-complet extrêmement simple avec seulement 8 commandes. - -``` -Tout caractère en dehors de "><+-.,[]" (en dehors des guillemets) est ignoré. - -Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et -un pointeur de données pointant sur la cellule courante. - -Il y a huit commandes : -+ : Incrémente la valeur de la cellule courante de un. -- : Décrémente la valeur de la cellule courante de un. -> : Déplace le pointeur de données sur la cellule suivante (à droite). -< : Déplace le pointeur de données sur la cellule précédente (à gauche). -. : Affiche la valeur ASCII de la cellule courante (par ex. 65 = 'A'). -, : Lit un caractère et le place dans la cellule courante. -[ : Si la valeur dans la cellule courante vaut 0, saute au ] correspondant. - Sinon, continue avec la commande suivante. -] : Si la valeur dans la cellule courante vaut 0, continue avec la commande - suivante. Sinon, retourne au [ correspondant. - -[ et ] forment une boucle « tant que » (« while »). Ils doivent évidemment -aller par paires. - -Regardons quelques programmes simples en brainfuck. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Ce programme affiche la lettre 'A'. Il commence par incrémenter la première -cellule à 6. Il entre ensuite dans une boucle et se déplace sur la seconde -cellule. Il l’incrémente 10 fois, retourne sur la première cellule, et la -décrémente. Cette boucle est exécutée 6 fois (ce qui correspond aux 6 -décrémentations de la première cellule pour la faire atteindre 0, ce qui fait -sortir de la boucle). - -À ce moment-là, nous sommes sur la première cellule, qui a une valeur de 0, -tandis que la seconde cellule a une valeur de 60. Nous nous déplaçons sur -celle-ci, l’incrémentons 5 fois, pour une valeur de 65, et affichons sa valeur. -En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal. - -, [ > + < - ] > . - -Ce programme lit un caractère sur l’entrée standard et le copie dans la -première cellule. Il commence ensuite une boucle : il bouge sur la seconde -cellule, incrémente sa valeur, retourne sur la première et décrémente sa -valeur. Il continue jusqu’à ce que la valeur de la première cellule soit à 0, -et que la seconde cellule contienne l’ancienne valeur de la première. Comme -nous sommes sur la première cellule à la fin de la boucle, il bouge sur la -seconde et affiche sa valeur en ASCII. - -Souvenez-vous que les espaces sont uniquement là pour favoriser la lisibilité, -vous pourriez tout aussi aisément écrire le programme comme ceci : - -,[>+<-]>. - -Essayez et devinez ce que ce programme fait : - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Ce programme prend deux nombres en entrée, et les multiplie. - -Il commence par lire deux entrées, puis commence une boucle externe, qui a une -condition sur la première cellule. Il bouge ensuite sur la seconde, et commence -une boucle interne sur celle-ci, en incrémentant la troisième cellule. Il y a -cependant un problème : à la fin de la boucle interne, la valeur de la seconde -cellule est à zéro. Dans ce cas, la boucle interne ne fonctionnera pas une -seconde fois. Pour régler le problème, nous incrémentons aussi la quatrième -cellule, puis recopions sa valeur dans la seconde cellule. -À la fin, la troisième cellule contient le résultat de la multiplication. -``` - -Et voilà ce qu’est le brainfuck. Pas très dur, hein ? Pour le fun, vous pouvez -écrire vos propres programmes en brainfuck, ou écrire un interpréteur brainfuck -dans un autre langage. L’interpréteur est relativement simple à implémenter, -mais si vous êtes un masochiste, essayez d’écrire un interpréteur brainfuck en… -brainfuck. diff --git a/it-it/bf-it.html.markdown b/it-it/bf-it.html.markdown new file mode 100644 index 00000000..a79710d0 --- /dev/null +++ b/it-it/bf-it.html.markdown @@ -0,0 +1,92 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Ivan Sala", "http://slavni96.github.io/"] + - ["Christian Grasso", "http://chris54721.net"] +lang: it-it +--- + +Brainfuck è un linguaggio di programmazione +[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza) +estremamente minimale, composto da solo 8 comandi. + +Puoi provarlo nel tuo browser utilizzando +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` + +Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici) +viene ignorato. +Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero +e da un puntatore che punta alla cella corrente. + +Vi sono otto comandi: ++ : Incrementa il valore della cella attuale di uno. +- : Decrementa il valore della cella attuale di uno. +> : Sposta il puntatore sulla cella seguente (sulla destra). +< : Sposta il puntatore sulla cella precendete (sulla sinistra). +. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A') +, : Legge un singolo carattere come input e lo salva nella cella corrente. +[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente. + Altrimenti, passa alla prossima istruzione. +] : Se il valore della cella corrente è zero, passa alla prossima istruzione. + Altrimenti, torna indietro fino alla [ corrispondente. + +[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati. +(Ad ogni [ dovrà corrispondere una ]) + +Ecco alcuni semplici esempi di programmi scritti in Brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa +la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo. +Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10 +volte, torna alla cella #1, e decrementa quest'ultima. +Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di +raggiungere lo 0, quindi prosegue oltre la corrispondente ]). + +A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha +valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo +il valore 65, quindi stampiamo il valore della cella #2. +Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale. + + +, [ > + < - ] > . + +Questo programma legge un carattere come input dall'utente, quindi salva il +carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2, +incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima. +Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2 +avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla +cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in +ASCII. + +Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere +una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi: + +,[>+<-]>. + +Proviamo, adesso, a capire cosa fa invece questo programma: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Il programma legge 2 numeri come input dall'utente, e li moltiplica. + +Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno +basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo +più interno basandosi sul valore della cella #2, incrementando la cella #3. +Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno +la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno. +Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il +valore di quest'ultima nella cella #2. +Il risultato sarà infine contenuto nella cella #3. +``` + +E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per +divertimento altri programmi in brainfuck, oppure scrivere un interprete +brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da +implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck. diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown deleted file mode 100644 index 08d2ede9..00000000 --- a/it-it/brainfuck-it.html.markdown +++ /dev/null @@ -1,92 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Ivan Sala", "http://slavni96.github.io/"] - - ["Christian Grasso", "http://chris54721.net"] -lang: it-it ---- - -Brainfuck è un linguaggio di programmazione -[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza) -estremamente minimale, composto da solo 8 comandi. - -Puoi provarlo nel tuo browser utilizzando -[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` - -Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici) -viene ignorato. -Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero -e da un puntatore che punta alla cella corrente. - -Vi sono otto comandi: -+ : Incrementa il valore della cella attuale di uno. -- : Decrementa il valore della cella attuale di uno. -> : Sposta il puntatore sulla cella seguente (sulla destra). -< : Sposta il puntatore sulla cella precendete (sulla sinistra). -. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A') -, : Legge un singolo carattere come input e lo salva nella cella corrente. -[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente. - Altrimenti, passa alla prossima istruzione. -] : Se il valore della cella corrente è zero, passa alla prossima istruzione. - Altrimenti, torna indietro fino alla [ corrispondente. - -[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati. -(Ad ogni [ dovrà corrispondere una ]) - -Ecco alcuni semplici esempi di programmi scritti in Brainfuck: - -++++++ [ > ++++++++++ < - ] > +++++ . - -Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa -la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo. -Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10 -volte, torna alla cella #1, e decrementa quest'ultima. -Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di -raggiungere lo 0, quindi prosegue oltre la corrispondente ]). - -A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha -valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo -il valore 65, quindi stampiamo il valore della cella #2. -Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale. - - -, [ > + < - ] > . - -Questo programma legge un carattere come input dall'utente, quindi salva il -carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2, -incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima. -Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2 -avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla -cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in -ASCII. - -Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere -una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi: - -,[>+<-]>. - -Proviamo, adesso, a capire cosa fa invece questo programma: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Il programma legge 2 numeri come input dall'utente, e li moltiplica. - -Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno -basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo -più interno basandosi sul valore della cella #2, incrementando la cella #3. -Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno -la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno. -Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il -valore di quest'ultima nella cella #2. -Il risultato sarà infine contenuto nella cella #3. -``` - -E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per -divertimento altri programmi in brainfuck, oppure scrivere un interprete -brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da -implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck. diff --git a/ko-kr/bf-kr.html.markdown b/ko-kr/bf-kr.html.markdown new file mode 100644 index 00000000..3d366d7c --- /dev/null +++ b/ko-kr/bf-kr.html.markdown @@ -0,0 +1,84 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["JongChan Choi", "http://0xABCDEF.com/"] + - ["Peter Lee", "http://peterjlee.com/"] +lang: ko-kr +--- + +Brainfuck(문장을 시작하는 단어가 아닌이상 첫글자는 대문자를 사용하지 않습니다)은 +여덟가지 명령어만으로 튜링-완전한 최소주의 프로그래밍 언어입니다. + +``` +"><+-.,[]" 이외의 문자들은 무시됩니다. (쌍따옴표는 제외) + +브레인퍽은 30,000 칸 짜리의 0으로 초기화된 배열과, +현재 칸을 가르키는 포인터로 표현됩니다. + +여덟가지의 명령어는 다음과 같습니다: ++ : 포인터가 가르키는 현재 칸의 값을 1 증가시킵니다. +- : 포인터가 가르키는 현재 칸의 값을 1 감소시킵니다. +> : 포인터가 다음 칸(오른쪽 칸)을 가르키도록 이동시킵니다. +< : 포인터가 이전 칸(왼쪽 칸)을 가르키도록 이동시킵니다. +. : 현재 칸의 값을 ASCII 문자로 출력합니다. (즉, 65 = 'A') +, : 하나의 문자를 입력받고 그 값을 현재 칸에 대입합니다. +[ : 현재 칸의 값이 0이면 짝이 맞는 ] 명령으로 넘어갑니다. + 0이 아니면 다음 명령어로 넘어갑니다. +] : 현재 칸의 값이 0이면 다음 명령어로 넘어갑니다. + 0이 아니면 짝이 맞는 [ 명령으로 다시 돌아갑니다. + +[이랑 ]은 while 루프를 만들어냅니다. 무조건, 짝이 맞아야 합니다. + +몇가지 간단한 브레인퍽 프로그램을 보겠습니다. + +++++++ [ > ++++++++++ < - ] > +++++ . + +이 프로그램은 문자 'A'를 출력합니다. 처음에는, 반복할 횟수를 정하기 위한 값을 +만들기 위해 첫번째 칸의 값을 6으로 증가시킵니다. 그리고 루프로 들어가서([) +두번째 칸으로 넘어갑니다. 루프 안에서는 두번째 칸의 값을 10 증가시키고, +다시 첫번째 칸으로 넘어가서 값을 1 감소시킵니다. 이 루프는 여섯번 돕니다. +(첫번째 칸의 값을 6번 감소시켜서 0이 될 때 까지는 ] 명령을 만날 때마다 +루프의 시작 지점으로 돌아갑니다) + +이 시점에서, 두번째 칸의 값은 60이고, 포인터는 값이 0인 첫번째 칸에 위치합니다. +여기서 두번째 칸으로 넘어간 다음 값을 5 증가시키면 두번째 칸의 값이 65가 되고, +65는 문자 'A'에 대응하는 아스키 코드이기 때문에, 두번째 칸의 값을 출력하면 +터미널에 'A'가 출력됩니다. + +, [ > + < - ] > . + +이 프로그램은 사용자로부터 문자 하나를 입력받아 첫번째 칸에 집어넣습니다. +그리고 루프에 들어가서, 두번째 칸으로 넘어가 값을 한 번 증가시킨 다음, +다시 첫번째 칸으로 넘어가서 값을 한 번 감소시킵니다. +이는 첫번째 칸의 값이 0이 될 때까지 지속되며, +두번째 칸은 첫번째 칸이 갖고있던 값을 가지게 됩니다. +루프가 종료되면 포인터는 첫번째 칸을 가르키기 때문에 두번째 칸으로 넘어가고, +해당 아스키 코드에 대응하는 문자를 출력합니다. + +또한 공백문자는 순전히 가독성을 위해서 작성되었다는 것을 기억하세요. +다음과 같이 작성해도 똑같이 돌아갑니다: + +,[>+<-]>. + +한 번 돌려보고 아래의 프로그램이 실제로 무슨 일을 하는지 맞춰보세요: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +이 프로그램은 두 개의 숫자를 입력받은 뒤, 그 둘을 곱합니다. + +위 코드는 일단 두 번의 입력을 받고, 첫번째 칸의 값만큼 바깥 루프를 돕니다. +그리고 루프 안에서 다시 두번째 칸의 값만큼 안쪽의 루프를 돕니다. +그리고 그 루프에서는 세번째 칸의 값을 증가시키는데, 문제가 하나 있습니다: +내부 루프가 한 번 끝나게 되면 두번째 칸의 값은 0이 됩니다. +그럼 다시 바깥 루프를 돌 때에 안쪽의 루프를 돌지 않게 되는데, 이를 해결하려면 +네번째 칸의 값도 같이 증가시킨 다음, 그 값을 두번째 칸으로 옮기면 됩니다. +그러면 세번째 칸에 곱셈의 결과가 남습니다. +``` + +여기까지 브레인퍽이었습니다. 참 쉽죠? +재미삼아 브레인퍽 프로그램이나 다른 언어로 브레인퍽 인터프리터를 작성해보세요. +인터프리터 구현은 간단한 편인데, +사서 고생하는 것을 즐기는 편이라면 한 번 작성해보세요… 브레인퍽으로. diff --git a/ko-kr/brainfuck-kr.html.markdown b/ko-kr/brainfuck-kr.html.markdown deleted file mode 100644 index c2e4341f..00000000 --- a/ko-kr/brainfuck-kr.html.markdown +++ /dev/null @@ -1,84 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["JongChan Choi", "http://0xABCDEF.com/"] - - ["Peter Lee", "http://peterjlee.com/"] -lang: ko-kr ---- - -Brainfuck(문장을 시작하는 단어가 아닌이상 첫글자는 대문자를 사용하지 않습니다)은 -여덟가지 명령어만으로 튜링-완전한 최소주의 프로그래밍 언어입니다. - -``` -"><+-.,[]" 이외의 문자들은 무시됩니다. (쌍따옴표는 제외) - -브레인퍽은 30,000 칸 짜리의 0으로 초기화된 배열과, -현재 칸을 가르키는 포인터로 표현됩니다. - -여덟가지의 명령어는 다음과 같습니다: -+ : 포인터가 가르키는 현재 칸의 값을 1 증가시킵니다. -- : 포인터가 가르키는 현재 칸의 값을 1 감소시킵니다. -> : 포인터가 다음 칸(오른쪽 칸)을 가르키도록 이동시킵니다. -< : 포인터가 이전 칸(왼쪽 칸)을 가르키도록 이동시킵니다. -. : 현재 칸의 값을 ASCII 문자로 출력합니다. (즉, 65 = 'A') -, : 하나의 문자를 입력받고 그 값을 현재 칸에 대입합니다. -[ : 현재 칸의 값이 0이면 짝이 맞는 ] 명령으로 넘어갑니다. - 0이 아니면 다음 명령어로 넘어갑니다. -] : 현재 칸의 값이 0이면 다음 명령어로 넘어갑니다. - 0이 아니면 짝이 맞는 [ 명령으로 다시 돌아갑니다. - -[이랑 ]은 while 루프를 만들어냅니다. 무조건, 짝이 맞아야 합니다. - -몇가지 간단한 브레인퍽 프로그램을 보겠습니다. - -++++++ [ > ++++++++++ < - ] > +++++ . - -이 프로그램은 문자 'A'를 출력합니다. 처음에는, 반복할 횟수를 정하기 위한 값을 -만들기 위해 첫번째 칸의 값을 6으로 증가시킵니다. 그리고 루프로 들어가서([) -두번째 칸으로 넘어갑니다. 루프 안에서는 두번째 칸의 값을 10 증가시키고, -다시 첫번째 칸으로 넘어가서 값을 1 감소시킵니다. 이 루프는 여섯번 돕니다. -(첫번째 칸의 값을 6번 감소시켜서 0이 될 때 까지는 ] 명령을 만날 때마다 -루프의 시작 지점으로 돌아갑니다) - -이 시점에서, 두번째 칸의 값은 60이고, 포인터는 값이 0인 첫번째 칸에 위치합니다. -여기서 두번째 칸으로 넘어간 다음 값을 5 증가시키면 두번째 칸의 값이 65가 되고, -65는 문자 'A'에 대응하는 아스키 코드이기 때문에, 두번째 칸의 값을 출력하면 -터미널에 'A'가 출력됩니다. - -, [ > + < - ] > . - -이 프로그램은 사용자로부터 문자 하나를 입력받아 첫번째 칸에 집어넣습니다. -그리고 루프에 들어가서, 두번째 칸으로 넘어가 값을 한 번 증가시킨 다음, -다시 첫번째 칸으로 넘어가서 값을 한 번 감소시킵니다. -이는 첫번째 칸의 값이 0이 될 때까지 지속되며, -두번째 칸은 첫번째 칸이 갖고있던 값을 가지게 됩니다. -루프가 종료되면 포인터는 첫번째 칸을 가르키기 때문에 두번째 칸으로 넘어가고, -해당 아스키 코드에 대응하는 문자를 출력합니다. - -또한 공백문자는 순전히 가독성을 위해서 작성되었다는 것을 기억하세요. -다음과 같이 작성해도 똑같이 돌아갑니다: - -,[>+<-]>. - -한 번 돌려보고 아래의 프로그램이 실제로 무슨 일을 하는지 맞춰보세요: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -이 프로그램은 두 개의 숫자를 입력받은 뒤, 그 둘을 곱합니다. - -위 코드는 일단 두 번의 입력을 받고, 첫번째 칸의 값만큼 바깥 루프를 돕니다. -그리고 루프 안에서 다시 두번째 칸의 값만큼 안쪽의 루프를 돕니다. -그리고 그 루프에서는 세번째 칸의 값을 증가시키는데, 문제가 하나 있습니다: -내부 루프가 한 번 끝나게 되면 두번째 칸의 값은 0이 됩니다. -그럼 다시 바깥 루프를 돌 때에 안쪽의 루프를 돌지 않게 되는데, 이를 해결하려면 -네번째 칸의 값도 같이 증가시킨 다음, 그 값을 두번째 칸으로 옮기면 됩니다. -그러면 세번째 칸에 곱셈의 결과가 남습니다. -``` - -여기까지 브레인퍽이었습니다. 참 쉽죠? -재미삼아 브레인퍽 프로그램이나 다른 언어로 브레인퍽 인터프리터를 작성해보세요. -인터프리터 구현은 간단한 편인데, -사서 고생하는 것을 즐기는 편이라면 한 번 작성해보세요… 브레인퍽으로. diff --git a/nl-nl/bf.html.markdown b/nl-nl/bf.html.markdown new file mode 100644 index 00000000..016e2ba2 --- /dev/null +++ b/nl-nl/bf.html.markdown @@ -0,0 +1,86 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jelle Besseling", "https://github.com/Jell-E"] +lang: nl-nl +--- + +Brainfuck (schrijf je niet met een hoofdletter behalve aan het begin van een +zin) is een extreem +minimalistische Turing-complete programmeertaal met maar acht commando's. + +``` +Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd. + +Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel +gevuld is met nullen en een pointer die wijst naar de huidige cel. + +Dit zijn de acht commando's: ++ : Verhoog de huidige cell met 1. +- : Verminder de huidige cell met 1. +> : Beweeg de pointer naar de volgende cell (één naar rechts). +< : Beweeg de pointer naar de vorige cell (één naar links). +. : Print de huidige cell als een ASCII karakter(d.w.z. 65 = 'A'). +, : Lees een karakter in de huidige cell. +[ : Als de huidige cell nul is ga dan naar de bijbehorende ] . + Als het geen nul is, ga dan gewoon verder. +] : Als de huidige cell nul is ga dan gewoon verder. + Als het geen nul is, ga dan terug naar de bijbehorende [ . + +[ en ] maken een while loop. Ze moeten uiteraard wel gebalanceerd zijn + +Laten we een kijkje nemen naar een paar brainfuck programma's. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Dit programma print het karakter 'A'. Eerst verhoogt het cell #1 tot 6. +Cell #1 wordt gebruikt om te loopen. Dan begint het de loop ([) en gaat +naar cell #2. Het verhoogt cell #2 tien keer, gaat terug naar cell #1, en +verlaagt cell #1. Deze loop gebeurt zes keer (na zes keer staat cell #1 +weer op nul, waarna het doorgaat naar het einde van de loop (]) en +verder gaat). + +De pointer staat nu weer op cell #1, deze heeft een waarde van 0, en cell #2 +heeft een waarde van 60. > beweegt de pointer naar cell #2, daarna verhoogt +het de cell vijf keer, waardoor het een waarde van 65 bevat, en print dan +de waarde van cell #2. 65 is 'A' in ASCII, dus 'A' wordt geprint in de terminal. + + +, [ > + < - ] > . + +Dit programma leest een karakter van de gebruiker in put en kopieert dat +karakter in cel #1. Dan start de loop. Ga naar cel #2, verhoog de waarde in +cel #2, ga terug naar cel #1, en verklein de waarde in cel #1. Dit gaat door +totdat cel #1 nul is en cel #2 de oude waarde heeft van cell #1. Omdat we +op cel #1 staan verplaatst > de pointer één naar rechts en . print het +karakter in cel #2. + +Houd wel in gedachten dat de spaties alleen zijn voor leesbaarheid, je kan het +bovenstaande programma net zo goed schrijven als: + +,[>+<-]>. + +Probeer maar eens te bedenken wat het volgende programma doet: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Dit programma neemt twee getallen als input, en vermenigvuldigt ze. + +In het begin leest het twee karakters in cel #1 en #2. Dan start het de +buitenste loop, met als teller cel #1. Het beweegt naar cel #2, dan start het +de binnenste loop met als teller cel #2, daar verhoogd het cel #3. Maar +dan is er een probleem als cel #2 nul wordt aan het einde van de binnenste loop. +Om dit op te lossen wordt ook cel #4 verhoogd naar het oorspronkelijke getal +uit cel #2 en daarna wordt cel #4 weer gekopieerd naar cell #2. +Het resultaat komt in cel #3 te staan. +``` + +En dat is dan brainfuck. Niet heel moeilijk, toch? Je kan zelf voor de lol +brainfuck programma's gaan schrijven, of je kan een interpreter schrijven +voor brainfuck in een andere taal. Het is namelijk redelijk makkelijk om te +implementeren aangezien brainfuck maar acht commando's heeft. En als je een +masochist bent kan je ook nog proberen om brainfuck te implementeren… in +brainfuck. diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/brainfuck-nl.html.markdown deleted file mode 100644 index 6062b24c..00000000 --- a/nl-nl/brainfuck-nl.html.markdown +++ /dev/null @@ -1,86 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Jelle Besseling", "https://github.com/Jell-E"] -lang: nl-nl ---- - -Brainfuck (schrijf je niet met een hoofdletter behalve aan het begin van een -zin) is een extreem -minimalistische Turing-complete programmeertaal met maar acht commando's. - -``` -Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd. - -Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel -gevuld is met nullen en een pointer die wijst naar de huidige cel. - -Dit zijn de acht commando's: -+ : Verhoog de huidige cell met 1. -- : Verminder de huidige cell met 1. -> : Beweeg de pointer naar de volgende cell (één naar rechts). -< : Beweeg de pointer naar de vorige cell (één naar links). -. : Print de huidige cell als een ASCII karakter(d.w.z. 65 = 'A'). -, : Lees een karakter in de huidige cell. -[ : Als de huidige cell nul is ga dan naar de bijbehorende ] . - Als het geen nul is, ga dan gewoon verder. -] : Als de huidige cell nul is ga dan gewoon verder. - Als het geen nul is, ga dan terug naar de bijbehorende [ . - -[ en ] maken een while loop. Ze moeten uiteraard wel gebalanceerd zijn - -Laten we een kijkje nemen naar een paar brainfuck programma's. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Dit programma print het karakter 'A'. Eerst verhoogt het cell #1 tot 6. -Cell #1 wordt gebruikt om te loopen. Dan begint het de loop ([) en gaat -naar cell #2. Het verhoogt cell #2 tien keer, gaat terug naar cell #1, en -verlaagt cell #1. Deze loop gebeurt zes keer (na zes keer staat cell #1 -weer op nul, waarna het doorgaat naar het einde van de loop (]) en -verder gaat). - -De pointer staat nu weer op cell #1, deze heeft een waarde van 0, en cell #2 -heeft een waarde van 60. > beweegt de pointer naar cell #2, daarna verhoogt -het de cell vijf keer, waardoor het een waarde van 65 bevat, en print dan -de waarde van cell #2. 65 is 'A' in ASCII, dus 'A' wordt geprint in de terminal. - - -, [ > + < - ] > . - -Dit programma leest een karakter van de gebruiker in put en kopieert dat -karakter in cel #1. Dan start de loop. Ga naar cel #2, verhoog de waarde in -cel #2, ga terug naar cel #1, en verklein de waarde in cel #1. Dit gaat door -totdat cel #1 nul is en cel #2 de oude waarde heeft van cell #1. Omdat we -op cel #1 staan verplaatst > de pointer één naar rechts en . print het -karakter in cel #2. - -Houd wel in gedachten dat de spaties alleen zijn voor leesbaarheid, je kan het -bovenstaande programma net zo goed schrijven als: - -,[>+<-]>. - -Probeer maar eens te bedenken wat het volgende programma doet: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Dit programma neemt twee getallen als input, en vermenigvuldigt ze. - -In het begin leest het twee karakters in cel #1 en #2. Dan start het de -buitenste loop, met als teller cel #1. Het beweegt naar cel #2, dan start het -de binnenste loop met als teller cel #2, daar verhoogd het cel #3. Maar -dan is er een probleem als cel #2 nul wordt aan het einde van de binnenste loop. -Om dit op te lossen wordt ook cel #4 verhoogd naar het oorspronkelijke getal -uit cel #2 en daarna wordt cel #4 weer gekopieerd naar cell #2. -Het resultaat komt in cel #3 te staan. -``` - -En dat is dan brainfuck. Niet heel moeilijk, toch? Je kan zelf voor de lol -brainfuck programma's gaan schrijven, of je kan een interpreter schrijven -voor brainfuck in een andere taal. Het is namelijk redelijk makkelijk om te -implementeren aangezien brainfuck maar acht commando's heeft. En als je een -masochist bent kan je ook nog proberen om brainfuck te implementeren… in -brainfuck. diff --git a/pl-pl/bf-pl.html.markdown b/pl-pl/bf-pl.html.markdown new file mode 100644 index 00000000..801f1a9a --- /dev/null +++ b/pl-pl/bf-pl.html.markdown @@ -0,0 +1,93 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jakub Młokosiewicz", "https://github.com/hckr"] +lang: pl-pl +--- + +Brainfuck (pisane małymi literami, za wyjątkiem początku zdania) jest bardzo +minimalistycznym, kompletnym w sensie Turinga, językiem programowania. +Zawiera zaledwie 8 poleceń. + +Możesz przetesotwać brainfucka w swojej przeglądarce, korzystając z narzędzia +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Wszystkie znaki oprócz "><+-.,[]" (wyłączając znaki zapytania) są ignorowane. + +Pamięć w brainfucku jest reprezentowana przez tablicę 30.000 komórek +zainicjalizowanych zerami, ze wskaźnikiem pokazującym na aktualną komórkę. + +Oto osiem poleceń brainfucka: ++ : inkrementuje (zwiększa o jeden) wartość aktualnie wskazywanej komórki +- : dekrementuje (zmniejsza o jeden) wartość aktualnie wskazywanej komórki +> : przesuwa wskaźnik na następną komórkę (w prawo) +< : przesuwa wskaźnik na poprzednią komórkę (w lewo) +. : wyświetla wartość bieżącej komórki (w formie znaku ASCII, np. 65 = 'A') +, : wczytuje (jeden) znak z wejścia do bieżącej komórki + (konkretnie jego numer z tabeli ASCII) +[ : jeśli wartość w bieżącej komórce jest rózna zero, przechodzi do + odpowiadającego ]; w przeciwnym wypdaku przechodzi do następnej instrukcji +] : Jeśli wartość w bieżącej komórce jest rózna od zera, przechodzi do + następnej instrukcji; w przeciwnym wypdaku przechodzi do odpowiadającego [ + +[ i ] oznaczają pętlę while. Oczywiście każda pętla rozpoczęta [ +musi być zakończona ]. + +Zobaczmy kilka prostych programów w brainfucku. + + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ten program wypisuje literę 'A'. Najpierw zwiększa wartość komórki #1 do 6. +Komórka #1 będzie wykorzystana w pętli. Następnie program wchodzi w pętlę ([) +i przechodzi do komórki #2. Pętla wykonuje się sześć razy (komórka #1 jest +dekrementowana sześć razy, nim osiągnie wartość zero, kiedy to program +przechodzi do odpowiadającego ] i wykonuje kolejne instrukcje). + +W tym momencie wskaźnik pokazuje na komórkę #1, mającą wartość 0, podczas gdy +komórka #2 ma wartość 60. Przesuwamy wskaźnik na komórkę #2, inkrementujemy ją +pięć razy, uzyskując wartość 65. Następnie wyświetlamy wartość komórki #2. +65 to 'A' w tabeli ASCII, więc właśnie ten znak jest wypisany na konsolę. + + +, [ > + < - ] > . + +Ten program wczytuje znak z wejścia i umieszcza jego kod ASCII w komórce #1. +Następnie zaczyna się pętla, w której znajdują się następujące instrukcje: +przesunięcie wskaźnika na komórkę #2, inkrementacja wartości komóri #2, +powrót do komórki #1 i dekrementacja wartości komórki #1. Instrukcje pętli +wykonują się aż wartość komórki #1 osiągnie zero, a komórka #2 osiągnie +poprednią wartość komórki #1. Ponieważ na końcu pętli wskaźnik pokazuje na +komórkę #1, po pętli następuje instrukcja przejścia do komórki #2 i wysłanie +jej wartości (w formie znaku ASCII) na wyjście. + +Zauważ, że odstępy służą wyłącznie poprawie czytelności. +Równie dobrze można powyższy program zapisać tak: + +,[>+<-]>. + + +Spróbuj odgadnąć, co robi poniższy program: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ten program pobiera z wejścia dwie liczby i je mnoży. + +Po wczytaniu dwóch wejść (do komórek #1 i #2) następuje pętla zewnętrzna, +warunkowana wartością komórki #1. Następnie program przechodzi do komórki #2 +i rozpoczyna pętlę wewnętrzną z warunkiem zakończenia w komórce #2, +inkrementującą komórkę #3. Tu jednak pojawia się problem: w chwili zakończenia +wewnętrznej pętli komórka #2 ma wartość zero. W takim razie wewętrzna pętla +nie wywoła się następny raz. Aby rozwiązać ten problem, inkrementujemy także +wartość komórki #4, a następnie kopiujemy jej wartość do komórki #2. +Ostatecznie wynik działania znajduje się w komórce #3. +``` + +I to właśnie jest brainfuck. Nie taki trudny, co? W ramach rozrywki możesz +napisać własne programy w brainfucku. Możesz też napisać interpreter brainfucka +w innym języku. Implementacja interpretera to dość proste zadanie. Jeśli +jesteś masochistą, spróbuj napisać interpreter brainfucka w... brainfucku. diff --git a/pl-pl/brainfuck-pl.html.markdown b/pl-pl/brainfuck-pl.html.markdown deleted file mode 100644 index 69d814c4..00000000 --- a/pl-pl/brainfuck-pl.html.markdown +++ /dev/null @@ -1,93 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Jakub Młokosiewicz", "https://github.com/hckr"] -lang: pl-pl ---- - -Brainfuck (pisane małymi literami, za wyjątkiem początku zdania) jest bardzo -minimalistycznym, kompletnym w sensie Turinga, językiem programowania. -Zawiera zaledwie 8 poleceń. - -Możesz przetesotwać brainfucka w swojej przeglądarce, korzystając z narzędzia -[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Wszystkie znaki oprócz "><+-.,[]" (wyłączając znaki zapytania) są ignorowane. - -Pamięć w brainfucku jest reprezentowana przez tablicę 30.000 komórek -zainicjalizowanych zerami, ze wskaźnikiem pokazującym na aktualną komórkę. - -Oto osiem poleceń brainfucka: -+ : inkrementuje (zwiększa o jeden) wartość aktualnie wskazywanej komórki -- : dekrementuje (zmniejsza o jeden) wartość aktualnie wskazywanej komórki -> : przesuwa wskaźnik na następną komórkę (w prawo) -< : przesuwa wskaźnik na poprzednią komórkę (w lewo) -. : wyświetla wartość bieżącej komórki (w formie znaku ASCII, np. 65 = 'A') -, : wczytuje (jeden) znak z wejścia do bieżącej komórki - (konkretnie jego numer z tabeli ASCII) -[ : jeśli wartość w bieżącej komórce jest rózna zero, przechodzi do - odpowiadającego ]; w przeciwnym wypdaku przechodzi do następnej instrukcji -] : Jeśli wartość w bieżącej komórce jest rózna od zera, przechodzi do - następnej instrukcji; w przeciwnym wypdaku przechodzi do odpowiadającego [ - -[ i ] oznaczają pętlę while. Oczywiście każda pętla rozpoczęta [ -musi być zakończona ]. - -Zobaczmy kilka prostych programów w brainfucku. - - -++++++ [ > ++++++++++ < - ] > +++++ . - -Ten program wypisuje literę 'A'. Najpierw zwiększa wartość komórki #1 do 6. -Komórka #1 będzie wykorzystana w pętli. Następnie program wchodzi w pętlę ([) -i przechodzi do komórki #2. Pętla wykonuje się sześć razy (komórka #1 jest -dekrementowana sześć razy, nim osiągnie wartość zero, kiedy to program -przechodzi do odpowiadającego ] i wykonuje kolejne instrukcje). - -W tym momencie wskaźnik pokazuje na komórkę #1, mającą wartość 0, podczas gdy -komórka #2 ma wartość 60. Przesuwamy wskaźnik na komórkę #2, inkrementujemy ją -pięć razy, uzyskując wartość 65. Następnie wyświetlamy wartość komórki #2. -65 to 'A' w tabeli ASCII, więc właśnie ten znak jest wypisany na konsolę. - - -, [ > + < - ] > . - -Ten program wczytuje znak z wejścia i umieszcza jego kod ASCII w komórce #1. -Następnie zaczyna się pętla, w której znajdują się następujące instrukcje: -przesunięcie wskaźnika na komórkę #2, inkrementacja wartości komóri #2, -powrót do komórki #1 i dekrementacja wartości komórki #1. Instrukcje pętli -wykonują się aż wartość komórki #1 osiągnie zero, a komórka #2 osiągnie -poprednią wartość komórki #1. Ponieważ na końcu pętli wskaźnik pokazuje na -komórkę #1, po pętli następuje instrukcja przejścia do komórki #2 i wysłanie -jej wartości (w formie znaku ASCII) na wyjście. - -Zauważ, że odstępy służą wyłącznie poprawie czytelności. -Równie dobrze można powyższy program zapisać tak: - -,[>+<-]>. - - -Spróbuj odgadnąć, co robi poniższy program: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Ten program pobiera z wejścia dwie liczby i je mnoży. - -Po wczytaniu dwóch wejść (do komórek #1 i #2) następuje pętla zewnętrzna, -warunkowana wartością komórki #1. Następnie program przechodzi do komórki #2 -i rozpoczyna pętlę wewnętrzną z warunkiem zakończenia w komórce #2, -inkrementującą komórkę #3. Tu jednak pojawia się problem: w chwili zakończenia -wewnętrznej pętli komórka #2 ma wartość zero. W takim razie wewętrzna pętla -nie wywoła się następny raz. Aby rozwiązać ten problem, inkrementujemy także -wartość komórki #4, a następnie kopiujemy jej wartość do komórki #2. -Ostatecznie wynik działania znajduje się w komórce #3. -``` - -I to właśnie jest brainfuck. Nie taki trudny, co? W ramach rozrywki możesz -napisać własne programy w brainfucku. Możesz też napisać interpreter brainfucka -w innym języku. Implementacja interpretera to dość proste zadanie. Jeśli -jesteś masochistą, spróbuj napisać interpreter brainfucka w... brainfucku. diff --git a/pt-br/bf.html.markdown b/pt-br/bf.html.markdown new file mode 100644 index 00000000..d6d7c6e9 --- /dev/null +++ b/pt-br/bf.html.markdown @@ -0,0 +1,85 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br +--- + +Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. + +Brainfuck é representado por um vetor com 30 000 células inicializadas em zero +e um ponteiro de dados que aponta para a célula atual. + +Existem 8 comandos: ++ : Incrementa o valor da célula atual em 1. +- : Decrementa o valor da célula atual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula atual. +[ : Se o valor da célula atual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula atual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vamos ver alguns exemplos básicos em brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor +65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tente descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e os multiplica. + +Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Porém existe um problema, no final do +ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +E isto é brainfuck. Simples, não? Por divertimento você pode escrever os +seus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck em outra linguagem. O interpretador é relativamente fácil de se +implementar, mas caso você seja masoquista, tente escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown deleted file mode 100644 index 9e4b458d..00000000 --- a/pt-br/brainfuck-pt.html.markdown +++ /dev/null @@ -1,85 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Suzane Sant Ana", "http://github.com/suuuzi"] - - ["Rodrigo Muniz", "http://github.com/muniz95"] -lang: pt-br ---- - -Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de -programação Turing-completa extremamente simples com apenas 8 comandos. - -``` -Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. - -Brainfuck é representado por um vetor com 30 000 células inicializadas em zero -e um ponteiro de dados que aponta para a célula atual. - -Existem 8 comandos: -+ : Incrementa o valor da célula atual em 1. -- : Decrementa o valor da célula atual em 1. -> : Move o ponteiro de dados para a célula seguinte (célula à direita). -< : Move o ponteiro de dados para a célula anterior (célula à esquerda). -. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). -, : Lê um único caractere para a célula atual. -[ : Se o valor da célula atual for zero, salta para o ] correspondente. - Caso contrário, passa para a instrução seguinte. -] : Se o valor da célula atual for zero, passa para a instrução seguinte. - Caso contrário, volta para a instrução relativa ao [ correspondente. - -[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. - -Vamos ver alguns exemplos básicos em brainfuck: - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. -A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se -o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 -vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se -a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para -a célula #1 chegar a 0, momento em que se salta para o ] correspondente, -continuando com a instrução seguinte). - -Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 -tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 -vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor -65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. - -, [ > + < - ] > . - -Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é -iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na -célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente -decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser -igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de -dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a -célula #2 e imprimimos o valor em ASCII. - -Os espaços servem apenas para tornar o programa mais legível. Podemos escrever -o mesmo programa da seguinte maneira: - -,[>+<-]>. - -Tente descobrir o que este programa faz: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa lê dois números e os multiplica. - -Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um -ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados -para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula -#2, incrementando o valor da célula #3. Porém existe um problema, no final do -ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da -célula #4 é também incrementado e copiado para a célula #2. -``` - -E isto é brainfuck. Simples, não? Por divertimento você pode escrever os -seus próprios programas em brainfuck, ou então escrever um interpretador de -brainfuck em outra linguagem. O interpretador é relativamente fácil de se -implementar, mas caso você seja masoquista, tente escrever um interpretador de -brainfuck… em brainfuck. diff --git a/pt-pt/bf.html.markdown b/pt-pt/bf.html.markdown new file mode 100644 index 00000000..da4c787f --- /dev/null +++ b/pt-pt/bf.html.markdown @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Joao Marques", "http://github.com/mrshankly"] +lang: pt-pt +--- + +Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere excepto "><+-.,[]" (não contar com as aspas) é ignorado. + +Brainfuck é representado por um vector com 30 000 células inicializadas a zero +e um ponteiro de dados que aponta para a célula actual. + +Existem 8 comandos: ++ : Incrementa o valor da célula actual em 1. +- : Decrementa o valor da célula actual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula actual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula actual. +[ : Se o valor da célula actual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula actual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vejamos alguns programas básicos de brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. Incrementa-se o valor da célula #2 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura encontramo-nos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, é então impresso o valor da célula #2. Ao valor +65 corresponde o caractere 'A' em ASCII, 'A' é então impresso para o terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1, finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está a apontar para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tenta descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e multiplica-os. + +Basicamente o programa pede dois caracteres ao utilizador. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Contudo, existe um problema, no final do +ciclo interior a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +Fica então explicado brainfuck. Simples, não? Por divertimento podes escrever os +teus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck noutra linguagem. O interpretador é relativamente fácil de se +implementar, mas se fores masoquista, tenta escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-pt/brainfuck-pt.html.markdown b/pt-pt/brainfuck-pt.html.markdown deleted file mode 100644 index da4c787f..00000000 --- a/pt-pt/brainfuck-pt.html.markdown +++ /dev/null @@ -1,84 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Joao Marques", "http://github.com/mrshankly"] -lang: pt-pt ---- - -Brainfuck (não capitalizado excepto no início de uma frase) é uma linguagem de -programação Turing-completa extremamente simples com apenas 8 comandos. - -``` -Qualquer caractere excepto "><+-.,[]" (não contar com as aspas) é ignorado. - -Brainfuck é representado por um vector com 30 000 células inicializadas a zero -e um ponteiro de dados que aponta para a célula actual. - -Existem 8 comandos: -+ : Incrementa o valor da célula actual em 1. -- : Decrementa o valor da célula actual em 1. -> : Move o ponteiro de dados para a célula seguinte (célula à direita). -< : Move o ponteiro de dados para a célula anterior (célula à esquerda). -. : Imprime o valor ASCII da célula actual. (ex. 65 = 'A'). -, : Lê um único caractere para a célula actual. -[ : Se o valor da célula actual for zero, salta para o ] correspondente. - Caso contrário, passa para a instrução seguinte. -] : Se o valor da célula actual for zero, passa para a instrução seguinte. - Caso contrário, volta para a instrução relativa ao [ correspondente. - -[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. - -Vejamos alguns programas básicos de brainfuck. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. -A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se -o ponteiro de dados para a célula #2. Incrementa-se o valor da célula #2 10 -vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se -a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para -a célula #1 chegar a 0, momento em que se salta para o ] correspondente, -continuando com a instrução seguinte). - -Nesta altura encontramo-nos na célula #1, cujo valor é 0, enquanto a célula #2 -tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 -vezes para um valor final de 65, é então impresso o valor da célula #2. Ao valor -65 corresponde o caractere 'A' em ASCII, 'A' é então impresso para o terminal. - -, [ > + < - ] > . - -Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é -iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na -célula #2, movemos o ponteiro de dados de volta para a célula #1, finalmente -decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser -igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de -dados está a apontar para a célula #1 no fim do ciclo, movemos o ponteiro para a -célula #2 e imprimimos o valor em ASCII. - -Os espaços servem apenas para tornar o programa mais legível. Podemos escrever -o mesmo programa da seguinte maneira: - -,[>+<-]>. - -Tenta descobrir o que este programa faz: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Este programa lê dois números e multiplica-os. - -Basicamente o programa pede dois caracteres ao utilizador. Depois é iniciado um -ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados -para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula -#2, incrementando o valor da célula #3. Contudo, existe um problema, no final do -ciclo interior a célula #2 tem o valor 0. Para resolver este problema o valor da -célula #4 é também incrementado e copiado para a célula #2. -``` - -Fica então explicado brainfuck. Simples, não? Por divertimento podes escrever os -teus próprios programas em brainfuck, ou então escrever um interpretador de -brainfuck noutra linguagem. O interpretador é relativamente fácil de se -implementar, mas se fores masoquista, tenta escrever um interpretador de -brainfuck… em brainfuck. diff --git a/ru-ru/bf.html.markdown b/ru-ru/bf.html.markdown new file mode 100644 index 00000000..20f0fa56 --- /dev/null +++ b/ru-ru/bf.html.markdown @@ -0,0 +1,85 @@ +--- +language: bf +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень +маленький Тьюринг-полный язык программирования лишь с 8 командами. + +Вы можете испытать brainfuck в вашем браузере с помощью [brainfuck-визуализатора](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. + +Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, +и указателем с позицией в текущей ячейке. + +Всего восемь команд: ++ : Увеличивает значение на единицу в текущей ячейке. +- : Уменьшает значение на единицу в текущей ячейке. +> : Смещает указатель данных на следующую ячейку (ячейку справа). +< : Смещает указатель данных на предыдущую ячейку (ячейку слева). +. : Печатает ASCII символ из текущей ячейки (напр. 65 = 'A'). +, : Записывает один входной символ в текущую ячейку. +[ : Если значение в текущей ячейке равно нулю, то пропустить все команды + до соответствующей ] . В противном случае, перейти к следующей инструкции. +] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. + В противном случае, вернуться назад к соответствующей [ . + +[ и ] образуют цикл while. Естественно, они должны быть сбалансированы. + +Давайте рассмотрим некоторые базовые brainfuck-программы. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Эта программа выводит букву 'A'. Сначала программа увеличивает значение +ячейки №1 до 6. Ячейка №1 будет использоваться циклом. Затем программа входит +в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим +назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 +уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] +и идет дальше). + +В этот момент мы находимся в ячейке №1, которая имеет значение 0, значение +ячейки №2 пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, +и затем выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, +так что 'A' выводится на терминал. + + +, [ > + < - ] > . + +Данная программа считывает символ из пользовательского ввода и копирует символ +в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение +ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается +до тех пор, пока ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение +ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2 и +затем выводим символ ASCII. + +Также имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете +легко написать и так: + +,[>+<-]>. + +Попытайтесь разгадать, что следующая программа делает: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Программа принимает два числа на вход и умножает их. + +Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, +сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается +внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется +проблема: В конце внутреннего цикла ячейка №2 равна нулю. В этом случае, +внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, +мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. +Итак, ячейка №3 - результат. +``` + +Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать +свою собственную brainfuck-программу или интерпретатор на другом языке. +Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте +написать brainfuck-интерпретатор... на языке brainfuck. diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown deleted file mode 100644 index fcee185f..00000000 --- a/ru-ru/brainfuck-ru.html.markdown +++ /dev/null @@ -1,85 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Dmitry Bessonov", "https://github.com/TheDmitry"] -lang: ru-ru ---- - -Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень -маленький Тьюринг-полный язык программирования лишь с 8 командами. - -Вы можете испытать brainfuck в вашем браузере с помощью [brainfuck-визуализатора](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. - -Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, -и указателем с позицией в текущей ячейке. - -Всего восемь команд: -+ : Увеличивает значение на единицу в текущей ячейке. -- : Уменьшает значение на единицу в текущей ячейке. -> : Смещает указатель данных на следующую ячейку (ячейку справа). -< : Смещает указатель данных на предыдущую ячейку (ячейку слева). -. : Печатает ASCII символ из текущей ячейки (напр. 65 = 'A'). -, : Записывает один входной символ в текущую ячейку. -[ : Если значение в текущей ячейке равно нулю, то пропустить все команды - до соответствующей ] . В противном случае, перейти к следующей инструкции. -] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. - В противном случае, вернуться назад к соответствующей [ . - -[ и ] образуют цикл while. Естественно, они должны быть сбалансированы. - -Давайте рассмотрим некоторые базовые brainfuck-программы. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Эта программа выводит букву 'A'. Сначала программа увеличивает значение -ячейки №1 до 6. Ячейка №1 будет использоваться циклом. Затем программа входит -в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим -назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 -уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] -и идет дальше). - -В этот момент мы находимся в ячейке №1, которая имеет значение 0, значение -ячейки №2 пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, -и затем выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, -так что 'A' выводится на терминал. - - -, [ > + < - ] > . - -Данная программа считывает символ из пользовательского ввода и копирует символ -в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение -ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается -до тех пор, пока ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение -ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2 и -затем выводим символ ASCII. - -Также имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете -легко написать и так: - -,[>+<-]>. - -Попытайтесь разгадать, что следующая программа делает: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Программа принимает два числа на вход и умножает их. - -Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, -сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается -внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется -проблема: В конце внутреннего цикла ячейка №2 равна нулю. В этом случае, -внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, -мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. -Итак, ячейка №3 - результат. -``` - -Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать -свою собственную brainfuck-программу или интерпретатор на другом языке. -Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте -написать brainfuck-интерпретатор... на языке brainfuck. diff --git a/tr-tr/bf-tr.html.markdown b/tr-tr/bf-tr.html.markdown new file mode 100644 index 00000000..e7015cd0 --- /dev/null +++ b/tr-tr/bf-tr.html.markdown @@ -0,0 +1,87 @@ +--- +language: bf +filename: brainfuck-tr +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io"] +translators: + - ["Haydar KULEKCI", "http://scanf.info/"] +lang: tr-tr +--- + +Brainfuck (normalde brainfuck olarak bütün harfleri küçük olarak yazılır.) +son derece minimal bir programlama dilidir. (Sadece 8 komut) ve tamamen +Turing'dir. + +``` +"><+-.,[]" (tırnak işaretleri hariç) karakterleri dışındaki her karakter +gözardı edilir. + +Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir +dizidir. İşaretçi ilk hücreyi işaret eder. + +Sekiz komut vardır: ++ : Geçerli hücrenin değerini bir artırır. +- : Geçerli hücrenin değerini bir azaltır. +> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). +< : Veri işaretçisini bir önceki hücreye hareket ettirir(soldaki hücreye). +. : Geçerli hücrenin ASCII değerini yazdırır (örn: 65 = 'A'). +, : Bir girdilik karakteri aktif hücre için okur. +[ : Eğer geçerli hücredeki değer sıfır ise, ]ifadesine atlar. + Diğer durumlarda bir sonraki yönergeye geçer. +] : Eğer geçerli hücredeki değer sıfır ise, bir sonraki yönergeye geçer. + Diğer durumlarda, [ ifadesine karşılık gelen yönergelere döner. + +[ ve ] bir while döngüsü oluşturur. Açıkça, dengeli olmalıdırlar. + +Basit bir brainfuck programına göz atalım. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Bu program 'A' karaterini ekrana basar. İlk olarak, #1'inci hücre 6'ya artırılır. +#1'inci hücre döngü için kullanılacaktır. Sonra, ([) döngüsüne girilir ve +#2'inci hücreye hareket edilir. #2'inci hücre 10 kez artırılır, #1'inci hücreye +geri dönülür. #1 hücresini bir azaltır. Bu döngü 6 kez gerçekleşir. (Bu 6 kez +azaltmak demektir, #1 hücresi 0 değerini alır ve bu noktada ] ifadesini atlar). + +Bu noktada, biz #1 hücresindeyiz, değeri şu anda 0 ve #2 hücresinin değeri +60'tır. Biz #2 hücresine hareket diyoruz ve bu hücreyi 5 defa artırıyoruz. +#2'nin şu anki değeri 65 olur. Sonra #2 hücresinin ASCII karşılığını +yazdırıyoruz. 65 değerinin ASCII karşılığı 'A'dır. Ekrana 'A' yazılacaktır. + + +, [ > + < - ] > . + +Bu program kullanıcıdan bir girdi okur, ve karakteri bir diğer hücreye yazdırır, +ve daha sonra aynı karakteri ekrana yazdırır. + +, ifadesi kullanıcıdan karakteri #1 hücresine okur. Sonra bir döngü +başlar. #2 hücresine hareket edilir, #2 hücresinin değeri bir artırılır, #1 +hücresine geri dönülür, ve #1 hücresinin değer bir azaltılır. Bu #1 hücresinin +değeri 0 olana kadar devam eder ve #2 hücresi #1'in eski değerini tutar. Çünkü +biz #1 hücresindeki verileri döngü süresince #2 hücresine taşıyoruz, ve sonunda +#2 hücresinin ASCII değerini yazdırıyoruz. + +Boşluk karakteri sadece okunabilirliği artırmak içindir. Aşağıdaki gibi de +yazabilirsiniz. + +,[>+<-]>. + + +Bu uygulamanın ne yaptığına bakalım: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Bu program 2 sayı alır, ve birbiri ile çarpar. + +Özetle, ilk olarak iki girdi alır. Sonra, #1 hücresinde şarta bağlı harici bir +döngü başlar. Sonra #2 ye hareket edilir, ve içerde #2 hücresine bağlı bir döngü +daha başlar ve #3 hücresinin değerini artırır. Ama, Bir problem vardır: iç +döngünün sonunda #2'inci hücrenin değeri 0 olacaktır. Bunu çözmek için #4 +hücresinin de değerini yükseltiyoruz, ve sonra #4 hücresinin değerini #2'ye +kopyalıyoruz. +``` + +İşte brainfuck. Zor değil değil mi? Eğlenmek için kendi programınızı +yazabilirsiniz, veya farklı bir dilde brainfuck yorumlayıcısı yazabilirsiniz. +Yorumlayıcı oldukça basittir, ama mazoşist iseniz, brainfuck içerisinde bir +brainfuck yorumlayıcısı yazmayı deneyebilirsiniz. diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown deleted file mode 100644 index bd842b17..00000000 --- a/tr-tr/brainfuck-tr.html.markdown +++ /dev/null @@ -1,87 +0,0 @@ ---- -language: brainfuck -filename: brainfuck-tr -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io"] -translators: - - ["Haydar KULEKCI", "http://scanf.info/"] -lang: tr-tr ---- - -Brainfuck (normalde brainfuck olarak bütün harfleri küçük olarak yazılır.) -son derece minimal bir programlama dilidir. (Sadece 8 komut) ve tamamen -Turing'dir. - -``` -"><+-.,[]" (tırnak işaretleri hariç) karakterleri dışındaki her karakter -gözardı edilir. - -Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir -dizidir. İşaretçi ilk hücreyi işaret eder. - -Sekiz komut vardır: -+ : Geçerli hücrenin değerini bir artırır. -- : Geçerli hücrenin değerini bir azaltır. -> : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). -< : Veri işaretçisini bir önceki hücreye hareket ettirir(soldaki hücreye). -. : Geçerli hücrenin ASCII değerini yazdırır (örn: 65 = 'A'). -, : Bir girdilik karakteri aktif hücre için okur. -[ : Eğer geçerli hücredeki değer sıfır ise, ]ifadesine atlar. - Diğer durumlarda bir sonraki yönergeye geçer. -] : Eğer geçerli hücredeki değer sıfır ise, bir sonraki yönergeye geçer. - Diğer durumlarda, [ ifadesine karşılık gelen yönergelere döner. - -[ ve ] bir while döngüsü oluşturur. Açıkça, dengeli olmalıdırlar. - -Basit bir brainfuck programına göz atalım. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Bu program 'A' karaterini ekrana basar. İlk olarak, #1'inci hücre 6'ya artırılır. -#1'inci hücre döngü için kullanılacaktır. Sonra, ([) döngüsüne girilir ve -#2'inci hücreye hareket edilir. #2'inci hücre 10 kez artırılır, #1'inci hücreye -geri dönülür. #1 hücresini bir azaltır. Bu döngü 6 kez gerçekleşir. (Bu 6 kez -azaltmak demektir, #1 hücresi 0 değerini alır ve bu noktada ] ifadesini atlar). - -Bu noktada, biz #1 hücresindeyiz, değeri şu anda 0 ve #2 hücresinin değeri -60'tır. Biz #2 hücresine hareket diyoruz ve bu hücreyi 5 defa artırıyoruz. -#2'nin şu anki değeri 65 olur. Sonra #2 hücresinin ASCII karşılığını -yazdırıyoruz. 65 değerinin ASCII karşılığı 'A'dır. Ekrana 'A' yazılacaktır. - - -, [ > + < - ] > . - -Bu program kullanıcıdan bir girdi okur, ve karakteri bir diğer hücreye yazdırır, -ve daha sonra aynı karakteri ekrana yazdırır. - -, ifadesi kullanıcıdan karakteri #1 hücresine okur. Sonra bir döngü -başlar. #2 hücresine hareket edilir, #2 hücresinin değeri bir artırılır, #1 -hücresine geri dönülür, ve #1 hücresinin değer bir azaltılır. Bu #1 hücresinin -değeri 0 olana kadar devam eder ve #2 hücresi #1'in eski değerini tutar. Çünkü -biz #1 hücresindeki verileri döngü süresince #2 hücresine taşıyoruz, ve sonunda -#2 hücresinin ASCII değerini yazdırıyoruz. - -Boşluk karakteri sadece okunabilirliği artırmak içindir. Aşağıdaki gibi de -yazabilirsiniz. - -,[>+<-]>. - - -Bu uygulamanın ne yaptığına bakalım: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Bu program 2 sayı alır, ve birbiri ile çarpar. - -Özetle, ilk olarak iki girdi alır. Sonra, #1 hücresinde şarta bağlı harici bir -döngü başlar. Sonra #2 ye hareket edilir, ve içerde #2 hücresine bağlı bir döngü -daha başlar ve #3 hücresinin değerini artırır. Ama, Bir problem vardır: iç -döngünün sonunda #2'inci hücrenin değeri 0 olacaktır. Bunu çözmek için #4 -hücresinin de değerini yükseltiyoruz, ve sonra #4 hücresinin değerini #2'ye -kopyalıyoruz. -``` - -İşte brainfuck. Zor değil değil mi? Eğlenmek için kendi programınızı -yazabilirsiniz, veya farklı bir dilde brainfuck yorumlayıcısı yazabilirsiniz. -Yorumlayıcı oldukça basittir, ama mazoşist iseniz, brainfuck içerisinde bir -brainfuck yorumlayıcısı yazmayı deneyebilirsiniz. diff --git a/zh-cn/bf-cn.html.markdown b/zh-cn/bf-cn.html.markdown new file mode 100644 index 00000000..6cea3012 --- /dev/null +++ b/zh-cn/bf-cn.html.markdown @@ -0,0 +1,70 @@ +--- +language: bf +lang: zh-cn +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["lyuehh", "https://github.com/lyuehh"] +--- + +Brainfuck 是一个极小的只有8个指令的图灵完全的编程语言。 + +``` +除"><+-.,[]"之外的的任何字符都会被忽略 (不包含双引号)。 + +Brainfuck 包含一个有30,000个单元为0的数组,和 +一个数据指针指向当前的单元。 + +8个指令如下: ++ : 指针指向的单元的值加1 +- : 指针指向的单元的值减1 +> : 将指针移动到下一个单元(右边的元素) +< : 将指针移动到上一个单元(左边的元素) +. : 打印当前单元的内容的ASCII值 (比如 65 = 'A'). +, : 读取一个字符到当前的单元 +[ : 如果当前单元的值是0,则向后调转到对应的]处 +] : 如果当前单元的值不是0,则向前跳转到对应的[处 + +[ 和 ] 组成了一个while循环。很明显,它们必须配对。 + +让我们看一些基本的brainfuck 程序。 + +++++++ [ > ++++++++++ < - ] > +++++ . + +这个程序打印字母'A'。首先,它把 #1 增加到6,使用它来作为循环条件, +然后,进入循环,将指针移动到 #2 ,将 #2 的值增加到10,然后 +移动回 #1,将单元 #1 的值减1,然后继续。循环共进行了6次。 + +这时,我们在 #1,它的值为0,#2 的值为60,我们移动到 +#2,将 #2 的内容加上5,然后将 #2 的内容打印出来,65在 +ASCII中表示'A', 所以'A'就会被打印出来。 + + +, [ > + < - ] > . + +这个程序从用户的输入中读取一个字符,然后把它复制到 #1。 +然后我们开始一个循环,移动到 #2,将 #2 的值加1,再移动回 #1,将 #1 +的值减1,直到 #1的值为0,这样 #2 里就保存了 #1 的旧值,循环结束时我们 +在 #1,这时我们移动到 #2,然后把字符以ASCII打印出来。 + +而且要记住的一点就是,空格在这里只是为了可读性,你可以将他们写成这样: + +,[>+<-]>. + +试着思考一下这段程序是干什么的: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +这段程序从输入接收2个参数,然后将他们相乘。 + +先读取2个输入,然后开始外层循环,以 #1 作为终止条件,然后将指针移动到 +#2,然后开始 #2 的内层循环,将 #3 加1。但是这里有一个小问题,在内层 +循环结束的时候,#2 的值是0了,那么下次执行外层循环的时候,就有问题了。 +为了解决这个问题,我们可以增加 #4 的值,然后把 #4 的值复制到 #2, +最后结果就保存在 #3 中了。 +``` +好了这就是brainfuck了。也没那么难,是吧?为了好玩,你可以写你自己的 +brainfuck程序,或者用其他语言写一个brainfuck的解释器,解释器非常容易 +实现,但是如果你是一个自虐狂的话,你可以尝试用brainfuck写一个brainfuk的 +解释器。 diff --git a/zh-cn/brainfuck-cn.html.markdown b/zh-cn/brainfuck-cn.html.markdown deleted file mode 100644 index a6f3fa09..00000000 --- a/zh-cn/brainfuck-cn.html.markdown +++ /dev/null @@ -1,70 +0,0 @@ ---- -language: brainfuck -lang: zh-cn -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["lyuehh", "https://github.com/lyuehh"] ---- - -Brainfuck 是一个极小的只有8个指令的图灵完全的编程语言。 - -``` -除"><+-.,[]"之外的的任何字符都会被忽略 (不包含双引号)。 - -Brainfuck 包含一个有30,000个单元为0的数组,和 -一个数据指针指向当前的单元。 - -8个指令如下: -+ : 指针指向的单元的值加1 -- : 指针指向的单元的值减1 -> : 将指针移动到下一个单元(右边的元素) -< : 将指针移动到上一个单元(左边的元素) -. : 打印当前单元的内容的ASCII值 (比如 65 = 'A'). -, : 读取一个字符到当前的单元 -[ : 如果当前单元的值是0,则向后调转到对应的]处 -] : 如果当前单元的值不是0,则向前跳转到对应的[处 - -[ 和 ] 组成了一个while循环。很明显,它们必须配对。 - -让我们看一些基本的brainfuck 程序。 - -++++++ [ > ++++++++++ < - ] > +++++ . - -这个程序打印字母'A'。首先,它把 #1 增加到6,使用它来作为循环条件, -然后,进入循环,将指针移动到 #2 ,将 #2 的值增加到10,然后 -移动回 #1,将单元 #1 的值减1,然后继续。循环共进行了6次。 - -这时,我们在 #1,它的值为0,#2 的值为60,我们移动到 -#2,将 #2 的内容加上5,然后将 #2 的内容打印出来,65在 -ASCII中表示'A', 所以'A'就会被打印出来。 - - -, [ > + < - ] > . - -这个程序从用户的输入中读取一个字符,然后把它复制到 #1。 -然后我们开始一个循环,移动到 #2,将 #2 的值加1,再移动回 #1,将 #1 -的值减1,直到 #1的值为0,这样 #2 里就保存了 #1 的旧值,循环结束时我们 -在 #1,这时我们移动到 #2,然后把字符以ASCII打印出来。 - -而且要记住的一点就是,空格在这里只是为了可读性,你可以将他们写成这样: - -,[>+<-]>. - -试着思考一下这段程序是干什么的: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -这段程序从输入接收2个参数,然后将他们相乘。 - -先读取2个输入,然后开始外层循环,以 #1 作为终止条件,然后将指针移动到 -#2,然后开始 #2 的内层循环,将 #3 加1。但是这里有一个小问题,在内层 -循环结束的时候,#2 的值是0了,那么下次执行外层循环的时候,就有问题了。 -为了解决这个问题,我们可以增加 #4 的值,然后把 #4 的值复制到 #2, -最后结果就保存在 #3 中了。 -``` -好了这就是brainfuck了。也没那么难,是吧?为了好玩,你可以写你自己的 -brainfuck程序,或者用其他语言写一个brainfuck的解释器,解释器非常容易 -实现,但是如果你是一个自虐狂的话,你可以尝试用brainfuck写一个brainfuk的 -解释器。 -- cgit v1.2.3 From f3b10beb01795bf7513ec8d06c9e90ab98df7a83 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 12 Feb 2016 23:04:31 -0800 Subject: Clean up various errors --- edn.html.markdown | 2 +- fr-fr/HTML-fr.html.markdown | 3 +- fr-fr/d.html.markdown | 12 +- fr-fr/make-fr.html.markdown | 4 +- fr-fr/objective-c-fr.html.markdown | 3 +- hu-hu/ruby-hu.html.markdown | 4 +- less.html.markdown | 2 +- nim.html.markdown | 2 +- nl-nl/amd-nl.html.markdown | 235 ------------------------------------- ru-ru/d-ru.html.markdown | 3 +- ta_in/css-ta.html.markdown | 6 +- ta_in/javascript-ta.html.markdown | 4 +- ta_in/xml-ta.html.markdown | 4 +- 13 files changed, 25 insertions(+), 259 deletions(-) delete mode 100644 nl-nl/amd-nl.html.markdown diff --git a/edn.html.markdown b/edn.html.markdown index d0bdddfc..ca04df89 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -14,7 +14,7 @@ Clojure, there are implementations of EDN for many other languages. The main benefit of EDN over JSON and YAML is that it is extensible. We will see how it is extended later on. -```Clojure +```clojure ; Comments start with a semicolon. ; Anything after the semicolon is ignored. diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown index fdde9107..4d2da921 100644 --- a/fr-fr/HTML-fr.html.markdown +++ b/fr-fr/HTML-fr.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] lang: fr-fr --- + HTML signifie HyperText Markup Language. C'est un langage (format de fichiers) qui permet d'écrire des pages internet. C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). @@ -17,7 +18,7 @@ Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parl Cet article porte principalement sur la syntaxe et quelques astuces. -```HTML +```html diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown index d9bd9b48..bfb9f2ce 100644 --- a/fr-fr/d.html.markdown +++ b/fr-fr/d.html.markdown @@ -8,7 +8,7 @@ translators: lang: fr-fr --- -```d +```c // Commençons par un classique module hello; @@ -30,7 +30,7 @@ D est activement développé par de nombreuses personnes très intelligents, gui [Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). Après cette petite introduction, jetons un coup d'oeil à quelques exemples. -```d +```c import std.stdio; void main() { @@ -75,7 +75,7 @@ On peut définir de nouveaux types avec les mots-clés `struct`, `class`, `union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés) De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. -```d +```c // Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. struct LinkedList(T) { T data = null; @@ -140,7 +140,7 @@ une méthode qui peut se comporter comme une lvalue. On peut donc utiliser la syntaxe des structures classiques (`struct.x = 7`) comme si il s'agissait de méthodes getter ou setter. -```d +```c // Considérons une classe paramétrée avec les types 'T' et 'U' class MyClass(T, U) { T _data; @@ -212,7 +212,7 @@ de premier ordre, les fonctions `pure` et les données immuables. De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter) sont disponibles dans le module `std.algorithm`. -```d +```c import std.algorithm : map, filter, reduce; import std.range : iota; // construit un intervalle excluant la dernière valeur. @@ -242,7 +242,7 @@ est de type A, comme si c'était une méthode de A. J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça Voyons comment on le fait en D ! -```d +```c import std.stdio; import std.parallelism : parallel; import std.math : sqrt; diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 5a1e03e7..48d24549 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -1,9 +1,9 @@ --- language: make contributors: - - ["Robert Steed", "https://github.com/robochat"] + - ["Robert Steed", "https://github.com/robochat"] translators: - - ["altaris", "https://github.com/altaris"] + - ["altaris", "https://github.com/altaris"] filename: Makefile-fr lang: fr-fr --- diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 4e31c4bf..fbe1741e 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -1,5 +1,4 @@ --- - language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] @@ -9,7 +8,6 @@ translators: - ["Yannick Loriot", "https://github.com/YannickL"] filename: LearnObjectiveC-fr.m lang: fr-fr - --- L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. @@ -519,6 +517,7 @@ __unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'es // l'objet est supprimé ``` + ## Lectures Complémentaires [La Page Wikipedia de l'Objective-C](http://fr.wikipedia.org/wiki/Objective-C) diff --git a/hu-hu/ruby-hu.html.markdown b/hu-hu/ruby-hu.html.markdown index 169f2b8e..f2fe4e5d 100644 --- a/hu-hu/ruby-hu.html.markdown +++ b/hu-hu/ruby-hu.html.markdown @@ -1,7 +1,7 @@ --- language: ruby lang: hu-hu -filenev: learnruby.rb +filename: learnruby-hu.rb contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] @@ -13,7 +13,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - ["Rahil Momin", "https://github.com/iamrahil"] - translators: +translators: - ["Zsolt Prontvai", "https://github.com/prozsolt"] --- diff --git a/less.html.markdown b/less.html.markdown index 41d66a54..7195271e 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -8,7 +8,7 @@ contributors: Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help developers to write maintainable and DRY (Don't Repeat Yourself) code. -```less +```css //Single line comments are removed when Less is compiled to CSS. diff --git a/nim.html.markdown b/nim.html.markdown index 79271732..4901ebfe 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -11,7 +11,7 @@ that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -```nimrod +```javascript var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown deleted file mode 100644 index d5e0022a..00000000 --- a/nl-nl/amd-nl.html.markdown +++ /dev/null @@ -1,235 +0,0 @@ ---- -category: tool -tool: amd -contributors: - - ["Frederik Ring", "https://github.com/m90"] -translators: - - ["Reinoud Kruithof", "https://github.com/reinoudk"] -filename: learnamd-nl.js -lang: nl-nl ---- - -## Aan de slag met AMD - -De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript - modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon - geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het - synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid, - debugging en cross-domain toegangsproblemen. - -### Basis concept -```javascript -// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require` -// and gaat vooral over de definitie en gebruik van modules: -// `define(id?, dependencies?, factory)` definieert een module -// `require(dependencies, callback)` importeert een set van dependencies en -// gebruikt ze in de gegeven callback - -// Laten we starten met het gebruiken van define om een nieuwe module (met naam) -// te creeren, welke geen dependencies heeft. Dit doen we door een naam -// en een zogeheten factory functie door te geven aan define: -define('awesomeAMD', function(){ - var isAMDAwesome = function(){ - return true; - }; - // De return waarde van een module's factory functie is - // wat andere modules of require calls ontvangen wanneer - // ze onze `awesomeAMD` module requiren. - // De gexporteerde waarde kan van alles zijn: (constructor) functies, - // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft). - return isAMDAwesome; -}); - - -// We gaan nu een andere module defineren die afhankelijk is van onze -// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument -// is die de dependencies van onze module defineert: -define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){ - // dependencies worden naar de factory's functieargumenten - // gestuurd in de volgorde waarin ze gespecificeert zijn - var vertelIedereen = function(){ - if (awesomeAMD()){ - alert('Dit is zOoOo cool!'); - } else { - alert('Vrij saai, niet?'); - } - }; - return vertelIedereen; -}); - -// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken -// om ons programma mee te starten. De vorm van `require` is -// `(arrayVanDependencies, callback)`. -require(['schreeuwlelijk'], function(schreewlelijk){ - schreeuwlelijk(); -}); - -// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic -// (niet-asynchrone) versie van AMD implementeren: -function define(naam, deps, factory){ - // merk op hoe modules zonder dependencies worden afgehandeld - define[naam] = require(factory ? deps : [], factory || deps); -} - -function require(deps, callback){ - var args = []; - // we halen eerst alle dependecies op die nodig zijn - // om require aan te roepen - for (var i = 0; i < deps.length; i++){ - args[i] = define[deps[i]]; - } - // voldoe aan alle dependencies van de callback - return callback.apply(null, args); -} -// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/ -``` - -### require.js in de echte wereld - -In contrast met het voorbeeld uit de introductie, implementeert `require.js` - (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk - om je modules en hun dependencies asynchroon in the laden via XHR: - -```javascript -/* file: app/main.js */ -require(['modules/someClass'], function(SomeClass){ - // de callback word uitgesteld tot de dependency geladen is - var things = new SomeClass(); -}); -console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd -``` - -De afspraak is dat je over het algemeen n module in n bestand opslaat. -`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie, -dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen - door hun locatie te gebruiken. -In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map, - relatief ten opzichte van de `baseUrl` uit je configuratie. - -* app/ - * main.js - * modules/ - * someClass.js - * someHelpers.js - * ... - * daos/ - * things.js - * ... - -Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren: - -```javascript -/* file: app/modules/someClass.js */ -define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ - // definitie van de module gebeurt, natuurlijk, ook asynchroon - function SomeClass(){ - this.method = function(){/**/}; - // ... - } - return SomeClass; -}); -``` -Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping - aan te passen in je `main.js`: - -```javascript -/* file: main.js */ -requirejs.config({ - baseUrl : 'app', - paths : { - // je kan ook modules uit andere locatie inladen - jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', - coolLibUitBower : '../bower_components/cool-lib/coollib' - } -}); -require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){ - // een `main` bestand moet require minstens eenmaal aanroepen, - // anders zal er geen code uitgevoerd worden - coolLib.doFancyDingenMet(helpers.transform($('#foo'))); -}); -``` -Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`) - welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut. -Deze zal automisch geladen en uitgevoerd worden als de pagina laadt: - -```html - - - - Honder script tags? Nooi meer! - - - - - -``` - -### Een heel project optimaliseren met r.js - -Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de - ontwikkelfase om code op een gezonde manier te organiseren maar - willen nog steeds een enkel scriptbestand gebruiken in productie in - plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt. - -`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk -uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de -dependency book van je project analyseert en een enkel bestand bouwt met daarin -al je module (juist genaamd), geminificeerd en klaar voor productie. - -Instaleren met `npm`: -```shell -$ npm install requirejs -g -``` - -Nu kun je het een configuratiebestand voeden: -```shell -$ r.js -o app.build.js -``` - -Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien: -```javascript -/* file : app.build.js */ -({ - name : 'main', // naam van het beginpunt - out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt - baseUrl : 'app', - paths : { - // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN, - // gebruik makend van de locatie gespecificeert in `main.js` - jquery : 'empty:', - coolLibUitBower : '../bower_components/cool-lib/coollib' - } -}) -``` -Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie: -```html - -``` - -Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is -beschikbar in de GitHub repo (Engels). - -Hieronder vind je nog meer informatie over AMD (Engels). - -### Onderwerpen die niet aan bod zijn gekomen -* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) -* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) -* [Advanced configuration](http://requirejs.org/docs/api.html#config) -* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) -* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) -* [Using almond.js for builds](https://github.com/jrburke/almond) - -### Verder lezen: - -* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) -* [Why AMD?](http://requirejs.org/docs/whyamd.html) -* [Universal Module Definition](https://github.com/umdjs/umd) - -### Implementaties: - -* [require.js](http://requirejs.org) -* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) -* [cujo.js](http://cujojs.com/) -* [curl.js](https://github.com/cujojs/curl) -* [lsjs](https://github.com/zazl/lsjs) -* [mmd](https://github.com/alexlawrence/mmd) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 8f4233fd..162ec4c8 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -7,11 +7,12 @@ contributors: - ["Andre Polykanine", "http://oire.me/"] lang: ru-ru --- + D - современный компилируемый язык общего назначения с Си-подобным синтаксисом, который сочетает удобство, продуманный дизайн и высокую производительность. D - это С++, сделанный правильно. -```d +```c // Welcome to D! Это однострочный комментарий /* многострочный diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown index 56f94ed0..cbe88f1e 100644 --- a/ta_in/css-ta.html.markdown +++ b/ta_in/css-ta.html.markdown @@ -7,9 +7,9 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: learncss.css -lang:in-ta + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: learncss-ta.css +lang: in-ta --- diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown index f0b0a36a..d3fe5a85 100644 --- a/ta_in/javascript-ta.html.markdown +++ b/ta_in/javascript-ta.html.markdown @@ -5,8 +5,8 @@ contributors: - ['Ariel Krakowski', 'http://www.learneroo.com'] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] -filename: javascript.js -lang:in-ta +filename: javascript-ta.js +lang: in-ta --- javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown index a9bfa9cd..d782399d 100644 --- a/ta_in/xml-ta.html.markdown +++ b/ta_in/xml-ta.html.markdown @@ -1,11 +1,11 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-ta.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Rasendran Kirushan", "https://github.com/kirushanr"] -lang:in-ta +lang: in-ta --- -- cgit v1.2.3 From 00e288cee1a9564e0a482a24bdf9e33170d7cd4e Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sat, 13 Feb 2016 15:37:31 -0700 Subject: corrected spelling --- make.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make.html.markdown b/make.html.markdown index e8cfd2b5..bf934c58 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -11,7 +11,7 @@ target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly on Unix) despite many competitors and criticisms. -There are many varieties of make in existance, this article assumes that +There are many varieties of make in existence, this article assumes that we are using GNU make which is the standard on Linux. ```make -- cgit v1.2.3 From 0c020f4da8563cbc9e509a63a1f03c1f53162c1c Mon Sep 17 00:00:00 2001 From: Adam Date: Sun, 14 Feb 2016 22:47:19 -0800 Subject: Fix up asciidoc --- asciidoc.html.markdown | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index f9ca8e21..7f2a4374 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -13,7 +13,7 @@ Headers are optional and can't contain blank lines. It must be offset from conte Title Only -```asciidoc +``` = Document Title First sentence of document. @@ -21,7 +21,7 @@ First sentence of document. Title and Author -```asciidoc +``` = Document Title First Last @@ -29,7 +29,8 @@ Start of this document. ``` Multiple Authors -```asciidoc + +``` = Document Title John Doe ; Jane Doe; Black Beard @@ -37,16 +38,18 @@ Start of a doc with multiple authors. ``` Revision Line (requires an author line) -```asciidoc + +``` = Doc Title V1 Potato Man v1.0, 2016-01-13 This article about chips is going to be fun. ``` + Paragraphs -```asciidoc +``` You don't need anything special for paragraphs. Add a blank line between paragraphs to seperate them. @@ -57,7 +60,7 @@ and you will recieve a line break! Formatting Text -```asciidoc +``` _underscore creates italics_ *asterisks for bold* *_combine for extra fun_* @@ -67,7 +70,7 @@ _underscore creates italics_ Section Titles -```asciidoc +``` = Level 0 (may only be used in document's header) == Level 1

@@ -87,34 +90,33 @@ Section Titles Lists To create a bulleted list use asterisks. -```asciidoc + +``` * foo * bar * baz ``` To create a numbered list use periods. -```asciidoc + +``` . item 1 . item 2 . item 3 ``` You can nest lists by adding extra asterisks or periods up to five times. -```asciidoc + +``` * foo 1 ** foo 2 *** foo 3 **** foo 4 ***** foo 5 -``` -```asciidoc + . foo 1 .. foo 2 ... foo 3 .... foo 4 ..... foo 5 ``` - - - -- cgit v1.2.3 From b02cceda8b6f63ee133c5c88cd31e16fe346c4a6 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 15 Feb 2016 10:29:42 -0800 Subject: new boolean[] not really required when initializing. Introducing this disrupts the flow a little bit to think, if specifying `new boolean[] ` required when intializing. --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 073135c9..50629ce1 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -175,7 +175,7 @@ public class LearnJava { // Another way to declare & initialize an array int[] y = {9000, 1000, 1337}; String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; - boolean bools[] = new boolean[] {true, false, false}; + boolean bools[] = {true, false, false}; // Indexing an array - Accessing an element System.out.println("intArray @ 0: " + intArray[0]); -- cgit v1.2.3 From 44251e1ac574739c436558ee5cd223f18b69c386 Mon Sep 17 00:00:00 2001 From: Petru Dimitriu Date: Mon, 15 Feb 2016 20:38:14 +0200 Subject: Fixed bf filename --- ro-ro/bf-ro.html.markdown | 90 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 ro-ro/bf-ro.html.markdown diff --git a/ro-ro/bf-ro.html.markdown b/ro-ro/bf-ro.html.markdown new file mode 100644 index 00000000..61b555ed --- /dev/null +++ b/ro-ro/bf-ro.html.markdown @@ -0,0 +1,90 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +lang: ro-ro +--- + +Brainfuck (un nume propriu care nu primește majusculă inițială decât la începutul +propoziției) este un limbaj de programare Turing-comple extrem de minimalist cu +doar 8 instrucțiuni. + +Puteți încerca brainfuck în navigatorul dumneavoastră cu [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Orice caracter in afara de "><+-.,[]" (fara ghilimele) este ignorat. + +Brainfuck se reprezinta ca un vector de 30 000 de celule initializate cu zero +si un pointer de date care trimite spre celula curenta. + +Exista opt comenzi: ++ : Incrementeaza valoarea celulei curente cu 1. +- : Decrementeaza valoarea celulei curente cu 1. +> : Muta pointerul de date la urmatoarea celula (o celula la dreapta). +< : Muta pointerul de date la celula precedenta (o celula la stanga). +. : Afiseaza valoarea caracterului ASCII din celul caurenta (ex. 65 = 'A'). +, : Citeste un singur caracter si plaseaza valoarea lui in celula curenta. +[ : Daca valoarea in celula curenta este zero, sare la urmatorul caracter ] . + Altfel, merge la urmatoarea instructiune. +] : Daca valoarea in celula curenta este zero, sare la urmatoarea + instructiune. + Altfel, se intoarce la instructiunea de dupa caracterul [ precedent . + +[ and ] formeaza un ciclu. Evident, trebuie ca parantezarea sa fie corecta. + +Sa privim cateva programe brainfuck simple. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Acest program afiseaza litera 'A'. Mai intai, incrementeaza celula #1 pana +la valoarea 6. Celula #1 va fi folosita pentru ciclare. Apoi, intra in ciclu +([) si muta pointerul la celula #2. Incrementeaza celula #2 de 10 ori, +muta pointerul la celula #1 si decrementeaza celula #1. Acest ciclu parcurge +6 iteratii (este nevoie de 6 decrementari pentru ca celula #1 sa ajunga la 0), +iar dupa aceea se trece la caracterul ] corespunzator si se continua executia. + +In acest moment, ne aflam in celula #1, care are valoarea 0, in timp ce celula +#2 are valoarea 60. Ne mutam pe celula #2, incrementam de 5 ori, pentru a +obtine valoarea 65, si apoi afisam valoarea celulei #2. 65 este codul ASCII +pentru 'A', deci se afiseaza 'A' in terminal. + +, [ > + < - ] > . + +Acest program citeste un caracter de la intrarea utilizator si copiaza caracterul +in celula #1. Apoi incepem un ciclu. Se muta pointerul in celula #2, se +incremneteaza valoarea de la celula #2, se muta inapoi la celula #1, se +decrementeaza valoarea de la celula #1. Aceasta continua pana cand celula #1 este +0 iar celula #2 retine vechea valoare a celulei #1. Deoarece ne aflam in celula +#1 la sfarsitul ciclului, ne mutam pe celula #2 si afisam simbolul corespunzator +in ASCII. + +Aveti in vedere ca spatiile sunt doar pentru usurinta citirii. La fel de bine +programul ar fi putut fi scris astfel: + +,[>+<-]>. + +Incercati sa va dati seama ce face acest program: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Acest program citeste doua numere ca intrare si le inmulteste. + +Pe scurt, programul citeste doua date de intrare, apoi incepe ciclul +mare, a carui conditie se afla in celula #1; apoi se muta la celula #2 +si incepe un ciclu imbricat a carui conditie de reluare se afla in +celula #2, si care incrementeaza celula #3. Totusi aici intervine o +problema: La sfarsitul ciclului imbricat, celula #2 este zero. In +acest caz, celula ciclul imbricat nu va mai functiona data viitoare. +Pentru a rezolva aceasta problema, incrementam celula si #4, si +recopiem celula #4 in celula #2. In final, celula #3 este rezultatul. + +``` + +Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru +amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți +scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul +este destul de ușor de implementat, dar dacă sunteți masochist, încercați +să implementați un interpretor de brainfuck… în brainfuck. \ No newline at end of file -- cgit v1.2.3 From 4da6849bc5caad78a437e85f33e316c97e755921 Mon Sep 17 00:00:00 2001 From: Petru Dimitriu Date: Mon, 15 Feb 2016 20:39:20 +0200 Subject: Removed old bf file --- ro-ro/brainfuck-ro.html.markdown | 90 ---------------------------------------- 1 file changed, 90 deletions(-) delete mode 100644 ro-ro/brainfuck-ro.html.markdown diff --git a/ro-ro/brainfuck-ro.html.markdown b/ro-ro/brainfuck-ro.html.markdown deleted file mode 100644 index 19209c2e..00000000 --- a/ro-ro/brainfuck-ro.html.markdown +++ /dev/null @@ -1,90 +0,0 @@ ---- -language: brainfuck -contributors: - - ["Prajit Ramachandran", "http://prajitr.github.io/"] - - ["Mathias Bynens", "http://mathiasbynens.be/"] -translators: - - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] -lang: ro-ro ---- - -Brainfuck (un nume propriu care nu primește majusculă inițială decât la începutul -propoziției) este un limbaj de programare Turing-comple extrem de minimalist cu -doar 8 instrucțiuni. - -Puteți încerca brainfuck în navigatorul dvs cu [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). - -``` -Orice caracter in afara de "><+-.,[]" (fara ghilimele) este ignorat. - -Brainfuck se reprezinta ca un vector de 30 000 de celule initializate cu zero -si un pointer de date care trimite spre celula curenta. - -Exista opt comenzi: -+ : Incrementeaza valoarea celulei curente cu 1. -- : Decrementeaza valoarea celulei curente cu 1. -> : Muta pointerul de date la urmatoarea celula (o celula la dreapta). -< : Muta pointerul de date la celula precedenta (o celula la stanga). -. : Afiseaza valoarea caracterului ASCII din celul caurenta (ex. 65 = 'A'). -, : Citeste un singur caracter si plaseaza valoarea lui in celula curenta. -[ : Daca valoarea in celula curenta este zero, sare la urmatorul caracter ] . - Altfel, merge la urmatoarea instructiune. -] : Daca valoarea in celula curenta este zero, sare la urmatoarea - instructiune. - Altfel, se intoarce la instructiunea de dupa caracterul [ precedent . - -[ and ] formeaza un ciclu. Evident, trebuie ca parantezarea sa fie corecta. - -Sa privim cateva programe brainfuck simple. - -++++++ [ > ++++++++++ < - ] > +++++ . - -Acest program afiseaza litera 'A'. Mai intai, incrementeaza celula #1 pana -la valoarea 6. Celula #1 va fi folosita pentru ciclare. Apoi, intra in ciclu -([) si muta pointerul la celula #2. Incrementeaza celula #2 de 10 ori, -muta pointerul la celula #1 si decrementeaza celula #1. Acest ciclu parcurge -6 iteratii (este nevoie de 6 decrementari pentru ca celula #1 sa ajunga la 0), -iar dupa aceea se trece la caracterul ] corespunzator si se continua executia. - -In acest moment, ne aflam in celula #1, care are valoarea 0, in timp ce celula -#2 are valoarea 60. Ne mutam pe celula #2, incrementam de 5 ori, pentru a -obtine valoarea 65, si apoi afisam valoarea celulei #2. 65 este codul ASCII -pentru 'A', deci se afiseaza 'A' in terminal. - -, [ > + < - ] > . - -Acest program citeste un caracter de la intrarea utilizator si copiaza caracterul -in celula #1. Apoi incepem un ciclu. Se muta pointerul in celula #2, se -incremneteaza valoarea de la celula #2, se muta inapoi la celula #1, se -decrementeaza valoarea de la celula #1. Aceasta continua pana cand celula #1 este -0 iar celula #2 retine vechea valoare a celulei #1. Deoarece ne aflam in celula -#1 la sfarsitul ciclului, ne mutam pe celula #2 si afisam simbolul corespunzator -in ASCII. - -Aveti in vedere ca spatiile sunt doar pentru usurinta citirii. La fel de bine -programul ar fi putut fi scris astfel: - -,[>+<-]>. - -Incercati sa va dati seama ce face acest program: - -,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> - -Acest program citeste doua numere ca intrare si le inmulteste. - -Pe scurt, programul citeste doua date de intrare, apoi incepe ciclul -mare, a carui conditie se afla in celula #1; apoi se muta la celula #2 -si incepe un ciclu imbricat a carui conditie de reluare se afla in -celula #2, si care incrementeaza celula #3. Totusi aici intervine o -problema: La sfarsitul ciclului imbricat, celula #2 este zero. In -acest caz, celula ciclul imbricat nu va mai functiona data viitoare. -Pentru a rezolva aceasta problema, incrementam celula si #4, si -recopiem celula #4 in celula #2. In final, celula #3 este rezultatul. - -``` - -Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru -amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți -scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul -este destul de ușor de implementat, dar dacă sunteți masochist, încercați -să implementați un interpretor de brainfuck… în brainfuck. \ No newline at end of file -- cgit v1.2.3 From 1d785f8e84fd5eb0dbf6b6df28044568739684fd Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Mon, 15 Feb 2016 11:03:10 -0800 Subject: memoize not memorize Let's use the correct term instead of the tongue-in-cheek term denoting the same concept. --- groovy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/groovy.html.markdown b/groovy.html.markdown index ea575248..94678c39 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -280,7 +280,7 @@ def clos = { print it } clos( "hi" ) /* - Groovy can memorize closure results [1][2][3] + Groovy can memoize closure results [1][2][3] */ def cl = {a, b -> sleep(3000) // simulate some time consuming processing -- cgit v1.2.3 From 1d562740f3d3b68fbb51a45f66ae6b60eee7b2de Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 15 Feb 2016 14:33:23 -0500 Subject: Remove a section from c++, fixes #2130 --- c++.html.markdown | 32 ++++++++------------------------ 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index a59b4db8..a02e7e5b 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -330,7 +330,7 @@ ECarTypes GetPreferredCarType() } // As of C++11 there is an easy way to assign a type to the enum which can be -// useful in serialization of data and converting enums back-and-forth between +// useful in serialization of data and converting enums back-and-forth between // the desired type and their respective constants enum ECarTypes : uint8_t { @@ -352,7 +352,7 @@ void WritePreferredCarTypeToFile(ECarTypes InputCarType) } // On the other hand you may not want enums to be accidentally cast to an integer -// type or to other enums so it is instead possible to create an enum class which +// type or to other enums so it is instead possible to create an enum class which // won't be implicitly converted enum class ECarTypes : uint8_t { @@ -468,7 +468,7 @@ int main() { // Inheritance: // This class inherits everything public and protected from the Dog class -// as well as private but may not directly access private members/methods +// as well as private but may not directly access private members/methods // without a public or protected method for doing so class OwnedDog : public Dog { @@ -825,10 +825,10 @@ fooMap.find(Foo(1)); //true /////////////////////////////////////// // lambdas are a convenient way of defining an anonymous function -// object right at the location where it is invoked or passed as +// object right at the location where it is invoked or passed as // an argument to a function. -// For example, consider sorting a vector of pairs using the second +// For example, consider sorting a vector of pairs using the second // value of the pair vector > tester; @@ -856,7 +856,7 @@ sort(tester.begin(), tester.end(), [](const pair& lhs, const pair dog_ids; // number_of_dogs = 3; for(int i = 0; i < 3; i++) { - dog_ids.push_back(i); + dog_ids.push_back(i); } int weight[3] = {30, 50, 10}; @@ -940,29 +940,13 @@ Foo f1; f1 = f2; -// How to truly clear a container: -class Foo { ... }; -vector v; -for (int i = 0; i < 10; ++i) - v.push_back(Foo()); - -// Following line sets size of v to 0, but destructors don't get called -// and resources aren't released! -v.clear(); -v.push_back(Foo()); // New value is copied into the first Foo we inserted - -// Truly destroys all values in v. See section about temporary objects for -// explanation of why this works. -v.swap(vector()); - - /////////////////////////////////////// // Tuples (C++11 and above) /////////////////////////////////////// #include -// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , // its elements are accessed by their order in the tuple. // We start with constructing a tuple. @@ -995,7 +979,7 @@ cout << tuple_size::value << "\n"; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. auto concatenated_tuple = tuple_cat(first, second, third); -// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141) +// concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A' ,3.14141) cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 -- cgit v1.2.3 From 05121bf808e0ccc3efd2a6ade55035ad0affe075 Mon Sep 17 00:00:00 2001 From: Antonio Ognio Date: Tue, 16 Feb 2016 12:38:53 -0500 Subject: Fixing broken link to Elixir's Getting Started documentation --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 720e080c..bf3c42a6 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -411,7 +411,7 @@ self() #=> #PID<0.27.0> ## References -* [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org) +* [Getting started guide](http://elixir-lang.org/getting-started/introduction.html) from the [Elixir website](http://elixir-lang.org) * [Elixir Documentation](http://elixir-lang.org/docs/master/) * ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas * [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) -- cgit v1.2.3 From 3d36c241d392221d757c9c237f3b3cdac4691cf6 Mon Sep 17 00:00:00 2001 From: lankeren Date: Wed, 17 Feb 2016 20:32:06 +0800 Subject: Fix typo --- zh-cn/scala-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 508dd58e..f3327b5b 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -369,7 +369,7 @@ object Dog { // Case 类是有额外内建功能的类。Scala 初学者常遇到的问题之一便是何时用类 // 和何时用 case 类。界线比较模糊,但通常类倾向于封装,多态和行为。类中的值 -// 的作用域一般为 private , 只有方向是暴露的。case 类的主要目的是放置不可变 +// 的作用域一般为 private , 只有方法是暴露的。case 类的主要目的是放置不可变 // 数据。它们通常只有几个方法,且方法几乎没有副作用。 case class Person(name: String, phoneNumber: String) -- cgit v1.2.3 From cfa79905912803e34a6a9f98d95f40fd013b4acd Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Wed, 17 Feb 2016 06:36:47 -0700 Subject: [asciidoc/en] fixed a couple of typos --- asciidoc.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index 7f2a4374..8326c581 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -52,10 +52,10 @@ Paragraphs ``` You don't need anything special for paragraphs. -Add a blank line between paragraphs to seperate them. +Add a blank line between paragraphs to separate them. To create a line blank add a + -and you will recieve a line break! +and you will receive a line break! ``` Formatting Text @@ -68,7 +68,7 @@ _underscore creates italics_ `*bolded monospace*` ``` -Section Titles +Section Titles ``` = Level 0 (may only be used in document's header) -- cgit v1.2.3 From 97cbeab8356fe72f487a2978ad22a82e4cddc128 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Wed, 17 Feb 2016 22:23:30 -0700 Subject: [bash-jp/ja-jp] Corrected spelling. seperated -> separated --- ja-jp/bash-jp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ja-jp/bash-jp.html.markdown b/ja-jp/bash-jp.html.markdown index 88e5ff1c..ea8fa49f 100644 --- a/ja-jp/bash-jp.html.markdown +++ b/ja-jp/bash-jp.html.markdown @@ -66,7 +66,7 @@ echo "Last program return value: $?" echo "Script's PID: $$" echo "Number of arguments: $#" echo "Scripts arguments: $@" -echo "Scripts arguments seperated in different variables: $1 $2..." +echo "Scripts arguments separated in different variables: $1 $2..." # 入力値の読み込み echo "What's your name?" @@ -117,7 +117,7 @@ echo "There are $(ls | wc -l) items here." echo "There are `ls | wc -l` items here." # BashはJavaやC++のように、case文による分岐ができます -case "$VARIABLE" in +case "$VARIABLE" in #分岐条件として使いたいパターンを並べてください 0) echo "There is a zero.";; 1) echo "There is a one.";; -- cgit v1.2.3 From c05d65750c10bcbb4bc423b4dd56e8a71759281f Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 17 Feb 2016 21:59:45 -0800 Subject: YESSSSS! --- PULL_REQUEST_TEMPLATE.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 PULL_REQUEST_TEMPLATE.md diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..3f55e3fb --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,4 @@ +- [ ] PR touches only one file (or a set of logically related files with similar changes made) +- [ ] Content changes are aimed at *intermediate to experienced programmers* (this is a poor format for explaining fundamental programming concepts) +- [ ] YAML Frontmatter formatted according to [CONTRIBUTING.md](https://github.com/adambard/learnxinyminutes-docs/blob/master/CONTRIBUTING.markdown) + - [ ] Seriously, look at it now. Watch for quotes and double-check field names. -- cgit v1.2.3 From 6981980ad5698e135b4185ef9fc5f3026509d88c Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Thu, 18 Feb 2016 13:02:55 -0700 Subject: [c/en] typos --- c.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index d92d2ee6..d4ff529d 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -723,8 +723,8 @@ typedef void (*my_fnp_type)(char *); /******************************* Header Files ********************************** Header files are an important part of c as they allow for the connection of c -source files and can simplify code and definitions by seperating them into -seperate files. +source files and can simplify code and definitions by separating them into +separate files. Header files are syntactically similar to c source files but reside in ".h" files. They can be included in your c source file by using the precompiler @@ -764,7 +764,7 @@ enum traffic_light_state {GREEN, YELLOW, RED}; Node createLinkedList(int *vals, int len); /* Beyond the above elements, other definitions should be left to a c source */ -/* file. Excessive includeds or definitions should, also not be contained in */ +/* file. Excessive includes or definitions should, also not be contained in */ /* a header file but instead put into separate headers or a c file. */ #endif /* End of the if precompiler directive. */ -- cgit v1.2.3 From 663f6e28f54a106204b9656d7a1ece1e9f225bcf Mon Sep 17 00:00:00 2001 From: Patrick Lee Date: Thu, 18 Feb 2016 15:59:00 -0500 Subject: Update php.html.markdown Added reference to add an element to an associative array. --- php.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/php.html.markdown b/php.html.markdown index ce178a15..0be8b427 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -146,6 +146,9 @@ echo $associative['One']; // prints 1 $array = ['One', 'Two', 'Three']; echo $array[0]; // => "One" +// Add an element to an associative array +$array['Four'] = 4; + // Add an element to the end of an array $array[] = 'Four'; // or -- cgit v1.2.3 From a5ae0795ba9e947b6b766707a0b93e5032ba8615 Mon Sep 17 00:00:00 2001 From: Patrick Lee Date: Thu, 18 Feb 2016 16:30:21 -0500 Subject: Update php.html.markdown Moved to group with associative arrays. --- php.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/php.html.markdown b/php.html.markdown index 0be8b427..4acdef98 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -142,13 +142,13 @@ $associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; echo $associative['One']; // prints 1 +// Add an element to an associative array +$array['Four'] = 4; + // List literals implicitly assign integer keys $array = ['One', 'Two', 'Three']; echo $array[0]; // => "One" -// Add an element to an associative array -$array['Four'] = 4; - // Add an element to the end of an array $array[] = 'Four'; // or -- cgit v1.2.3 From c50ff1ddc874ace092507982f881510b27a2e173 Mon Sep 17 00:00:00 2001 From: Patrick Lee Date: Thu, 18 Feb 2016 16:38:15 -0500 Subject: Update php.html.markdown Changed var name to $associative --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 4acdef98..6944390c 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -143,7 +143,7 @@ $associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; echo $associative['One']; // prints 1 // Add an element to an associative array -$array['Four'] = 4; +$associative['Four'] = 4; // List literals implicitly assign integer keys $array = ['One', 'Two', 'Three']; -- cgit v1.2.3 From 8d6d142e4afab0c6f9c3e27aef67bb82ac83587c Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 18 Feb 2016 19:18:35 -0800 Subject: Update markdown.html.markdown --- cs-cz/markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index b5e5894f..0d44bc12 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Michal Martinek", "https://github.com/MichalMartinek"] -filename: markdown.md +filename: markdown-cz.md lang: cs-cz --- -- cgit v1.2.3 From 4e4163141750bf2bf13ef3618e2d0bd1274f7398 Mon Sep 17 00:00:00 2001 From: Shawn Zhang Date: Fri, 19 Feb 2016 19:16:39 +0800 Subject: Create the zh-cn version of typescript --- zh-cn/typescript-cn.html.markdown | 173 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 zh-cn/typescript-cn.html.markdown diff --git a/zh-cn/typescript-cn.html.markdown b/zh-cn/typescript-cn.html.markdown new file mode 100644 index 00000000..af870279 --- /dev/null +++ b/zh-cn/typescript-cn.html.markdown @@ -0,0 +1,173 @@ +--- +language: TypeScript +category: language +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Shawn Zhang", "https://github.com/shawnzhang009"] +filename: learntypescript-cn.ts +lang: zh-cn +--- + +TypeScript是一门为开发大型JavaScript应用而设计的语言。TypeScript在JavaScript的基础上增加了类、模块、接口、泛型和静态类型(可选)等常见的概念。它是JavaScript的一个超集:所有JavaScript代码都是有效的TypeScript代码,所以任何JavaScript项目都可以无缝引入TypeScript. TypeScript编译器会把TypeScript代码编译成JavaScript代码。 + +本文只关注TypeScript额外增加的语法,区别于[JavaScript](../javascript-cn/). + +如需测试TypeScript编译器,你可以在[Playground](http://www.typescriptlang.org/Playground)码代码,它会自动编译成JavaScript代码然后直接显示出来。 + +```js +// TypeScript有三种基本类型 +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// 如果不知道是什么类型,可以使用"Any"(任意)类型 +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // 亦可,定义为布尔型 + +// 对于集合的声明, 有类型化数组和泛型数组 +var list: number[] = [1, 2, 3]; +// 另外一种,使用泛型数组 +var list: Array = [1, 2, 3]; + +// 枚举: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// 最后,"void"用于函数没有任何返回的特殊情况下 +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// 函数是"第一等公民"(first class citizens), 支持使用箭头表达式和类型推断 + +// 以下是相等的,TypeScript编译器会把它们编译成相同的JavaScript代码 +var f1 = function(i: number): number { return i * i; } +// 返回推断类型的值 +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// 返回推断类型的值 +var f4 = (i: number) => { return i * i; } +// 返回推断类型的值, 单行程式可以不需要return关键字和大括号 +var f5 = (i: number) => i * i; + +// 接口是结构化的,任何具有这些属性的都需要兼容该接口 +interface Person { + name: string; + // 可选属性,使用"?"标识 + age?: number; + // 函数 + move(): void; +} + +// 实现"Person"接口的对象,当它有了"name"和"move"方法之后可被视为一个"Person" +var p: Person = { name: "Bobby", move: () => {} }; +// 带了可选参数的对象 +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// 因为"age"不是"number"类型所以这不是一个"Person" +var invalidPerson: Person = { name: "Bobby", age: true }; + +// 接口同样可以描述一个函数的类型 +interface SearchFunc { + (source: string, subString: string): boolean; +} +// 参数名并不重要,参数类型才是重要的 +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// 类 - 成员默认为公共的(public) +class Point { + // 属性 + x: number; + + // 构造器 - 这里面的public/private关键字会为属性和初始化值生成样板化代码 + // 这个例子中, 不需要更多的代码就可以把"y"定义成和"x"一样 + // 同样支持默认值 + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // 函数 + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // 静态成员 + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y为0 + +// 继承 +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // 必须显式调用父类的构造器 + } + + // 重写 + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// 模块, "."可以作为子模块的分隔符 +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// 引入模块并定义本地别名 +import G = Geometry; + +var s2 = new G.Square(10); + +// 泛型 +// 类 +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// 接口 +interface Pair { + item1: T; + item2: T; +} + +// 以及函数 +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// 引用定义文件 +// + +// 模板字符串(使用反引号的字符串) +// 嵌入变量的模板字符串 +var name = 'Tyrone'; +var greeting = `Hi ${name}, how are you?` +// 有多行内容的模板字符串 +var multiline = `This is an example +of a multiline string`; + +``` + +## 参考资料 + * [TypeScript官网](http://www.typescriptlang.org/) + * [TypeScript语言规范说明书(pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - TypeScript介绍](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [GitHub源码](https://github.com/Microsoft/TypeScript) + * [Definitely Typed - 类型定义仓库](http://definitelytyped.org/) -- cgit v1.2.3 From 48b2244ac353890d7ebf3ecff908a6baab625ebb Mon Sep 17 00:00:00 2001 From: gprasant Date: Fri, 19 Feb 2016 08:13:46 -0800 Subject: Add documentation comment for If let --- swift.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/swift.html.markdown b/swift.html.markdown index 46768375..e921e7ea 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -94,6 +94,8 @@ var unwrappedString: String! = "Value is expected." // same as above, but ! is a postfix operator (more syntax candy) var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." +// If let structure - +// If let is a special structure in Swift that allows you to check if an Optional rhs holds a value, and in case it does - unwraps and assigns it to the lhs. if let someOptionalStringConstant = someOptionalString { // has `Some` value, non-nil if !someOptionalStringConstant.hasPrefix("ok") { -- cgit v1.2.3 From 4c8db7ae471dd023f373479d0d311d330f10eece Mon Sep 17 00:00:00 2001 From: ven Date: Sat, 20 Feb 2016 18:34:45 +0100 Subject: is it case sensitive --- ru-ru/d-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 162ec4c8..bfa3f085 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: d +language: D filename: learnd-ru.d contributors: - ["Anton Pastukhov", "http://dprogramming.ru/"] -- cgit v1.2.3 From 58455011343dd9ad36ae3134870105e451ef3741 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Mon, 22 Feb 2016 20:27:17 -0700 Subject: [self-en] separeated -> separated --- self.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/self.html.markdown b/self.html.markdown index 9290a0c9..fc7f69db 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -60,7 +60,7 @@ also sending the message 'true' to the lobby." # Sending messages to objects -Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace. +Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separated from their destination by whitespace. ``` "unary message, sends 'printLine' to the object '23' -- cgit v1.2.3 From 3453e953557a68eb752e8098ff90c255188b5668 Mon Sep 17 00:00:00 2001 From: chenbridge Date: Tue, 23 Feb 2016 12:08:17 +0800 Subject: Update to Swift 2.1 Update to Swift 2.1 --- zh-cn/swift-cn.html.markdown | 43 ++++++++++++++++++------------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index 3efe4941..017a7812 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -31,7 +31,7 @@ import UIKit // Swift2.0 println() 及 print() 已经整合成 print()。 print("Hello, world") // 这是原本的 println(),会自动进入下一行 -print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false +print("Hello, world", terminator: "") // 如果不要自动进入下一行,需设定结束符为空串 // 变量 (var) 的值设置后可以随意改变 // 常量 (let) 的值设置后不能改变 @@ -171,8 +171,8 @@ while i < 1000 { i *= 2 } -// do-while 循环 -do { +// repeat-while 循环 +repeat { print("hello") } while 1 == 2 @@ -212,11 +212,11 @@ default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情 func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } -greet("Bob", "Tuesday") +greet("Bob", day: "Tuesday") -// 函数参数前带 `#` 表示外部参数名和内部参数名使用同一个名称。 +// 第一个参数表示外部参数名和内部参数名使用同一个名称。 // 第二个参数表示外部参数名使用 `externalParamName` ,内部参数名使用 `localParamName` -func greet2(#requiredName: String, externalParamName localParamName: String) -> String { +func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } greet2(requiredName:"John", externalParamName: "Sunday") // 调用时,使用命名参数来指定参数的值 @@ -235,8 +235,8 @@ print("Gas price: \(price)") // 可变参数 func setup(numbers: Int...) { // 可变参数是个数组 - let number = numbers[0] - let argCount = numbers.count + let _ = numbers[0] + let _ = numbers.count } // 函数变量以及函数作为返回值返回 @@ -257,7 +257,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { } var someIntA = 7 var someIntB = 3 -swapTwoInts(&someIntA, &someIntB) +swapTwoInts(&someIntA, b: &someIntB) print(someIntB) // 7 @@ -286,17 +286,10 @@ numbers = numbers.map({ number in 3 * number }) print(numbers) // [3, 6, 18] // 简洁的闭包 -numbers = sorted(numbers) { $0 > $1 } -// 函数的最后一个参数可以放在括号之外,上面的语句是这个语句的简写形式 -// numbers = sorted(numbers, { $0 > $1 }) +numbers = numbers.sort { $0 > $1 } print(numbers) // [18, 6, 3] -// 超级简洁的闭包,因为 `<` 是个操作符函数 -numbers = sorted(numbers, < ) - -print(numbers) // [3, 6, 18] - // // MARK: 结构体 @@ -305,7 +298,7 @@ print(numbers) // [3, 6, 18] // 结构体和类非常类似,可以有属性和方法 struct NamesTable { - let names = [String]() + let names: [String] // 自定义下标运算符 subscript(index: Int) -> String { @@ -516,7 +509,7 @@ protocol ShapeGenerator { // 一个类实现一个带 optional 方法的协议时,可以实现或不实现这个方法 // optional 方法可以使用 optional 规则来调用 @objc protocol TransformShape { - optional func reshaped() + optional func reshape() optional func canReshape() -> Bool } @@ -528,9 +521,9 @@ class MyShape: Rect { // 在 optional 属性,方法或下标运算符后面加一个问号,可以优雅地忽略 nil 值,返回 nil。 // 这样就不会引起运行时错误 (runtime error) - if let allow = self.delegate?.canReshape?() { + if let reshape = self.delegate?.canReshape?() where reshape { // 注意语句中的问号 - self.delegate?.reshaped?() + self.delegate?.reshape?() } } } @@ -542,8 +535,8 @@ class MyShape: Rect { // 扩展: 给一个已经存在的数据类型添加功能 -// 给 Square 类添加 `Printable` 协议的实现,现在其支持 `Printable` 协议 -extension Square: Printable { +// 给 Square 类添加 `CustomStringConvertible` 协议的实现,现在其支持 `CustomStringConvertible` 协议 +extension Square: CustomStringConvertible { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" } @@ -567,8 +560,8 @@ print(14.multiplyBy(3)) // 42 // 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。 // 如果只有一个类型限制,可以省略 `where` 关键字 -func findIndex(array: [T], valueToFind: T) -> Int? { - for (index, value) in enumerate(array) { +func findIndex(array: [T], _ valueToFind: T) -> Int? { + for (index, value) in array.enumerate() { if value == valueToFind { return index } -- cgit v1.2.3 From 4b4148c2c2af801a13bbc7320bdbf19f00497d3f Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Tue, 23 Feb 2016 09:21:48 -0700 Subject: [smalltalk/en] fix typos --- smalltalk.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 3b388505..2c17b753 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -37,7 +37,7 @@ Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/j `"Comments are enclosed in quotes"` -`"Period (.) is the statement seperator"` +`"Period (.) is the statement separator"` ## Transcript: ``` @@ -305,7 +305,7 @@ result := (switch at: $B) value. x := 4. y := 1. [x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" [x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop" -x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)" +x timesRepeat: [y := y * 2]. "times repeat loop (i := 1 to x)" 1 to: x do: [:a | y := y * 2]. "for loop" 1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" #(5 4 3) do: [:a | x := x + a]. "iterate over array elements" @@ -320,7 +320,7 @@ y := x isUppercase. "test if upper case" y := x isLetter. "test if letter" y := x isDigit. "test if digit" y := x isAlphaNumeric. "test if alphanumeric" -y := x isSeparator. "test if seperator char" +y := x isSeparator. "test if separator char" y := x isVowel. "test if vowel" y := x digitValue. "convert to numeric digit value" y := x asLowercase. "convert to lower case" -- cgit v1.2.3 From cb9575a6c93637c980976db921b6699d449e70bd Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 23 Feb 2016 19:39:08 +0100 Subject: Update amd.html.markdown --- pt-br/amd.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pt-br/amd.html.markdown b/pt-br/amd.html.markdown index 626481ff..690fc8da 100644 --- a/pt-br/amd.html.markdown +++ b/pt-br/amd.html.markdown @@ -5,7 +5,8 @@ contributors: - ["Frederik Ring", "https://github.com/m90"] translators: - ["Felipe Tarijon", "http://nanoincub.com/"] -filename: learnamd.js +lang: ptr-br +filename: learnamd-pt.js --- ## Começando com AMD @@ -214,4 +215,4 @@ Uma incrível e detalhada visão geral [de build options](https://github.com/jrb * [cujo.js](http://cujojs.com/) * [curl.js](https://github.com/cujojs/curl) * [lsjs](https://github.com/zazl/lsjs) -* [mmd](https://github.com/alexlawrence/mmd) \ No newline at end of file +* [mmd](https://github.com/alexlawrence/mmd) -- cgit v1.2.3 From 484300f1db4509b08ed48526c61fcfcb48a6152b Mon Sep 17 00:00:00 2001 From: Zach Latta Date: Tue, 23 Feb 2016 16:12:44 -0800 Subject: Fix capitalization of GitHub --- chapel.html.markdown | 2 +- cs-cz/markdown.html.markdown | 10 +++++----- de-de/markdown-de.html.markdown | 10 +++++----- es-es/markdown-es.html.markdown | 10 +++++----- fi-fi/markdown-fi.html.markdown | 12 ++++++------ fr-fr/markdown.html.markdown | 10 +++++----- hy.html.markdown | 2 +- ko-kr/lua-kr.html.markdown | 2 +- markdown.html.markdown | 12 ++++++------ pt-br/hy-pt.html.markdown | 2 +- pt-br/markdown-pt.html.markdown | 8 ++++---- ru-ru/markdown-ru.html.markdown | 8 ++++---- tr-tr/markdown-tr.html.markdown | 8 ++++---- zh-cn/markdown-cn.html.markdown | 8 ++++---- 14 files changed, 52 insertions(+), 52 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 866e92d2..9c1daf40 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1066,7 +1066,7 @@ The more information you give the Chapel development team about issues you encou Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). If you're really interested in the development of the compiler or contributing to the project, -[check out the master Github repository](https://github.com/chapel-lang/chapel). +[check out the master GitHub repository](https://github.com/chapel-lang/chapel). It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0). Installing the Compiler diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 0d44bc12..568e4343 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -53,7 +53,7 @@ __Stejně jako tento.__ **_Jako tento!_** *__A tento!__* - + ~~Tento text je prošktrnutý.~~ @@ -152,7 +152,7 @@ Tento box bude zašktrnutý Jan nevědel, jak se dělá `go_to()` funkce! - + \`\`\`ruby def neco @@ -160,7 +160,7 @@ def neco end \`\`\` - @@ -232,13 +232,13 @@ Dejte text, který chcete zobrazit, do [] následovaný url v závorkách () a j Chci napsat *tento text obklopený hvězdičkami*, ale nechci aby to bylo kurzívou, tak udělám: \*tento text obklopený hvězdičkami\*. - + Váš počítač přestal pracovat? Zkuste Ctrl+Alt+Del - | Sloupec1 | Sloupec2 | Sloupec3 | diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown index 6a90980b..2c838660 100644 --- a/de-de/markdown-de.html.markdown +++ b/de-de/markdown-de.html.markdown @@ -56,7 +56,7 @@ __Genau wie dieser.__ **_Dieser auch!_** *__Und dieser genau so!__* - ~~Dieser Text wird durchgestrichen dargestellt.~~ @@ -148,7 +148,7 @@ indem du eine Zeile mit vier Leerzeichen oder einem Tabulator einrückst --> Hermann hatte nicht die leiseste Ahnung, was dieses `go_to()` bedeuten könnte! - \`\`\`ruby @@ -157,7 +157,7 @@ def foobar end \`\`\` -<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt Github +<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt GitHub Syntax-Highlighting für die nach dem ``` angegebene Sprache hinzu --> @@ -233,7 +233,7 @@ Ich würde *diesen Teil gerne mit Sternen umschließen*, doch ohne dass er kursi wird. Also mache ich folgendes: \*Ich umschließe diesen Text mit Sternen\*! - | Spalte1 | Spalte2 | Spalte3 | @@ -253,4 +253,4 @@ Ganz schön hässlich | vielleicht doch lieber | wieder aufhören Mehr Informationen gibt es in [John Gruber's offiziellem Blog-Post](http://daringfireball.net/projects/markdown/syntax) und bei Adam Pritchards [grandiosem Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -Infos zu Github Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown). \ No newline at end of file +Infos zu GitHub Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown). \ No newline at end of file diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index bc481df7..0505b4cb 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -57,8 +57,8 @@ __Al igual que este texto.__ **_Al igual que este!_** *__¡Y este!__* - + ~~Este texto está tachado.~~ @@ -150,7 +150,7 @@ para indentar dentro del código --> ¡John no sabía lo que la función `go_to()` hacía! - + \`\`\`ruby def foobar @@ -158,7 +158,7 @@ def foobar end \`\`\` - @@ -231,7 +231,7 @@ Quiero escribir *este texto rodeado por asteriscos* pero no quiero que esté en así que hago esto: \*Este texto está rodeado de asteriscos\*. - | Col1 | Col2 | Col3 | diff --git a/fi-fi/markdown-fi.html.markdown b/fi-fi/markdown-fi.html.markdown index 14b0f1d9..c5ee52b0 100644 --- a/fi-fi/markdown-fi.html.markdown +++ b/fi-fi/markdown-fi.html.markdown @@ -50,8 +50,8 @@ __Kuten on tämäkin teksti.__ **_Kuten tämäkin!_** *__Kuten tämäkin!__* - + ~~Tämä teksti on yliviivattua.~~ @@ -150,7 +150,7 @@ rivin neljällä välilyönnillä tai tabulaattorilla. --> John ei tiennyt edes mitä `go_to()` -funktio teki! - + \`\`\`ruby def foobar @@ -158,7 +158,7 @@ def foobar end \`\`\` - @@ -231,13 +231,13 @@ haluan kirjoittaa *tämän tekstin jonka ympärillä on asteriskit* mutta en hal sen kursivoituvan, joten teen näin: \*tämän tekstin ympärillä on asteriskit\*. - + Tietokoneesi kaatui? Kokeile painaa Ctrl+Alt+Del - | Kolumni1 | Kolumni2 | Kolumni3 | diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index 66f0efbe..2e4e8461 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -62,8 +62,8 @@ __Celui-là aussi.__ **_Pareil ici_** *__Et là!__* - + ~~Ce texte est barré avec strikethrough.~~ @@ -172,7 +172,7 @@ fonctionne aussi à l'intérieur du bloc de code --> La fonction `run()` ne vous oblige pas à aller courir! - \`\`\`ruby @@ -183,7 +183,7 @@ puts "Hello world!" end \`\`\` -<-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github +<-- Pas besoin d'indentation pour le code juste au dessus, de plus, GitHub va utiliser une coloration syntaxique pour le langage indiqué après les ``` --> @@ -264,7 +264,7 @@ Pour taper *ce texte* entouré d'astérisques mais pas en italique : Tapez \*ce texte\*. - diff --git a/hy.html.markdown b/hy.html.markdown index 9beaff0c..fa039bfd 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -169,6 +169,6 @@ This tutorial is just a very basic introduction to hy/lisp/python. Hy docs are here: [http://hy.readthedocs.org](http://hy.readthedocs.org) -Hy's Github repo: [http://github.com/hylang/hy](http://github.com/hylang/hy) +Hy's GitHub repo: [http://github.com/hylang/hy](http://github.com/hylang/hy) On freenode irc #hy, twitter hashtag #hylang diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index b4a018ef..ce3b71cb 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -418,5 +418,5 @@ lua-users.org에 있는 Github의 Gist에서도 확인할 수 있습니다. +GitHub의 Gist에서도 확인할 수 있습니다. 루아로 즐거운 시간을 보내세요! diff --git a/markdown.html.markdown b/markdown.html.markdown index 05eeecbe..b4ad3202 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -72,8 +72,8 @@ __And so is this text.__ *__And this!__* ``` -In Github Flavored Markdown, which is used to render markdown files on -Github, we also have strikethrough: +In GitHub Flavored Markdown, which is used to render markdown files on +GitHub, we also have strikethrough: ```markdown ~~This text is rendered with strikethrough.~~ @@ -200,7 +200,7 @@ Inline code can be created using the backtick character ` John didn't even know what the `go_to()` function did! ``` -In Github Flavored Markdown, you can use a special syntax for code +In GitHub Flavored Markdown, you can use a special syntax for code
 ```ruby
@@ -209,7 +209,7 @@ def foobar
 end
 ```
-The above text doesn't require indenting, plus Github will use syntax +The above text doesn't require indenting, plus GitHub will use syntax highlighting of the language you specify after the \`\`\` ## Horizontal rule @@ -298,7 +298,7 @@ in italics, so I do this: \*this text surrounded by asterisks\*. ### Keyboard keys -In Github Flavored Markdown, you can use a `` tag to represent keyboard keys. +In GitHub Flavored Markdown, you can use a `` tag to represent keyboard keys. ```markdown Your computer crashed? Try sending a @@ -306,7 +306,7 @@ Your computer crashed? Try sending a ``` ### Tables -Tables are only available in Github Flavored Markdown and are slightly +Tables are only available in GitHub Flavored Markdown and are slightly cumbersome, but if you really want it: ```markdown diff --git a/pt-br/hy-pt.html.markdown b/pt-br/hy-pt.html.markdown index 4230579d..5fa4df75 100644 --- a/pt-br/hy-pt.html.markdown +++ b/pt-br/hy-pt.html.markdown @@ -171,6 +171,6 @@ Este tutorial é apenas uma introdução básica para hy/lisp/python. Docs Hy: [http://hy.readthedocs.org](http://hy.readthedocs.org) -Repo Hy no Github: [http://github.com/hylang/hy](http://github.com/hylang/hy) +Repo Hy no GitHub: [http://github.com/hylang/hy](http://github.com/hylang/hy) Acesso ao freenode irc com #hy, hashtag no twitter: #hylang diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown index 4030ce3c..f22093f9 100644 --- a/pt-br/markdown-pt.html.markdown +++ b/pt-br/markdown-pt.html.markdown @@ -56,7 +56,7 @@ __E este também está._ *--Danouse! Este também__* +GitHub, nós também temos: --> ~~Este texto é processado com tachado.~~ @@ -148,7 +148,7 @@ dentro do seu código --> John não sabia nem o que o função 'goto()' fazia! - + \`\`\`ruby @@ -157,7 +157,7 @@ def foobar end \`\`\` -<-- O texto acima não requer recuo, mas o Github vai usar a sintaxe +<-- O texto acima não requer recuo, mas o GitHub vai usar a sintaxe destacando do idioma que você especificar após a ``` --> @@ -230,7 +230,7 @@ Quero digitar * Este texto entre asteriscos *, mas eu não quero que ele seja em itálico, então eu faço o seguinte: \*Este texto entre asteriscos \*. - | Col1 | Col2 | Col3 | diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index eb8e4881..c41e9676 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -61,7 +61,7 @@ __И этот тоже.__ **_И тут!_** *__И даже здесь!__* - ~~Зачёркнутый текст.~~ @@ -157,7 +157,7 @@ __И этот тоже.__ Например, можно выделить имя функции `go_to()` прямо посреди текста. - \`\`\`ruby @@ -167,7 +167,7 @@ end \`\`\` <-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами, -поскольку Github сам в состоянии определить границы блока - по строкам "```" --> +поскольку GitHub сам в состоянии определить границы блока - по строкам "```" --> - diff --git a/tr-tr/markdown-tr.html.markdown b/tr-tr/markdown-tr.html.markdown index bac8f6fc..b8f11e39 100644 --- a/tr-tr/markdown-tr.html.markdown +++ b/tr-tr/markdown-tr.html.markdown @@ -52,7 +52,7 @@ __Bu yazı da kalın.__ **_Bu da öyle!_** *__Hatta bu bile!__* - + ~~Bu yazı üstü çizili olarak gözükecek.~~ @@ -151,7 +151,7 @@ kullanabilirsiniz --> Ahmet `go_to()` fonksiyonun ne yaptığını bilmiyor! - + \`\`\`ruby def foobar @@ -159,7 +159,7 @@ def foobar end \`\`\` - @@ -230,7 +230,7 @@ Bu yazının *yıldızlar arasında gözükmesini* istiyorum fakat italik olmama bunun için, şu şekilde: \*bu yazı italik değil, yıldızlar arasında\*. - | Sütun1 | Sütun 2 | Sütün 3 | diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index b633714d..87ed46ad 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -53,7 +53,7 @@ __此文本也是__ **_或者这样。_** *__这个也是!__* - + ~~此文本为删除线效果。~~ @@ -142,7 +142,7 @@ __此文本也是__ John 甚至不知道 `go_to()` 方程是干嘛的! - + \`\`\`ruby def foobar @@ -150,7 +150,7 @@ def foobar end \`\`\` - + @@ -220,7 +220,7 @@ end 斜体化, 所以我就: \*这段置文字于星号之间\*。 - + | 第一列 | 第二列 | 第三列 | | :---------- | :------: | ----------: | -- cgit v1.2.3 From 2094f59079b79fb94326166dc2dc820962eb15a0 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 25 Feb 2016 15:10:53 +0100 Subject: Update coffeescript-it.html.markdown --- it-it/coffeescript-it.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown index 31973369..d30ba819 100644 --- a/it-it/coffeescript-it.html.markdown +++ b/it-it/coffeescript-it.html.markdown @@ -4,8 +4,6 @@ contributors: - ["Luca 'Kino' Maroni", "http://github.com/kino90"] - ["Tenor Biel", "http://github.com/L8D"] - ["Xavier Yao", "http://github.com/xavieryao"] -translators: - - ["Tommaso Pifferi","http://github.com/neslinesli93"] filename: coffeescript-it.coffee lang: it-it --- -- cgit v1.2.3 From 38d92105b268e2057521a51c10370b29898ddfe0 Mon Sep 17 00:00:00 2001 From: Nigel Thorne Date: Fri, 26 Feb 2016 09:30:35 +1100 Subject: spelling/typo --- purescript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/purescript.html.markdown b/purescript.html.markdown index 6d8cfbb9..7dd97a18 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -197,7 +197,7 @@ let even x = x `mod` 2 == 0 filter even (1..10) -- [2,4,6,8,10] map (\x -> x + 11) (1..5) -- [12,13,14,15,16] --- Requires purescript-foldable-traversabe (Data.Foldable) +-- Requires purescript-foldable-traversable (Data.Foldable) foldr (+) 0 (1..10) -- 55 sum (1..10) -- 55 -- cgit v1.2.3 From 3e429e86b2a98e34131f5a0e743ed90f4d30fda6 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Thu, 25 Feb 2016 17:32:08 -0800 Subject: Fix lang --- pt-br/asymptotic-notation-pt.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/pt-br/asymptotic-notation-pt.html.markdown b/pt-br/asymptotic-notation-pt.html.markdown index c89fb622..2e299d09 100644 --- a/pt-br/asymptotic-notation-pt.html.markdown +++ b/pt-br/asymptotic-notation-pt.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: - ["João Farias", "https://github.com/JoaoGFarias"] +lang: pt-br --- # Notação Assintótica -- cgit v1.2.3 From 9de59a839695c281d02a4154b9b4cd52b911e0a7 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Thu, 25 Feb 2016 21:45:55 -0700 Subject: [julia/en] fix typos dimentional -> dimensional fuction -> function --- julia.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 2810555e..db72e8ba 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -155,7 +155,7 @@ b = [4; 5; 6] # => 3-element Int64 Array: [4, 5, 6] b[1] # => 4 b[end] # => 6 -# 2-dimentional arrays use space-separated values and semicolon-separated rows. +# 2-dimensional arrays use space-separated values and semicolon-separated rows. matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] # Arrays of a particular Type @@ -420,7 +420,7 @@ varargs(1,2,3) # => (1,2,3) # The ... is called a splat. # We just used it in a function definition. -# It can also be used in a fuction call, +# It can also be used in a function call, # where it will splat an Array or Tuple's contents into the argument list. Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # produces a Set of Arrays Set([1,2,3]...) # => Set{Int64}(1,2,3) # this is equivalent to Set(1,2,3) -- cgit v1.2.3 From 95bb627df8d5adebcb99f02088a8fc7acee94255 Mon Sep 17 00:00:00 2001 From: Jearvon Dharrie Date: Fri, 26 Feb 2016 17:43:41 -0500 Subject: Fix typo --- ocaml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index 8faab297..a346550c 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;; let sqr2 = sqr (-2) ;; (* Every function must have at least one argument. - Since some funcions naturally don't take any arguments, there's + Since some functions naturally don't take any arguments, there's "unit" type for it that has the only one value written as "()" *) let print_hello () = print_endline "hello world" ;; -- cgit v1.2.3 From e1d9cfc97fac1972b3680d05c710d6c55a9f48bb Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 31 Oct 2015 20:47:13 +0200 Subject: Added Ukrainian translation for Java Translated from beginning to arrays (including). Translation in progress --- ua-ua/java-ua.html.markdown | 803 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 803 insertions(+) create mode 100644 ua-ua/java-ua.html.markdown diff --git a/ua-ua/java-ua.html.markdown b/ua-ua/java-ua.html.markdown new file mode 100644 index 00000000..1a0bb670 --- /dev/null +++ b/ua-ua/java-ua.html.markdown @@ -0,0 +1,803 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] +translators: + - ["Oleksandr Tatarchuk", "http://github.com/tatarchuk"] +filename: LearnJava.java +lang: uk-ua +--- + +Java є об'єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах. +[Read more here.](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Однорядковий коментар починається з // +/* +Багаторядковий коментар виглядає так. +*/ +/** +JavaDoc коментар виглядає так. Використовується для опису класу та членів класу. +*/ + +// Імпорт класу ArrayList з пакету java.util +import java.util.ArrayList; +// Імпорт усіх класів з пакету java.security +import java.security.*; + +// Кожний .java файл містить один зовнішній публічний клас, ім'я якого співпадає +// з і менем файлу. +public class LearnJava { + + // Для запуску програма, написана на java, повинна мати точку входу у вигляді методу main. + public static void main (String[] args) { + + // Використання System.out.println() для виводу на друк рядків. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Для друку з нового рядкка використовується System.out.print(). + System.out.print("Hello "); + System.out.print("World"); + + // Використання System.out.printf() для простого форматованого виводу на друк. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /////////////////////////////////////// + // Змінні + /////////////////////////////////////// + + /* + * Оголошення змінних + */ + // Для оголошення змінних використовується формат <тип> <змінна> + int fooInt; + // Оголошення декількох змінних одного типу <тип> <ім'я1>, <ім'я2>, <ім'я3> + int fooInt1, fooInt2, fooInt3; + + /* + * Ініціалізація змінних + */ + + // Ініціалізація змінної з використанням формату <тип> <ім'я> = <значення> + int fooInt = 1; + // Ініціалізація декількох змінних одного типу з одним значенням <тип> <ім'я1>, <ім'я2>, <ім'я3> = <значення> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Типи змінних + */ + // Байт - 8-бітне ціле число зі знаком + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-бітне ціле число зі знаком + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-бітне ціле число зі знаком + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-бітне ціле число зі знаком + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L використовується для позначення того, що число має тип Long; + // інакше число буде трактуватись як integer. + + // Примітка: Java не має беззнакових типів. + + // Float - 32-бітне число з плаваючою комою одиничної точності за стандартом IEEE 754 + // 2^-149 <= float <= (2-2^-23) * 2^127 + float fooFloat = 234.5f; + // f or F використовується для позначення того, що змінна має тип float; + // інакше трактується як double. + + // Double - 64-бітне число з плаваючою комою подвійної точності за стандартом IEEE 754 + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double fooDouble = 123.4; + + // Boolean - true & false (істина чи неправда) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - 16-бітний символ Unicode + char fooChar = 'A'; + + // final - посилання на такі змінні не можуть бути присвоєні іншим об'єктам, + final int HOURS_I_WORK_PER_WEEK = 9001; + // але вони можуть мати відкладену ініціалізацію. + final double E; + E = 2.71828; + + + // BigInteger -Незмінні знакові цілі числа довільної точності + // + // BigInteger є типом даних, який дає можливість розробнику виконувати операції з + // з цілими числами, розрядність яких більша за 64 біти. Числа зберігаються у масиві + // байтів, операції над ними виконуються функціями, які має клас BigInteger + // + // BigInteger можна ініціалізувати, використовуючи масив байтів чи рядок. + + BigInteger fooBigInteger = new BigInteger(fooByteArray); + + + // BigDecimal - Незмінні знакові дробові числа довільної точності + // + // BigDecimal складається з двох частин: цілого числа довільної точності + // з немасштабованим значенням та 32-бітного масштабованого цілого числа + // + // BigDecimal дозволяє розробника контролювати десяткове округлення. + // Рекомндовано використовувати BigDecimal зі значеннями валют + // і там, де необхідна точність дробових обчислень. + // + // BigDecimal може бути ініціалізований типами даних int, long, double or String + // чи немасштабованим значенням (BigInteger) і масштабованим значенням (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + // Для дотримання заданої точності рекомендується використовувати + // конструктор, який приймає String + + BigDecimal tenCents = new BigDecimal("0.1"); + + + // Рядки + String fooString = "Це мій рядок!"; + + // \n символ переходу на новий рядок + String barString = "Друк з нового рялка?\nНема питань!"; + // \t символ табуляції + String bazString = "Хочете додати табуляцію?\tТримайте!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Масиви + // Розмір масиву має бути визначений перед ініціалізацією + // Наведений формат ілюструє ініціалізацію масивів + // <тип даних>[] <ім'я змінної> = new <тип даних>[<розмір масиву>]; + // <тип даних> <ім'я змінної>[] = new <тип даних>[<розмір масиву>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Інший шлях оголошення та ініціалізації масиву + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Індексація масиву - доступ за елементами + System.out.println("intArray @ 0: " + intArray[0]); + + // Масиви є змінними та мають нульовий елемент. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Додатково + // ArrayLists - Схожі на масив, але мають більший функціонал та змінний розмір. + // LinkedLists - Реалізація двозв'язного списку. Всі операції + // виконуються так, як очікується від + // двозв'язного списку. + // Maps - Множина об'єктів, які пов'язують ключ зі значенням. Map є + // інтерфейсом, тому не може бути успадкований. + // Типи ключів і значень, які зберігаються в Map мають + // вказуватись у класі, який його реалізує. + // Ключ не може повторюватись і пов'язаний лише з одним значенням + // HashMaps - Цей клас використовує хеш-таблицю для реалізації інтерфейсу Map. + // Це дозволяє виконувати певні операції, + // такі як отримання та вставка елемента, + // за сталий час для будь-якої кількості значень. + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + System.out.println("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Comparison operators + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Boolean operators + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed/Arithmetic right shift + >>> Unsigned/Logical right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + // The ++ and -- operators increment and decrement by 1 respectively. + // If they are placed before the variable, they increment then return; + // after the variable they return then increment. + System.out.println(i++); // i = 1, prints 0 (post-increment) + System.out.println(++i); // i = 2, prints 2 (pre-increment) + System.out.println(i--); // i = 1, prints 2 (post-decrement) + System.out.println(--i); // i = 0, prints 0 (pre-decrement) + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + System.out.println("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) { + System.out.println("I get printed"); + } else if (j > 10) { + System.out.println("I don't"); + } else { + System.out.println("I also don't"); + } + + // While loop + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Increment the counter + // Iterated 100 times, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Value: " + fooWhile); + + // Do While Loop + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Increment the counter + // Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("fooDoWhile Value: " + fooDoWhile); + + // For Loop + // for loop structure => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // Iterated 10 times, fooFor 0->9 + } + System.out.println("fooFor Value: " + fooFor); + + // Nested For Loop Exit with Label + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // breaks out of outer loop instead of only the inner one + } + } + } + + // For Each Loop + // The for loop is also able to iterate over arrays as well as objects + // that implement the Iterable interface. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // for each loop structure => for ( : ) + // reads as: for each element in the iterable + // note: the object type must match the element type of the iterable. + + for (int bar : fooList) { + System.out.println(bar); + //Iterates 9 times and prints 1-9 on new lines + } + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), the + // String class, and a few special classes that wrap primitive types: + // Character, Byte, Short, and Integer. + int month = 3; + String monthString; + switch (month) { + case 1: monthString = "January"; + break; + case 2: monthString = "February"; + break; + case 3: monthString = "March"; + break; + default: monthString = "Some other month"; + break; + } + System.out.println("Switch Case Result: " + monthString); + + // Starting in Java 7 and above, switching Strings works like this: + String myAnswer = "maybe"; + switch(myAnswer) { + case "yes": + System.out.println("You answered yes."); + break; + case "no": + System.out.println("You answered no."); + break; + case "maybe": + System.out.println("You answered maybe."); + break; + default: + System.out.println("You answered " + myAnswer); + break; + } + + // Conditional Shorthand + // You can use the '?' operator for quick assignments or logic forks. + // Reads as "If (statement) is true, use , otherwise, use + // " + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Prints A, because the statement is true + + + //////////////////////////////////////// + // Converting Data Types And Typecasting + //////////////////////////////////////// + + // Converting data + + // Convert String To Integer + Integer.parseInt("123");//returns an integer version of "123" + + // Convert Integer To String + Integer.toString(123);//returns a string version of 123 + + // For other conversions check out the following classes: + // Double + // Long + // String + + // Typecasting + // You can also cast Java objects, there's a lot of details and deals + // with some more intermediate concepts. Feel free to check it out here: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Classes And Functions + /////////////////////////////////////// + + System.out.println("\n->Classes & Functions"); + + // (definition of the Bicycle class follows) + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.speedUp(3); // You should always use setter and getter methods + trek.setCadence(100); + + // toString returns this Object's string representation. + System.out.println("trek info: " + trek.toString()); + + // Double Brace Initialization + // The Java Language has no syntax for how to create static Collections + // in an easy way. Usually you end up in the following way: + + private static final Set COUNTRIES = new HashSet(); + static { + validCodes.add("DENMARK"); + validCodes.add("SWEDEN"); + validCodes.add("FINLAND"); + } + + // But there's a nifty way to achieve the same thing in an + // easier way, by using something that is called Double Brace + // Initialization. + + private static final Set COUNTRIES = new HashSet() {{ + add("DENMARK"); + add("SWEDEN"); + add("FINLAND"); + }} + + // The first brace is creating a new AnonymousInnerClass and the + // second one declares an instance initializer block. This block + // is called when the anonymous inner class is created. + // This does not only work for Collections, it works for all + // non-final classes. + + } // End main method +} // End LearnJava class + + +// You can include other, non-public outer-level classes in a .java file, +// but it is good practice. Instead split classes into separate files. + + +// Class Declaration Syntax: +// class { +// // data fields, constructors, functions all inside. +// // functions are called as methods in Java. +// } + +class Bicycle { + + // Bicycle's Fields/Variables + public int cadence; // Public: Can be accessed from anywhere + private int speed; // Private: Only accessible from within the class + protected int gear; // Protected: Accessible from the class and subclasses + String name; // default: Only accessible from within this package + + static String className; // Static class variable + + // Static block + // Java has no implementation of static constructors, but + // has a static block that can be used to initialize class variables + // (static variables). + // This block will be called when the class is loaded. + static { + className = "Bicycle"; + } + + // Constructors are a way of creating classes + // This is a constructor + public Bicycle() { + // You can also call another constructor: + // this(1, 50, 5, "Bontrager"); + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // This is a constructor that takes arguments + public Bicycle(int startCadence, int startSpeed, int startGear, + String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Method Syntax: + // () + + // Java classes often implement getters and setters for their fields + + // Method declaration syntax: + // () + public int getCadence() { + return cadence; + } + + // void methods require no return statement + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Method to display the attribute values of this Object. + @Override // Inherited from the Object class. + public String toString() { + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; + } +} // end class Bicycle + +// PennyFarthing is a subclass of Bicycle +class PennyFarthing extends Bicycle { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Call the parent constructor with super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // You should mark a method you're overriding with an @annotation. + // To learn more about what annotations are and their purpose check this + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } +} + +// Interfaces +// Interface declaration syntax +// interface extends { +// // Constants +// // Method declarations +// } + +// Example - Food: +public interface Edible { + public void eat(); // Any class that implements this interface, must + // implement this method. +} + +public interface Digestible { + public void digest(); +} + + +// We can now create a class that implements both of these interfaces. +public class Fruit implements Edible, Digestible { + + @Override + public void eat() { + // ... + } + + @Override + public void digest() { + // ... + } +} + +// In Java, you can extend only one class, but you can implement many +// interfaces. For example: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, + InterfaceTwo { + + @Override + public void InterfaceOneMethod() { + } + + @Override + public void InterfaceTwoMethod() { + } + +} + +// Abstract Classes + +// Abstract Class declaration syntax +// abstract extends { +// // Constants and variables +// // Method declarations +// } + +// Marking a class as abstract means that it contains abstract methods that must +// be defined in a child class. Similar to interfaces, abstract classes cannot +// be instantiated, but instead must be extended and the abstract methods +// defined. Different from interfaces, abstract classes can contain a mixture of +// concrete and abstract methods. Methods in an interface cannot have a body, +// unless the method is static, and variables are final by default, unlike an +// abstract class. Also abstract classes CAN have the "main" method. + +public abstract class Animal +{ + public abstract void makeSound(); + + // Method can have a body + public void eat() + { + System.out.println("I am an animal and I am Eating."); + // Note: We can access private variable here. + age = 30; + } + + // No need to initialize, however in an interface + // a variable is implicitly final and hence has + // to be initialized. + protected int age; + + public void printAge() + { + System.out.println(age); + } + + // Abstract classes can have main function. + public static void main(String[] args) + { + System.out.println("I am abstract"); + } +} + +class Dog extends Animal +{ + // Note still have to override the abstract methods in the + // abstract class. + @Override + public void makeSound() + { + System.out.println("Bark"); + // age = 30; ==> ERROR! age is private to Animal + } + + // NOTE: You will get an error if you used the + // @Override annotation here, since java doesn't allow + // overriding of static methods. + // What is happening here is called METHOD HIDING. + // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Dog pluto = new Dog(); + pluto.makeSound(); + pluto.eat(); + pluto.printAge(); + } +} + +// Final Classes + +// Final Class declaration syntax +// final { +// // Constants and variables +// // Method declarations +// } + +// Final classes are classes that cannot be inherited from and are therefore a +// final child. In a way, final classes are the opposite of abstract classes +// because abstract classes must be extended, but final classes cannot be +// extended. +public final class SaberToothedCat extends Animal +{ + // Note still have to override the abstract methods in the + // abstract class. + @Override + public void makeSound() + { + System.out.println("Roar"); + } +} + +// Final Methods +public abstract class Mammal() +{ + // Final Method Syntax: + // final () + + // Final methods, like, final classes cannot be overridden by a child class, + // and are therefore the final implementation of the method. + public final boolean isWarmBlooded() + { + return true; + } +} + + +// Enum Type +// +// An enum type is a special data type that enables for a variable to be a set +// of predefined constants. The variable must be equal to one of the values that +// have been predefined for it. Because they are constants, the names of an enum +// type's fields are in uppercase letters. In the Java programming language, you +// define an enum type by using the enum keyword. For example, you would specify +// a days-of-the-week enum type as: + +public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY +} + +// We can use our enum Day like that: + +public class EnumTest { + + // Variable Enum + Day day; + + public EnumTest(Day day) { + this.day = day; + } + + public void tellItLikeItIs() { + switch (day) { + case MONDAY: + System.out.println("Mondays are bad."); + break; + + case FRIDAY: + System.out.println("Fridays are better."); + break; + + case SATURDAY: + case SUNDAY: + System.out.println("Weekends are best."); + break; + + default: + System.out.println("Midweek days are so-so."); + break; + } + } + + public static void main(String[] args) { + EnumTest firstDay = new EnumTest(Day.MONDAY); + firstDay.tellItLikeItIs(); // => Mondays are bad. + EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); + thirdDay.tellItLikeItIs(); // => Midweek days are so-so. + } +} + +// Enum types are much more powerful than we show above. +// The enum body can include methods and other fields. +// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + +**Official Oracle Guides**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +**Online Practice and Tutorials** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Books**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From b71d01fd8aba1a9da6305dc1f52fb748ee824adf Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 31 Oct 2015 20:52:42 +0200 Subject: Changed the name of Ukrainian translation uk-ua is more correctly --- ua-ua/java-ua.html.markdown | 803 -------------------------------------------- uk-ua/java-ua.html.markdown | 803 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 803 insertions(+), 803 deletions(-) delete mode 100644 ua-ua/java-ua.html.markdown create mode 100644 uk-ua/java-ua.html.markdown diff --git a/ua-ua/java-ua.html.markdown b/ua-ua/java-ua.html.markdown deleted file mode 100644 index 1a0bb670..00000000 --- a/ua-ua/java-ua.html.markdown +++ /dev/null @@ -1,803 +0,0 @@ ---- -language: java -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] - - ["Jakukyo Friel", "http://weakish.github.io"] - - ["Madison Dickson", "http://github.com/mix3d"] - - ["Simon Morgan", "http://sjm.io/"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] - - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - - ["Rachel Stiyer", "https://github.com/rstiyer"] -translators: - - ["Oleksandr Tatarchuk", "http://github.com/tatarchuk"] -filename: LearnJava.java -lang: uk-ua ---- - -Java є об'єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах. -[Read more here.](http://docs.oracle.com/javase/tutorial/java/) - -```java -// Однорядковий коментар починається з // -/* -Багаторядковий коментар виглядає так. -*/ -/** -JavaDoc коментар виглядає так. Використовується для опису класу та членів класу. -*/ - -// Імпорт класу ArrayList з пакету java.util -import java.util.ArrayList; -// Імпорт усіх класів з пакету java.security -import java.security.*; - -// Кожний .java файл містить один зовнішній публічний клас, ім'я якого співпадає -// з і менем файлу. -public class LearnJava { - - // Для запуску програма, написана на java, повинна мати точку входу у вигляді методу main. - public static void main (String[] args) { - - // Використання System.out.println() для виводу на друк рядків. - System.out.println("Hello World!"); - System.out.println( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // Для друку з нового рядкка використовується System.out.print(). - System.out.print("Hello "); - System.out.print("World"); - - // Використання System.out.printf() для простого форматованого виводу на друк. - System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 - - /////////////////////////////////////// - // Змінні - /////////////////////////////////////// - - /* - * Оголошення змінних - */ - // Для оголошення змінних використовується формат <тип> <змінна> - int fooInt; - // Оголошення декількох змінних одного типу <тип> <ім'я1>, <ім'я2>, <ім'я3> - int fooInt1, fooInt2, fooInt3; - - /* - * Ініціалізація змінних - */ - - // Ініціалізація змінної з використанням формату <тип> <ім'я> = <значення> - int fooInt = 1; - // Ініціалізація декількох змінних одного типу з одним значенням <тип> <ім'я1>, <ім'я2>, <ім'я3> = <значення> - int fooInt1, fooInt2, fooInt3; - fooInt1 = fooInt2 = fooInt3 = 1; - - /* - * Типи змінних - */ - // Байт - 8-бітне ціле число зі знаком - // (-128 <= byte <= 127) - byte fooByte = 100; - - // Short - 16-бітне ціле число зі знаком - // (-32,768 <= short <= 32,767) - short fooShort = 10000; - - // Integer - 32-бітне ціле число зі знаком - // (-2,147,483,648 <= int <= 2,147,483,647) - int fooInt = 1; - - // Long - 64-бітне ціле число зі знаком - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; - // L використовується для позначення того, що число має тип Long; - // інакше число буде трактуватись як integer. - - // Примітка: Java не має беззнакових типів. - - // Float - 32-бітне число з плаваючою комою одиничної точності за стандартом IEEE 754 - // 2^-149 <= float <= (2-2^-23) * 2^127 - float fooFloat = 234.5f; - // f or F використовується для позначення того, що змінна має тип float; - // інакше трактується як double. - - // Double - 64-бітне число з плаваючою комою подвійної точності за стандартом IEEE 754 - // 2^-1074 <= x <= (2-2^-52) * 2^1023 - double fooDouble = 123.4; - - // Boolean - true & false (істина чи неправда) - boolean fooBoolean = true; - boolean barBoolean = false; - - // Char - 16-бітний символ Unicode - char fooChar = 'A'; - - // final - посилання на такі змінні не можуть бути присвоєні іншим об'єктам, - final int HOURS_I_WORK_PER_WEEK = 9001; - // але вони можуть мати відкладену ініціалізацію. - final double E; - E = 2.71828; - - - // BigInteger -Незмінні знакові цілі числа довільної точності - // - // BigInteger є типом даних, який дає можливість розробнику виконувати операції з - // з цілими числами, розрядність яких більша за 64 біти. Числа зберігаються у масиві - // байтів, операції над ними виконуються функціями, які має клас BigInteger - // - // BigInteger можна ініціалізувати, використовуючи масив байтів чи рядок. - - BigInteger fooBigInteger = new BigInteger(fooByteArray); - - - // BigDecimal - Незмінні знакові дробові числа довільної точності - // - // BigDecimal складається з двох частин: цілого числа довільної точності - // з немасштабованим значенням та 32-бітного масштабованого цілого числа - // - // BigDecimal дозволяє розробника контролювати десяткове округлення. - // Рекомндовано використовувати BigDecimal зі значеннями валют - // і там, де необхідна точність дробових обчислень. - // - // BigDecimal може бути ініціалізований типами даних int, long, double or String - // чи немасштабованим значенням (BigInteger) і масштабованим значенням (int). - - BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); - - // Для дотримання заданої точності рекомендується використовувати - // конструктор, який приймає String - - BigDecimal tenCents = new BigDecimal("0.1"); - - - // Рядки - String fooString = "Це мій рядок!"; - - // \n символ переходу на новий рядок - String barString = "Друк з нового рялка?\nНема питань!"; - // \t символ табуляції - String bazString = "Хочете додати табуляцію?\tТримайте!"; - System.out.println(fooString); - System.out.println(barString); - System.out.println(bazString); - - // Масиви - // Розмір масиву має бути визначений перед ініціалізацією - // Наведений формат ілюструє ініціалізацію масивів - // <тип даних>[] <ім'я змінної> = new <тип даних>[<розмір масиву>]; - // <тип даних> <ім'я змінної>[] = new <тип даних>[<розмір масиву>]; - int[] intArray = new int[10]; - String[] stringArray = new String[1]; - boolean boolArray[] = new boolean[100]; - - // Інший шлях оголошення та ініціалізації масиву - int[] y = {9000, 1000, 1337}; - String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; - boolean bools[] = new boolean[] {true, false, false}; - - // Індексація масиву - доступ за елементами - System.out.println("intArray @ 0: " + intArray[0]); - - // Масиви є змінними та мають нульовий елемент. - intArray[1] = 1; - System.out.println("intArray @ 1: " + intArray[1]); // => 1 - - // Додатково - // ArrayLists - Схожі на масив, але мають більший функціонал та змінний розмір. - // LinkedLists - Реалізація двозв'язного списку. Всі операції - // виконуються так, як очікується від - // двозв'язного списку. - // Maps - Множина об'єктів, які пов'язують ключ зі значенням. Map є - // інтерфейсом, тому не може бути успадкований. - // Типи ключів і значень, які зберігаються в Map мають - // вказуватись у класі, який його реалізує. - // Ключ не може повторюватись і пов'язаний лише з одним значенням - // HashMaps - Цей клас використовує хеш-таблицю для реалізації інтерфейсу Map. - // Це дозволяє виконувати певні операції, - // такі як отримання та вставка елемента, - // за сталий час для будь-якої кількості значень. - - /////////////////////////////////////// - // Operators - /////////////////////////////////////// - System.out.println("\n->Operators"); - - int i1 = 1, i2 = 2; // Shorthand for multiple declarations - - // Arithmetic is straightforward - System.out.println("1+2 = " + (i1 + i2)); // => 3 - System.out.println("2-1 = " + (i2 - i1)); // => 1 - System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) - System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 - - // Modulo - System.out.println("11%3 = "+(11 % 3)); // => 2 - - // Comparison operators - System.out.println("3 == 2? " + (3 == 2)); // => false - System.out.println("3 != 2? " + (3 != 2)); // => true - System.out.println("3 > 2? " + (3 > 2)); // => true - System.out.println("3 < 2? " + (3 < 2)); // => false - System.out.println("2 <= 2? " + (2 <= 2)); // => true - System.out.println("2 >= 2? " + (2 >= 2)); // => true - - // Boolean operators - System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false - System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true - System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true - - // Bitwise operators! - /* - ~ Unary bitwise complement - << Signed left shift - >> Signed/Arithmetic right shift - >>> Unsigned/Logical right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR - */ - - // Incrementations - int i = 0; - System.out.println("\n->Inc/Dec-rementation"); - // The ++ and -- operators increment and decrement by 1 respectively. - // If they are placed before the variable, they increment then return; - // after the variable they return then increment. - System.out.println(i++); // i = 1, prints 0 (post-increment) - System.out.println(++i); // i = 2, prints 2 (pre-increment) - System.out.println(i--); // i = 1, prints 2 (post-decrement) - System.out.println(--i); // i = 0, prints 0 (pre-decrement) - - /////////////////////////////////////// - // Control Structures - /////////////////////////////////////// - System.out.println("\n->Control Structures"); - - // If statements are c-like - int j = 10; - if (j == 10) { - System.out.println("I get printed"); - } else if (j > 10) { - System.out.println("I don't"); - } else { - System.out.println("I also don't"); - } - - // While loop - int fooWhile = 0; - while(fooWhile < 100) { - System.out.println(fooWhile); - // Increment the counter - // Iterated 100 times, fooWhile 0,1,2...99 - fooWhile++; - } - System.out.println("fooWhile Value: " + fooWhile); - - // Do While Loop - int fooDoWhile = 0; - do { - System.out.println(fooDoWhile); - // Increment the counter - // Iterated 99 times, fooDoWhile 0->99 - fooDoWhile++; - } while(fooDoWhile < 100); - System.out.println("fooDoWhile Value: " + fooDoWhile); - - // For Loop - // for loop structure => for(; ; ) - for (int fooFor = 0; fooFor < 10; fooFor++) { - System.out.println(fooFor); - // Iterated 10 times, fooFor 0->9 - } - System.out.println("fooFor Value: " + fooFor); - - // Nested For Loop Exit with Label - outer: - for (int i = 0; i < 10; i++) { - for (int j = 0; j < 10; j++) { - if (i == 5 && j ==5) { - break outer; - // breaks out of outer loop instead of only the inner one - } - } - } - - // For Each Loop - // The for loop is also able to iterate over arrays as well as objects - // that implement the Iterable interface. - int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - // for each loop structure => for ( : ) - // reads as: for each element in the iterable - // note: the object type must match the element type of the iterable. - - for (int bar : fooList) { - System.out.println(bar); - //Iterates 9 times and prints 1-9 on new lines - } - - // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), the - // String class, and a few special classes that wrap primitive types: - // Character, Byte, Short, and Integer. - int month = 3; - String monthString; - switch (month) { - case 1: monthString = "January"; - break; - case 2: monthString = "February"; - break; - case 3: monthString = "March"; - break; - default: monthString = "Some other month"; - break; - } - System.out.println("Switch Case Result: " + monthString); - - // Starting in Java 7 and above, switching Strings works like this: - String myAnswer = "maybe"; - switch(myAnswer) { - case "yes": - System.out.println("You answered yes."); - break; - case "no": - System.out.println("You answered no."); - break; - case "maybe": - System.out.println("You answered maybe."); - break; - default: - System.out.println("You answered " + myAnswer); - break; - } - - // Conditional Shorthand - // You can use the '?' operator for quick assignments or logic forks. - // Reads as "If (statement) is true, use , otherwise, use - // " - int foo = 5; - String bar = (foo < 10) ? "A" : "B"; - System.out.println(bar); // Prints A, because the statement is true - - - //////////////////////////////////////// - // Converting Data Types And Typecasting - //////////////////////////////////////// - - // Converting data - - // Convert String To Integer - Integer.parseInt("123");//returns an integer version of "123" - - // Convert Integer To String - Integer.toString(123);//returns a string version of 123 - - // For other conversions check out the following classes: - // Double - // Long - // String - - // Typecasting - // You can also cast Java objects, there's a lot of details and deals - // with some more intermediate concepts. Feel free to check it out here: - // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - - - /////////////////////////////////////// - // Classes And Functions - /////////////////////////////////////// - - System.out.println("\n->Classes & Functions"); - - // (definition of the Bicycle class follows) - - // Use new to instantiate a class - Bicycle trek = new Bicycle(); - - // Call object methods - trek.speedUp(3); // You should always use setter and getter methods - trek.setCadence(100); - - // toString returns this Object's string representation. - System.out.println("trek info: " + trek.toString()); - - // Double Brace Initialization - // The Java Language has no syntax for how to create static Collections - // in an easy way. Usually you end up in the following way: - - private static final Set COUNTRIES = new HashSet(); - static { - validCodes.add("DENMARK"); - validCodes.add("SWEDEN"); - validCodes.add("FINLAND"); - } - - // But there's a nifty way to achieve the same thing in an - // easier way, by using something that is called Double Brace - // Initialization. - - private static final Set COUNTRIES = new HashSet() {{ - add("DENMARK"); - add("SWEDEN"); - add("FINLAND"); - }} - - // The first brace is creating a new AnonymousInnerClass and the - // second one declares an instance initializer block. This block - // is called when the anonymous inner class is created. - // This does not only work for Collections, it works for all - // non-final classes. - - } // End main method -} // End LearnJava class - - -// You can include other, non-public outer-level classes in a .java file, -// but it is good practice. Instead split classes into separate files. - - -// Class Declaration Syntax: -// class { -// // data fields, constructors, functions all inside. -// // functions are called as methods in Java. -// } - -class Bicycle { - - // Bicycle's Fields/Variables - public int cadence; // Public: Can be accessed from anywhere - private int speed; // Private: Only accessible from within the class - protected int gear; // Protected: Accessible from the class and subclasses - String name; // default: Only accessible from within this package - - static String className; // Static class variable - - // Static block - // Java has no implementation of static constructors, but - // has a static block that can be used to initialize class variables - // (static variables). - // This block will be called when the class is loaded. - static { - className = "Bicycle"; - } - - // Constructors are a way of creating classes - // This is a constructor - public Bicycle() { - // You can also call another constructor: - // this(1, 50, 5, "Bontrager"); - gear = 1; - cadence = 50; - speed = 5; - name = "Bontrager"; - } - - // This is a constructor that takes arguments - public Bicycle(int startCadence, int startSpeed, int startGear, - String name) { - this.gear = startGear; - this.cadence = startCadence; - this.speed = startSpeed; - this.name = name; - } - - // Method Syntax: - // () - - // Java classes often implement getters and setters for their fields - - // Method declaration syntax: - // () - public int getCadence() { - return cadence; - } - - // void methods require no return statement - public void setCadence(int newValue) { - cadence = newValue; - } - - public void setGear(int newValue) { - gear = newValue; - } - - public void speedUp(int increment) { - speed += increment; - } - - public void slowDown(int decrement) { - speed -= decrement; - } - - public void setName(String newName) { - name = newName; - } - - public String getName() { - return name; - } - - //Method to display the attribute values of this Object. - @Override // Inherited from the Object class. - public String toString() { - return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + - " name: " + name; - } -} // end class Bicycle - -// PennyFarthing is a subclass of Bicycle -class PennyFarthing extends Bicycle { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) - - public PennyFarthing(int startCadence, int startSpeed){ - // Call the parent constructor with super - super(startCadence, startSpeed, 0, "PennyFarthing"); - } - - // You should mark a method you're overriding with an @annotation. - // To learn more about what annotations are and their purpose check this - // out: http://docs.oracle.com/javase/tutorial/java/annotations/ - @Override - public void setGear(int gear) { - gear = 0; - } -} - -// Interfaces -// Interface declaration syntax -// interface extends { -// // Constants -// // Method declarations -// } - -// Example - Food: -public interface Edible { - public void eat(); // Any class that implements this interface, must - // implement this method. -} - -public interface Digestible { - public void digest(); -} - - -// We can now create a class that implements both of these interfaces. -public class Fruit implements Edible, Digestible { - - @Override - public void eat() { - // ... - } - - @Override - public void digest() { - // ... - } -} - -// In Java, you can extend only one class, but you can implement many -// interfaces. For example: -public class ExampleClass extends ExampleClassParent implements InterfaceOne, - InterfaceTwo { - - @Override - public void InterfaceOneMethod() { - } - - @Override - public void InterfaceTwoMethod() { - } - -} - -// Abstract Classes - -// Abstract Class declaration syntax -// abstract extends { -// // Constants and variables -// // Method declarations -// } - -// Marking a class as abstract means that it contains abstract methods that must -// be defined in a child class. Similar to interfaces, abstract classes cannot -// be instantiated, but instead must be extended and the abstract methods -// defined. Different from interfaces, abstract classes can contain a mixture of -// concrete and abstract methods. Methods in an interface cannot have a body, -// unless the method is static, and variables are final by default, unlike an -// abstract class. Also abstract classes CAN have the "main" method. - -public abstract class Animal -{ - public abstract void makeSound(); - - // Method can have a body - public void eat() - { - System.out.println("I am an animal and I am Eating."); - // Note: We can access private variable here. - age = 30; - } - - // No need to initialize, however in an interface - // a variable is implicitly final and hence has - // to be initialized. - protected int age; - - public void printAge() - { - System.out.println(age); - } - - // Abstract classes can have main function. - public static void main(String[] args) - { - System.out.println("I am abstract"); - } -} - -class Dog extends Animal -{ - // Note still have to override the abstract methods in the - // abstract class. - @Override - public void makeSound() - { - System.out.println("Bark"); - // age = 30; ==> ERROR! age is private to Animal - } - - // NOTE: You will get an error if you used the - // @Override annotation here, since java doesn't allow - // overriding of static methods. - // What is happening here is called METHOD HIDING. - // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ - public static void main(String[] args) - { - Dog pluto = new Dog(); - pluto.makeSound(); - pluto.eat(); - pluto.printAge(); - } -} - -// Final Classes - -// Final Class declaration syntax -// final { -// // Constants and variables -// // Method declarations -// } - -// Final classes are classes that cannot be inherited from and are therefore a -// final child. In a way, final classes are the opposite of abstract classes -// because abstract classes must be extended, but final classes cannot be -// extended. -public final class SaberToothedCat extends Animal -{ - // Note still have to override the abstract methods in the - // abstract class. - @Override - public void makeSound() - { - System.out.println("Roar"); - } -} - -// Final Methods -public abstract class Mammal() -{ - // Final Method Syntax: - // final () - - // Final methods, like, final classes cannot be overridden by a child class, - // and are therefore the final implementation of the method. - public final boolean isWarmBlooded() - { - return true; - } -} - - -// Enum Type -// -// An enum type is a special data type that enables for a variable to be a set -// of predefined constants. The variable must be equal to one of the values that -// have been predefined for it. Because they are constants, the names of an enum -// type's fields are in uppercase letters. In the Java programming language, you -// define an enum type by using the enum keyword. For example, you would specify -// a days-of-the-week enum type as: - -public enum Day { - SUNDAY, MONDAY, TUESDAY, WEDNESDAY, - THURSDAY, FRIDAY, SATURDAY -} - -// We can use our enum Day like that: - -public class EnumTest { - - // Variable Enum - Day day; - - public EnumTest(Day day) { - this.day = day; - } - - public void tellItLikeItIs() { - switch (day) { - case MONDAY: - System.out.println("Mondays are bad."); - break; - - case FRIDAY: - System.out.println("Fridays are better."); - break; - - case SATURDAY: - case SUNDAY: - System.out.println("Weekends are best."); - break; - - default: - System.out.println("Midweek days are so-so."); - break; - } - } - - public static void main(String[] args) { - EnumTest firstDay = new EnumTest(Day.MONDAY); - firstDay.tellItLikeItIs(); // => Mondays are bad. - EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); - thirdDay.tellItLikeItIs(); // => Midweek days are so-so. - } -} - -// Enum types are much more powerful than we show above. -// The enum body can include methods and other fields. -// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html - -``` - -## Further Reading - -The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. - -**Official Oracle Guides**: - -* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) - -* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - -* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): - * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) - * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) - * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - -* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - -* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - -* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) - -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) - -**Online Practice and Tutorials** - -* [Learneroo.com - Learn Java](http://www.learneroo.com) - -* [Codingbat.com](http://codingbat.com/java) - - -**Books**: - -* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) - -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) - -* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) - -* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown new file mode 100644 index 00000000..1a0bb670 --- /dev/null +++ b/uk-ua/java-ua.html.markdown @@ -0,0 +1,803 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] +translators: + - ["Oleksandr Tatarchuk", "http://github.com/tatarchuk"] +filename: LearnJava.java +lang: uk-ua +--- + +Java є об'єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах. +[Read more here.](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Однорядковий коментар починається з // +/* +Багаторядковий коментар виглядає так. +*/ +/** +JavaDoc коментар виглядає так. Використовується для опису класу та членів класу. +*/ + +// Імпорт класу ArrayList з пакету java.util +import java.util.ArrayList; +// Імпорт усіх класів з пакету java.security +import java.security.*; + +// Кожний .java файл містить один зовнішній публічний клас, ім'я якого співпадає +// з і менем файлу. +public class LearnJava { + + // Для запуску програма, написана на java, повинна мати точку входу у вигляді методу main. + public static void main (String[] args) { + + // Використання System.out.println() для виводу на друк рядків. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Для друку з нового рядкка використовується System.out.print(). + System.out.print("Hello "); + System.out.print("World"); + + // Використання System.out.printf() для простого форматованого виводу на друк. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /////////////////////////////////////// + // Змінні + /////////////////////////////////////// + + /* + * Оголошення змінних + */ + // Для оголошення змінних використовується формат <тип> <змінна> + int fooInt; + // Оголошення декількох змінних одного типу <тип> <ім'я1>, <ім'я2>, <ім'я3> + int fooInt1, fooInt2, fooInt3; + + /* + * Ініціалізація змінних + */ + + // Ініціалізація змінної з використанням формату <тип> <ім'я> = <значення> + int fooInt = 1; + // Ініціалізація декількох змінних одного типу з одним значенням <тип> <ім'я1>, <ім'я2>, <ім'я3> = <значення> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Типи змінних + */ + // Байт - 8-бітне ціле число зі знаком + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-бітне ціле число зі знаком + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-бітне ціле число зі знаком + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-бітне ціле число зі знаком + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L використовується для позначення того, що число має тип Long; + // інакше число буде трактуватись як integer. + + // Примітка: Java не має беззнакових типів. + + // Float - 32-бітне число з плаваючою комою одиничної точності за стандартом IEEE 754 + // 2^-149 <= float <= (2-2^-23) * 2^127 + float fooFloat = 234.5f; + // f or F використовується для позначення того, що змінна має тип float; + // інакше трактується як double. + + // Double - 64-бітне число з плаваючою комою подвійної точності за стандартом IEEE 754 + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double fooDouble = 123.4; + + // Boolean - true & false (істина чи неправда) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - 16-бітний символ Unicode + char fooChar = 'A'; + + // final - посилання на такі змінні не можуть бути присвоєні іншим об'єктам, + final int HOURS_I_WORK_PER_WEEK = 9001; + // але вони можуть мати відкладену ініціалізацію. + final double E; + E = 2.71828; + + + // BigInteger -Незмінні знакові цілі числа довільної точності + // + // BigInteger є типом даних, який дає можливість розробнику виконувати операції з + // з цілими числами, розрядність яких більша за 64 біти. Числа зберігаються у масиві + // байтів, операції над ними виконуються функціями, які має клас BigInteger + // + // BigInteger можна ініціалізувати, використовуючи масив байтів чи рядок. + + BigInteger fooBigInteger = new BigInteger(fooByteArray); + + + // BigDecimal - Незмінні знакові дробові числа довільної точності + // + // BigDecimal складається з двох частин: цілого числа довільної точності + // з немасштабованим значенням та 32-бітного масштабованого цілого числа + // + // BigDecimal дозволяє розробника контролювати десяткове округлення. + // Рекомндовано використовувати BigDecimal зі значеннями валют + // і там, де необхідна точність дробових обчислень. + // + // BigDecimal може бути ініціалізований типами даних int, long, double or String + // чи немасштабованим значенням (BigInteger) і масштабованим значенням (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + // Для дотримання заданої точності рекомендується використовувати + // конструктор, який приймає String + + BigDecimal tenCents = new BigDecimal("0.1"); + + + // Рядки + String fooString = "Це мій рядок!"; + + // \n символ переходу на новий рядок + String barString = "Друк з нового рялка?\nНема питань!"; + // \t символ табуляції + String bazString = "Хочете додати табуляцію?\tТримайте!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Масиви + // Розмір масиву має бути визначений перед ініціалізацією + // Наведений формат ілюструє ініціалізацію масивів + // <тип даних>[] <ім'я змінної> = new <тип даних>[<розмір масиву>]; + // <тип даних> <ім'я змінної>[] = new <тип даних>[<розмір масиву>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Інший шлях оголошення та ініціалізації масиву + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Індексація масиву - доступ за елементами + System.out.println("intArray @ 0: " + intArray[0]); + + // Масиви є змінними та мають нульовий елемент. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Додатково + // ArrayLists - Схожі на масив, але мають більший функціонал та змінний розмір. + // LinkedLists - Реалізація двозв'язного списку. Всі операції + // виконуються так, як очікується від + // двозв'язного списку. + // Maps - Множина об'єктів, які пов'язують ключ зі значенням. Map є + // інтерфейсом, тому не може бути успадкований. + // Типи ключів і значень, які зберігаються в Map мають + // вказуватись у класі, який його реалізує. + // Ключ не може повторюватись і пов'язаний лише з одним значенням + // HashMaps - Цей клас використовує хеш-таблицю для реалізації інтерфейсу Map. + // Це дозволяє виконувати певні операції, + // такі як отримання та вставка елемента, + // за сталий час для будь-якої кількості значень. + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + System.out.println("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Comparison operators + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Boolean operators + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed/Arithmetic right shift + >>> Unsigned/Logical right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + System.out.println("\n->Inc/Dec-rementation"); + // The ++ and -- operators increment and decrement by 1 respectively. + // If they are placed before the variable, they increment then return; + // after the variable they return then increment. + System.out.println(i++); // i = 1, prints 0 (post-increment) + System.out.println(++i); // i = 2, prints 2 (pre-increment) + System.out.println(i--); // i = 1, prints 2 (post-decrement) + System.out.println(--i); // i = 0, prints 0 (pre-decrement) + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + System.out.println("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) { + System.out.println("I get printed"); + } else if (j > 10) { + System.out.println("I don't"); + } else { + System.out.println("I also don't"); + } + + // While loop + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Increment the counter + // Iterated 100 times, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Value: " + fooWhile); + + // Do While Loop + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Increment the counter + // Iterated 99 times, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("fooDoWhile Value: " + fooDoWhile); + + // For Loop + // for loop structure => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // Iterated 10 times, fooFor 0->9 + } + System.out.println("fooFor Value: " + fooFor); + + // Nested For Loop Exit with Label + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // breaks out of outer loop instead of only the inner one + } + } + } + + // For Each Loop + // The for loop is also able to iterate over arrays as well as objects + // that implement the Iterable interface. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // for each loop structure => for ( : ) + // reads as: for each element in the iterable + // note: the object type must match the element type of the iterable. + + for (int bar : fooList) { + System.out.println(bar); + //Iterates 9 times and prints 1-9 on new lines + } + + // Switch Case + // A switch works with the byte, short, char, and int data types. + // It also works with enumerated types (discussed in Enum Types), the + // String class, and a few special classes that wrap primitive types: + // Character, Byte, Short, and Integer. + int month = 3; + String monthString; + switch (month) { + case 1: monthString = "January"; + break; + case 2: monthString = "February"; + break; + case 3: monthString = "March"; + break; + default: monthString = "Some other month"; + break; + } + System.out.println("Switch Case Result: " + monthString); + + // Starting in Java 7 and above, switching Strings works like this: + String myAnswer = "maybe"; + switch(myAnswer) { + case "yes": + System.out.println("You answered yes."); + break; + case "no": + System.out.println("You answered no."); + break; + case "maybe": + System.out.println("You answered maybe."); + break; + default: + System.out.println("You answered " + myAnswer); + break; + } + + // Conditional Shorthand + // You can use the '?' operator for quick assignments or logic forks. + // Reads as "If (statement) is true, use , otherwise, use + // " + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Prints A, because the statement is true + + + //////////////////////////////////////// + // Converting Data Types And Typecasting + //////////////////////////////////////// + + // Converting data + + // Convert String To Integer + Integer.parseInt("123");//returns an integer version of "123" + + // Convert Integer To String + Integer.toString(123);//returns a string version of 123 + + // For other conversions check out the following classes: + // Double + // Long + // String + + // Typecasting + // You can also cast Java objects, there's a lot of details and deals + // with some more intermediate concepts. Feel free to check it out here: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Classes And Functions + /////////////////////////////////////// + + System.out.println("\n->Classes & Functions"); + + // (definition of the Bicycle class follows) + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.speedUp(3); // You should always use setter and getter methods + trek.setCadence(100); + + // toString returns this Object's string representation. + System.out.println("trek info: " + trek.toString()); + + // Double Brace Initialization + // The Java Language has no syntax for how to create static Collections + // in an easy way. Usually you end up in the following way: + + private static final Set COUNTRIES = new HashSet(); + static { + validCodes.add("DENMARK"); + validCodes.add("SWEDEN"); + validCodes.add("FINLAND"); + } + + // But there's a nifty way to achieve the same thing in an + // easier way, by using something that is called Double Brace + // Initialization. + + private static final Set COUNTRIES = new HashSet() {{ + add("DENMARK"); + add("SWEDEN"); + add("FINLAND"); + }} + + // The first brace is creating a new AnonymousInnerClass and the + // second one declares an instance initializer block. This block + // is called when the anonymous inner class is created. + // This does not only work for Collections, it works for all + // non-final classes. + + } // End main method +} // End LearnJava class + + +// You can include other, non-public outer-level classes in a .java file, +// but it is good practice. Instead split classes into separate files. + + +// Class Declaration Syntax: +// class { +// // data fields, constructors, functions all inside. +// // functions are called as methods in Java. +// } + +class Bicycle { + + // Bicycle's Fields/Variables + public int cadence; // Public: Can be accessed from anywhere + private int speed; // Private: Only accessible from within the class + protected int gear; // Protected: Accessible from the class and subclasses + String name; // default: Only accessible from within this package + + static String className; // Static class variable + + // Static block + // Java has no implementation of static constructors, but + // has a static block that can be used to initialize class variables + // (static variables). + // This block will be called when the class is loaded. + static { + className = "Bicycle"; + } + + // Constructors are a way of creating classes + // This is a constructor + public Bicycle() { + // You can also call another constructor: + // this(1, 50, 5, "Bontrager"); + gear = 1; + cadence = 50; + speed = 5; + name = "Bontrager"; + } + + // This is a constructor that takes arguments + public Bicycle(int startCadence, int startSpeed, int startGear, + String name) { + this.gear = startGear; + this.cadence = startCadence; + this.speed = startSpeed; + this.name = name; + } + + // Method Syntax: + // () + + // Java classes often implement getters and setters for their fields + + // Method declaration syntax: + // () + public int getCadence() { + return cadence; + } + + // void methods require no return statement + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void speedUp(int increment) { + speed += increment; + } + + public void slowDown(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Method to display the attribute values of this Object. + @Override // Inherited from the Object class. + public String toString() { + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; + } +} // end class Bicycle + +// PennyFarthing is a subclass of Bicycle +class PennyFarthing extends Bicycle { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + public PennyFarthing(int startCadence, int startSpeed){ + // Call the parent constructor with super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // You should mark a method you're overriding with an @annotation. + // To learn more about what annotations are and their purpose check this + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGear(int gear) { + gear = 0; + } +} + +// Interfaces +// Interface declaration syntax +// interface extends { +// // Constants +// // Method declarations +// } + +// Example - Food: +public interface Edible { + public void eat(); // Any class that implements this interface, must + // implement this method. +} + +public interface Digestible { + public void digest(); +} + + +// We can now create a class that implements both of these interfaces. +public class Fruit implements Edible, Digestible { + + @Override + public void eat() { + // ... + } + + @Override + public void digest() { + // ... + } +} + +// In Java, you can extend only one class, but you can implement many +// interfaces. For example: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, + InterfaceTwo { + + @Override + public void InterfaceOneMethod() { + } + + @Override + public void InterfaceTwoMethod() { + } + +} + +// Abstract Classes + +// Abstract Class declaration syntax +// abstract extends { +// // Constants and variables +// // Method declarations +// } + +// Marking a class as abstract means that it contains abstract methods that must +// be defined in a child class. Similar to interfaces, abstract classes cannot +// be instantiated, but instead must be extended and the abstract methods +// defined. Different from interfaces, abstract classes can contain a mixture of +// concrete and abstract methods. Methods in an interface cannot have a body, +// unless the method is static, and variables are final by default, unlike an +// abstract class. Also abstract classes CAN have the "main" method. + +public abstract class Animal +{ + public abstract void makeSound(); + + // Method can have a body + public void eat() + { + System.out.println("I am an animal and I am Eating."); + // Note: We can access private variable here. + age = 30; + } + + // No need to initialize, however in an interface + // a variable is implicitly final and hence has + // to be initialized. + protected int age; + + public void printAge() + { + System.out.println(age); + } + + // Abstract classes can have main function. + public static void main(String[] args) + { + System.out.println("I am abstract"); + } +} + +class Dog extends Animal +{ + // Note still have to override the abstract methods in the + // abstract class. + @Override + public void makeSound() + { + System.out.println("Bark"); + // age = 30; ==> ERROR! age is private to Animal + } + + // NOTE: You will get an error if you used the + // @Override annotation here, since java doesn't allow + // overriding of static methods. + // What is happening here is called METHOD HIDING. + // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Dog pluto = new Dog(); + pluto.makeSound(); + pluto.eat(); + pluto.printAge(); + } +} + +// Final Classes + +// Final Class declaration syntax +// final { +// // Constants and variables +// // Method declarations +// } + +// Final classes are classes that cannot be inherited from and are therefore a +// final child. In a way, final classes are the opposite of abstract classes +// because abstract classes must be extended, but final classes cannot be +// extended. +public final class SaberToothedCat extends Animal +{ + // Note still have to override the abstract methods in the + // abstract class. + @Override + public void makeSound() + { + System.out.println("Roar"); + } +} + +// Final Methods +public abstract class Mammal() +{ + // Final Method Syntax: + // final () + + // Final methods, like, final classes cannot be overridden by a child class, + // and are therefore the final implementation of the method. + public final boolean isWarmBlooded() + { + return true; + } +} + + +// Enum Type +// +// An enum type is a special data type that enables for a variable to be a set +// of predefined constants. The variable must be equal to one of the values that +// have been predefined for it. Because they are constants, the names of an enum +// type's fields are in uppercase letters. In the Java programming language, you +// define an enum type by using the enum keyword. For example, you would specify +// a days-of-the-week enum type as: + +public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY +} + +// We can use our enum Day like that: + +public class EnumTest { + + // Variable Enum + Day day; + + public EnumTest(Day day) { + this.day = day; + } + + public void tellItLikeItIs() { + switch (day) { + case MONDAY: + System.out.println("Mondays are bad."); + break; + + case FRIDAY: + System.out.println("Fridays are better."); + break; + + case SATURDAY: + case SUNDAY: + System.out.println("Weekends are best."); + break; + + default: + System.out.println("Midweek days are so-so."); + break; + } + } + + public static void main(String[] args) { + EnumTest firstDay = new EnumTest(Day.MONDAY); + firstDay.tellItLikeItIs(); // => Mondays are bad. + EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); + thirdDay.tellItLikeItIs(); // => Midweek days are so-so. + } +} + +// Enum types are much more powerful than we show above. +// The enum body can include methods and other fields. +// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + +**Official Oracle Guides**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +**Online Practice and Tutorials** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Books**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From 6d60e96a1296637e8f1c425c179af241b80838ed Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 31 Oct 2015 21:25:21 +0200 Subject: improving java Ukrainian translation added operators --- uk-ua/java-ua.html.markdown | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index 1a0bb670..cd3dae56 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -200,23 +200,23 @@ public class LearnJava { // за сталий час для будь-якої кількості значень. /////////////////////////////////////// - // Operators + // Оператори /////////////////////////////////////// System.out.println("\n->Operators"); - int i1 = 1, i2 = 2; // Shorthand for multiple declarations + int i1 = 1, i2 = 2; // Коротка форма присвоєння - // Arithmetic is straightforward + // Арифметичні операції виконуються System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int повертається як int) System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 - // Modulo + // Ділення з остачею System.out.println("11%3 = "+(11 % 3)); // => 2 - // Comparison operators + // Оператори порівняння System.out.println("3 == 2? " + (3 == 2)); // => false System.out.println("3 != 2? " + (3 != 2)); // => true System.out.println("3 > 2? " + (3 > 2)); // => true @@ -224,28 +224,28 @@ public class LearnJava { System.out.println("2 <= 2? " + (2 <= 2)); // => true System.out.println("2 >= 2? " + (2 >= 2)); // => true - // Boolean operators + // Логічні оператори System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true - // Bitwise operators! + // Бітові оператори! /* - ~ Unary bitwise complement - << Signed left shift - >> Signed/Arithmetic right shift - >>> Unsigned/Logical right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ~ Унарне бітове доповнення + << Знаковий зсув уліво + >> Знаковий/Арифметичний зсув управо + >>> Беззнаковий/Логічний зсув управо + & Бітове І + ^ Бітови виключне АБО + | Бітове АБО */ - // Incrementations + // Інкремнт int i = 0; - System.out.println("\n->Inc/Dec-rementation"); - // The ++ and -- operators increment and decrement by 1 respectively. - // If they are placed before the variable, they increment then return; - // after the variable they return then increment. + System.out.println("\n->Інкремент/Декремент"); + // Оператори ++ і -- здійснюють інкремент та декремент ретроспективно. + // Якщо вони розташовані перед змінною, операція виконається перед поверненням; + // після - повернеться інкремент або декремент. System.out.println(i++); // i = 1, prints 0 (post-increment) System.out.println(++i); // i = 2, prints 2 (pre-increment) System.out.println(i--); // i = 1, prints 2 (post-decrement) -- cgit v1.2.3 From ce3a57d4a08b858e2f5006922bf70b65cbce1d68 Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 31 Oct 2015 21:35:19 +0200 Subject: translated further reading --- uk-ua/java-ua.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index cd3dae56..a142680f 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -762,37 +762,37 @@ public class EnumTest { ``` -## Further Reading +## Додатково для прочитання The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. -**Official Oracle Guides**: +**Офіційні посібники Oracle**: * [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) -* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) +* [Java модифікатори доступу](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) -* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): +* [ООП концепції](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) -* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) +* [Виключення](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) -* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) +* [Інтерфейси](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) -* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) +* [параметризація](http://docs.oracle.com/javase/tutorial/java/generics/index.html) * [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) -**Online Practice and Tutorials** +**Online практика та посібники** * [Learneroo.com - Learn Java](http://www.learneroo.com) * [Codingbat.com](http://codingbat.com/java) -**Books**: +**Книжки**: * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -- cgit v1.2.3 From 5668de06465df72933b0d5c5c33ad1ccf7f4a806 Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 31 Oct 2015 21:40:26 +0200 Subject: tech upgrade --- uk-ua/java-ua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index a142680f..3582f73d 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -9,7 +9,7 @@ contributors: - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - ["Rachel Stiyer", "https://github.com/rstiyer"] translators: - - ["Oleksandr Tatarchuk", "http://github.com/tatarchuk"] + - ["Oleksandr Tatarchuk", "http://github.com/tatarchuk"] filename: LearnJava.java lang: uk-ua --- -- cgit v1.2.3 From dee2ed5f7c46f5ddaf2a85871f9f97ca819e940d Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 31 Oct 2015 23:12:56 +0200 Subject: final Java translation can be used --- uk-ua/java-ua.html.markdown | 321 +++++++++++++++++++++----------------------- 1 file changed, 150 insertions(+), 171 deletions(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index 3582f73d..63472b3f 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -9,8 +9,8 @@ contributors: - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - ["Rachel Stiyer", "https://github.com/rstiyer"] translators: - - ["Oleksandr Tatarchuk", "http://github.com/tatarchuk"] -filename: LearnJava.java + - ["Oleksandr Tatarchuk", "https://github.com/tatarchuk"] +filename: LearnJavaUa.java lang: uk-ua --- @@ -252,92 +252,88 @@ public class LearnJava { System.out.println(--i); // i = 0, prints 0 (pre-decrement) /////////////////////////////////////// - // Control Structures + // Управляючі конструкції /////////////////////////////////////// System.out.println("\n->Control Structures"); - // If statements are c-like + // Оператор if використовується так само, як у мові С int j = 10; if (j == 10) { - System.out.println("I get printed"); + System.out.println("Це надрукується"); } else if (j > 10) { - System.out.println("I don't"); + System.out.println("А це - ні"); } else { - System.out.println("I also don't"); + System.out.println("Це - також ні"); } - // While loop + // Цикл з передумовою While int fooWhile = 0; while(fooWhile < 100) { System.out.println(fooWhile); - // Increment the counter - // Iterated 100 times, fooWhile 0,1,2...99 + // Інкремент лічильника + // Виконається 100 разів, fooWhile 0,1,2...99 fooWhile++; } System.out.println("fooWhile Value: " + fooWhile); - // Do While Loop + // Цикл з післяумовою Do While int fooDoWhile = 0; do { System.out.println(fooDoWhile); - // Increment the counter - // Iterated 99 times, fooDoWhile 0->99 + // Інкремент лічильника + // Виконається 99 разів, fooDoWhile 0->99 fooDoWhile++; } while(fooDoWhile < 100); System.out.println("fooDoWhile Value: " + fooDoWhile); - // For Loop - // for loop structure => for(; ; ) + // Цикл з параметром For + // структура циклу => for(<початковий стан>; <умова завершення>; <крок>) for (int fooFor = 0; fooFor < 10; fooFor++) { System.out.println(fooFor); - // Iterated 10 times, fooFor 0->9 + // Виконається 10 разів, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - // Nested For Loop Exit with Label + // Вихід з вкладеного циклу через Label outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (i == 5 && j ==5) { break outer; - // breaks out of outer loop instead of only the inner one + // вихід із зовнішнього циклу, а не лише внутрішнього } } } - // For Each Loop - // The for loop is also able to iterate over arrays as well as objects - // that implement the Iterable interface. - int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - // for each loop structure => for ( : ) - // reads as: for each element in the iterable - // note: the object type must match the element type of the iterable. + // Цикл For Each + // Призначений для перебору масивів та колекцій + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for (int bar : fooList) { System.out.println(bar); //Iterates 9 times and prints 1-9 on new lines } - // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), the - // String class, and a few special classes that wrap primitive types: - // Character, Byte, Short, and Integer. + // Оператор вибору Switch Case + // Оператор вибору працює з типами даних byte, short, char, int. + // Також працює з переліками Enum, + // класом String та класами-обгортками примітивних типів: + // Character, Byte, Short та Integer. int month = 3; String monthString; switch (month) { - case 1: monthString = "January"; + case 1: monthString = "Січень"; break; - case 2: monthString = "February"; + case 2: monthString = "Лютий"; break; - case 3: monthString = "March"; + case 3: monthString = "Березень"; break; - default: monthString = "Some other month"; + default: monthString = "Інший місяць"; break; } - System.out.println("Switch Case Result: " + monthString); + System.out.println("Switch Case результат: " + monthString); - // Starting in Java 7 and above, switching Strings works like this: + // Починаючи з Java 7 і далі, вибір рядкових змінних здійснюється так: String myAnswer = "maybe"; switch(myAnswer) { case "yes": @@ -354,59 +350,55 @@ public class LearnJava { break; } - // Conditional Shorthand - // You can use the '?' operator for quick assignments or logic forks. - // Reads as "If (statement) is true, use , otherwise, use - // " + // Тернарний оператор вибору + // Можна використовувати '?' оператор для визначення умови. + // Читається так "Якщо (умова) вірна, то <перше значення>, інакше + // <друге значення" int foo = 5; String bar = (foo < 10) ? "A" : "B"; - System.out.println(bar); // Prints A, because the statement is true + System.out.println(bar); // Надрукується А, бо умова вірна //////////////////////////////////////// - // Converting Data Types And Typecasting + // Перетворення типів //////////////////////////////////////// - // Converting data + // Перетворення String на Integer + Integer.parseInt("123");//поверне числову версію рядка "123" - // Convert String To Integer - Integer.parseInt("123");//returns an integer version of "123" + // Перетворення Integer на String + Integer.toString(123);//повертає рядкову версію 123 - // Convert Integer To String - Integer.toString(123);//returns a string version of 123 - - // For other conversions check out the following classes: + // Для інших перетворень є наступні класи: // Double // Long // String - // Typecasting - // You can also cast Java objects, there's a lot of details and deals - // with some more intermediate concepts. Feel free to check it out here: + // Приведення типів + // Тут можна прочитати про приведення об'єктів: // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html /////////////////////////////////////// - // Classes And Functions + // Класи та функції /////////////////////////////////////// System.out.println("\n->Classes & Functions"); - // (definition of the Bicycle class follows) + // (Клас Bicycle наведений нижче) - // Use new to instantiate a class + // Новий об'єкт класу Bicycle trek = new Bicycle(); - // Call object methods - trek.speedUp(3); // You should always use setter and getter methods + // Виклик методу об'єкта + trek.speedUp(3); // Постійно використовуються методи з назвами set і get trek.setCadence(100); - // toString returns this Object's string representation. + // toString повертає рядкове представленя об'єкту. System.out.println("trek info: " + trek.toString()); - - // Double Brace Initialization - // The Java Language has no syntax for how to create static Collections - // in an easy way. Usually you end up in the following way: + + // У Java немає синтаксису для явного створення статичних колекцій. + // Це можна зробити так: private static final Set COUNTRIES = new HashSet(); static { @@ -415,9 +407,7 @@ public class LearnJava { validCodes.add("FINLAND"); } - // But there's a nifty way to achieve the same thing in an - // easier way, by using something that is called Double Brace - // Initialization. + // Але є інший спосіб - Double Brace Initialization. private static final Set COUNTRIES = new HashSet() {{ add("DENMARK"); @@ -425,49 +415,44 @@ public class LearnJava { add("FINLAND"); }} - // The first brace is creating a new AnonymousInnerClass and the - // second one declares an instance initializer block. This block - // is called when the anonymous inner class is created. - // This does not only work for Collections, it works for all - // non-final classes. + // Використовується анонімний внутрішній клас - } // End main method -} // End LearnJava class + } // Кінець методу main +} // Кінець класу LearnJava -// You can include other, non-public outer-level classes in a .java file, -// but it is good practice. Instead split classes into separate files. +// Можна додавати інші, не public класи зовнішнього рівня у .java файл, +// але це не є хорошою практикою. Розміщуйте класи в окремих файлах. -// Class Declaration Syntax: +// Синтаксис оголошення класу: // class { -// // data fields, constructors, functions all inside. -// // functions are called as methods in Java. +// // поля, конструктори, функції та ін. +// // у Java функції називаються методами. // } class Bicycle { - // Bicycle's Fields/Variables - public int cadence; // Public: Can be accessed from anywhere - private int speed; // Private: Only accessible from within the class - protected int gear; // Protected: Accessible from the class and subclasses - String name; // default: Only accessible from within this package + // Поля (змінні) класу Bicycle + public int cadence; // Public: доступно звідусіль + private int speed; // Private: доступно лише у межах класу + protected int gear; // Protected: доступно лише класу та нащадкам + String name; // default: доступно у даному пакеті - static String className; // Static class variable + static String className; // статична змінна класу - // Static block - // Java has no implementation of static constructors, but - // has a static block that can be used to initialize class variables - // (static variables). - // This block will be called when the class is loaded. + // статичний блок + // Java не має статичних конструкторів, але + // має статичний блок ініціалізації змінних класу + // Цей блок виконується при завантаженні класу. static { className = "Bicycle"; } - // Constructors are a way of creating classes - // This is a constructor + // Конструктори є способом створення класу + // Це - конструктор public Bicycle() { - // You can also call another constructor: + // Можна викликати інший конструктор: // this(1, 50, 5, "Bontrager"); gear = 1; cadence = 50; @@ -475,7 +460,7 @@ class Bicycle { name = "Bontrager"; } - // This is a constructor that takes arguments + // Цей конструктор приймає аргументи public Bicycle(int startCadence, int startSpeed, int startGear, String name) { this.gear = startGear; @@ -484,18 +469,18 @@ class Bicycle { this.name = name; } - // Method Syntax: - // () + // Синтаксис методу: + // <тип повернутого значення> <ім'я методу>(<аргументи>) - // Java classes often implement getters and setters for their fields + // Java класи часто мають методи для отримання та встановлення змінних - // Method declaration syntax: - // () + // Синтаксис оголошення методу: + // <модифікатор доступу> <тип повернутого значення> <ім'я методу>(<аргументи>) public int getCadence() { return cadence; } - // void methods require no return statement + // void методи не повертають значень public void setCadence(int newValue) { cadence = newValue; } @@ -520,26 +505,26 @@ class Bicycle { return name; } - //Method to display the attribute values of this Object. + //Метод показує значення змінних об'єкту. @Override // Inherited from the Object class. public String toString() { return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + " name: " + name; } -} // end class Bicycle +} // кінець класу Bicycle -// PennyFarthing is a subclass of Bicycle +// PennyFarthing є розширенням (нащадком) класу Bicycle class PennyFarthing extends Bicycle { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) + // (Penny Farthings мають велике переднє колесо. + // Вони не мають передач.) public PennyFarthing(int startCadence, int startSpeed){ - // Call the parent constructor with super + // Виклик батьківського конструктора через super super(startCadence, startSpeed, 0, "PennyFarthing"); } - // You should mark a method you're overriding with an @annotation. - // To learn more about what annotations are and their purpose check this + // Перевизначений метод має відти відмічений аннотацією @annotation. + // Для ознайомлення з аннотаціями перейдіть за посиланням // out: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { @@ -547,17 +532,17 @@ class PennyFarthing extends Bicycle { } } -// Interfaces -// Interface declaration syntax -// interface extends { -// // Constants -// // Method declarations +// Інтерфейси +// Синтаксис оголошення інтерфейсів +// <рівень доступу> interface <ім'я інтерфейсу> extends <супер-інтерфейс> { +// // Констатнти +// // Оголошення методів // } -// Example - Food: +//Приклад - Food: public interface Edible { - public void eat(); // Any class that implements this interface, must - // implement this method. + public void eat(); // Будь-які класи, що реалізують цей інтерфейс + // повинні реалізувати цей метод. } public interface Digestible { @@ -565,7 +550,7 @@ public interface Digestible { } -// We can now create a class that implements both of these interfaces. +// Можна створити клас, що реалізує обидва інтерфейси. public class Fruit implements Edible, Digestible { @Override @@ -579,8 +564,8 @@ public class Fruit implements Edible, Digestible { } } -// In Java, you can extend only one class, but you can implement many -// interfaces. For example: +// В Java можна успадковувати лише один клас, але реалізовувати багато +// інтерфейсів. Наприклад: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { @@ -594,37 +579,35 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, } -// Abstract Classes +// Абстрактні класи -// Abstract Class declaration syntax -// abstract extends { -// // Constants and variables -// // Method declarations +// Синтаксис оголошення абстрактних класів: +// <ріаень доступу> abstract <ім1я класу> extends <супер-абстрактний клас> { +// // Константи і змінні +// // Оголошення методів // } -// Marking a class as abstract means that it contains abstract methods that must -// be defined in a child class. Similar to interfaces, abstract classes cannot -// be instantiated, but instead must be extended and the abstract methods -// defined. Different from interfaces, abstract classes can contain a mixture of -// concrete and abstract methods. Methods in an interface cannot have a body, -// unless the method is static, and variables are final by default, unlike an -// abstract class. Also abstract classes CAN have the "main" method. +// Позначення класу як абстрактного означає, що оголошені у ньому методи мають +// бути реалізовані у дочірніх класах. Подібно до інтерфейсів, не можна створити екземпляри +// абстракних класів, але їх можна успадковувати. Нащадок зобов'язаний реалізувати всі абстрактні +// методи. на відміну від інтерфейсів, абстрактні класи можуть мати як визначені, +// так і абстрактні методи. Методи в інтерфейсах не мають тіла, +// за вийнятком статичних методів, а змінні неявно мають модифікатор final, на відміну від +// абстрактного класу. Абстрактні класи МОЖУТЬ мати метод "main". public abstract class Animal { public abstract void makeSound(); - // Method can have a body + // Метод може мати тіло public void eat() { System.out.println("I am an animal and I am Eating."); - // Note: We can access private variable here. + // Зауваження: є доступ до privat змінних. age = 30; } - // No need to initialize, however in an interface - // a variable is implicitly final and hence has - // to be initialized. + // Ініціалізація не потрібна protected int age; public void printAge() @@ -632,7 +615,7 @@ public abstract class Animal System.out.println(age); } - // Abstract classes can have main function. + // Абстрактні класи МОЖУТЬ мати метод "main". public static void main(String[] args) { System.out.println("I am abstract"); @@ -641,20 +624,19 @@ public abstract class Animal class Dog extends Animal { - // Note still have to override the abstract methods in the - // abstract class. + // Слід помічати перевизначення абстрактних методів @Override public void makeSound() { System.out.println("Bark"); - // age = 30; ==> ERROR! age is private to Animal + // age = 30; ==> ПОМИЛКА! age є private для Animal } - // NOTE: You will get an error if you used the - // @Override annotation here, since java doesn't allow - // overriding of static methods. - // What is happening here is called METHOD HIDING. - // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ + // NOTE: Буде помилка, якщо використати аннотацію + // @Override тут, так як у java не можна + // перевизначати статичні методи. + // Те, що тут відбувається, називається METHOD HIDING. + // Більш детально: http://stackoverflow.com/questions/16313649/ public static void main(String[] args) { Dog pluto = new Dog(); @@ -664,22 +646,20 @@ class Dog extends Animal } } -// Final Classes +// Final класи -// Final Class declaration syntax -// final { -// // Constants and variables -// // Method declarations +// Синтаксис оголошення Final класів +// <рівень доступу> final <ім'я класу> { +// // Константи і змінні +// // Оголошення методів // } -// Final classes are classes that cannot be inherited from and are therefore a -// final child. In a way, final classes are the opposite of abstract classes -// because abstract classes must be extended, but final classes cannot be -// extended. +// Final не можуть мати нащадків, також самі вони є останніми нащадками. +// Final класи є протилежністю абстрактних у цьому плані. + public final class SaberToothedCat extends Animal { - // Note still have to override the abstract methods in the - // abstract class. + // Перевизначення методу @Override public void makeSound() { @@ -687,14 +667,14 @@ public final class SaberToothedCat extends Animal } } -// Final Methods +// Final методи public abstract class Mammal() { - // Final Method Syntax: - // final () + // Синтаксис Final методів: + // <модифікаор доступу> final <тип повернутого значення> <ім'я функції>(<аргументи>) - // Final methods, like, final classes cannot be overridden by a child class, - // and are therefore the final implementation of the method. + // Final методи не можуть бути перевизначені класом-нащадком, + // вони є остаточною реалізацією методу. public final boolean isWarmBlooded() { return true; @@ -702,21 +682,20 @@ public abstract class Mammal() } -// Enum Type +// Тип Enum (перелік) // -// An enum type is a special data type that enables for a variable to be a set -// of predefined constants. The variable must be equal to one of the values that -// have been predefined for it. Because they are constants, the names of an enum -// type's fields are in uppercase letters. In the Java programming language, you -// define an enum type by using the enum keyword. For example, you would specify -// a days-of-the-week enum type as: +// Enum є спеціальним типом даних, який дозволяє змінним бути певною множиною +// визначених констант. Змінна має відповідати одному зі значень, що +// заздалегідь визначені для неї. Так як це константи, імена типів полів у enum +// задаються у верхньому регістрі. У Java задається тип переліку за допомогою +// ключового слова. Наприклад, перелік днів тижня можна задати так: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } -// We can use our enum Day like that: +// Можна використовувати перелік Day так: public class EnumTest { @@ -756,13 +735,13 @@ public class EnumTest { } } -// Enum types are much more powerful than we show above. -// The enum body can include methods and other fields. -// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html +// Переліки набагато потужніші, ніж тут показано. +// Тіло переліків може містити методи та інші змінні. +// Дивіться більше тут: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html ``` -## Додатково для прочитання +## Додатково для читання The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. -- cgit v1.2.3 From 6a76bb326c246e3f78db6dbe35e879daafab7ed3 Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 31 Oct 2015 23:20:04 +0200 Subject: some bug fixing --- uk-ua/java-ua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index 63472b3f..3127f7f5 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -10,7 +10,7 @@ contributors: - ["Rachel Stiyer", "https://github.com/rstiyer"] translators: - ["Oleksandr Tatarchuk", "https://github.com/tatarchuk"] -filename: LearnJavaUa.java +filename: LearnJava.java lang: uk-ua --- -- cgit v1.2.3 From 3df055f2f71d7fe27186a9d61c1d8af66d2295d9 Mon Sep 17 00:00:00 2001 From: Oleksandr Tatarchuk Date: Sat, 14 Nov 2015 20:13:56 +0200 Subject: Added -ua to the filename In order to Java Code Conventions, LearnJavaUa.java --- uk-ua/java-ua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index 3127f7f5..63472b3f 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -10,7 +10,7 @@ contributors: - ["Rachel Stiyer", "https://github.com/rstiyer"] translators: - ["Oleksandr Tatarchuk", "https://github.com/tatarchuk"] -filename: LearnJava.java +filename: LearnJavaUa.java lang: uk-ua --- -- cgit v1.2.3 From 4c814b4df9bb73f200b2ab08e5660b6c74c5397f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=20Polykanine=20A=2EK=2EA=2E=20Menelion=20Elens=C3=BA?= =?UTF-8?q?l=C3=AB?= Date: Sat, 27 Feb 2016 18:24:20 +0200 Subject: [java/uk] Applied comments to #1969 --- uk-ua/java-ua.html.markdown | 293 ++++++++++++++++++++++---------------------- 1 file changed, 147 insertions(+), 146 deletions(-) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index 63472b3f..1ea30f3d 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -10,12 +10,13 @@ contributors: - ["Rachel Stiyer", "https://github.com/rstiyer"] translators: - ["Oleksandr Tatarchuk", "https://github.com/tatarchuk"] + - ["Andre Polykanine", "https://github.com/Oire"] filename: LearnJavaUa.java lang: uk-ua --- -Java є об'єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах. -[Read more here.](http://docs.oracle.com/javase/tutorial/java/) +Java є об’єктно-орієнтованою мовою програмування загального призначення з підтримкою паралельного програмування, яка базується на класах. +[Детальніше читайте тут, англ.](http://docs.oracle.com/javase/tutorial/java/) ```java // Однорядковий коментар починається з // @@ -23,31 +24,31 @@ Java є об'єктно-орієнтованою мовою програмува Багаторядковий коментар виглядає так. */ /** -JavaDoc коментар виглядає так. Використовується для опису класу та членів класу. +JavaDoc-коментар виглядає так. Використовується для опису класу та членів класу. */ -// Імпорт класу ArrayList з пакету java.util +// Імпорт класу ArrayList з пакета java.util import java.util.ArrayList; -// Імпорт усіх класів з пакету java.security +// Імпорт усіх класів з пакета java.security import java.security.*; -// Кожний .java файл містить один зовнішній публічний клас, ім'я якого співпадає -// з і менем файлу. +// Кожний .java файл містить один зовнішній публічний клас, ім’я якого співпадає +// з іменем файлу. public class LearnJava { // Для запуску програма, написана на java, повинна мати точку входу у вигляді методу main. public static void main (String[] args) { // Використання System.out.println() для виводу на друк рядків. - System.out.println("Hello World!"); + System.out.println("Привіт, світе!"); System.out.println( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); + " Ціле число: " + 10 + + " Число з рухомою комою подвійної точности: " + 3.14 + + " Булеве значення: " + true); - // Для друку з нового рядкка використовується System.out.print(). - System.out.print("Hello "); - System.out.print("World"); + // Для друку без переходу на новий рядок використовується System.out.print(). + System.out.print("Привіт, "); + System.out.print("світе"); // Використання System.out.printf() для простого форматованого виводу на друк. System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 @@ -61,60 +62,60 @@ public class LearnJava { */ // Для оголошення змінних використовується формат <тип> <змінна> int fooInt; - // Оголошення декількох змінних одного типу <тип> <ім'я1>, <ім'я2>, <ім'я3> + // Оголошення декількох змінних одного типу <тип> <ім’я1>, <ім’я2>, <ім’я3> int fooInt1, fooInt2, fooInt3; /* * Ініціалізація змінних */ - // Ініціалізація змінної з використанням формату <тип> <ім'я> = <значення> + // Ініціалізація змінної з використанням формату <тип> <ім’я> = <значення> int fooInt = 1; - // Ініціалізація декількох змінних одного типу з одним значенням <тип> <ім'я1>, <ім'я2>, <ім'я3> = <значення> + // Ініціалізація декількох змінних одного типу з одним значенням <тип> <ім’я1>, <ім’я2>, <ім’я3> = <значення> int fooInt1, fooInt2, fooInt3; fooInt1 = fooInt2 = fooInt3 = 1; /* * Типи змінних */ - // Байт - 8-бітне ціле число зі знаком + // Байт — 8-бітне ціле число зі знаком // (-128 <= byte <= 127) byte fooByte = 100; - // Short - 16-бітне ціле число зі знаком - // (-32,768 <= short <= 32,767) + // Short — 16-бітне ціле число зі знаком + // (-32 768 <= short <= 32 767) short fooShort = 10000; - // Integer - 32-бітне ціле число зі знаком - // (-2,147,483,648 <= int <= 2,147,483,647) + // Integer — 32-бітне ціле число зі знаком + // (-2 147 483 648 <= int <= 2 147 483 647) int fooInt = 1; - // Long - 64-бітне ціле число зі знаком - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + // Long — 64-бітне ціле число зі знаком + // (-9 223 372 036 854 775 808 <= long <= 9 223 372 036 854 775 807) long fooLong = 100000L; // L використовується для позначення того, що число має тип Long; // інакше число буде трактуватись як integer. // Примітка: Java не має беззнакових типів. - // Float - 32-бітне число з плаваючою комою одиничної точності за стандартом IEEE 754 + // Float — 32-бітне число з рухомою комою одиничної точності за стандартом IEEE 754 // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; - // f or F використовується для позначення того, що змінна має тип float; + // f або F використовується для позначення того, що змінна має тип float; // інакше трактується як double. - // Double - 64-бітне число з плаваючою комою подвійної точності за стандартом IEEE 754 + // Double — 64-бітне число з рухомою комою подвійної точності за стандартом IEEE 754 // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; - // Boolean - true & false (істина чи неправда) + // Boolean — true & false (істина чи хиба) boolean fooBoolean = true; boolean barBoolean = false; - // Char - 16-бітний символ Unicode + // Char — 16-бітний символ Unicode char fooChar = 'A'; - // final - посилання на такі змінні не можуть бути присвоєні іншим об'єктам, + // final - посилання на такі змінні не можуть бути присвоєні іншим об’єктам, final int HOURS_I_WORK_PER_WEEK = 9001; // але вони можуть мати відкладену ініціалізацію. final double E; @@ -123,25 +124,25 @@ public class LearnJava { // BigInteger -Незмінні знакові цілі числа довільної точності // - // BigInteger є типом даних, який дає можливість розробнику виконувати операції з + // BigInteger є типом даних, який дає можливість розробнику виконувати операції // з цілими числами, розрядність яких більша за 64 біти. Числа зберігаються у масиві - // байтів, операції над ними виконуються функціями, які має клас BigInteger + // байтів, операції над ними виконуються функціями, які мають клас BigInteger // // BigInteger можна ініціалізувати, використовуючи масив байтів чи рядок. BigInteger fooBigInteger = new BigInteger(fooByteArray); - // BigDecimal - Незмінні знакові дробові числа довільної точності + // BigDecimal — Незмінні знакові дробові числа довільної точності // // BigDecimal складається з двох частин: цілого числа довільної точності // з немасштабованим значенням та 32-бітного масштабованого цілого числа // - // BigDecimal дозволяє розробника контролювати десяткове округлення. - // Рекомндовано використовувати BigDecimal зі значеннями валют + // BigDecimal дозволяє розробникам контролювати десяткове округлення. + // Рекомендовано використовувати BigDecimal зі значеннями валют // і там, де необхідна точність дробових обчислень. // - // BigDecimal може бути ініціалізований типами даних int, long, double or String + // BigDecimal може бути ініціалізований типами даних int, long, double або String // чи немасштабованим значенням (BigInteger) і масштабованим значенням (int). BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); @@ -155,9 +156,9 @@ public class LearnJava { // Рядки String fooString = "Це мій рядок!"; - // \n символ переходу на новий рядок - String barString = "Друк з нового рялка?\nНема питань!"; - // \t символ табуляції + // \n є символом переходу на новий рядок + String barString = "Друк з нового рядка?\nНема питань!"; + // \t — це символ табуляції String bazString = "Хочете додати табуляцію?\tТримайте!"; System.out.println(fooString); System.out.println(barString); @@ -166,8 +167,8 @@ public class LearnJava { // Масиви // Розмір масиву має бути визначений перед ініціалізацією // Наведений формат ілюструє ініціалізацію масивів - // <тип даних>[] <ім'я змінної> = new <тип даних>[<розмір масиву>]; - // <тип даних> <ім'я змінної>[] = new <тип даних>[<розмір масиву>]; + // <тип даних>[] <ім’я змінної> = new <тип даних>[<розмір масиву>]; + // <тип даних> <ім’я змінної>[] = new <тип даних>[<розмір масиву>]; int[] intArray = new int[10]; String[] stringArray = new String[1]; boolean boolArray[] = new boolean[100]; @@ -177,7 +178,7 @@ public class LearnJava { String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; boolean bools[] = new boolean[] {true, false, false}; - // Індексація масиву - доступ за елементами + // Індексація масиву — доступ за елементами System.out.println("intArray @ 0: " + intArray[0]); // Масиви є змінними та мають нульовий елемент. @@ -185,28 +186,28 @@ public class LearnJava { System.out.println("intArray @ 1: " + intArray[1]); // => 1 // Додатково - // ArrayLists - Схожі на масив, але мають більший функціонал та змінний розмір. - // LinkedLists - Реалізація двозв'язного списку. Всі операції + // ArrayLists — Схожі на масив, але мають більший функціонал та змінний розмір. + // LinkedLists — Реалізація двозв’язного списку. Всі операції // виконуються так, як очікується від - // двозв'язного списку. - // Maps - Множина об'єктів, які пов'язують ключ зі значенням. Map є + // двозв’язного списку. + // Maps — Множина об’єктів, які пов’язують ключ зі значенням. Map є // інтерфейсом, тому не може бути успадкований. - // Типи ключів і значень, які зберігаються в Map мають + // Типи ключів і значень, які зберігаються в Map, мають // вказуватись у класі, який його реалізує. - // Ключ не може повторюватись і пов'язаний лише з одним значенням - // HashMaps - Цей клас використовує хеш-таблицю для реалізації інтерфейсу Map. + // Ключ не може повторюватись і пов’язаний лише з одним значенням + // HashMaps — Цей клас використовує хеш-таблицю для реалізації інтерфейсу Map. // Це дозволяє виконувати певні операції, - // такі як отримання та вставка елемента, - // за сталий час для будь-якої кількості значень. + // такі, як отримання та вставка елемента, + // залишаючись постійними навіть для великої кількості елементів. /////////////////////////////////////// // Оператори /////////////////////////////////////// - System.out.println("\n->Operators"); + System.out.println("\n->Оператори"); int i1 = 1, i2 = 2; // Коротка форма присвоєння - // Арифметичні операції виконуються + // Арифметичні операції виконуються очевидним способом System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 @@ -240,30 +241,30 @@ public class LearnJava { | Бітове АБО */ - // Інкремнт + // Інкремент int i = 0; System.out.println("\n->Інкремент/Декремент"); // Оператори ++ і -- здійснюють інкремент та декремент ретроспективно. // Якщо вони розташовані перед змінною, операція виконається перед поверненням; - // після - повернеться інкремент або декремент. - System.out.println(i++); // i = 1, prints 0 (post-increment) - System.out.println(++i); // i = 2, prints 2 (pre-increment) - System.out.println(i--); // i = 1, prints 2 (post-decrement) - System.out.println(--i); // i = 0, prints 0 (pre-decrement) + // якщо після неї — повернеться інкремент або декремент. + System.out.println(i++); // i = 1, друкує 0 (постінкремент) + System.out.println(++i); // i = 2, друкує 2 (преінкремент) + System.out.println(i--); // i = 1, друкує 2 (постдекремент) + System.out.println(--i); // i = 0, друкує 0 (предекремент) /////////////////////////////////////// - // Управляючі конструкції + // Керуючі конструкції /////////////////////////////////////// - System.out.println("\n->Control Structures"); + System.out.println("\n->Керуючі конструкції"); - // Оператор if використовується так само, як у мові С + // Оператор if використовується так само, як у мові C int j = 10; if (j == 10) { System.out.println("Це надрукується"); } else if (j > 10) { - System.out.println("А це - ні"); + System.out.println("А це — ні"); } else { - System.out.println("Це - також ні"); + System.out.println("Це — також ні"); } // Цикл з передумовою While @@ -284,7 +285,7 @@ public class LearnJava { // Виконається 99 разів, fooDoWhile 0->99 fooDoWhile++; } while(fooDoWhile < 100); - System.out.println("fooDoWhile Value: " + fooDoWhile); + System.out.println("Значення fooDoWhile: " + fooDoWhile); // Цикл з параметром For // структура циклу => for(<початковий стан>; <умова завершення>; <крок>) @@ -292,9 +293,9 @@ public class LearnJava { System.out.println(fooFor); // Виконається 10 разів, fooFor 0->9 } - System.out.println("fooFor Value: " + fooFor); + System.out.println("Значення fooFor: " + fooFor); - // Вихід з вкладеного циклу через Label + // Вихід із вкладеного циклу через мітку outer: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { @@ -311,7 +312,7 @@ public class LearnJava { for (int bar : fooList) { System.out.println(bar); - //Iterates 9 times and prints 1-9 on new lines + // Повторюється 9 разів та друкує числа від 1 до 9 на нових рядках } // Оператор вибору Switch Case @@ -331,29 +332,29 @@ public class LearnJava { default: monthString = "Інший місяць"; break; } - System.out.println("Switch Case результат: " + monthString); + System.out.println("Результат Switch Case: " + monthString); // Починаючи з Java 7 і далі, вибір рядкових змінних здійснюється так: - String myAnswer = "maybe"; + String myAnswer = "можливо"; switch(myAnswer) { - case "yes": - System.out.println("You answered yes."); + case "так": + System.out.println("Ви відповіли «Так»."); break; - case "no": - System.out.println("You answered no."); + case "ні": + System.out.println("Ви відповіли «ні»."); break; - case "maybe": - System.out.println("You answered maybe."); + case "можливо": + System.out.println("Ви відповіли «Можливо»."); break; default: - System.out.println("You answered " + myAnswer); + System.out.println("Ви відповіли «" + myAnswer + "»"); break; } // Тернарний оператор вибору - // Можна використовувати '?' оператор для визначення умови. - // Читається так "Якщо (умова) вірна, то <перше значення>, інакше - // <друге значення" + // Можна використовувати оператор «?» (знак питання) для визначення умови. + // Читається так: «Якщо (умова) вірна, то <перше значення>, інакше + // <друге значення>» int foo = 5; String bar = (foo < 10) ? "A" : "B"; System.out.println(bar); // Надрукується А, бо умова вірна @@ -375,7 +376,7 @@ public class LearnJava { // String // Приведення типів - // Тут можна прочитати про приведення об'єктів: + // Тут можна прочитати про приведення об’єктів (англ.): // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html @@ -383,19 +384,19 @@ public class LearnJava { // Класи та функції /////////////////////////////////////// - System.out.println("\n->Classes & Functions"); + System.out.println("\n->Класи та функції"); // (Клас Bicycle наведений нижче) - // Новий об'єкт класу + // Новий об’єкт класу Bicycle trek = new Bicycle(); - // Виклик методу об'єкта + // Виклик методу об’єкта trek.speedUp(3); // Постійно використовуються методи з назвами set і get trek.setCadence(100); - // toString повертає рядкове представленя об'єкту. - System.out.println("trek info: " + trek.toString()); + // toString повертає рядкове представлення об’єкту. + System.out.println("Інформація про об’єкт trek: " + trek.toString()); // У Java немає синтаксису для явного створення статичних колекцій. // Це можна зробити так: @@ -407,7 +408,7 @@ public class LearnJava { validCodes.add("FINLAND"); } - // Але є інший спосіб - Double Brace Initialization. + // Але є інший спосіб — ініціалізація з подвійними фігурними дужками. private static final Set COUNTRIES = new HashSet() {{ add("DENMARK"); @@ -421,12 +422,12 @@ public class LearnJava { } // Кінець класу LearnJava -// Можна додавати інші, не public класи зовнішнього рівня у .java файл, +// У .java-файл можна додавати інші, не public класи зовнішнього рівня, // але це не є хорошою практикою. Розміщуйте класи в окремих файлах. // Синтаксис оголошення класу: -// class { +// class <ім’я класу> { // // поля, конструктори, функції та ін. // // у Java функції називаються методами. // } @@ -436,8 +437,8 @@ class Bicycle { // Поля (змінні) класу Bicycle public int cadence; // Public: доступно звідусіль private int speed; // Private: доступно лише у межах класу - protected int gear; // Protected: доступно лише класу та нащадкам - String name; // default: доступно у даному пакеті + protected int gear; // Protected: доступно лише класові та його нащадкам + String name; // за замовчанням: доступно у даному пакеті static String className; // статична змінна класу @@ -450,7 +451,7 @@ class Bicycle { } // Конструктори є способом створення класу - // Це - конструктор + // Оце — конструктор public Bicycle() { // Можна викликати інший конструктор: // this(1, 50, 5, "Bontrager"); @@ -470,17 +471,17 @@ class Bicycle { } // Синтаксис методу: - // <тип повернутого значення> <ім'я методу>(<аргументи>) + // <тип повернутого значення> <ім’я методу>(<аргументи>) - // Java класи часто мають методи для отримання та встановлення змінних + // Java-класи часто мають методи для отримання та встановлення змінних // Синтаксис оголошення методу: - // <модифікатор доступу> <тип повернутого значення> <ім'я методу>(<аргументи>) + // <модифікатор доступу> <тип повернутого значення> <ім’я методу>(<аргументи>) public int getCadence() { return cadence; } - // void методи не повертають значень + // void-методи не повертають значень public void setCadence(int newValue) { cadence = newValue; } @@ -505,8 +506,8 @@ class Bicycle { return name; } - //Метод показує значення змінних об'єкту. - @Override // Inherited from the Object class. + //Метод показує значення змінних об’єкту. + @Override // Успадковано від класу Object. public String toString() { return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + " name: " + name; @@ -523,9 +524,9 @@ class PennyFarthing extends Bicycle { super(startCadence, startSpeed, 0, "PennyFarthing"); } - // Перевизначений метод має відти відмічений аннотацією @annotation. + // Перевизначений метод має бути відмічений аннотацією, яка починається зі знака @. // Для ознайомлення з аннотаціями перейдіть за посиланням - // out: http://docs.oracle.com/javase/tutorial/java/annotations/ + // http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { gear = 0; @@ -534,14 +535,14 @@ class PennyFarthing extends Bicycle { // Інтерфейси // Синтаксис оголошення інтерфейсів -// <рівень доступу> interface <ім'я інтерфейсу> extends <супер-інтерфейс> { -// // Констатнти +// <рівень доступу> interface <ім’я інтерфейсу> extends <батьківський інтерфейс> { +// // Константи // // Оголошення методів // } -//Приклад - Food: +//Приклад — їжа (Food): public interface Edible { - public void eat(); // Будь-які класи, що реалізують цей інтерфейс + public void eat(); // Будь-які класи, що реалізують цей інтерфейс, // повинні реалізувати цей метод. } @@ -582,18 +583,18 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // Абстрактні класи // Синтаксис оголошення абстрактних класів: -// <ріаень доступу> abstract <ім1я класу> extends <супер-абстрактний клас> { +// <рівень доступу> abstract <ім’я класу> extends <батьківський абстрактний клас> { // // Константи і змінні // // Оголошення методів // } // Позначення класу як абстрактного означає, що оголошені у ньому методи мають // бути реалізовані у дочірніх класах. Подібно до інтерфейсів, не можна створити екземпляри -// абстракних класів, але їх можна успадковувати. Нащадок зобов'язаний реалізувати всі абстрактні +// абстракних класів, але їх можна успадковувати. Нащадок зобов’язаний реалізувати всі абстрактні // методи. на відміну від інтерфейсів, абстрактні класи можуть мати як визначені, // так і абстрактні методи. Методи в інтерфейсах не мають тіла, -// за вийнятком статичних методів, а змінні неявно мають модифікатор final, на відміну від -// абстрактного класу. Абстрактні класи МОЖУТЬ мати метод "main". +// за винятком статичних методів, а змінні неявно мають модифікатор final, на відміну від +// абстрактного класу. Абстрактні класи МОЖУТЬ мати метод «main». public abstract class Animal { @@ -602,8 +603,8 @@ public abstract class Animal // Метод може мати тіло public void eat() { - System.out.println("I am an animal and I am Eating."); - // Зауваження: є доступ до privat змінних. + System.out.println("Я тварина, і я їм."); + // Зауваження: є доступ до приватних змінних. age = 30; } @@ -615,10 +616,10 @@ public abstract class Animal System.out.println(age); } - // Абстрактні класи МОЖУТЬ мати метод "main". + // Абстрактні класи МОЖУТЬ мати метод «main». public static void main(String[] args) { - System.out.println("I am abstract"); + System.out.println("Я абстрактний"); } } @@ -628,14 +629,14 @@ class Dog extends Animal @Override public void makeSound() { - System.out.println("Bark"); + System.out.println("Гав!"); // age = 30; ==> ПОМИЛКА! age є private для Animal } - // NOTE: Буде помилка, якщо використати аннотацію + // Зауваження: Буде помилка, якщо використати аннотацію // @Override тут, так як у java не можна // перевизначати статичні методи. - // Те, що тут відбувається, називається METHOD HIDING. + // Те, що тут відбувається, називається приховування методів. // Більш детально: http://stackoverflow.com/questions/16313649/ public static void main(String[] args) { @@ -646,16 +647,16 @@ class Dog extends Animal } } -// Final класи +// Фінальні класи -// Синтаксис оголошення Final класів -// <рівень доступу> final <ім'я класу> { +// Синтаксис оголошення фінальних класів +// <рівень доступу> final <ім’я класу> { // // Константи і змінні // // Оголошення методів // } -// Final не можуть мати нащадків, також самі вони є останніми нащадками. -// Final класи є протилежністю абстрактних у цьому плані. +// Фінальні класи не можуть мати нащадків, також самі вони є останніми нащадками. +// Фінальні класи є протилежністю абстрактних у цьому плані. public final class SaberToothedCat extends Animal { @@ -663,17 +664,17 @@ public final class SaberToothedCat extends Animal @Override public void makeSound() { - System.out.println("Roar"); + System.out.println("Гррр!"); } } -// Final методи +// Фінальні методи public abstract class Mammal() { - // Синтаксис Final методів: - // <модифікаор доступу> final <тип повернутого значення> <ім'я функції>(<аргументи>) + // Синтаксис фінальних методів: + // <модифікатор доступу> final <тип повернутого значення> <ім’я функції>(<аргументи>) - // Final методи не можуть бути перевизначені класом-нащадком, + // Фінальні методи не можуть бути перевизначені класом-нащадком, // вони є остаточною реалізацією методу. public final boolean isWarmBlooded() { @@ -686,20 +687,20 @@ public abstract class Mammal() // // Enum є спеціальним типом даних, який дозволяє змінним бути певною множиною // визначених констант. Змінна має відповідати одному зі значень, що -// заздалегідь визначені для неї. Так як це константи, імена типів полів у enum -// задаються у верхньому регістрі. У Java задається тип переліку за допомогою -// ключового слова. Наприклад, перелік днів тижня можна задати так: +// заздалегідь визначені для неї. Оскільки це константи, імена типів полів у enum +// задаються у верхньому регістрі. Тип «перелік» у Java задається за допомогою +// ключового слова enum. Наприклад, перелік днів тижня можна задати так: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } -// Можна використовувати перелік Day так: +// Перелік Day можна використовувати так: public class EnumTest { - // Variable Enum + // Змінна того же типу, що й перелік Day day; public EnumTest(Day day) { @@ -709,29 +710,29 @@ public class EnumTest { public void tellItLikeItIs() { switch (day) { case MONDAY: - System.out.println("Mondays are bad."); + System.out.println("Понеділкі важкі."); break; case FRIDAY: - System.out.println("Fridays are better."); + System.out.println("П’ятниці краще."); break; case SATURDAY: case SUNDAY: - System.out.println("Weekends are best."); + System.out.println("Вихідні найліпші."); break; default: - System.out.println("Midweek days are so-so."); + System.out.println("Середина тижня так собі."); break; } } public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); - firstDay.tellItLikeItIs(); // => Mondays are bad. + firstDay.tellItLikeItIs(); // => Понеділки важкі. EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); - thirdDay.tellItLikeItIs(); // => Midweek days are so-so. + thirdDay.tellItLikeItIs(); // => Середина тижня так собі. } } @@ -743,18 +744,18 @@ public class EnumTest { ## Додатково для читання -The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. +Посилання, наведені нижче, дозволяють тільки зрозуміти тему. Щоб знайти конкретні приклади, використовуйте Ґуґл. **Офіційні посібники Oracle**: -* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) +* [Посібник Java від Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) -* [Java модифікатори доступу](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) +* [Java — модифікатори доступу](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) -* [ООП концепції](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): - * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) - * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) - * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) +* [ООП-концепції](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Наслідування](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Поліморфізм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Абстракція](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) * [Виключення](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) @@ -762,11 +763,11 @@ The links provided here below are just to get an understanding of the topic, fee * [параметризація](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) +* [Стиль коду у Java](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) -**Online практика та посібники** +**Online-практика та посібники** -* [Learneroo.com - Learn Java](http://www.learneroo.com) +* [Learneroo.com — Вивчаємо Java](http://www.learneroo.com) * [Codingbat.com](http://codingbat.com/java) -- cgit v1.2.3 From 952a7da82a30d4509d0d5aa8cfc61e63f6b11ce5 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sat, 27 Feb 2016 15:38:22 -0700 Subject: [purescript/en] comparisions -> comparisons --- purescript.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/purescript.html.markdown b/purescript.html.markdown index 7dd97a18..b413a9e3 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -48,7 +48,7 @@ not true -- false 23 == 23 -- true 1 /= 4 -- true 1 >= 4 -- false --- Comparisions < <= > >= +-- Comparisons < <= > >= -- are defined in terms of compare compare 1 2 -- LT compare 2 2 -- EQ @@ -62,7 +62,7 @@ true && (9 >= 19 || 1 < 2) -- true "Hellow\ \orld" -- "Helloworld" -- Multiline string with newlines -"""Hello +"""Hello world""" -- "Hello\nworld" -- Concatenate "such " ++ "amaze" -- "such amaze" @@ -208,4 +208,3 @@ any even [1,2,3] -- true all even [1,2,3] -- false ``` - -- cgit v1.2.3 From 878bd1a68d51077f918f82bae9cdc9a570ed10e6 Mon Sep 17 00:00:00 2001 From: Fadil Mamedov Date: Thu, 23 Jul 2015 16:34:07 +0300 Subject: [typescript/ru] Russian translation of the TypeScript article --- ru-ru/typescript-ru.html.markdown | 171 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 ru-ru/typescript-ru.html.markdown diff --git a/ru-ru/typescript-ru.html.markdown b/ru-ru/typescript-ru.html.markdown new file mode 100644 index 00000000..fe1653ff --- /dev/null +++ b/ru-ru/typescript-ru.html.markdown @@ -0,0 +1,171 @@ +--- +language: TypeScript +lang: ru-ru +contributors: + - ["Fadil Mamedov", "https://github.com/fadilmamedov"] +filename: learntypescript-ru.ts +--- + +TypeScript - это язык программирования, целью которого является легкая разработка широко-масштабируемых JavaScript приложений. +TypeScript добавляет общие концепции, такие как классы, модули, интерфейсы, дженерики и (опционально) статическую типизацию в JavaScript. +Это надмножество языка JavaScript: весь JavaScript код является валидным TypeScript кодом, следовательно может быть добавлен бесшовно в любой проект. +Компилятор TypeScript генерирует JavaScript код. + +Эта статья концентрируется только на синтаксисе TypeScript, в противовес статьте о [JavaScript](../javascript/). + +Для тестирования компилятора TypeScript, пройдите по ссылке в [песочницу](http://www.typescriptlang.org/Playground). +Там вы можете написать код (с поддержкой автодополнения) и сразу же увидеть сгенерированный JavaScript код. + +```js +// В TypeScript есть 3 базовых типа +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Тип "Any" для случаев, когда заранее неизвестен тип переменной +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // а теперь логический тип + +// Для коллекций есть типизированные массивы и дженерик-массивы +var list: number[] = [1, 2, 3]; +// Как альтернатива, использование дженерик-массива +var list: Array = [1, 2, 3]; + +// Для перечислений: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Наконец, "void" используется для обозначения того, что функция ничего не возвращает +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Функции - это первый члены класса. Они поддерживают лябмда-синтаксис (=>) +// и используют интерфейс типа + +// Следующий строки кода являются эквивалентными, компилятором предполагается +// одинаковая сигнатура, на выходе генерируется одинаковый JavaScript код +var f1 = function(i: number): number { return i * i; } +// Предполагается возвращаемый тип +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Предполагается возвращаемый тип +var f4 = (i: number) => { return i * i; } +// Return type inferred, one-liner means no return keyword needed +// Предполагается возвращаемый тип, ключевое слово "return" не нужно +var f5 = (i: number) => i * i; + +// Интерфейсы являются структурными; все, что имеет свойства совместимо в интерфейсом +interface Person { + name: string; + // Опциональные свойства, помеченные символом "?" + age?: number; + // И конечно функции + move(): void; +} + +// Объект, который реализует интерфейс "Person" +// К нему можно обращаться как к "Person", так как он имеет свойства "name" и "move" +var p: Person = { name: "Bobby", move: () => {} }; +// Объекты, которые могут иметь опциональные свойства: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Это не "Person", поскольку "age" не является числовым значением +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Интерфейсы могут также описывать функциональный тип +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Важны только типы параметров, имена - нет. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Классы - члены класса по умолчанию являются публичными +class Point { + // Свойства + x: number; + + // Конструктор - ключевые слова public/private в данном контексте сгенерируют + // шаблонный код для свойства и для инициализации в конструкторе + // В данном примере, "y" будет определен также как и "x", но меньшим количеством кода + // Значения по умолчанию также поддерживаются + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Функции + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Статические члены + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y will be 0 + +// Наследование +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Явный вызов конструктора базового класса обязателен + } + + // Перегрузка + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Модули, "." может быть использован как разделитель для обозначения подмодулей +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Локальный псевдоним для ссылки на модуль +import G = Geometry; + +var s2 = new G.Square(10); + +// Дженерики +// Классы +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Интерфейсы +interface Pair { + item1: T; + item2: T; +} + +// И функции +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Включение ссылки на файл определения: +/// + +``` + +## Для дальнейшего чтения + * [Официальный веб-сайт TypeScript](http://www.typescriptlang.org/) + * [Спецификация языка TypeScript (pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript на Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Исходный код на GitHub](https://github.com/Microsoft/TypeScript) + * [Definitely Typed - репозиторий определений типов](http://definitelytyped.org/) -- cgit v1.2.3 From d80f8d2c80156f2d24532509fbdca24252f18f02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=20Polykanine=20A=2EK=2EA=2E=20Menelion=20Elens=C3=BA?= =?UTF-8?q?l=C3=AB?= Date: Sun, 28 Feb 2016 16:11:06 +0200 Subject: Applied comments to #1173 --- ru-ru/typescript-ru.html.markdown | 78 ++++++++++++++++++++------------------- 1 file changed, 40 insertions(+), 38 deletions(-) diff --git a/ru-ru/typescript-ru.html.markdown b/ru-ru/typescript-ru.html.markdown index fe1653ff..67b58a38 100644 --- a/ru-ru/typescript-ru.html.markdown +++ b/ru-ru/typescript-ru.html.markdown @@ -2,95 +2,97 @@ language: TypeScript lang: ru-ru contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: - ["Fadil Mamedov", "https://github.com/fadilmamedov"] + - "Andre Polykanine", "https://github.com/Oire"] filename: learntypescript-ru.ts --- -TypeScript - это язык программирования, целью которого является легкая разработка широко-масштабируемых JavaScript приложений. -TypeScript добавляет общие концепции, такие как классы, модули, интерфейсы, дженерики и (опционально) статическую типизацию в JavaScript. -Это надмножество языка JavaScript: весь JavaScript код является валидным TypeScript кодом, следовательно может быть добавлен бесшовно в любой проект. -Компилятор TypeScript генерирует JavaScript код. +TypeScript — это язык программирования, целью которого является лёгкая разработка широкомасштабируемых JavaScript-приложений. +TypeScript добавляет в Javascript общие концепции, такие, как классы, модули, интерфейсы, обобщённое программирование и (опционально) статическую типизацию. +Это надмножество языка JavaScript: весь JavaScript-код является валидным TypeScript-кодом, следовательно, может быть добавлен бесшовно в любой проект. +Компилятор TypeScript генерирует JavaScript-код. -Эта статья концентрируется только на синтаксисе TypeScript, в противовес статьте о [JavaScript](../javascript/). +Эта статья концентрируется только на синтаксисе TypeScript, в противовес статье о [JavaScript](javascript-ru/). -Для тестирования компилятора TypeScript, пройдите по ссылке в [песочницу](http://www.typescriptlang.org/Playground). +Для тестирования компилятора TypeScript пройдите по ссылке в [песочницу](http://www.typescriptlang.org/Playground). Там вы можете написать код (с поддержкой автодополнения) и сразу же увидеть сгенерированный JavaScript код. ```js // В TypeScript есть 3 базовых типа var isDone: boolean = false; var lines: number = 42; -var name: string = "Anders"; +var name: string = "Андерс"; -// Тип "Any" для случаев, когда заранее неизвестен тип переменной +// Тип «any» для случаев, когда заранее неизвестен тип переменной var notSure: any = 4; -notSure = "maybe a string instead"; +notSure = "а может быть, строка"; notSure = false; // а теперь логический тип -// Для коллекций есть типизированные массивы и дженерик-массивы +// Для коллекций есть типизированные массивы и обобщённые массивы var list: number[] = [1, 2, 3]; -// Как альтернатива, использование дженерик-массива +// Как альтернатива, использование обобщённого массива var list: Array = [1, 2, 3]; -// Для перечислений: +// Перечисления: enum Color {Red, Green, Blue}; var c: Color = Color.Green; -// Наконец, "void" используется для обозначения того, что функция ничего не возвращает +// Наконец, «void» используется для обозначения того, что функция ничего не возвращает function bigHorribleAlert(): void { - alert("I'm a little annoying box!"); + alert("Я маленькое надоедливое окошко!"); } -// Функции - это первый члены класса. Они поддерживают лябмда-синтаксис (=>) -// и используют интерфейс типа +// Функции — это объекты первого класса. Они поддерживают лямбда-синтаксис (=>) +// и используют вывод типов (type inference) -// Следующий строки кода являются эквивалентными, компилятором предполагается -// одинаковая сигнатура, на выходе генерируется одинаковый JavaScript код +// Следующие строки кода являются эквивалентными, компилятором предполагается +// одинаковая сигнатура, на выходе генерируется одинаковый JavaScript-код var f1 = function(i: number): number { return i * i; } // Предполагается возвращаемый тип var f2 = function(i: number) { return i * i; } var f3 = (i: number): number => { return i * i; } // Предполагается возвращаемый тип var f4 = (i: number) => { return i * i; } -// Return type inferred, one-liner means no return keyword needed -// Предполагается возвращаемый тип, ключевое слово "return" не нужно +// Предполагается возвращаемый тип, в однострочной функции ключевое слово «return» не нужно var f5 = (i: number) => i * i; -// Интерфейсы являются структурными; все, что имеет свойства совместимо в интерфейсом +// Интерфейсы являются структурными; всё, что имеет свойства, совместимо с интерфейсом interface Person { name: string; - // Опциональные свойства, помеченные символом "?" + // Опциональные свойства, помеченные символом «?» age?: number; - // И конечно функции + // И, конечно, функции move(): void; } -// Объект, который реализует интерфейс "Person" -// К нему можно обращаться как к "Person", так как он имеет свойства "name" и "move" -var p: Person = { name: "Bobby", move: () => {} }; +// Объект, который реализует интерфейс «Person» +// К нему можно обращаться, как к «Person», так как он имеет свойства «name» и «move» +var p: Person = { name: "Бобби", move: () => {} }; // Объекты, которые могут иметь опциональные свойства: -var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; -// Это не "Person", поскольку "age" не является числовым значением -var invalidPerson: Person = { name: "Bobby", age: true }; +var validPerson: Person = { name: "Бобби", age: 42, move: () => {} }; +// Это не «Person», поскольку «age» не является числовым значением +var invalidPerson: Person = { name: "Бобби", age: true }; // Интерфейсы могут также описывать функциональный тип interface SearchFunc { (source: string, subString: string): boolean; } -// Важны только типы параметров, имена - нет. +// Важны только типы параметров, имена — нет. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; } -// Классы - члены класса по умолчанию являются публичными +// Классы. Члены класса по умолчанию являются публичными class Point { // Свойства x: number; - // Конструктор - ключевые слова public/private в данном контексте сгенерируют + // Конструктор — ключевые слова public/private в данном контексте сгенерируют // шаблонный код для свойства и для инициализации в конструкторе - // В данном примере, "y" будет определен также как и "x", но меньшим количеством кода + // В данном примере «y» будет определён так же, как и «x», но меньшим количеством кода // Значения по умолчанию также поддерживаются constructor(x: number, public y: number = 0) { @@ -105,7 +107,7 @@ class Point { } var p1 = new Point(10 ,20); -var p2 = new Point(25); //y will be 0 +var p2 = new Point(25); //y будет равен 0 // Наследование class Point3D extends Point { @@ -120,7 +122,7 @@ class Point3D extends Point { } } -// Модули, "." может быть использован как разделитель для обозначения подмодулей +// Модули, знак «.» может быть использован как разделитель для обозначения подмодулей module Geometry { export class Square { constructor(public sideLength: number = 0) { @@ -138,7 +140,7 @@ import G = Geometry; var s2 = new G.Square(10); -// Дженерики +// Обобщённое программирование // Классы class Tuple { constructor(public item1: T1, public item2: T2) { @@ -166,6 +168,6 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); ## Для дальнейшего чтения * [Официальный веб-сайт TypeScript](http://www.typescriptlang.org/) * [Спецификация языка TypeScript (pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) - * [Anders Hejlsberg - Introducing TypeScript на Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Anders Hejlsberg — Introducing TypeScript на Channel 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) * [Исходный код на GitHub](https://github.com/Microsoft/TypeScript) - * [Definitely Typed - репозиторий определений типов](http://definitelytyped.org/) + * [Definitely Typed — репозиторий определений типов](http://definitelytyped.org/) -- cgit v1.2.3 From 9f6ecfddd2237a55cd5d9087b7bd48fe6688c2b2 Mon Sep 17 00:00:00 2001 From: Taesung Jung Date: Wed, 17 Feb 2016 15:11:43 -0800 Subject: adds Korean translation for Erlang --- ko-kr/erlang-kr.html.markdown | 333 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 333 insertions(+) create mode 100644 ko-kr/erlang-kr.html.markdown diff --git a/ko-kr/erlang-kr.html.markdown b/ko-kr/erlang-kr.html.markdown new file mode 100644 index 00000000..b0b1dd2a --- /dev/null +++ b/ko-kr/erlang-kr.html.markdown @@ -0,0 +1,333 @@ +--- +language: erlang +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +filename: learnerlang-kr.erl +translators: + - ["Taesung Jung", "https://github.com/tsj"] +lang: ko-kr +--- + +```erlang +% 퍼센트 기호는 한 줄 주석을 시작한다. + +%% 두 개의 퍼센트 문자는 함수의 주석에 사용된다. + +%%% 세 개의 퍼센트 문자는 모듈의 주석에 사용된다. + +% Erlang에선 3가지 유형의 문장 부호를 사용한다. +% 쉼표(`,`)는 함수 호출에서 인수, 데이터 생성자(constructors), 패턴을 구분한다. +% 마침표(`.`)(다음에 오는 공백)는 셸에서 함수 전체와 식을 구분한다. +% 세미콜론(`;`)은 절을 구분한다. 몇 가지 문맥(contexts)에서 절이 발견된다: +% 함수 정의와 `case`, `if`, `try..catch`, 그리고 `receive` 식 + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. 변수와 패턴 매칭 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang에서 새로운 변수는 `=` 문장에 의해 바인딩 된다. +Num = 42. % 모든 변수 이름은 반드시 대문자로 시작해야 한다. + +% Erlang은 단일 할당 변수(single-assignment variables)를 가진다; +% 만약 다른 값을 `Num` 변수에 할당하려고 시도하면 오류가 발생한다. +Num = 43. % ** 예외 오류: 우변의 값 43과 매칭되지 않음 + +% 대부분 언어에서 `=`는 할당문을 나타낸다. 그러나 Erlang에서 +% `=`는 패턴 매칭 연산자를 나타낸다. 비어 있는 변수가 `=` 연산자의 좌변에 +% 사용되면 바인드(할당) 된다, 그러나 바인드 변수가 좌변에 사용된 경우에 +% 다음 행동은 그 바인드 변수가 관측된다. +% `Lhs = Rhs`의 진짜 의미: 우변(`Rhs`)을 평가하고, 그리고 +% 그 결과를 좌변(`Lhs`)의 패턴과 매치시켜라. +Num = 7 * 6. + +% 부동 소수점 수. +Pi = 3.14159. + +% Atom은 숫자가 아닌 서로 다른 상숫값을 표현하는 데 사용한다. Atom은 +% 소문자로 시작하고, 연속적인 영숫자(alphanumeric) 문자나 밑줄(`_`) 또는 +% 골뱅이(`@`) 기호가 따라온다. +Hello = hello. +OtherNode = example@node. + +% 영숫자 값이 아닌 Atom은 작은따옴표로 묶여서 작성될 수 있다. +AtomWithSpace = 'some atom with space'. + +% Tuple은 C의 struct와 비슷하다. +Point = {point, 10, 45}. + +% Tuple에서 어떤 값을 추출하려면, 패턴 매칭 연산자 `=`를 사용한다. +{point, X, Y} = Point. % X = 10, Y = 45 + +% 관심 없는 변수를 위해 자리 표시자(placeholder) `_`를 사용할 수 있다. +% 기호 `_`는 익명 변수(anonymous variable)라 부른다. 일반적인 변수들과 +% 다르게 같은 패턴에서 여러 번 나오더라도 동일한 값으로 바인드되지 않아도 된다. +Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. +{_, {_, {_, Who}, _}, _} = Person. % Who = joe + +% List를 만들기 위해서 List의 원소는 대괄호([])로 둘러싸고 쉼표(,)로 구분한다. +% List의 각각의 원소는 어떤 타입도 가능하다. +% List의 첫 번째 원소는 List의 HEAD이다. 만약 List의 HEAD를 제거하면, +% 남은 부분은 List의 TAIL이라 부른다. +ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. + +% 만약 `T`가 List이면, `[H|T]`도 HEAD가 `H`이고 TAIL이 `T`인 List이다. +% 세로 막대(`|`)는 List의 HEAD와 TAIL을 분리한다. `[]`는 빈 List다. +% List의 원소들은 패턴 매칭 연산으로 추출할 수 있다. +% 만약 비어있지 않은 List `L`이 있을 때, `[X|Y] = L` 식의 `X`와 `Y`가 +% 바인드되지 않은 변수이면, List의 HEAD는 X에 그리고 TAIL은 Y로 추출된다. +[FirstThing|OtherThingsToBuy] = ThingsToBuy. +% FirstThing = {apples, 10} +% OtherThingsToBuy = [{pears, 6}, {milk, 3}] + +% Erlang에는 문자열(String)이 없다. 문자열은 사실 정수의 List일 뿐이다. +% 문자열은 큰따옴표(`"`)로 묶인다. +Name = "Hello". +[72, 101, 108, 108, 111] = "Hello". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. 순차 프로그래밍 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang에서 Module은 코드의 기본 단위이다. 우리가 작성한 모든 함수는 +% Module에 담긴다. Module은 확장자가 `.erl`인 파일에 저장된다. +% 코드가 실행되기 전에 Module은 컴파일되어야 한다. 컴파일된 Module은 +% `.beam` 확장자를 가진다. +-module(geometry). +-export([area/1]). % Module로부터 내보내진(exported) 함수의 List + +% 함수 `area`는 두 개의 절로 구성된다. 절은 세미콜론(`;`)으로 구분되며, +% 마지막 절은 마침표-공백(dot-whitespace)으로 끝난다. +% 각 절은 서문(head)과 본문(body)을 가진다. 서문은 함수의 이름에 이어서 +% 패턴이(괄호 속에) 따라온다. 본문은 연속적인 식으로 구성되고, +% 연속적인 식은 서문의 패턴과 호출한 인수가 성공적으로 매치되면 평가된다. +% 패턴은 함수 정의가 나타나는 순서대로 매치된다. +area({rectangle, Width, Ht}) -> Width * Ht; +area({circle, R}) -> 3.14159 * R * R. + +% geometry.erl 파일의 코드 컴파일 +c(geometry). % {ok,geometry} + +% 호출하려는 함수를 정확히 알아내기 위해 함수 이름을 Module 이름과 함께 +% 명시하는 것이 필요하다. +geometry:area({rectangle, 10, 5}). % 50 +geometry:area({circle, 1.4}). % 6.15752 + +% Erlang에서, 같은 Module에 이름이 같고 Arity(인수의 갯수)가 다른 +% 두 함수는 전혀 다른 함수를 나타낸다. +-module(lib_misc). +-export([sum/1]). % Arity가 1인 내보내진(export) 함수 `sum` + % 하나의 인수만 받음: 정수의 List +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% Fun은 "익명(anonymous)" 함수다. 이름이 없어서 이렇게 부른다. +% 그러나, 변수에 할당될 수 있다. +Double = fun(X) -> 2 * X end. % `Double`은 익명 함수를 가리킨다: + % #Fun +Double(2). % 4 + +% 함수는 인수로 Fun을 받거나, Fun을 반환할 수 있다. +Mult = fun(Times) -> ( fun(X) -> X * Times end ) end. +Triple = Mult(3). +Triple(5). % 15 + +% List 해석(List comprehensions)은 Fun, Map, Filter 없이 List를 만드는 식이다. +% 표기법 `[F(X) || X <- L]`은 `F(X)`의 List라는 의미이다. +% 이때 `X`는 List `L`로부터 가져온다. +L = [1,2,3,4,5]. +[2 * X || X <- L]. % [2,4,6,8,10] +% List 해석은 Generator와 생성된 값들의 부분 집합을 선택하는 Filter를 가질 수 있다. +EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% Guard는 패턴 매칭의 능력을 향상시키는데 사용할 수 있는 구조다. +% Guard를 사용하면, 패턴에 있는 변수에 대해 간단한 검사와 비교를 수행할 수 있다. +% 함수 정의의 서문(head)에 `when` 키워드로 시작되는 Guard를 사용할 수도 있고, +% 또는 식이 허용되는 언어의 어떤 곳에도 사용될 수 있다. +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% Guard는 쉼표(`,`)로 구분된 연속된 Guard 식이다. +% 모든 Guard 식 `GuardExpr1`, `GuardExpr2`, ..., `GuardExprN`이 +% `true`로 평가된다면, Guard `GuardExpr1`, `GuardExpr2`, ..., `GuardExprN`는 +% 참이다. +is_cat(A) when is_atom(A), A =:= cat -> true; +is_cat(A) -> false. +is_dog(A) when is_atom(A), A =:= dog -> true; +is_dog(A) -> false. + +% `=:=` 연산자는 여기서 자세히 다루지 않을 것이다; 두 개의 Erlang 식의 값이 같고 +% *그리고* 같은 타입인지 검사하는 데 사용된다고만 알면 된다. +% `==` 연산자의 작동과 대조할 것: +1 + 2 =:= 3. % true +1 + 2 =:= 3.0. % false +1 + 2 == 3.0. % true + +% 연속적인 Guard는 단일 Guard 또는 세미콜론(`;`)으로 구분된 연속된 Guard다. +% Guard `G1; G2; ...; Gn` 중에 적어도 하나의 Guard가 `true`로 평가된다면, +% 연속적인 Guard `G1; G2; ...; Gn`는 참이다. +is_pet(A) when is_atom(A), (A =:= dog);(A =:= cat) -> true; +is_pet(A) -> false. + +% 주의: 모든 유효한 Erlang 식이 Guard 식으로 사용될 수 있는 것은 아니다; +% 특히, 함수 `is_cat`과 `is_dog`는 `is_pet`의 정의 안에 있는 +% 연속적인 Guard 사이에 사용될 수 없다. +% 연속적인 Guard에 허용되는 식의 자세한 설명은 Erlang 레퍼런스 메뉴얼 +% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912) +% 을 참조하라. + +% Record는 Tuple 안에 이름과 특정 요소를 연결하는 방법을 제공한다. +% Record 정의는 Erlang 소스 코드 파일에 포함되거나 Erlang 소스 코드 파일에 +% 포함될 수 있는 확장자가 `.hrl`인 파일에 집어넣을 수 있다. +-record(todo, { + status = reminder, % 기본 값 + who = joe, + text +}). + +% Record를 사용할 수 있기 전에 Record 정의를 반드시 셸로 읽어 들여야 한다. +% 셸로 읽어 들이기 위해 셸 함수 `rr`(read records의 약자)을 사용한다. +rr("records.hrl"). % [todo] + +% Record 생성과 수정 +X = #todo{}. +% #todo{status = reminder, who = joe, text = undefined} +X1 = #todo{status = urgent, text = "Fix errata in book"}. +% #todo{status = urgent, who = joe, text = "Fix errata in book"} +X2 = X1#todo{status = done}. +% #todo{status = done, who = joe, text = "Fix errata in book"} + +% `case` 식 +% `filter`는 List `L`의 원소 `X` 중에서 `P(X)`가 참인 모든 `X`의 List를 반환한다. +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% `if` 식. +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil + end. + +% 주의: 적어도 if 식의 Guard 중의 하나는 반드시 `true`로 평가되어야 한다. +% 그렇지 않으면 예외가 발생한다. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. 예외 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% 예외는 내부에 에러가 생겼거나 명시적으로 `throw(Exception)`, +% `exit(Exception)` 또는 `erlang:error(Exception)`를 호출하면 +% 시스템에 의해 발생한다. +generate_exception(1) -> a; +generate_exception(2) -> throw(a); +generate_exception(3) -> exit(a); +generate_exception(4) -> {'EXIT', a}; +generate_exception(5) -> erlang:error(a). + +% Erlang은 예외를 잡는 두 가지 방법을 가지고 있다. 한 가지는 +% 예외를 발생시키는 함수의 호출 부분을 `try...catch` 식으로 감싸는 것이다. +catcher(N) -> + try generate_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% 다른 방법은 그 호출 부분을 `catch` 식으로 감싸는 것이다. +% 예외를 잡았을 때, 그 예외는 오류를 설명하는 Tuple로 변환된다. +catcher(N) -> catch generate_exception(N). + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 4. 병행성 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang은 병행성을 위해 Actor 모델을 사용한다. Erlang에서 병행 프로그램을 +% 작성하는 데 필요한 모든 것은 3가지 기본 형식(primitivies)이다: +% 프로세스 생성, 메시지 보내기, 메시지 받기 + +% 새로운 프로세스를 시작하기 위해, 함수를 인수로 받는 `spawn` 함수를 사용한다. + +F = fun() -> 2 + 2 end. % #Fun +spawn(F). % <0.44.0> + +% `spawn`은 pid(프로세스 식별자)를 반환한다. 이 pid를 프로세스로 +% 메시지를 보내는 데 사용할 수 있다. 메시지 전달을 위해, `!` 연산자를 사용한다. +% 위의 기능이 유용하려면, 메시지를 받을 수 있어야 한다. 메시지를 받는 것은 +% `receive` 메커니즘을 사용한다. + +-module(calculateGeometry). +-compile(export_all). +calculateArea() -> + receive + {rectangle, W, H} -> + W * H; + {circle, R} -> + 3.14 * R * R; + _ -> + io:format("We can only calculate area of rectangles or circles.") + end. + +% Module을 컴파일하고 셸에서 `calculateArea`를 평가한 프로세스를 생성한다. +c(calculateGeometry). +CalculateArea = spawn(calculateGeometry, calculateArea, []). +CalculateArea ! {circle, 2}. % 12.56000000000000049738 + +% 셸도 마찬가지로 프로세스이다. 현재 pid를 얻기 위해서 `self`를 사용할 수 있다. +self(). % <0.41.0> + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 5. EUnit과 테스트 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% EUnit의 테스트 생성기(generators)와 assert 매크로를 이용해 +% 단위 테스트를 작성할 수 있다. +-module(fib). +-export([fib/1]). +-include_lib("eunit/include/eunit.hrl"). + +fib(0) -> 1; +fib(1) -> 1; +fib(N) when N > 1 -> fib(N-1) + fib(N-2). + +fib_test_() -> + [?_assert(fib(0) =:= 1), + ?_assert(fib(1) =:= 1), + ?_assert(fib(2) =:= 2), + ?_assert(fib(3) =:= 3), + ?_assert(fib(4) =:= 5), + ?_assert(fib(5) =:= 8), + ?_assertException(error, function_clause, fib(-1)), + ?_assert(fib(31) =:= 2178309) + ]. + +% EUnit은 Erlang 셸에서 테스트를 실행할 수 있게 +% 자동으로 test() 함수를 내보낸다(export). +fib:test() + +% Erlang의 유명한 빌드 툴인 Rebar는 EUnit과 호환된다. +% ``` +% rebar eunit +% ``` + +``` + +## 참조 + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [조 암스트롱, 김석준 역, "프로그래밍 얼랭: Software for a Concurrent World", 인사이트](http://ebook.insightbook.co.kr/book/23) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) -- cgit v1.2.3 From ecba01b4b1c35cbcf58c5e030b9e79a5c30be55c Mon Sep 17 00:00:00 2001 From: Braxton Fair Date: Sun, 28 Feb 2016 20:33:57 -0600 Subject: Write a bit better code --- pythonstatcomp.html.markdown | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index f8d83b98..0b02dca8 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -150,9 +150,8 @@ ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" r = requests.get(url) fp = "hre.csv" -f = open(fp, "wb") -f.write(r.text.encode("UTF-8")) -f.close() +with open(fp, "wb") as f: + f.write(r.text.encode("UTF-8")) hre = pd.read_csv(fp) -- cgit v1.2.3 From d1740256b23a200cbf5069bf2b8efbfaecdce8ac Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Thu, 3 Mar 2016 00:45:43 +0530 Subject: fixed typos and spellings, added content --- make.html.markdown | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index bf934c58..ed452521 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -2,6 +2,7 @@ language: make contributors: - ["Robert Steed", "https://github.com/robochat"] + - ["Divay Prakash", "https://github.com/divayprakash"] filename: Makefile --- @@ -9,16 +10,16 @@ A Makefile defines a graph of rules for creating a target (or targets). Its purpose is to do the minimum amount of work needed to update a target to the most recent version of the source. Famously written over a weekend by Stuart Feldman in 1976, it is still widely used (particularly -on Unix) despite many competitors and criticisms. +on Unix and Linux) despite many competitors and criticisms. -There are many varieties of make in existence, this article assumes that -we are using GNU make which is the standard on Linux. +There are many varieties of make in existence, however this article +assumes that we are using GNU make which is the standard on Linux. ```make # Comments can be written like this. -# Files should be named Makefile and then be can run as `make `. +# File should be named Makefile and then can be run as `make `. # Otherwise we use `make -f "filename" `. # Warning - only use TABS to indent in Makefiles, never spaces! @@ -27,13 +28,16 @@ we are using GNU make which is the standard on Linux. # Basics #----------------------------------------------------------------------- +# Rules are of the format +# target: +# where prerequisites are optional. + # A rule - this rule will only run if file0.txt doesn't exist. file0.txt: echo "foo" > file0.txt # Even comments in these 'recipe' sections get passed to the shell. # Try `make file0.txt` or simply `make` - first rule is the default. - # This rule will only run if file0.txt is newer than file1.txt. file1.txt: file0.txt cat file0.txt > file1.txt @@ -99,8 +103,8 @@ process: ex1.txt file0.txt %.png: %.svg inkscape --export-png $^ -# Pattern rules will only do anything if make decides to create the \ -target. +# Pattern rules will only do anything if make decides to create the +# target. # Directory paths are normally ignored when matching pattern rules. But # make will try to use the most appropriate rule available. @@ -185,7 +189,7 @@ var := hello var2 ::= $(var) hello #:= and ::= are equivalent. -# These variables are evaluated procedurely (in the order that they +# These variables are evaluated procedurally (in the order that they # appear), thus breaking with the rest of the language ! # This doesn't work -- cgit v1.2.3 From b6fd0657ea5d0bbc8deb3f1865bbdc008ee294d4 Mon Sep 17 00:00:00 2001 From: Chris Martin Date: Wed, 2 Mar 2016 18:27:01 -0800 Subject: Initial Nix tutorial --- nix.html.markdown | 354 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 354 insertions(+) create mode 100644 nix.html.markdown diff --git a/nix.html.markdown b/nix.html.markdown new file mode 100644 index 00000000..2979098f --- /dev/null +++ b/nix.html.markdown @@ -0,0 +1,354 @@ +--- +language: nix +filename: learn.nix +contributors: + - ["Chris Martin", "http://chris-martin.org/"] +--- + +Nix is a simple functional language developed for the +[Nix package manager](https://nixos.org/nix/) and +[NixOS](https://nixos.org/). + +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). + +```nix +with builtins; [ + + # Comments + #========================================= + + # Inline comments look like this. + + /* Multi-line comments + look like this. */ + + + # Booleans + #========================================= + + (true && false) # And + #=> false + + (true || false) # Or + #=> true + + (if 3 < 4 then "a" else "b") # Conditional + #=> "a" + + + # Integers + #========================================= + + # Integers are the only numeric type. + + 1 0 42 (-3) # Some integers + + (4 + 6 + 12 - 2) # Addition + #=> 20 + + (7 / 2) # Division + #=> 3 + + + # Strings + #========================================= + + "Strings literals are in double quotes." + + " + String literals can span + multiple lines. + " + + '' + This is called an "indented string" literal. + It intelligently strips leading whitespace. + '' + + '' + a + b + '' + #=> "a\n b" + + ("ab" + "cd") # String concatenation + #=> "abcd" + + # Antiquotation lets you embed values into strings. + ("Your home directory is ${getEnv "HOME"}") + #=> "Your home directory is /home/alice" + + + # Paths + #========================================= + + # Nix has a primitive data type for paths. + /tmp/tutorials/learn.nix + + # A relative path is resolved to an absolute path at parse + # time, relative to the file in which it occurs. + tutorials/learn.nix + #=> /the-base-path/tutorials/learn.nix + + # A path must contain at least one slash, so a relative + # path for a file in the same directory needs a ./ prefix, + ./learn.nix + #=> /the-base-path/learn.nix + + # The / operator must be surrounded by whitespace if + # you want it to signify division. + + 7/2 # This is a path literal + (7 / 2) # This is integer division + + + # Imports + #========================================= + + # A nix file contains a single top-level expression with no free + # variables. An import expression evaluates to the value of the + # file that it imports. + (import /tmp/foo.nix) + + # Imports can also be specified by strings. + (import "/tmp/foo.nix") + + # Import paths must be absolute. Path literals + # are automatically resolved, so this is fine. + (import ./foo.nix) + + # But this does not happen with strings. + (import "./foo.nix") + #=> error: string ‘foo.nix’ doesn't represent an absolute path + + + # Let + #========================================= + + # `let` blocks allow us to bind values to variables. + (let x = "a"; in + x + x + x) + #=> "aaa" + + # Bindings can refer to each other, and their order does not matter. + (let y = x + "b"; + x = "a"; in + y + "c") + #=> "abc" + + # Inner bindings shadow outer bindings. + (let a = 1; in + let a = 2; in + a) + #=> 2 + + + # Functions + #========================================= + + (n: n + 1) # Function that adds 1 + + ((n: n + 1) 5) # That same function, applied to 5 + #=> 6 + + # There is no syntax for named functions, but they + # can be bound by `let` blocks like any other value. + (let succ = (n: n + 1); in succ 5) + #=> 6 + + # A function has exactly one argument. + # Multiple arguments can be achieved with currying. + ((x: y: x + "-" + y) "a" "b") + #=> "a-b" + + # We can also have named function arguments, + # which we'll get to later after we introduce sets. + + + # Lists + #========================================= + + # Lists are denoted by square brackets. + + (length [1 2 3 "x"]) + #=> 4 + + ([1 2 3] ++ [4 5]) + #=> [1 2 3 4 5] + + (concatLists [[1 2] [3 4] [5]]) + #=> [1 2 3 4 5] + + (head [1 2 3]) + #=> 1 + (tail [1 2 3]) + #=> [2 3] + + (elemAt ["a" "b" "c" "d"] 2) + #=> "c" + + (elem 2 [1 2 3]) + #=> true + (elem 5 [1 2 3]) + #=> false + + (filter (n: n < 3) [1 2 3 4]) + #=> [ 1 2 ] + + + # Sets + #========================================= + + # A "set" is an unordered mapping with string keys. + { foo = [1 2]; bar = "x"; } + + # The . operator pulls a value out of a set. + { a = 1; b = 2; }.a + #=> 1 + + # The // operator merges two sets. + ({ a = 1; } // { b = 2; }) + #=> { a = 1; b = 2; } + + # Values on the right override values on the left. + ({ a = 1; b = 2; } // { a = 3; c = 4; }) + #=> { a = 3; b = 2; c = 4; } + + # The rec keyword denotes a "recursive set", + # in which attributes can refer to each other. + (let a = 1; in { a = 2; b = a; }.b) + #=> 1 + (let a = 1; in rec { a = 2; b = a; }.b) + #=> 2 + + # Nested sets can be defined in a piecewise fashion. + { + a.b = 1; + a.c.d = 2; + a.c.e = 3; + }.a.c + #=> { d = 2; e = 3; } + + # An attribute's descendants cannot be assigned in this + # way if the attribute itself has been directly assigned. + { + a = { b = 1; }; + a.c = 2; + } + #=> error: attribute ‘a’ already defined + + + # With + #========================================= + + # The body of a `with` block is evaluated with + # a set's mappings bound to variables. + (with { a = 1; b = 2; }; + a + b) + # => 3 + + # Inner bindings shadow outer bindings. + (with { a = 1; b = 2; }; + (with { a = 5; }; + a + b)) + #=> 7 + + # This first line of tutorial starts with "with builtins;" + # because builtins is a set the contains all of the built-in + # functions (length, head, tail, filter, etc.). This saves + # us from having to write, for example, "builtins.length" + # instead of just "length". + + + # Set patterns + #========================================= + + # Sets are useful when we need to pass multiple values + # to a function. + (args: args.x + "-" + args.y) { x = "a"; y = "b"; } + #=> "a-b" + + # This can be written more clearly using set patterns. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; } + #=> "a-b" + + # By default, the pattern fails on sets containing extra keys. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> error: anonymous function called with unexpected argument ‘z’ + + # Adding ", ..." allows ignoring extra keys. + ({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> "a-b" + + + # Errors + #========================================= + + # `throw` causes evaluation to abort with an error message. + (2 + (throw "foo")) + #=> error: foo + + # `tryEval` catches thrown errors. + (tryEval 42) + #=> { success = true; value = 42; } + (tryEval (2 + (throw "foo"))) + #=> { success = false; value = false; } + + # `abort` is like throw, but it's fatal; it cannot be caught. + (tryEval (abort "foo")) + #=> error: evaluation aborted with the following error message: ‘foo’ + + # `assert` evaluates to the given value if true; + # otherwise it throws a catchable exception. + (assert 1 < 2; 42) + #=> 42 + (assert 1 > 2; 42) + #=> error: assertion failed at (string):1:1 + (tryEval (assert 1 > 2; 42)) + #=> { success = false; value = false; } + + + # Impurity + #========================================= + + # 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. + + # You can refer to environment variables. + (getEnv "HOME") + #=> "/home/alice" + + # The trace function is used for debugging. It prints the first + # argument to stderr and evaluates to the second argument. + (trace 1 2) + #=> trace: 1 + #=> 2 + + # You can write files into the Nix store. Although impure, this is + # fairly safe because the file name is derived from the hash of + # its contents. You can read files from anywhere. In this example, + # we write a file into the store, and then read it back out. + (let filename = toFile "foo.txt" "hello!"; in + [filename (builtins.readFile filename)]) + #=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ] + + # We can also download files into the Nix store. + (fetchurl "https://example.com/package-1.2.3.tgz") + #=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz" + +] +``` + +### Further Reading + +* [Nix Manual - Nix expression language] + (https://nixos.org/nix/manual/#ch-expression-language) + +* [James Fisher - Nix by example - Part 1: The Nix expression language] + (https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55) + +* [Susan Potter - Nix Cookbook - Nix By Example] + (http://funops.co/nix-cookbook/nix-by-example/) -- cgit v1.2.3 From bb74c468c2673de7ff92cd63830d93c455e18a33 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Thu, 3 Mar 2016 11:41:52 +0530 Subject: fixed whitespaces removed whitespaces all over document --- c.html.markdown | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index d4ff529d..06673588 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Marco Scannadinari", "https://marcoms.github.io"] - ["Zachary Ferguson", "https://github.io/zfergus2"] - ["himanshu", "https://github.com/himanshu81494"] + - ["Divay Prakash", "https://github.com/divayprakash"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -36,7 +37,6 @@ Multi-line comments don't nest /* Be careful */ // comment ends on this line... enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT}; // MON gets 2 automatically, TUE gets 3, etc. - // Import headers with #include #include #include @@ -114,7 +114,6 @@ int main (int argc, char** argv) // sizeof(obj) yields the size of the expression (variable, literal, etc.). printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) - // If the argument of the `sizeof` operator is an expression, then its argument // is not evaluated (except VLAs (see below)). // The value it yields in this case is a compile-time constant. @@ -130,7 +129,6 @@ int main (int argc, char** argv) int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes // (assuming 4-byte words) - // You can initialize an array to 0 thusly: char my_array[20] = {0}; @@ -347,7 +345,6 @@ int main (int argc, char** argv) this will print out "Error occured at i = 52 & j = 99." */ - /////////////////////////////////////// // Typecasting /////////////////////////////////////// @@ -386,7 +383,6 @@ int main (int argc, char** argv) // (%p formats an object pointer of type void *) // => Prints some address in memory; - // Pointers start with * in their declaration int *px, not_a_pointer; // px is a pointer to an int px = &x; // Stores the address of x in px @@ -432,7 +428,6 @@ int main (int argc, char** argv) printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); // probably prints "40, 4" or "40, 8" - // Pointers are incremented and decremented based on their type // (this is called pointer arithmetic) printf("%d\n", *(x_ptr + 1)); // => Prints 19 @@ -578,8 +573,6 @@ void testFunc2() { } //**You may also declare functions as static to make them private** - - /////////////////////////////////////// // User-defined types and structs /////////////////////////////////////// @@ -696,6 +689,7 @@ typedef void (*my_fnp_type)(char *); "%o"; // octal "%%"; // prints % */ + /////////////////////////////////////// // Order of Evaluation /////////////////////////////////////// @@ -786,4 +780,4 @@ Readable code is better than clever code and fast code. For a good, sane coding Other than that, Google is your friend. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file -- cgit v1.2.3 From 3bb265de2e75eba68ca51d3c63173211bb4d59de Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Thu, 3 Mar 2016 12:07:58 +0530 Subject: removed whitespaces, fixed content extending beyond 80 chars --- java.html.markdown | 92 ++++++++++++++++++++---------------------------------- 1 file changed, 33 insertions(+), 59 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 50629ce1..946bfc17 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Zachary Ferguson", "http://github.com/zfergus2"] - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Divay Prakash", "http://github.com/divayprakash"] filename: LearnJava.java --- @@ -17,9 +18,11 @@ programming language. ```java // Single-line comments start with // + /* Multi-line comments look like this. */ + /** JavaDoc comments look like this. Used to describe the Class or various attributes of a Class. @@ -30,11 +33,12 @@ import java.util.ArrayList; // Import all classes inside of java.security package import java.security.*; -// Each .java file contains one outer-level public class, with the same name as -// the file. +// Each .java file contains one outer-level public class, with the same name +// as the file. public class LearnJava { - // In order to run a java program, it must have a main method as an entry point. + // In order to run a java program, it must have a main method as an entry + // point. public static void main (String[] args) { // Use System.out.println() to print lines. @@ -60,7 +64,8 @@ public class LearnJava { */ // Declare a variable using int fooInt; - // Declare multiple variables of the same type , , + // Declare multiple variables of the same + // type , , int fooInt1, fooInt2, fooInt3; /* @@ -69,7 +74,8 @@ public class LearnJava { // Initialize a variable using = int fooInt = 1; - // Initialize multiple variables of same type with same value , , = + // Initialize multiple variables of same type with same + // value , , = int fooInt1, fooInt2, fooInt3; fooInt1 = fooInt2 = fooInt3 = 1; @@ -119,18 +125,15 @@ public class LearnJava { final double E; E = 2.71828; - // BigInteger - Immutable arbitrary-precision integers // // BigInteger is a data type that allows programmers to manipulate // integers longer than 64-bits. Integers are stored as an array of // of bytes and are manipulated using functions built into BigInteger // - // BigInteger can be initialized using an array of bytes or a string. - + // BigInteger can be initialized using an array of bytes or a string. BigInteger fooBigInteger = new BigInteger(fooByteArray); - // BigDecimal - Immutable, arbitrary-precision signed decimal number // // A BigDecimal takes two parts: an arbitrary precision integer @@ -142,16 +145,13 @@ public class LearnJava { // // BigDecimal can be initialized with an int, long, double or String // or by initializing the unscaled value (BigInteger) and scale (int). - BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); // Be wary of the constructor that takes a float or double as // the inaccuracy of the float/double will be copied in BigDecimal. // Prefer the String constructor when you need an exact value. - BigDecimal tenCents = new BigDecimal("0.1"); - // Strings String fooString = "My String Is Here!"; @@ -184,7 +184,7 @@ public class LearnJava { intArray[1] = 1; System.out.println("intArray @ 1: " + intArray[1]); // => 1 - // Others to check out + // Other data types worth checking out // ArrayLists - Like arrays except more functionality is offered, and // the size is mutable. // LinkedLists - Implementation of doubly-linked list. All of the @@ -212,7 +212,7 @@ public class LearnJava { System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int) System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 // Modulo @@ -242,7 +242,7 @@ public class LearnJava { | Bitwise inclusive OR */ - // Incrementations + // Increment operators int i = 0; System.out.println("\n->Inc/Dec-rementation"); // The ++ and -- operators increment and decrement by 1 respectively. @@ -314,7 +314,6 @@ public class LearnJava { // for each loop structure => for ( : ) // reads as: for each element in the iterable // note: the object type must match the element type of the iterable. - for (int bar : fooList) { System.out.println(bar); //Iterates 9 times and prints 1-9 on new lines @@ -364,7 +363,6 @@ public class LearnJava { String bar = (foo < 10) ? "A" : "B"; System.out.println(bar); // Prints A, because the statement is true - //////////////////////////////////////// // Converting Data Types And Typecasting //////////////////////////////////////// @@ -387,7 +385,6 @@ public class LearnJava { // with some more intermediate concepts. Feel free to check it out here: // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - /////////////////////////////////////// // Classes And Functions /////////////////////////////////////// @@ -409,7 +406,6 @@ public class LearnJava { // Double Brace Initialization // The Java Language has no syntax for how to create static Collections // in an easy way. Usually you end up in the following way: - private static final Set COUNTRIES = new HashSet(); static { validCodes.add("DENMARK"); @@ -420,7 +416,6 @@ public class LearnJava { // But there's a nifty way to achieve the same thing in an // easier way, by using something that is called Double Brace // Initialization. - private static final Set COUNTRIES = new HashSet() {{ add("DENMARK"); add("SWEDEN"); @@ -436,11 +431,9 @@ public class LearnJava { } // End main method } // End LearnJava class - // You can include other, non-public outer-level classes in a .java file, // but it is not good practice. Instead split classes into separate files. - // Class Declaration Syntax: // class { // // data fields, constructors, functions all inside. @@ -454,7 +447,6 @@ class Bicycle { private int speed; // Private: Only accessible from within the class protected int gear; // Protected: Accessible from the class and subclasses String name; // default: Only accessible from within this package - static String className; // Static class variable // Static block @@ -476,7 +468,6 @@ class Bicycle { speed = 5; name = "Bontrager"; } - // This is a constructor that takes arguments public Bicycle(int startCadence, int startSpeed, int startGear, String name) { @@ -501,23 +492,18 @@ class Bicycle { public void setCadence(int newValue) { cadence = newValue; } - public void setGear(int newValue) { gear = newValue; } - public void speedUp(int increment) { speed += increment; } - public void slowDown(int decrement) { speed -= decrement; } - public void setName(String newName) { name = newName; } - public String getName() { return name; } @@ -566,10 +552,8 @@ public interface Digestible { public void digest(); } - // We can now create a class that implements both of these interfaces. -public class Fruit implements Edible, Digestible { - +public class Fruit implements Edible, Digestible { @Override public void eat() { // ... @@ -585,7 +569,6 @@ public class Fruit implements Edible, Digestible { // interfaces. For example: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { - @Override public void InterfaceOneMethod() { } @@ -604,14 +587,13 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne, // // Method declarations // } -// Marking a class as abstract means that it contains abstract methods that must -// be defined in a child class. Similar to interfaces, abstract classes cannot -// be instantiated, but instead must be extended and the abstract methods -// defined. Different from interfaces, abstract classes can contain a mixture of +// Marking a class as abstract means that it contains abstract methods that +// must be defined in a child class. Similar to interfaces, abstract classes +// cannot be instantiated, but instead must be extended and the abstract +// methods defined. Different from interfaces, abstract classes can contain a // concrete and abstract methods. Methods in an interface cannot have a body, -// unless the method is static, and variables are final by default, unlike an -// abstract class. Also abstract classes CAN have the "main" method. - +// mixture of unless the method is static, and variables are final by default, +// unlike an abstract class. Also abstract classes CAN have the "main" method. public abstract class Animal { public abstract void makeSound(); @@ -656,7 +638,7 @@ class Dog extends Animal // @Override annotation here, since java doesn't allow // overriding of static methods. // What is happening here is called METHOD HIDING. - // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ + // Check out this SO post: http://stackoverflow.com/questions/16313649/ public static void main(String[] args) { Dog pluto = new Dog(); @@ -695,33 +677,29 @@ public abstract class Mammal() // Final Method Syntax: // final () - // Final methods, like, final classes cannot be overridden by a child class, - // and are therefore the final implementation of the method. + // Final methods, like, final classes cannot be overridden by a child + // class, and are therefore the final implementation of the method. public final boolean isWarmBlooded() { return true; } } - // Enum Type // // An enum type is a special data type that enables for a variable to be a set -// of predefined constants. The variable must be equal to one of the values that -// have been predefined for it. Because they are constants, the names of an enum -// type's fields are in uppercase letters. In the Java programming language, you -// define an enum type by using the enum keyword. For example, you would specify -// a days-of-the-week enum type as: - +// of predefined constants. The variable must be equal to one of the values +// that have been predefined for it. Because they are constants, the names of +// an enum type's fields are in uppercase letters. In the Java programming +// language, you define an enum type by using the enum keyword. For example, +// you would specify a days-of-the-week enum type as: public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } // We can use our enum Day like that: - public class EnumTest { - // Variable Enum Day day; @@ -734,16 +712,13 @@ public class EnumTest { case MONDAY: System.out.println("Mondays are bad."); break; - case FRIDAY: System.out.println("Fridays are better."); - break; - + break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); - break; - + break; default: System.out.println("Midweek days are so-so."); break; @@ -793,7 +768,6 @@ The links provided here below are just to get an understanding of the topic, fee * [Codingbat.com](http://codingbat.com/java) - **Books**: * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) @@ -802,4 +776,4 @@ The links provided here below are just to get an understanding of the topic, fee * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) -* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) \ No newline at end of file -- cgit v1.2.3 From d88564513fa334263e9e1a03d98f1f9d766c6bca Mon Sep 17 00:00:00 2001 From: Jean-Gabriel Young Date: Fri, 4 Mar 2016 11:02:20 -0500 Subject: Update elixir.html.markdown The variable is only bound in the case statements --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index bf3c42a6..eb708576 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -170,7 +170,7 @@ case {:one, :two} do {:four, :five} -> "This won't match" {:one, x} -> - "This will match and bind `x` to `:two`" + "This will match and bind `x` to `:two` in this clause" _ -> "This will match any value" end -- cgit v1.2.3 From be873f83fa818899a8b4bd29f1d3933e3be958c5 Mon Sep 17 00:00:00 2001 From: Divay Prakash Date: Sat, 5 Mar 2016 02:02:54 +0530 Subject: Added content --- asymptotic-notation.html.markdown | 45 +++++++++++++++++++++++++++++++++------ 1 file changed, 39 insertions(+), 6 deletions(-) diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown index a516737e..fec2bcf3 100644 --- a/asymptotic-notation.html.markdown +++ b/asymptotic-notation.html.markdown @@ -3,6 +3,7 @@ category: Algorithms & Data Structures name: Asymptotic Notation contributors: - ["Jake Prather", "http://github.com/JakeHP"] + - ["Divay Prakash", "http://github.com/divayprakash"] --- # Asymptotic Notations @@ -67,9 +68,10 @@ Exponential - a^n, where a is some constant ``` ### Big-O -Big-O, commonly written as O, is an Asymptotic Notation for the worst case, or ceiling of growth -for a given function. Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time complexity -you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0), +Big-O, commonly written as **O**, is an Asymptotic Notation for the worst case, or ceiling of growth +for a given function. It provides us with an _**asymptotic uppper bound**_ for the growth rate of runtime of an algorithm. +Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time complexity +you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for some real constant c (c > 0), `f(n)` <= `c g(n)` for every input size n (n > 0). *Example 1* @@ -114,10 +116,41 @@ Is there some constant c that satisfies this for all n? No, there isn't. `f(n)` is NOT O(g(n)). ### Big-Omega -Big-Omega, commonly written as Ω, is an Asymptotic Notation for the best case, or a floor growth rate -for a given function. +Big-Omega, commonly written as **Ω**, is an Asymptotic Notation for the best case, or a floor growth rate +for a given function. It provides us with an _**asymptotic lower bound**_ for the growth rate of runtime of an algorithm. -`f(n)` is Ω(g(n)), if for any real constant c (c > 0), `f(n)` is >= `c g(n)` for every input size n (n > 0). +`f(n)` is Ω(g(n)), if for some real constant c (c > 0), `f(n)` is >= `c g(n)` for every input size n (n > 0). + +### Note + +The asymptotic growth rates provided by big-O and big-omega notation may or may not be asymptotically tight. +Thus we use small-o and small-omega notation to denote bounds that are not asymptotically tight. + +### Small-o +Small-o, commanly written as **o**, is an Asymptotic Notation to denote the upper bound (that is not asmptotically tight) +on the growth rate of runtime of an algorithm. + +`f(n)` is o(g(n)), if for any real constant c (c > 0), `f(n)` is < `c g(n)` for every input size n (n > 0). + +The definitions of O-notation and o-notation are similar. The main difference is that in f(n) = O(g(n)), the bound f(n) <= g(n) +holds for _**some**_ constant c > 0, but in f(n) = o(g(n)), the bound f(n) < c g(n) holds for _**all**_ constants c > 0. + +### Small-omega +Small-omega, commanly written as **ω**, is an Asymptotic Notation to denote the lower bound (that is not asmptotically tight) +on the growth rate of runtime of an algorithm. + +`f(n)` is ω(g(n)), if for any real constant c (c > 0), `f(n)` is > `c g(n)` for every input size n (n > 0). + +The definitions of Ω-notation and ω-notation are similar. The main difference is that in f(n) = Ω(g(n)), the bound f(n) >= g(n) +holds for _**some**_ constant c > 0, but in f(n) = ω(g(n)), the bound f(n) > c g(n) holds for _**all**_ constants c > 0. + +### Theta +Theta, commonly written as **Θ**, is an Asymptotic Notation to denote the _**asmptotically tight bound**_ on the growth rate +of runtime of an algorithm. + +`f(n)` is Θ(g(n)), if for some real constants c1, c2 (c1 > 0, c2 > 0), `c1 g(n)` is < `f(n)` is < `c2 g(n)` for every input size n (n > 0). + +∴ `f(n)` is Θ(g(n)) implies `f(n)` is O(g(n)) as well as `f(n)` is Ω(g(n)). Feel free to head over to additional resources for examples on this. Big-O is the primary notation used for general algorithm time complexity. -- cgit v1.2.3 From e2221d36cc32d7d59a79736fbb0490c6edb71bd7 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sat, 5 Mar 2016 17:57:08 -0700 Subject: [factor/en] minor typo. dont -> don't --- factor.html.markdown | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/factor.html.markdown b/factor.html.markdown index a0726420..79596d83 100644 --- a/factor.html.markdown +++ b/factor.html.markdown @@ -24,33 +24,33 @@ Code in this file can be typed into Factor, but not directly imported because th 5 4 + ! No output ! `.` pops the top result from the stack and prints it. -. ! 9 +. ! 9 ! More examples of arithmetic: -6 7 * . ! 42 -1360 23 - . ! 1337 -12 12 / . ! 1 -13 2 mod . ! 1 +6 7 * . ! 42 +1360 23 - . ! 1337 +12 12 / . ! 1 +13 2 mod . ! 1 -99 neg . ! -99 --99 abs . ! 99 -52 23 max . ! 52 -52 23 min . ! 23 +99 neg . ! -99 +-99 abs . ! 99 +52 23 max . ! 52 +52 23 min . ! 23 ! A number of words are provided to manipulate the stack, collectively known as shuffle words. 3 dup - ! duplicate the top item (1st now equals 2nd): 3 - 3 2 5 swap / ! swap the top with the second element: 5 / 2 -4 0 drop 2 / ! remove the top item (dont print to screen): 4 / 2 +4 0 drop 2 / ! remove the top item (don't print to screen): 4 / 2 1 2 3 nip .s ! remove the second item (similar to drop): 1 3 1 2 clear .s ! wipe out the entire stack -1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 +1 2 3 4 over .s ! duplicate the second item to the top: 1 2 3 4 3 1 2 3 4 2 pick .s ! duplicate the third item to the top: 1 2 3 4 2 3 -! Creating Words +! Creating Words ! The `:` word sets Factor into compile mode until it sees the `;` word. : square ( n -- n ) dup * ; ! No output -5 square . ! 25 +5 square . ! 25 ! We can view what a word does too. ! \ suppresses evaluation of a word and pushes its identifier on the stack instead. @@ -88,9 +88,9 @@ Code in this file can be typed into Factor, but not directly imported because th 0 [ "Zero is true" . ] when ! Zero is true f [ "F is true" . ] when ! No output f [ "F is false" . ] unless ! F is false -2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true +2 [ "Two is true" . ] [ "Two is false" . ] if ! Two is true -! By default the conditionals consume the value under test, but starred variants +! By default the conditionals consume the value under test, but starred variants ! leave it alone if it's true: 5 [ . ] when* ! 5 @@ -100,7 +100,7 @@ f [ . ] when* ! No output, empty stack, f is consumed because it's false ! Loops ! You've guessed it.. these are higher order words too. -5 [ . ] each-integer ! 0 1 2 3 4 +5 [ . ] each-integer ! 0 1 2 3 4 4 3 2 1 0 5 [ + . ] each-integer ! 0 2 4 6 8 5 [ "Hello" . ] times ! Hello Hello Hello Hello Hello @@ -114,7 +114,7 @@ f [ . ] when* ! No output, empty stack, f is consumed because it's false ! Loop reducing or building lists: { 1 2 3 4 5 } [ 2 mod 0 = ] filter ! Keeps only list members for which quotation yields true: { 2 4 } { 2 4 6 8 } 0 [ + ] reduce . ! Like "fold" in functional languages: prints 20 (0+2+4+6+8) -{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 +{ 2 4 6 8 } 0 [ + ] accumulate . . ! Like reduce but keeps the intermediate values in a list: prints { 0 2 6 12 } then 20 1 5 [ 2 * dup ] replicate . ! Loops the quotation 5 times and collects the results in a list: { 2 4 8 16 32 } 1 [ dup 100 < ] [ 2 * dup ] produce ! Loops the second quotation until the first returns false and collects the results: { 2 4 8 16 32 64 128 } @@ -142,7 +142,7 @@ name get-global . ! "Bob" 2 :> c ! Declares immutable variable c to hold 2 c . ; ! Print it out -! In a word declared this way, the input side of the stack declaration +! In a word declared this way, the input side of the stack declaration ! becomes meaningful and gives the variable names stack values are captured into :: double ( a -- result ) a 2 * ; @@ -150,7 +150,7 @@ name get-global . ! "Bob" :: mword2 ( a! -- x y ) ! Capture top of stack in mutable variable a a ! Push a a 2 * a! ! Multiply a by 2 and store result back in a - a ; ! Push new value of a + a ; ! Push new value of a 5 mword2 ! Stack: 5 10 ! Lists and Sequences @@ -167,7 +167,7 @@ name get-global . ! "Bob" "Concat" "enate" append ! "Concatenate" - strings are sequences too "Concatenate" "Reverse " prepend ! "Reverse Concatenate" { "Concatenate " "seq " "of " "seqs" } concat ! "Concatenate seq of seqs" -{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" +{ "Connect" "subseqs" "with" "separators" } " " join ! "Connect subseqs with separators" ! And if you want to get meta, quotations are sequences and can be dismantled.. 0 [ 2 + ] nth ! 2 -- cgit v1.2.3 From 9e4ec769f02c03517a7133b90980f861139e4e42 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Sun, 6 Mar 2016 20:18:36 -0700 Subject: [less/en] paranthesis -> parenthesis --- less.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/less.html.markdown b/less.html.markdown index 7195271e..a1018ca3 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -89,7 +89,7 @@ div { background-color: #A3A4FF; } -/* You can omit the mixin code from being compiled by adding paranthesis +/* You can omit the mixin code from being compiled by adding parenthesis after the selector */ .center() { -- cgit v1.2.3 From f0a211b8dd082d9802067a24b8b39a62f867a7f1 Mon Sep 17 00:00:00 2001 From: Nathan Reynolds Date: Mon, 7 Mar 2016 11:33:19 +0000 Subject: Update link to Salesforce Git cheat sheet --- git.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/git.html.markdown b/git.html.markdown index e7ca07d6..35f24b2d 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -540,7 +540,7 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) -* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) +* [SalesForce Cheat Sheet](http://res.cloudinary.com/hy4kyit2a/image/upload/SF_git_cheatsheet.pdf) * [GitGuys](http://www.gitguys.com/) -- cgit v1.2.3 From f0967a8550657e5774a298a976a3ae331852c214 Mon Sep 17 00:00:00 2001 From: Jacob Ward Date: Mon, 7 Mar 2016 13:10:10 -0700 Subject: [make/en] enviroment -> environment --- make.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index bf934c58..b3425b8a 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -145,11 +145,11 @@ echo: # In order of priority from highest to lowest: # 1: commandline arguments # 2: Makefile -# 3: shell enviroment variables - make imports these automatically. +# 3: shell environment variables - make imports these automatically. # 4: make has some predefined variables name4 ?= Jean -# Only set the variable if enviroment variable is not already defined. +# Only set the variable if environment variable is not already defined. override name5 = David # Stops commandline arguments from changing this variable. -- cgit v1.2.3 From b5720ab4b6f298df30c53d92ef4db6650b7d82d3 Mon Sep 17 00:00:00 2001 From: Anton Davydov Date: Wed, 9 Mar 2016 00:40:29 +0300 Subject: Fix typos and punctuation --- ru-ru/tmux-ru.html.markdown | 99 ++++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 50 deletions(-) diff --git a/ru-ru/tmux-ru.html.markdown b/ru-ru/tmux-ru.html.markdown index b379fb4b..aa7545cc 100644 --- a/ru-ru/tmux-ru.html.markdown +++ b/ru-ru/tmux-ru.html.markdown @@ -5,14 +5,14 @@ contributors: - ["mdln", "https://github.com/mdln"] translators: - ["Davydov Anton", "https://github.com/davydovanton"] -filename: LearnTmux.txt +filename: LearnTmux-ru.txt lang: ru-ru --- [tmux](http://tmux.sourceforge.net) - терминальный мультиплексор. Он позволяет создавать, получать доступ и контролировать любое количество терминалов из единого окна. -Сессия tmux также может быть закрыта из экрана терминала, и она +Сессия tmux также может быть свернута в фоновый режим, и она будет работать в фоне, а после к ней можно будет подключиться. @@ -27,11 +27,11 @@ lang: ru-ru -c "/dir" # Запустить сессию в конкретной директории attach # Подключиться к последней/существующей сессии - -t "#" # Подключиться к определенной сессии + -t "№" # Подключиться к определенной сессии -d # Завершить определенную сессию ls # Список открытых сессий - -a # Список всех открытых сессиий + -a # Список всех открытых сессий lsw # Список окон -a # Список всех окон @@ -45,20 +45,20 @@ lang: ru-ru kill-window # Закрыть текущее окно -t "#" # Закрыть конкретное окно -a # Закрыть все окна - -a -t "#" # Закрыть все окна кроме конкретного + -a -t "#" # Закрыть все окна, кроме конкретного kill-session # Завершить текущую сессию -t "#" # Завершить конкретную сессию -a # Завершить все сессии - -a -t "#" # Завершить все сессии кроме конкретной + -a -t "#" # Завершить все сессии, кроме конкретной ``` -### Горячие клавиши +### "Горячие" клавиши Способ, с помощью которого контролируется любая tmux -сессия - комбинация клавиш, называемая 'Префиксом'. +сессия, - комбинация клавиш, называемая 'Префиксом'. ``` ---------------------------------------------------------------------- @@ -68,52 +68,52 @@ lang: ru-ru (M-1) = Meta + 1 -или- Alt + 1 ---------------------------------------------------------------------- - ? # Список всех горячих клавиш - : # Начать ввод в командной строке tmux - r # Принудительная перерисовка текущего клиента - c # Создать новое окно + ? # Список всех горячих клавиш + : # Начать ввод в командной строке tmux + r # Принудительная перерисовка текущего клиента + c # Создать новое окно - ! # Переместить текущую панель в отдельное окно - % # Разделить текущую панель на две: левую и правую - " # Разделить текущую панель на две: верхнюю и нижнюю + ! # Переместить текущую панель в отдельное окно + % # Разделить текущую панель на две: левую и правую + " # Разделить текущую панель на две: верхнюю и нижнюю - n # Переместиться на следующее окно - p # Переместиться на предыдущее окно - { # Заменить текущую панель на предыдущую - } # Заменить текущую панель на следующую + n # Переместиться на следующее окно + p # Переместиться на предыдущее окно + { # Заменить текущую панель на предыдущую + } # Заменить текущую панель на следующую - s # Интерактивный выбор запущенных сессий - w # Интерактивный выбор текущего окна - от 0 до 9 # Выбрать окно номер 0..9 + s # Интерактивный выбор запущенных сессий + w # Интерактивный выбор текущего окна + от 0 до 9 # Выбрать окно номер 0..9 - d # Отключить текущий клиент - D # Выбрать клиент, который будет отключен + d # Отключить текущий клиент + D # Выбрать клиент, который будет отключен - & # Закрыть текущее окно - x # Закрыть текущую панель + & # Закрыть текущее окно + x # Закрыть текущую панель - Up, Down # Переместиться на панель выше, ниже, левее - Left, Right # или правее + Стрелки вверх, вниз # Переместиться на панель выше, ниже, левее + влево, вправо # или правее - M-1 to M-5 # Расставить панели: - # 1) выровнять по горизонтали - # 2) выровнять по вертикали - # 3) основное горизонтально - # 4) основное вертикально - # 5) мозаикой + M-1 to M-5 # Расставить панели: + # 1) выровнять по горизонтали + # 2) выровнять по вертикали + # 3) основное горизонтально + # 4) основное вертикально + # 5) мозаикой - C-Up, C-Down # Изменение размера текущей панели с шагом в одну - C-Left, C-Right # колонку + C-Up, C-Down # Изменение размера текущей панели с шагом в одну + C-Left, C-Right # колонку - M-Up, M-Down # Изменение размера текущей панели с шагом в пять - M-Left, M-Right # колонок + M-Up, M-Down # Изменение размера текущей панели с шагом в пять + M-Left, M-Right # колонок ``` ### Настройка ~/.tmux.conf -tmux.conf файл может быть использован для автоматической установки +Файл tmux.conf может быть использован для автоматической установки опций при старте, как, например, .vimrc или init.el. ``` @@ -121,7 +121,7 @@ tmux.conf файл может быть использован для автом # 2014.10 -### Основные конфигурации +### Общее ########################################################################### # Включить поддержку UTF-8 @@ -134,7 +134,7 @@ set -g history-limit 2048 # Порядковый номер первой панели set -g base-index 1 -# Включить поддержу мыши +# Включить поддержку мыши set-option -g mouse-select-pane on # Принудительная перезагрузка конфигурационного файла @@ -163,7 +163,7 @@ bind F12 set-option -g prefix ` setw -g mode-keys vi set-option -g status-keys vi -# Перемещение между панелями как в vim +# Перемещение между панелями, как в vim bind h select-pane -L bind j select-pane -D bind k select-pane -U @@ -175,20 +175,20 @@ bind f next-window bind E swap-window -t -1 bind F swap-window -t +1 -# Комманды упрощающие разделением панелей +# Комманды, упрощающие разделением панелей bind = split-window -h bind - split-window -v unbind '"' unbind % -# Активировать inner-most сессию (когда вложенный tmux) для отправки команд +# Активировать центральную сессию (когда вложенный tmux) для отправки команд bind a send-prefix ### Цветовая схема ########################################################################### -# Цветовая палитра статусбара +# Цветовая палитра строки состояния set-option -g status-justify left set-option -g status-bg black set-option -g status-fg white @@ -205,7 +205,7 @@ set-option -g pane-border-bg black set-option -g message-fg black set-option -g message-bg green -# Цветовая палитра окна статусов +# Цветовая палитра статус окна setw -g window-status-bg black setw -g window-status-current-fg green setw -g window-status-bell-attr default @@ -216,10 +216,10 @@ setw -g window-status-activity-attr default setw -g window-status-activity-fg yellow -### UI +### Интерфейс ########################################################################### -# Нотификации +# Уведомления setw -g monitor-activity on set -g visual-activity on set-option -g bell-action any @@ -229,7 +229,7 @@ set-option -g visual-bell off set-option -g set-titles on set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) -# Настройки статусбара +# Настройки строки состояния set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" # Показывать системные характеристики в статусбаре @@ -239,7 +239,6 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | ``` - ### Ссылки [Tmux | Домашняя страница](http://tmux.sourceforge.net) -- cgit v1.2.3 From 1fb6e144c5b0975e6ba86c5c93fa3d37ab22c40e Mon Sep 17 00:00:00 2001 From: Simone Vittori Date: Wed, 9 Mar 2016 11:04:11 +0000 Subject: Fix typos --- elm.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/elm.html.markdown b/elm.html.markdown index 944ab770..fa10671f 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -85,7 +85,7 @@ snd ("elm", 42) -- 42 -- Access a field with a dot and the field name. { x = 3, y = 7 }.x -- 3 --- Or with an accessor fuction, which is a dot and the field name on its own. +-- Or with an accessor function, which is a dot and the field name on its own. .y { x = 3, y = 7 } -- 7 -- Update the fields of a record. (It must have the fields already.) @@ -309,7 +309,7 @@ import Graphics.Collage as C -- An incoming port is just a type signature. port clientID : Int --- An outgoing port has a defintion. +-- An outgoing port has a definition. port clientOrders : List String port clientOrders = ["Books", "Groceries", "Furniture"] @@ -342,7 +342,7 @@ $ elm package diff evancz/elm-html 3.0.0 4.0.2 ``` The Elm language is surprisingly small. You can now look through almost any Elm -source code and have a rough idea of what is going on. However, the possibilties +source code and have a rough idea of what is going on. However, the possibilities for error-resistant and easy-to-refactor code are endless! Here are some useful resources. -- cgit v1.2.3 From 5073a784a5881fd54e68b44872a2a81ea702403e Mon Sep 17 00:00:00 2001 From: Ukaza Perdana Date: Thu, 10 Mar 2016 22:28:12 +0700 Subject: [ruby/id-id] Added Indonesian translation for Ruby --- id-id/ruby-id.html.markdown | 622 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 622 insertions(+) create mode 100644 id-id/ruby-id.html.markdown diff --git a/id-id/ruby-id.html.markdown b/id-id/ruby-id.html.markdown new file mode 100644 index 00000000..28135da1 --- /dev/null +++ b/id-id/ruby-id.html.markdown @@ -0,0 +1,622 @@ +--- +language: ruby +filename: learnruby-id.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] +translators: + - ["Ukaza Perdana", "https://github.com/ukazap"] +lang: id-id +--- + +```ruby +# Ini adalah sebuah komentar + +=begin +Ini adalah komentar multibaris +Tak seorang pun menggunakannya +Kamu juga tidak perlu +=end + +# Pertama-tama dan yang terpenting: Semuanya adalah objek. + +# Angka adalah objek + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Beberapa aritmetika dasar +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 + +# Operator-operator bitwise +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 + +# Aritmetika tidak lain adalah pemanis sintaks (syntactic sugar) +# untuk memanggil sebuah metode pada suatu objek +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Nilai-nilai khusus adalah objek +nil # setara dengan "null" di bahasa-bahasa lain +true # kebenaran +false # ketidakbenaran + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Kesamaan +1 == 1 #=> true +2 == 1 #=> false + +# Ketidaksamaan +1 != 1 #=> false +2 != 1 #=> true + +# selain false itu sendiri, nil adalah nilai lain yang "salah" +!nil #=> true +!false #=> true +!0 #=> false + +# Perbandingan lain +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Operator pembanding yang dikombinasikan ("spaceship operator") +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Operator-operator logika +true && false #=> false +true || false #=> true +!true #=> false + +# Terdapat versi-versi operator logika yang berbeda dengan lebih sedikit awalan. +# Mereka digunakan sebagai kendali alur untuk merangkai beberapa pernyataan +# hingga salah satunya mengembalikan (return) nilai true atau false. + +# `lakukan_suatu_lainnya` hanya dipanggil jika `lakukan_sesuatu` berhasil. +lakukan_sesuatu() and lakukan_suatu_lainnya() +# `catat_error` hanya dipanggil jika `lakukan_sesuatu` gagal. +lakukan_sesuatu() or catat_error() + + +# String adalah objek + +'Aku adalah string'.class #=> String +"Aku juga adalah string".class #=> String + +wadah = 'menggunakan string interpolation' +"Aku bisa #{wadah} ketika memakai tanda kutip ganda" +#=> "Aku bisa menggunakan string interpolation ketika memakai tanda kutip ganda" + +# Gunakan tanda kutip tunggal daripada tanda kutip ganda jika memungkinkan +# String bertanda kutip ganda melakukan kalkulasi tambahan di dalam + +# Kombinasikan string, tapi tidak dengan angka +'halo ' + 'dunia' #=> "halo dunia" +'halo ' + 3 #=> TypeError: can't convert Fixnum into String +'halo ' + 3.to_s #=> "halo 3" + +# Kombinasikan string dengan operator +'halo ' * 3 #=> "halo halo halo " + +# Membubuhkan ke string +'halo' << ' dunia' #=> "halo dunia" + +# cetak ke output dan buat baris baru (newline) di akhir +puts "Aku mencetak!" +#=> Aku mencetak! +#=> nil + +# cetak ke output tanpa baris baru +print "Aku mencetak!" +#=> Aku mencetak! => nil + +# Variabel +x = 25 #=> 25 +x #=> 25 + +# Catat bahwa pemberian nilai mengembalikan nilai yang diberikan +# Artinya kamu bisa melakukan pemberian nilai secara jamak: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Berdasarkan adat, gunakan gaya snake_case untuk menulis nama variabel +snake_case = true + +# Gunakan nama variabel yang deskriptif +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Simbol (adalah objek) +# Simbol adalah konstanta yang dapat didaur ulang yang tidak dapat diubah +# (immutable), secara internal diwakili oleh nilai integer. Seringkali +# digunakan sebagai pengganti string untuk menyampaikan nilai yang mengandung +# makna spesifik secara efisien. + +:menunggu.class #=> Symbol + +status = :menunggu + +status == :menunggu #=> true + +status == 'menunggu' #=> false + +status == :diterima #=> false + +# Array + +# Ini adalah sebuah array +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Array bisa menampung item dengan beragam tipe + +[1, 'halo', false] #=> [1, "halo", false] + +# Array bisa di-indeks-kan +# Dari depan +array[0] #=> 1 +array.first #=> 1 +array[12] #=> nil + +# Sama dengan aritmetika, pengaksesan [var] +# hanyalah pemanis sintaks +# untuk memanggil metode [] pada suatu objek +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Dari belakang +array[-1] #=> 5 +array.last #=> 5 + +# Dengan indeks awal dan panjang (jumlah item) +array[2, 3] #=> [3, 4, 5] + +# Membalik sebuah Array +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Atau menggunakan jangkauan (range) +array[1..3] #=> [2, 3, 4] + +# Tambahkan ke array seperti ini +array << 6 #=> [1, 2, 3, 4, 5, 6] +# Atau seperti ini +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Periksa apakah suatu item ada dalam sebuah array +array.include?(1) #=> true + +# Hash adalah kamus utama Ruby berupa pasangan kunci/nilai (key/value pair). +# Hash ditandai dengan kurung kurawal: +hash = { 'warna' => 'hijau', 'angka' => 5 } + +hash.keys #=> ['warna', 'angka'] + +# Nilai dalam Hash bisa diperoleh menggunakan kunci: +hash['warna'] #=> 'hijau' +hash['angka'] #=> 5 + +# Meminta hash untuk kunci yang tidak ada akan mengembalikan nil: +hash['tidak ada di sini'] #=> nil + +# Sejak Ruby 1.9, ada sintaks khusus ketika menggunakan simbol sebagai kunci: + +hash_baru = { defcon: 3, action: true } + +hash_baru.keys #=> [:defcon, :action] + +# Periksa ada/atau tidaknya kunci dan nilai dalam hash +hash_baru.key?(:defcon) #=> true +hash_baru.value?(3) #=> true + +# Tip: Baik array maupun hash adalah Enumerable +# Mereka berbagi banyak metode yang berguna diantaranya each, map, count, dll. + +# Struktur-struktur kendali + +if true + 'pernyataan if' +elsif false + 'else if, opsional' +else + 'else, opsional juga' +end + +for penghitung in 1..5 + puts "iterasi #{penghitung}" +end +#=> iterasi 1 +#=> iterasi 2 +#=> iterasi 3 +#=> iterasi 4 +#=> iterasi 5 + +# NAMUN, tidak ada orang yang menggunakan pengulangan for. +# Sebagai ganti, gunakan metode "each" dan memberinya sebuah blok (block). +# Blok adalah serangkaian kode yang bisa dimasukkan ke metode seperti "each". +# Ia serupa dengan lambda, fungsi anonim atau closure di bahasa lainnya. +# +# Metode "each" dari range menjalankan blok untuk setiap elemen dari range. +# Bloknya diberikan penghitung sebagai parameter. +# Memanggil metode "each" dengan blok terlihat seperti ini: + +(1..5).each do |penghitung| + puts "iterasi #{penghitung}" +end +#=> iterasi 1 +#=> iterasi 2 +#=> iterasi 3 +#=> iterasi 4 +#=> iterasi 5 + +# Kamu juga bisa mengurung blok dalam kurung kurawal: +(1..5).each { |penghitung| puts "iterasi #{penghitung}" } + +# Isi dari struktur-struktur data juga bisa di-iterasi menggunakan each. +array.each do |elemen| + puts "#{elemen} adalah bagian dari array" +end +hash.each do |kunci, nilai| + puts "#{kunci} adalah #{nilai}" +end + +# Jika kamu masih membutuhkan indeks, bisa menggunakan "each_with_index" +# dan definisikan variabel indeks +array.each_with_index do |elemen, indeks| + puts "#{elemen} adalah nomor #{indeks} dalam array" +end + +penghitung = 1 +while penghitung <= 5 do + puts "iterasi #{penghitung}" + penghitung += 1 +end +#=> iterasi 1 +#=> iterasi 2 +#=> iterasi 3 +#=> iterasi 4 +#=> iterasi 5 + +# Ada kumpulan fungsi pengulangan lainnya yang berguna di Ruby, +# contohnya "map", "reduce", "inject", daftarnya sangat panjang. Map, +# misalnya, mengambil array yang di-iterasi-nya, melakukan sesuatu pada +# setiap elemen sesuai definisi pada blok, dan mengembalikan array baru. +array = [1,2,3,4,5] +berganda = array.map do |elemen| + elemen * 2 +end +puts berganda +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + +nilai = 'B' + +case nilai +when 'A' + puts 'Pertahankan, nak' +when 'B' + puts 'Semoga lebih beruntung di lain waktu' +when 'C' + puts 'Kamu bisa lebih baik' +when 'D' + puts 'Susah payah' +when 'F' + puts 'Kamu gagal!' +else + puts 'Sistem penilaian lainnya, heh?' +end +#=> "Semoga lebih beruntung di lain waktu" + +# case juga bisa menggunakan range +nilai = 82 +case nilai +when 90..100 + puts 'Hore!' +when 80...90 + puts 'Cukup bagus' +else + puts 'Kamu gagal!' +end +#=> "Cukup bagus" + +# penanganan kesalahan (exception handling): +begin + # kode di sini yang mungkin membangkitkan exception + raise NoMemoryError, 'Kamu kehabisan memori.' +rescue NoMemoryError => variabel_exception + puts 'NoMemoryError dibangkitkan', variabel_exception +rescue RuntimeError => variabel_exception_lainnya + puts 'RuntimeError dibangkitkan sekarang' +else + puts 'Ini dijalankan bila tidak ada exceptions sama sekali' +ensure + puts 'Kode ini akan berjalan bagaimanapun juga' +end + +# Fungsi (atau metode) + +def gandakan(x) + x * 2 +end + +# Fungsi dan semua blok secara tersirat mengembalikan nilai pernyataan terakhir +gandakan(2) #=> 4 + +# Tanda kurung bersifat optional, boleh ditiadakan jika tidak ambigu +gandakan 3 #=> 6 + +gandakan gandakan 3 #=> 12 + +def jumlah(x, y) + x + y +end + +# Argumen-argumen dari metode dipisahkan dengan koma +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# Semua metode secara tersirat mempunyai parameter blok opsional +# yang bisa dipanggil dengan kata kunci 'yield' + +def kurung + puts '{' + yield + puts '}' +end + +kurung { puts 'halo dunia' } + +# { +# halo dunia +# } + + +# Kamu bisa memasukkan blok ke sebuah fungsi +# "&" adalah penanda blok yang masuk +def tamu_tamu(&blok) + blok.call 'beberapa_argumen' +end + +# Kamu bisa memasukkan daftar argumen yang akan dikonversi menjadi array +# Itulah gunanya operator splat ("*") +def tamu_tamu(*array) + array.each { |tamu| puts tamu } +end + +# Bila metode mengembalikan array, bisa memberi nilai dengan destrukturisasi +# (destructuring assignment): +def makanan + ['tempe penyet', 'sayur asam', 'nasi goreng'] +end +sarapan, makan_siang, makan_malam = makanan +sarapan #=> 'tempe penyet' +makan_malam #=> 'nasi goreng' + +# Menurut adat, nama metode yang mengembalikan boolean diakhiri tanda tanya +5.even? # false +5.odd? # true + +# Dan jika suatu metode berakhiran tanda seru, ia melakukan sesuatu yang merusak +# seperti mengubah penerimanya. Banyak metode mempunyai versi ! untuk melakukan +# perubahan dan versi non-! untuk sekedar mengembalikan perubahannya +nama_perusahaan = "Putra Sejahtera" +nama_perusahaan.upcase #=> "PUTRA SEJAHTERA" +nama_perusahaan #=> "Putra Sejahtera" +nama_perusahaan.upcase! # kali ini kita benar-benar mengubah nama_perusahaan! +nama_perusahaan #=> "PUTRA SEJAHTERA" + + +# Definisikan kelas menggunakan kata kunci class +class Manusia + + # Variabel kelas. Ini dibagi oleh semua instans (instance) dari kelas ini. + @@spesies = 'H. sapiens' + + # Inisialisasi dasar + def initialize(nama, usia = 0) + # Berikan argumen ke variabel instans "nama" dalam instans ini + @nama = nama + # Jika tidak diberi usia, nilai default dalam daftar argumen digunakan. + @usia = usia + end + + # Metode setter dasar + def nama=(nama) + @nama = nama + end + + # Metode getter dasar + def nama + @nama + end + + # Fungsi di atas bisa disingkat dengan metode attr_accessor sebagai berikut + attr_accessor :nama + + # Metode getter/setter juga bisa dibuat secara terpisah seperti ini + attr_reader :nama + attr_writer :nama + + # Metode kelas menggunakan self untuk membedakannya dari metode instans. + # Ia hanya bisa dipanggil pada kelas, bukan pada instans-nya. + def self.katakan(pesan) + puts pesan + end + + def spesies + @@spesies + end +end + + +# Membuat instans kelas +jim = Manusia.new('Jim Halpert') + +dwight = Manusia.new('Dwight K. Schrute') + +# Mari panggil beberapa metode +jim.spesies #=> "H. sapiens" +jim.nama #=> "Jim Halpert" +jim.nama = "Jim Halpert II" #=> "Jim Halpert II" +jim.nama #=> "Jim Halpert II" +dwight.spesies #=> "H. sapiens" +dwight.nama #=> "Dwight K. Schrute" + +# Panggil metode kelas +Manusia.katakan('Hai') #=> "Hai" + +# Lingkup variabel didefinisikan berdasarkan bagaimana kita memberikannya nama +# Variabel yang berawalan $ memiliki lingkup global +$var = "Aku adalah variabel global" +defined? $var #=> "global-variable" + +# Variabel yang berawalan @ memiliki lingkup instans +@var = "Aku adalah variabel instans" +defined? @var #=> "instance-variable" + +# Variabel yang berawalan @@ memiliki lingkup kelas +@@var = "Aku adalah variabel kelas" +defined? @@var #=> "class variable" + +# Variabel yang berawalan huruf kapital adalah konstanta +Var = "Aku adalah konstanta" +defined? Var #=> "constant" + +# Kelas juga adalah objek sehingga kelas bisa memiliki variabel instans. +# Variabel kelas dibagi diantara kelas dan semua pewarisnya. + +# kelas dasar +class Manusia + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(nilai) + @@foo = nilai + end +end + +# kelas turunan +class Buruh < Manusia +end + +Manusia.foo # 0 +Buruh.foo # 0 + +Manusia.foo = 2 # 2 +Buruh.foo # 2 + +# Variabel instans milik kelas tidak dibagikan dengan pewaris kelas tersebut. + +class Manusia + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(nilai) + @bar = nilai + end +end + +class Dokter < Manusia +end + +Manusia.bar # 0 +Dokter.bar # nil + +module ContohModul + def foo + 'foo' + end +end + +# Include modul mengikat metode-metodenya pada instans-instans kelas +# Extend modul mengikat metode-metodenya pada kelas + +class Orang + include ContohModul +end + +class Buku + extend ContohModul +end + +Orang.foo # => NoMethodError: undefined method `foo' for Orang:Class +Orang.new.foo # => 'foo' +Buku.foo # => 'foo' +Buku.new.foo # => NoMethodError: undefined method `foo' + +# Callbacks dijalankan ketika meng-include dan meng-extend sebuah modul + +module ContohUrusan + def self.included(base) + base.extend(MetodeKelas) + base.send(:include, MetodeInstans) + end + + module MetodeKelas + def bar + 'bar' + end + end + + module MetodeInstans + def qux + 'qux' + end + end +end + +class Sesuatu + include ContohUrusan +end + +Sesuatu.bar # => 'bar' +Sesuatu.qux # => NoMethodError: undefined method `qux' +Sesuatu.new.bar # => NoMethodError: undefined method `bar' +Sesuatu.new.qux # => 'qux' +``` + +## Sumber tambahan + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - Varian dari referensi ini dengan tantangan dalam browser. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Belajar Ruby melalui serangkaian tutorial interaktif. +- [Dokumentasi resmi](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Edisi lama yang [gratis](http://ruby-doc.com/docs/ProgrammingRuby/) tersedia online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - Panduan penulisan kode Ruby oleh komunitas. +- [Try Ruby](http://tryruby.org) - Pelajari dasar bahasa pemrograman Ruby, secara interaktif di browser. -- cgit v1.2.3 From 1b0c8979824a797ffec3691ef345f66090ddb1c0 Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Thu, 10 Mar 2016 23:05:24 +0100 Subject: Add a -cz suffix to the filename --- cs-cz/brainfuck.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/brainfuck.html.markdown b/cs-cz/brainfuck.html.markdown index 92424ecf..29abc21f 100644 --- a/cs-cz/brainfuck.html.markdown +++ b/cs-cz/brainfuck.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] -filename: learnbrainfuck.bf +filename: learnbrainfuck-cz.bf lang: cs-cz --- -- cgit v1.2.3 From 2e57c76561195431e09291378b934502483e3545 Mon Sep 17 00:00:00 2001 From: Vojta Svoboda Date: Thu, 10 Mar 2016 23:06:40 +0100 Subject: Add a -cz suffix to the filename --- cs-cz/json.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/json.html.markdown b/cs-cz/json.html.markdown index 8a685524..a566ee12 100644 --- a/cs-cz/json.html.markdown +++ b/cs-cz/json.html.markdown @@ -6,7 +6,7 @@ contributors: - ["Marco Scannadinari", "https://github.com/marcoms"] translators: - ["Vojta Svoboda", "https://github.com/vojtasvoboda/"] -filename: learnjson.json +filename: learnjson-cz.json lang: cs-cz --- -- cgit v1.2.3 From 7740af83e71ceaed96d39d3d97f0a5fc02d1c9ab Mon Sep 17 00:00:00 2001 From: S0lll0s Date: Thu, 8 Oct 2015 12:33:01 +0200 Subject: [haml/de] Add Haml/de article --- de-de/haml-de.html.markdown | 156 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 de-de/haml-de.html.markdown diff --git a/de-de/haml-de.html.markdown b/de-de/haml-de.html.markdown new file mode 100644 index 00000000..7272b365 --- /dev/null +++ b/de-de/haml-de.html.markdown @@ -0,0 +1,156 @@ +--- +language: haml +filename: learnhaml-de.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] + - ["Sol Bekic", "https://github.com/S0lll0s"] +lang: de-de +--- + +Haml ist eine Markup- und Templatingsprache, aufgesetzt auf Ruby, mit der HTML Dokumente einfach beschrieben werden können. + +Haml vermindert Wiederholung und Fehleranfälligkeit, indem es Tags basierend auf der Markup-Struktur schließt und schachtelt. +Dadurch ergibt sich kurzes, präzises und logisches Markup. + +Haml kann außerhalb eines Ruby-projekts verwendet werden. Mit dem installierten Haml gem kann man das Terminal benutzen um Haml zu HTML umzuwandeln: + +$ haml input_file.haml output_file.html + + +```haml +/ ------------------------------------------- +/ Einrückung +/ ------------------------------------------- + +/ + Einrückung ist ein wichtiges Element des Haml Syntax, deswegen ist es + wichtig ein konsequentes Schema zu verwenden. Meistens werden zwei spaces + verwendet, solange die Einrückungen das gleiche Schema verfolgen können + aber auch andere Breiten und Tabs verwendet werden + + +/ ------------------------------------------- +/ Kommentare +/ ------------------------------------------- + +/ Kommentare beginnen mit einem Slash + +/ + Mehrzeilige Kommentare werden eingerückt und mit einem Slash + eingeführt + +-# Diese Zeile ist ein "stummes" Kommentar, es wird nicht mitgerendert + + +/ ------------------------------------------- +/ HTML Elemente +/ ------------------------------------------- + +/ Tags werden durch ein Prozentzeichen und den Tagnamen erzeugt +%body + %header + %nav + +/ Die Zeilen oben würden folgendes ergeben: + +
+ +
+ + +/ Text kann direkt nach dem Tagnamen eingefügt werden: +%h1 Headline copy + +/ Mehrzeilige Inhalte müssen stattdessen eingerückt werden: +%p + This is a lot of content that we could probably split onto two + separate lines. + +/ + HTML kann mit &= escaped werden. So werden HTML-sensitive Zeichen + enkodiert. Zum Beispiel: + +%p + &= "Ja & Nein" + +/ würde 'Ja & Nein' ergeben + +/ HTML kann mit != dekodiert werden: +%p + != "so schreibt man ein Paragraph-Tag:

" + +/ ...was 'This is how you write a paragraph tag

' ergeben würde + +/ CSS Klassen können mit '.classname' an Tags angehängt werden: +%div.foo.bar + +/ oder über einen Ruby Hash: +%div{:class => 'foo bar'} + +/ Das div Tag wird standardmäßig verwendet, divs können also verkürzt werden: +.foo + +/ andere Attribute können über den Hash angegeben werden: +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ Booleesche Attribute können mit 'true' gesetzt werden: +%input{:selected => true} + +/ data-Attribute können in einem eigenen Hash im :data key angegeben werden: +%div{:data => {:attribute => 'foo'}} + + +/ ------------------------------------------- +/ Verwendung von Ruby +/ ------------------------------------------- + +/ Mit dem = Zeichen können Ruby-werte evaluiert und als Tag-text verwendet werden: + +%h1= book.name + +%p + = book.author + = book.publisher + + +/ Code nach einem Bindestrich wird ausgeführt aber nicht gerendert: +- books = ['book 1', 'book 2', 'book 3'] + +/ So können zum Beispiel auch Blöcke verwendet werden: +- books.shuffle.each_with_index do |book, index| + %h1= book + + if book do + %p This is a book + +/ + Auch hier werden wieder keine End-Tags benötigt! + Diese ergeben sich aus der Einrückung. + + +/ ------------------------------------------- +/ Inline Ruby / Ruby Interpolation +/ ------------------------------------------- + +/ Ruby variablen können mit #{} in Text interpoliert werden: +%p dein bestes Spiel ist #{best_game} + + +/ ------------------------------------------- +/ Filter +/ ------------------------------------------- + +/ + Mit dem Doppelpinkt können Haml Filter benutzt werden. + Zum Beispiel gibt es den :javascript Filter, mit dem inline JS + geschrieben werden kann: + +:javascript + console.log('Dies ist ein + + +``` + +### R.js का उपयोग कर एक पूरी परियोजना का अनुकूलन + +कई लोगों को विकास के दौरान समझदार कोड संगठन के लिए एएमडी का उपयोग कर पसंद करते हैं, लेकिन अभी भी पेज लोड पर XHRs के सैकड़ों करने के बजाय उत्पादन में एक भी स्क्रिप्ट फ़ाइल जहाज करने के लिए चाहते हैं। + +(राइनो भी समर्थन किया है, तो आप शायद Node.js में चलेगा ) ` require.js` ( अपनी परियोजना की निर्भरता ग्राफ का विश्लेषण , और अपने सभी मॉड्यूल युक्त एक एकल फाइल निर्माण कर सकते हैं कि ` r.js` नामक एक स्क्रिप्ट के साथ आता है ठीक से minified और उपभोग के लिए तैयार है, ) नाम दिया है। +Install it using `npm`: +```shell +$ npm install requirejs -g +``` + +अब आप एक विन्यास फाइल के साथ फ़ीड कर सकते हैं: +```shell +$ r.js -o app.build.js +``` + +हमारे ऊपर के उदाहरण के लिए विन्यास की तरह लग सकता है: +```javascript +/* file : app.build.js */ +({ + name : 'main', // प्रवेश बिंदु के नाम + out : 'main-built.js', // फ़ाइल का नाम करने के लिए उत्पादन में लिखने के लिए + baseUrl : 'app', + paths : { + // ` empty :` का उपयोग कर , यह अभी भी समन्वय से लोड किया जाना चाहिए कि r.js बताता है + // main.js में निर्दिष्ट स्थान + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +उत्पादन में बनाया फ़ाइल का उपयोग करने के लिए, बस ` Data-main` स्वैप: +```html + +``` + +एक अविश्वसनीय रूप से विस्तृत [निर्माण विकल्पों में से अवलोकन] (https://github.com/jrburke/r.js/blob/master/build/example.build.js) GitHub रेपो में उपलब्ध है। + +### विषय इस ट्यूटोरियल में शामिल नहीं +* [लोडर प्लगइन्स / रूपांतरण] (http://requirejs.org/docs/plugins.html) +* [CommonJS शैली लोड हो रहा है और निर्यात] (http://requirejs.org/docs/commonjs.html) +* [उन्नत विन्यास] (http://requirejs.org/docs/api.html#config) +* [शिम विन्यास (गैर एएमडी मॉड्यूल लोडिंग)] (http://requirejs.org/docs/api.html#config-shim) +* [सीएसएस लदान और require.js साथ अनुकूलन] (http://requirejs.org/docs/optimization.html#onecss) +* (Https://github.com/jrburke/almond) [बनाता है के लिए almond.js का प्रयोग] + +### अग्रिम पठन: + +* [सरकारी कल्पना] (https://github.com/amdjs/amdjs-api/wiki/AMD) +* [क्यों एएमडी?] (Http://requirejs.org/docs/whyamd.html) +* [यूनिवर्सल मॉड्यूल परिभाषा] (https://github.com/umdjs/umd) + +### कार्यान्वयन: + +* [Require.js] (http://requirejs.org) +* [डोजो टूलकिट] (http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [Cujo.js] (http://cujojs.com/) +* [Curl.js] (https://github.com/cujojs/curl) +* [Lsjs] (https://github.com/zazl/lsjs) +* [एमडी] (https://github.com/alexlawrence/mmd) diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown new file mode 100644 index 00000000..80cf3bed --- /dev/null +++ b/hd-hd/d.html.markdown @@ -0,0 +1,256 @@ +--- +language: D +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +lang: en +--- + +```c +//क्या आ रहा है पता है ... +module hello; + +import std.stdio; + +void main(string[] args) { + writeln("Hello, World!"); +} +``` + +अगर आप मेरे जैसे हैं और इंटरनेट पर समय बहुत अधिक समय खर्च करते हैं, तो आप बाधाओं के बारे में सुना है +के बारे में [डी ] ( http://dlang.org/ )। डी प्रोग्रामिंग भाषा में एक आधुनिक, सामान्य प्रयोजन है , +सब कुछ के लिए समर्थन कम स्तर की सुविधाओं से करने के साथ बहु - प्रतिमान भाषा +अर्थपूर्ण उच्च स्तरीय चीजें । + +D सक्रिय रूप से सुपर स्मार्ट लोगों का एक बड़ा समूह द्वारा विकसित की है और नेतृत्व द्वारा किया जाता है +[ वाल्टर ब्राइट ] ( https://en.wikipedia.org/wiki/Walter_Bright ) और +[ आंद्रेई Alexandrescu ] ( https://en.wikipedia.org/wiki/Andrei_Alexandrescu )। +जिस तरह की है कि सभी के साथ बाहर, चलो कुछ उदाहरणों पर गौर करते हैं! + + +```c +import std.stdio; + +void main() { + + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // 'auto' can be used for inferring types. + auto n = 1; + + // संख्यात्मक literals स्पष्टता के लिए एक अंकों विभाजक के रूप में '_' का उपयोग कर सकते हैं। + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); +    // लिए और जब तक अच्छा कर रहे हैं, लेकिन D में हम 'foreach' छोरों पसंद करते हैं। +    // '..' पहला मान सहित एक सतत श्रृंखला बनाता है, +    // लेकिन पिछले छोड़कर। + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // वहाँ भी 'foreach_reverse' आप पीछे की ओर पाश करना चाहते हैं। + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("No!"); + } + } +} +``` + +हम ' struct`, `class`,` union`, और `` enum` साथ नए प्रकार परिभाषित कर सकते हैं। Structs और unions +मूल्य से कार्य करने के लिए पारित कर रहे हैं (यानी नकल) और वर्गों के संदर्भ द्वारा पारित कर रहे हैं। इसके अलावा, +हम प्रकारों और मानों दोनों पर करने के लिए टेम्पलेट का उपयोग कर सकते हैं! + +```c +// इधर, 'T' एक प्रकार पैरामीटर है। लगता है कि '<+T>' C++ / C/ Java से। +struct LinkedList(T) { + T data = null; + + // '!'का प्रयोग करें , एक पैरामिट्रीकृत प्रकार इन्स्तांत । फिर, '' लगता है। + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + +// केवल एक टेम्पलेट पैरामीटर नहीं है, तो , हम कोष्ठकों छोड़ सकते हैं। + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// उपयोग उर्फ प्रकार (alias) के लिए संक्षिप्त बनाने के लिए। +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +//हम के रूप में अच्छी तरह से कार्य टेम्पलेट्स बना सकते हैं! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// संदर्भ द्वारा पारित सुनिश्चित करने के लिए रेफरी कीवर्ड का प्रयोग करें । यही कारण है कि यहां तक ​​कि 'A' और 'B' , तो है +//मान प्रकार वे हमेशा ' swap()' के संदर्भ द्वारा पारित हो जाएगा हैं । +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// टेम्पलेट्स के साथ, हम भी मूल्यों पर परमेटेराइज़ कर सकते हैं , न सिर्फ types.With टेम्पलेट्स, हम भी नहीं है, बस प्रकार , मूल्यों पर parameterize कर सकते हैं। +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); + +``` + +Classes की बात हो रही है , एक दूसरे के लिए गुणों के बारे में बात करते हैं। एक संपत्ति +एक value की तरह कार्य कर सकते हैं कि एक समारोह में मोटे तौर पर है, इसलिए हम कर सकते हैं +के शब्दों के साथ पॉड संरचनाओं की वाक्य रचना (` structure.x = 7` ) है +मनुष्य और सेटर तरीकों ( ` object.setX (7) `) ! + +```c +// Consider a class parameterized on types 'T' & 'U'. +class MyClass(T, U) { + T _data; + U _other; +} + +// And "getter" and "setter" methods like so: +class MyClass(T, U) { + T _data; + U _other; + + // भवन निर्माताओं हमेशा नामित कर रहे हैं 'this'. + this(T t, U u) { + //यह नीचे सेटर तरीकों से मुलाकात करेंगे। + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +//और हम इस तरह से उन का उपयोग करें : +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + करने के लिए लिखने के लिए मानक पुस्तकालय से + // आयात ' stdio ' मॉड्यूल + // सांत्वना (आयात एक गुंजाइश के लिए स्थानीय हो सकता है) । + import std.stdio; + + // Call the getters to fetch the values. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // Call the setters to assign new values. + mc.data = 8; + mc.other = "eight"; + + // Call the getters again to fetch the new values. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` + +गुणों के साथ, हम तर्क की किसी भी राशि को जोड़ सकते हैं +हमारे मनुष्य और सेटर तरीकों, और की साफ वाक्य रचना रखना +सीधे सदस्यों तक पहुँचने ! + +हमारे निपटान पर अन्य वस्तु उन्मुख उपहार +` interface`s , ` सार class`es शामिल +और ` तरीकों override`ing । डी सिर्फ जावा की तरह विरासत करता है: +आप कृपया के रूप में कई इंटरफेस को लागू करने, एक वर्ग का विस्तार । + +हम डी एस OOP सुविधाओं देखा , लेकिन स्विच गियर छोड़ दिया । डी प्रस्तावों +प्रथम श्रेणी के कार्यों के साथ कार्यात्मक प्रोग्रामिंग, ` pure` +काम करता है, और अपरिवर्तनीय डेटा । इसके अलावा, अपने पसंदीदा के सभी +कार्यात्मक एल्गोरिदम ( नक्शा, फिल्टर , कम करने और मित्र हो सकते हैं) +अद्भुत ` std.algorithm` मॉड्यूल में पाया! + +```c +import std.algorithm : map, filter, reduce; +import std.range : iota; // builds an end-exclusive range + +void main() { + // हम भी ints के वर्गों की एक सूची का योग मुद्रित करना चाहते हैं + // 1 से 100 के लिए आसान करने के लिए! + + // बस टेम्पलेट पैरामीटर के रूप में लैम्ब्डा भाव के पास! + // आप आप की तरह किसी भी पुराने समारोह पारित कर सकते हैं , लेकिन lambdas यहाँ सुविधाजनक हैं। + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +हम NUM गणना करने के लिए एक अच्छा Haskellian पाइपलाइन का निर्माण करने के लिए मिला सूचना कैसे ? +यही कारण है कि एक डी नवाचार करने के लिए धन्यवाद वर्दी समारोह कॉल सिंटेक्स के रूप में जानते हैं। +UFCS के साथ, हम एक विधि के रूप में एक समारोह कॉल लिखने के लिए चुन सकते हैं +या मुफ्त समारोह कॉल ! वाल्टर इस पर एक अच्छा लेख लिखा था +[यहाँ ।] ( http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394 ) +संक्षेप में, आप जिनकी पहली पैरामीटर कार्यों कॉल कर सकते हैं +एक विधि के रूप में ग्रुप ए की किसी भी अभिव्यक्ति पर कुछ प्रकार एक की है । + +मैं समानता चाहते । समानता की तरह कोई और? ज़रूर तुम करना। चलो कुछ करते हैं! +```c +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // हम हमारे सरणी में वर्गमूल हर नंबर ले जाना चाहता हूँ , + // हम उपलब्ध है के रूप में और के रूप में कई कोर का लाभ ले। + auto arr = new double[1_000_000]; + + // संदर्भ के द्वारा एक सूचकांक , और एक सरणी तत्व का प्रयोग + // और सिर्फ सरणी पर समानांतर फोन! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` -- cgit v1.2.3 From b76ab9f2b56298d8f4d9c7ddf861db2f0692a9b3 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:32:48 +0200 Subject: Fixup metadata for #1673 --- hd-hd/d.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown index 80cf3bed..96274e2b 100644 --- a/hd-hd/d.html.markdown +++ b/hd-hd/d.html.markdown @@ -1,9 +1,9 @@ --- language: D -filename: learnd.d +filename: learnd-hd.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] -lang: en +lang: hd --- ```c -- cgit v1.2.3 From b46e577526dc05d188950f3e4d85d027035a1bf3 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:33:01 +0200 Subject: Metadata fixups for #1673 --- hd-hd/amd.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown index ac8400ad..0a6581d6 100644 --- a/hd-hd/amd.html.markdown +++ b/hd-hd/amd.html.markdown @@ -3,7 +3,8 @@ category: tool tool: amd contributors: - ["Frederik Ring", "https://github.com/m90"] -filename: learnamd.js +filename: learnamd-hd.js +lang: hd --- ## एएमडी के साथ प्रारंभ करना -- cgit v1.2.3 From d4aa031d55e03a08f92fd2e3c407655eaf3ef4f2 Mon Sep 17 00:00:00 2001 From: Carolina Knoll Date: Sun, 26 Jun 2016 09:34:35 -0300 Subject: Create asymptoticnotation-pt.html.markdown (#1820) --- pt-br/asymptoticnotation-pt.html.markdown | 161 ++++++++++++++++++++++++++++++ 1 file changed, 161 insertions(+) create mode 100644 pt-br/asymptoticnotation-pt.html.markdown diff --git a/pt-br/asymptoticnotation-pt.html.markdown b/pt-br/asymptoticnotation-pt.html.markdown new file mode 100644 index 00000000..c5299a11 --- /dev/null +++ b/pt-br/asymptoticnotation-pt.html.markdown @@ -0,0 +1,161 @@ +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +translators: + - ["Carolina Knoll", "http://github.com/carolinaknoll"] +lang: pt-br +--- + +# Aprenda X em Y minutos +## Onde X=Notação Assintótica + +# Notações Assintóticas +## O que são? + +Notações assintóticas são notações matemáticas que nos permitem analisar tempo de execução +de um algoritmo, identificando o seu comportamento de acordo como o tamanho de entrada para +o algoritmo aumenta. Também é conhecido como taxa de "crescimento" de um algoritmo. O algoritmo +simplesmente se torna incrivelmente lento conforme o seu tamanho aumenta? Será que pode-se na +maior parte manter o seu tempo de execução rápido mesmo quando o tamanho de entrada aumenta? +A notação assintótica nos dá a capacidade de responder a essas perguntas. + +## Além desta, existem outras alternativas para responder a essas perguntas? + +Uma forma seria a de contar o número de operações primitivas em diferentes tamanhos de entrada. +Embora esta seja uma solução válida, a quantidade de trabalho necessário, mesmo para algoritmos +simples, não justifica a sua utilização. + +Outra maneira é a de medir fisicamente a quantidade de tempo que leva para se executar um algoritmo +de diferentes tamanhos. No entanto, a precisão e a relatividade (já que tempos obtidos só teriam +relação à máquina em que eles foram testados) deste método estão ligadas a variáveis ambientais, +tais como especificações de hardware, poder de processamento, etc. + +## Tipos de Notação Assintótica + +Na primeira seção deste documento nós descrevemos como uma notação assintótica identifica o comportamento +de um algoritmo como as alterações de tamanho de entrada (input). Imaginemos um algoritmo como uma função +f, n como o tamanho da entrada, e f (n) sendo o tempo de execução. Assim, para um determinado algoritmo f, +com tamanho de entrada n você obtenha algum tempo de execução resultante f (n). Isto resulta num gráfico, +em que o eixo Y representa o tempo de execução, o eixo X é o tamanho da entrada, e os pontos marcados são +os resultantes da quantidade de tempo para um dado tamanho de entrada. + +Pode-se rotular uma função ou algoritmo com uma notação assintótica de diversas maneiras diferentes. +Dentre seus exemplos, está descrever um algoritmo pelo seu melhor caso, pior caso, ou caso equivalente. +O mais comum é o de analisar um algoritmo pelo seu pior caso. Isso porque você normalmente não avaliaria +pelo melhor caso, já que essas condições não são as que você está planejando. Um bom exemplo disto é o de +algoritmos de ordenação; especificamente, a adição de elementos a uma estrutura de tipo árvore. O melhor +caso para a maioria dos algoritmos pode ser tão simples como uma única operação. No entanto, na maioria +dos casos, o elemento que você está adicionando terá de ser ordenado de forma adequada através da árvore, +o que poderia significar a análise de um ramo inteiro. Este é o pior caso, e é por ele que precisamos seguir. + +### Tipos de funções, limites, e simplificação + +``` +Função Logaritmica - log n +Função Linear - an + b +Função Quadrática - an^2 + bn + c +Função Polinomial - an^z + . . . + an^2 + a*n^1 + a*n^0, onde z é uma constante +Função Exponencial - a^n, onde a é uma constante +``` + +Estas são algumas classificações básicas de crescimento de função usados em várias notações. A lista +começa com a função crescimento mais lento (logarítmica, com tempo de execução mais rápido) e vai até +a mais rápida (exponencial, com tempo de execução mais lento). Observe que 'n', ou nossa entrada, +cresce em cada uma dessas funções, e o resultado claramente aumenta muito mais rapidamente em função +quadrática, polinomial e exponencial, em comparação com a logarítmica e a linear. + +Uma observação de boa importância é que, para as notações a serem discutidas, deve-se fazer o melhor +para utilizar termos mais simples. Isto significa desrespeitar constantes, e simplificar termos de +ordem, porque, como o tamanho da entrada (ou n no nosso f (n) exemplo) aumenta infinitamente (limites +matemáticos), os termos em ordens mais baixas e constantes são de pouca ou nenhuma importância. Dito +isto, se você possui constantes com valor 2^9001, ou alguma outra quantidade ridícula, inimaginável, +perceberá que a simplificação distorcerá a precisão de sua notação. + +Já que nós queremos a forma mais simples, vamos modificar nossas funções um pouco. + +``` +Logaritmica - log n +Linear - n +Quadrática - n^2 +Polinomial - n^z, onde z é uma constante +Exponencial - a^n, onde a é uma constante +``` + +### O Grande-O + +Grande-O, geralmente escrita como O, é uma Notação Assintótica para o pior caso para uma dada função. Digamos +que `f(n)` é o tempo de execução de seu algoritmo, e `g(n)` é uma complexidade de tempo arbitrário que você está +tentando se relacionar com o seu algoritmo. `f(n)` será O(g(n)), se, por qualquer constante real c (c > 0), +`f(n)` <= `c g(n)` para cada tamanho de entrada n (n > 0). + +*Exemplo 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +É `f(n)` um O(g(n))? +É 3 `log n + 100` igual a O(log n)? +Vamos checar na definição de Grande-O. + +``` +3log n + 100 <= c * log n +``` + +Existe alguma constante c que satisfaça isso para todo n? + +``` +3log n + 100 <= 150 * log n, n > 2 (indefinido em n = 1) +``` + +Sim! A definição de Grande-O foi satisfeita. Sendo assim, `f(n)` é O(g(n)). + +*Exemplo 2* + +``` +f(n) = 3 * n^2 +g(n) = n +``` + +É `f(n)` um O(g(n))? +É `3 * n^2` um O(n)? +Vamos ver na definição de Grande-O. + +``` +3 * n^2 <= c * n +``` + +Existe alguma constante que satisfaça isso para todo n? +Não, não existe. `f(n)` NÃO É O(g(n)). + +### Grande-Omega + +Grande-Omega, comumente escrito como Ω, é uma Notação Assintótica para o melhor caso, ou +uma taxa de crescimento padrão para uma determinada função. + +`f(n)` é Ω(g(n)), se, por qualquer constante c real (c > 0), `f(n)` é >= `c g(n)` para cada +tamanho de entrada n (n > 0). + +Sinta-se livre para pesquisar recursos adicionais e obter mais exemplos sobre este assunto! +Grande-O é a notação primária utilizada para tempo de execução de algoritmos, de modo geral. + +### Notas de Finalização + +É complicado exibir este tipo de assunto de forma tão curta, então é definitivamente recomendado +pesquisar além dos livros e recursos on-line listados. Eles serão capazes de analisar o assunto com +uma profundidade muito maior, além de ter definições e exemplos. Mais sobre onde X="Algoritmos e +Estruturas de Dados" está a caminho: Haverá conteúdo focado na análise de exemplos de códigos reais +em breve. + +## Livros + +* [Algorithms] (http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design] (http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Recursos Online + +* [MIT] (http://web.mit.edu/16.070/www/lecture/big_o.pdf) +* [KhanAcademy] (https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) -- cgit v1.2.3 From d1216a4253c1b03641c10b171030d04227ad8408 Mon Sep 17 00:00:00 2001 From: Sachin Divekar Date: Sun, 26 Jun 2016 18:08:05 +0530 Subject: Add an example of trap command (#1826) * Begin writing document for PCRE Started writing learnxinyminutes document for PCRE to cover general purpose regular expressions. Added introduction and a couple of details. * Change introductory example for regex The old example was incorrect. It's replaced with a simple one. * Add some more introductory text * Add first example * Added more example and a table for proper formatting * Add few more examples * Formatting * Improve example * Edit description of character classes * Add a way to test regex Add https://regex101.com/ web application to test the regex provided in example. * Add example of trap command trap is a very important command to intercept a fatal signal, perform cleanup, and then exit gracefully. It needs an entry in this document. Here a simple and most common example of using trap command i.e. cleanup upon receiving signal is added. * Revert "Add example of trap command" * Add an example of trap command `trap` is a very important command to intercept a fatal signal, perform cleanup, and then exit gracefully. It needs an entry in this document. Here a simple and most common example of using `trap` command i.e. cleanup upon receiving signal is added. --- bash.html.markdown | 3 ++ pcre.html.markdown | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 pcre.html.markdown diff --git a/bash.html.markdown b/bash.html.markdown index 02d7f31e..c2c3e3f1 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -272,6 +272,9 @@ grep -c "^foo.*bar$" file.txt # and not the regex, use fgrep (or grep -F) fgrep "foobar" file.txt +# trap command allows you to execute a command when a signal is received by your script. +# Here trap command will execute rm if any one of the three listed signals is received. +trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM # Read Bash shell builtins documentation with the bash 'help' builtin: help diff --git a/pcre.html.markdown b/pcre.html.markdown new file mode 100644 index 00000000..0b61653d --- /dev/null +++ b/pcre.html.markdown @@ -0,0 +1,82 @@ +--- +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/`. + +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) + $ assert end of string (or line, in multiline mode) + . match any character except newline (by default) + [ start character class definition + | start of alternative branch + ( start subpattern + ) end subpattern + ? extends the meaning of ( + also 0 or 1 quantifier + also quantifier minimizer + * 0 or more quantifier + + 1 or more quantifier + also "possessive quantifier" + { start min/max quantifier +``` + +* 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. +``` + \d any decimal digit + \D any character that is not a decimal digit + \h any horizontal white space character + \H any character that is not a horizontal white space character + \s any white space character + \S any character that is not a white space character + \v any vertical white space character + \V any character that is not a vertical white space character + \w any "word" character + \W any "non-word" character +``` + +## 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. + +| Regex | Result | Comment | +| :---- | :-------------- | :------ | +| GET | GET | GET matches the characters GET literally (case sensitive) | +| \d+.\d+.\d+.\d+ | 66.249.64.13 | `\d+` match a digit [0-9] one or more times defined by `+` quantifier, `\.` matches `.` literally | +| (\d+\.){3}\d+ | 66.249.64.13 | `(\d+\.){3}` is trying to match group (`\d+\.`) exactly three times. | +| \[.+\] | [18/Sep/2004:11:07:48 +1000] | `.+` matches any character (except newline), `.` is any character | +| ^\S+ | 66.249.64.13 | `^` means start of the line, `\S+` matches any number of non-space characters | +| \+[0-9]+ | +1000 | `\+` matches the character `+` literally. `[0-9]` character class means single number. Same can be achieved using `\+\d+` | + +All these examples can be tried at https://regex101.com/ + +1. Copy the example string in `TEST STRING` section +2. Copy regex code in `Regular Expression` section +3. The web application will show the matching result + + +## Further Reading + + -- cgit v1.2.3 From 243ef338ab06a030ae9461a4162ae53f8f9603a3 Mon Sep 17 00:00:00 2001 From: julianaortga Date: Sun, 26 Jun 2016 07:38:29 -0500 Subject: update further reading [c/es] (#1829) --- es-es/c-es.html.markdown | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 5d3aae0c..8bc1eabb 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -418,8 +418,18 @@ typedef void (*my_fnp_type)(char *); ## Otras lecturas -Lo mejor que puedes en contrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) +Lo mejor que puedes encontrar es una copia de [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language). Es *el* +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://c.learncodethehardway.org/book/). + +Si tienes una pregunta, lee [compl.lang.c Frequently Asked Questions](http://c-faq.com). + +Es muy importante utilizar el espaciado y la sangría apropiados y ser coherente +con su estilo de codificación en general. El código legible es mejor que el +código rápido. Para adoptar un buen estilo de codificación, vea el +[Estilo de codificación del kernel Linux] (https://www.kernel.org/doc/Documentation/CodingStyle). Aparte de eso, Google es tu amigo. -- cgit v1.2.3 From 9592b8fc431708a5ddbcf0c18aef4e3b8c978cd3 Mon Sep 17 00:00:00 2001 From: julianaortga Date: Sun, 26 Jun 2016 07:39:14 -0500 Subject: [css/es] Updated translation (#1830) * updated resources and further reading [css/es] * minor fix and spellchecking --- es-es/css-es.html.markdown | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown index 31000785..6395f5fd 100644 --- a/es-es/css-es.html.markdown +++ b/es-es/css-es.html.markdown @@ -233,12 +233,21 @@ en todos los navegadores y dispositivos. Pero siempre es vital tener en mente la compatibilidad y disponibilidad del CSS que uses con respecto a los navegadores y dispositivos para los que desarrolles. - [QuirksMode CSS](http://www.quirksmode.org/css/) es una excelente referencia para esto. -## Referencias +## Recursos + +* Para ejecutar un test de compatibilidad, revisa [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS). +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/). + +## Otras lecturas -* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) -* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/). +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/). +* [QuirksMode CSS](http://www.quirksmode.org/css/). * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) y [LESS](http://lesscss.org/) para preprocesamiento CSS. +* [CSS-Tricks](https://css-tricks.com). -- cgit v1.2.3 From a24bafe5cbb26c4da8629439e19bb210ca1c9ee2 Mon Sep 17 00:00:00 2001 From: julianaortga Date: Sun, 26 Jun 2016 07:39:28 -0500 Subject: [git/es] updated further information (#1831) --- es-es/git-es.html.markdown | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 4e1e68ba..1a8e275a 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -398,6 +398,10 @@ $ git rm /directorio/del/archivo/FooBar.c * [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1) +* [Udemy tutorial de Git: Una guía completa](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Inmersión Git - Una visita guiada caminando a través de los fundamentos de git](http://gitimmersion.com/) + * [git-scm - Video-tutoriales](http://git-scm.com/videos) * [git-scm - Documentacion](http://git-scm.com/book/es) @@ -407,3 +411,9 @@ $ git rm /directorio/del/archivo/FooBar.c * [SalesForce Chuleta](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) * [GitGuys](http://www.gitguys.com/) + +* [Git - La guía simple](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) + +* [Una introducción a Git y Github para principiantes (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From 1311f4dbb29085167248e8a746b27a5e1bee7459 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:41:30 +0200 Subject: manually merge #1838 --- objective-c.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 0dbb3ae3..e41e71c3 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -20,7 +20,7 @@ Multi-line comments look like this */ // XCode supports pragma mark directive that improve jump bar readability -#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions' +#pragma mark Navigation Functions // New tag o@"Third number = %@", thirdNumber); // prin jump bar named 'Navigation Functions' #pragma mark - Navigation Functions // Same tag, now with a separator // Imports the Foundation headers with #import @@ -133,6 +133,8 @@ int main (int argc, const char * argv[]) NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3" + // Since Xcode 7, NSArray objects can be typed (Generics) + NSArray *stringArray = @[@"hello", @"world"]; // NSMutableArray is a mutable version of NSArray, allowing you to change // the items in the array and to extend or shrink the array object. // Convenient, but not as efficient as NSArray. @@ -146,6 +148,8 @@ int main (int argc, const char * argv[]) NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; NSLog(@"Object = %@", valueObject); // prints => "Object = (null)" + // Since Xcode 7, NSDictionary objects can be typed (Generics) + NSDictionary *numberDictionary = @{@"a": @1, @"b": @2}; // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; @@ -161,6 +165,8 @@ int main (int argc, const char * argv[]) // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) + // Since Xcode 7, NSSet objects can be typed (Generics) + NSSet *stringSet = [NSSet setWithObjects:@"hello", @"world", nil]; // NSMutableSet also available as a mutable set object NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; [mutableSet addObject:@"Hello"]; -- cgit v1.2.3 From d7af1e0b709a19506c4a6158537b1d1a14e79207 Mon Sep 17 00:00:00 2001 From: Sam van Kampen Date: Sun, 26 Jun 2016 14:43:53 +0200 Subject: Clarify sentences and fix spelling and space usage in nl-nl/yaml (#1822) --- nl-nl/yaml-nl.html.markdown | 53 +++++++++++++++++++++++---------------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown index a4a9d5fc..11af784f 100644 --- a/nl-nl/yaml-nl.html.markdown +++ b/nl-nl/yaml-nl.html.markdown @@ -5,21 +5,22 @@ contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Niels van Velzen", "https://nielsvanvelzen.me"] + - ["Sam van Kampen", "http://tehsvk.net"] lang: nl-nl --- -YAML is een data serialisatie taal ontworpen om snel te kunnen worden begrepen door mensen. +YAML is een dataserialisatietaal ontworpen om snel te kunnen worden begrepen door mensen. -Het is een strikte superset van JSON en bevat nieuwe regels en een stricte manier van inspringen, zoals bij Python. In tegenstelling tot Python kan je alleen geen tab tekens gebruiken. +Het is een strikte superset van JSON en bevat nieuwe regels en een strikte manier van inspringen die lijkt op de manier van Python. In tegenstelling tot Python kan je alleen geen tabtekens gebruiken. ```yaml # Commentaar in YAML ziet er zo uit -################ -# SCALAR TYPES # -################ +################## +# SCALAIRE TYPES # +################## -# Ons hoofd object (Wat in het hele document gebruikt wordt) is een map, +# Ons hoofdobject (Wat in het hele document gebruikt wordt) is een map; # dit staat gelijk aan een dictionary, hash of object in andere talen. sleutel: waarde nog_een_sleutel: Een andere waarde @@ -35,10 +36,10 @@ quote_waarde: "Een string in quotes" # Tekst over meerdere lijnen kan je schrijven als een 'letterlijk blok' (met |) # Of een 'gevouwen blok' (met >) letterlijk_blok: | - Dit hele blok met tekst is de waarde van de 'letterlijk_blok' sleutel, + Dit hele blok met tekst is de waarde van de 'letterlijk_blok'-sleutel, met nieuwe lijnen behouden. - Het blok blijft door gaan tot het geeindigd wordt door korter te inspringen. + Het blok blijft door gaan tot het geeindigd wordt door korter in te springen. Lijnen die groter zijn ingesprongen behouden dit. gevouwen_stijl: > @@ -50,9 +51,9 @@ gevouwen_stijl: > Meer ingesprongen lijnen zullen hun nieuwe lijnen ook behouden, deze tekst zal over 2 lijnen te zien zijn. -#################### -# COLLECTION TYPES # -#################### +################## +# COLLECTIETYPES # +################## # Nesten wordt bereikt met inspringen. geneste_map: @@ -61,7 +62,7 @@ geneste_map: andere_geneste_map: hallo: wereld -# In een map is een sleutel niet verplicht om een string te gebruiken +# In een map hoeft de sleutel geen string te zijn. 0.25: een float als sleutel # Sleutels kunnen ook meerdere lijnen gebruiken met behulp van het vraagteken @@ -70,14 +71,14 @@ geneste_map: met meerdere lijnen : en dit is de waarde -# YAML staat ook collection types toe in sleutels, maar veel programmeertalen +# YAML staat ook collectietypes toe in sleutels, maar veel programmeertalen # zullen hierover klagen. # Sequences (gelijk aan lijsten of arrays) zien er zo uit: een_sequence: - Item 1 - Item 2 - - 0.5 # sequences kunnen meerdere type waardes bevatten. + - 0.5 # sequences kunnen meerdere typen waardes bevatten. - Item 4 - sleutel: waarde andere_sleutel: andere waarde @@ -85,13 +86,13 @@ een_sequence: - Dit is een sequence - in een andere sequence -# Doordat YAML een superset van JSON is kan je ook JSON-stijl mappen en -# sequences maken: +# Doordat YAML een superset van JSON is kan je ook mappen en +# sequences volgens de JSON-stijl maken: json_map: {"sleutel": "waarde"} json_seq: [3, 2, 1, "takeoff"] ####################### -# EXTRA YAML FUNCTIES # +# EXTRA YAML-FUNCTIES # ####################### # YAML heeft ook een handige functie genaamd 'anchors' (ankers), deze laten je @@ -102,16 +103,16 @@ andere_anker: *anker_naam # YAML heeft ook tags, deze gebruik je om een expliciet type te verklaren expliciete_string: !!str 0.5 -# Sommige parsers gebruiken taal specifieke tags, zoals deze voor Python's -# complexe nummer type: +# Sommige parsers gebruiken taalspecifieke tags, zoals deze voor Python's +# complexe nummertype: python_complex_nummer: !!python/complex 1+2j -#################### -# EXTRA YAML TYPES # -#################### +####################### +# EXTRA TYPES IN YAML # +####################### -# Strings en nummer zijn niet de enige types die YAML begrijpt. -# ISO opgemaakte datum en datumtijd notaties werken ook: +# Strings en nummers zijn niet de enige types die YAML begrijpt. +# ISO opgemaakte datum- en datumtijdnotaties werken ook: datumtijd: 2001-12-15T02:59:43.1Z datumtijd_met_spaties: 2001-12-14 21:59:43.10 -5 datum: 2002-12-14 @@ -124,13 +125,13 @@ gif_bestand: !!binary | +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML heeft ook een set type, dat ziet er zo uit: +# YAML heeft ook een settype, dat ziet er zo uit: set: ? item1 ? item2 ? item3 -# Zoals in Python zijn sets gewoon mappen met null waardes; +# Zoals in Python zijn sets gewoon mappen met nulwaarden; # bovenstaand is gelijk aan: set2: item1: null -- cgit v1.2.3 From efec1d63ee081781e3009286b3df24b1dbea0ac6 Mon Sep 17 00:00:00 2001 From: Caio Mariano Date: Sun, 26 Jun 2016 09:45:07 -0300 Subject: correcoes ortograficas e adicao de alguns exemplos (#1849) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * correcoes ortogrÃaficas e adicao de alguns exemplos * mais explicacoes no documento * somente explicacoes mais detalhadas --- pt-br/php-pt.html.markdown | 66 ++++++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 31 deletions(-) diff --git a/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown index 0e710742..8a1c956e 100644 --- a/pt-br/php-pt.html.markdown +++ b/pt-br/php-pt.html.markdown @@ -7,7 +7,7 @@ translators: - ["Abdala Cerqueira", "http://abda.la"] - ["Raquel Diniz", "http://twitter.com/raquelrdiniz"] lang: pt-br -filename: learnphp-pt.php +filename: php-pt.html.markdown --- Este documento descreve PHP 5+. @@ -20,21 +20,23 @@ 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 (aka pound symbol) também inicia, mas // é mais comum. /* O texto envolto por barra-asterisco e asterisco-barra - faz um comentário de múltiplas linhas + faz um comentário de múltiplas linhas. */ -// Utilize "echo" ou "print" para imprimir a saída -print('Olá '); // Imprime "Olá " sem quebra de linha +// Utilize "echo" ou "print" para imprimir a saída. +print('Olá '); // Imprime "Olá " sem quebra de linha. +print 'Olá '; // Não tem a necessidade de utilizar as chaves. // () são opcionais para print e echo -echo "Mundo\n"; // Imprime "Mundo" com quebra de linha -// (Todas as declarações devem terminar com um ponto e vírgula) +echo "Mundo\n"; // Imprime "Mundo" com quebra de linha. +echo ("Mundo\n"); // Podemos tambem utilizar com chaves no echo. +// (Todas as declarações devem terminar com um ponto e vírgula.) -// Qualquer coisa fora da tag Olá mundo novamente! '$String' // Evite o uso de aspas duplas, exceto para incorporar outras variáveis $dbl_quotes = "Esta é uma $sgl_quotes."; // => 'Esta é uma $String.' -// Os caracteres especiais só são escapados entre aspas duplas -$escapado = "Este contém um \t caractere tab."; -$naoescapado = 'Este contém somente a barra e o t: \t'; +// Os caracteres especiais só são escapados entre aspas duplas. +$escapado = "Este contém um \t caractere tab."; +echo $escapado; //Imprime: Este contém um caractere tab. +$naoescapado = 'Este contém somente a barra e o t: \t'; +echo $naoescapado; //Imprime: Este contém somente a barra e o t: \t -// Coloque uma variável entre chaves se necessário +// Coloque uma variável entre chaves se necessário. $dinheiro = "Eu tenho $${numero} no banco."; // Desde o PHP 5.3, nowdocs podem ser usados para múltiplas linhas sem análise @@ -105,7 +109,7 @@ $sgl_quotes FIM; // Concatenação de string é feita com . -echo 'Esta string ' . 'é concatenada'; +echo 'Esta string ' . 'é concatenada'; //Imprime: 'Esta string é concatenada' /******************************** @@ -120,7 +124,7 @@ echo 'Esta string ' . 'é concatenada'; define("FOO", "alguma coisa"); // Acesso a uma constante é possível usando diretamente o nome escolhido -echo 'Isto sairá '.FOO; +echo 'Isto sairá '.FOO; //Imprime: Isto sairá alguma coisa /******************************** @@ -135,16 +139,16 @@ $associativo = array('Um' => 1, 'Dois' => 2, 'Tres' => 3); // PHP 5.4 introduziu uma nova sintaxe $associativo = ['Um' => 1, 'Dois' => 2, 'Tres' => 3]; -echo $associativo['Um']; // imprime 1 +echo $associativo['Um']; // Imprime 1. // Uma lista de literais atribui chaves inteiras implicitamente $array = ['Um', 'Dois', 'Tres']; -echo $array[0]; // => "Um" +echo $array[0]; // Imprime => "Um" // Adiciona um elemento no final do array $array[] = 'Quatro'; -// Remove um elemento do array +// Remove um elemento do array. unset($array[3]); /******************************** @@ -155,12 +159,12 @@ echo('Olá Mundo!'); // Imprime Olá Mundo! para stdout. // Stdout é uma página web se executado em um navegador. -print('Olá Mundo!'); // O mesmo que o echo +print('Olá Mundo!'); // O mesmo que o echo. // echo é atualmente um construtor de linguagem, então você pode // remover os parênteses. -echo 'Olá Mundo!'; -print 'Olá Mundo!'; // O print também é +echo 'Olá Mundo!'; // Imprime: Olá Mundo! +print 'Olá Mundo!'; // O print também é - Imprime: Olá Mundo! $paragrafo = 'parágrafo'; @@ -181,11 +185,11 @@ $z = &$y; // $z irá mudar o valor de $y também, e vice-versa. // $x irá permanecer inalterado com o valor original de $y -echo $x; // => 2 -echo $z; // => 2 +echo $x; // Imprime => 2 +echo $z; // Imprime => 2 $y = 0; -echo $x; // => 2 -echo $z; // => 0 +echo $x; // Imprime => 2 +echo $z; // Imprime => 0 // Despeja tipos e valores de variável para o stdout var_dump($z); // imprime int(0) @@ -222,13 +226,13 @@ assert(1 !== '1'); // As variáveis podem ser convertidas entre tipos, dependendo da sua utilização. $inteiro = 1; -echo $inteiro + $inteiro; // => 2 +echo $inteiro + $inteiro; // Imprime => 2 $string = '1'; -echo $string + $string; // => 2 (strings são coagidas para inteiros) +echo $string + $string; // Imprime => 2 (strings são coagidas para inteiros) $string = 'one'; -echo $string + $string; // => 0 +echo $string + $string; // Imprime => 0 // Imprime 0 porque o operador + não pode fundir a string 'um' para um número // Tipo de fundição pode ser utilizado para tratar uma variável -- cgit v1.2.3 From ebd74da99a73d9cbdba23285afc745a740a87e28 Mon Sep 17 00:00:00 2001 From: Harry Date: Sun, 26 Jun 2016 13:45:20 +0100 Subject: Added main attributes of javadocs. (#1850) --- java.html.markdown | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index a025bbba..fb0913f1 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -23,8 +23,17 @@ Multi-line comments look like this. */ /** -JavaDoc comments look like this. Used to describe the Class or various -attributes of a Class. + * JavaDoc comments look like this. Used to describe the Class or various + * attributes of a Class. + * Main attributes: + * + * @author Name (and contact information such as email) of author(s). + * @version Current version of the program. + * @since When this part of the program was first added. + * @param For describing the different parameters for a method. + * @return For describing what the method returns. + * @deprecated For showing the code is outdated or shouldn't be used. + * @see Links to another part of documentation. */ // Import ArrayList class inside of the java.util package -- cgit v1.2.3 From 9d17f8bc578c96bda52bd2611625bacb8b518afb Mon Sep 17 00:00:00 2001 From: Yi Hong Ang Date: Sun, 26 Jun 2016 20:45:45 +0800 Subject: Add a section on code sections/cells (#1855) --- matlab.html.markdown | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/matlab.html.markdown b/matlab.html.markdown index ddc0cb40..51b7bd4e 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -25,6 +25,23 @@ like this %} +% Two percent signs denote the start of a new code section +% Individual code sections can be run by moving the cursor to the section followed by +% either clicking the "Run Section" button +% or using Ctrl+Shift+Enter (Windows) or Cmd+Shift+Return (OS X) + +%% This is the start of a code section +% One way of using sections is to separate expensive but unchanging start-up code like loading data +load myFile.mat y + +%% This is another code section +% This section can be edited and run repeatedly on its own, and is helpful for exploratory programming and demos +A = A * 2; +plot(A); + +%% Code sections are also known as code cells or cell mode (not to be confused with cell arrays) + + % commands can span multiple lines, using '...': a = 1 + 2 + ... + 4 -- cgit v1.2.3 From e9ce4e2e6e401b9bb1f495d35c57141b4cffba22 Mon Sep 17 00:00:00 2001 From: Shawn McGuire Date: Sun, 26 Jun 2016 07:47:36 -0500 Subject: [csharp/en] Add string interpolation (#1864) Added example of using string interpolation --- csharp.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/csharp.html.markdown b/csharp.html.markdown index 8d185462..69aef257 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Wouter Van Schandevijl", "http://github.com/laoujin"] - ["Jo Pearce", "http://github.com/jdpearce"] - ["Chris Zimmerman", "https://github.com/chriszimmerman"] + - ["Shawn McGuire", "https://github.com/bigbash"] filename: LearnCSharp.cs --- @@ -947,6 +948,24 @@ on a new line! ""Wow!"", the masses cried"; A.A2(); } } + + // String interpolation by prefixing the string with $ + // and wrapping the expression you want to interpolate with { braces } + public class Rectangle + { + public int Length { get; set; } + public int Width { get; set; } + } + + class Program + { + static void Main(string[] args) + { + Rectangle rect = new Rectangle { Length = 5, Width = 3 }; + Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}"); + } + } + } // End Namespace ``` -- cgit v1.2.3 From 0387bd30fc91f82b19e8e60c8969391a5c04fc28 Mon Sep 17 00:00:00 2001 From: Prashant Khanduri Date: Sun, 26 Jun 2016 05:50:05 -0700 Subject: Generator explanation for python (#1870) More details and code on the same example as before. --- python.html.markdown | 51 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 2105748c..6c9da9a9 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -678,29 +678,46 @@ dir(math) ## 7. Advanced #################################################### -# Generators help you make lazy code +# Generators +# A generator "generates" values as they are requested instead of storing +# everything up front + +# The following method (*NOT* a generator) will double all values and store it +# in `double_arr`. For large size of iterables, that might get huge! def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + +# Running the following would mean we'll double all values first and return all +# of them back to be checked by our condition +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + +# We could instead use a generator to "generate" the doubled value as the item +# is being requested +def double_numbers_generator(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# Note xrange is a generator that does the same thing range does. -# Creating a list 1-900000000 would take lot of time and space to be made. -# xrange creates an xrange generator object instead of creating the entire list -# like range does. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -xrange_ = xrange(1, 900000000) - -# will double all numbers until a result >=30 found -for i in double_numbers(xrange_): - print i - if i >= 30: +# Running the same code as before, but with a generator, now allows us to iterate +# over the values and doubling them one by one as they are being consumed by +# our logic. Hence as soon as we see a value > 5, we stop break out of the +# loop and don't need to double most of the values sent in (MUCH FASTER!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: break +# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? +# Just as `double_numbers_generator` is the generator version of `double_numbers` +# We have `xrange` as the generator version of `range` +# `range` would return back and array with 1000000 values for us to use +# `xrange` would generate 1000000 values for us as we request / iterate over those items + + # Decorators # in this example beg wraps say -- cgit v1.2.3 From 8e19b8ebba863acd3f140320649cd472d1928564 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Costa?= Date: Sun, 26 Jun 2016 13:50:52 +0100 Subject: [swift/pt-pt] Add Swift Portuguese translation (#1740) * Start swift pt-pt translation * Start swift pt-pt translation * Finish Collections Section * Finish Control Flow Section * Finish Functions Section * Finish Structures Section * Finish Classes Section * Finish translating Enums Section * Finish Protocols Sections translation * Finish Other Section translation --- pt-pt/swift.html.markdown | 608 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 608 insertions(+) create mode 100644 pt-pt/swift.html.markdown diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift.html.markdown new file mode 100644 index 00000000..f27c3043 --- /dev/null +++ b/pt-pt/swift.html.markdown @@ -0,0 +1,608 @@ +--- +language: swift +filename: learnswift-pt.swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] + - ["Clayton Walker", "https://github.com/cwalk"] + - ["João Costa", "https://github.com/joaofcosta"] +lang: pt-pt +--- + +Swift é uma linguagem de programação criada pela Apple para o desenvolvimento em iOS e OS X. +Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple. +Swift usa o compilador LLVM incluido no XCode 6+. + +O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via iBooks. + +Consulta também o [guia de iniciação](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) da Apple, que contêm um tutorial completo em Swift. + +```swift +// importar um módulo +import UIKit + +// +// MARK: Básico +// + +// O Xcode suporta landmarks para anotação de código e lista-as na jump bar +// MARK: Marco de secção (MARK) +// TODO: Algo a fazer em breve +// FIXME: Reparar este código + +// Em Swift 2, println e print foram unidos num só método print. O print automaticamente acrescenta uma nova linha. +print("Hello, world") // println mudou para print +print("Hello, world", appendNewLine: false) // imprimir sem acrescentar uma nova linha + +// variáveis (var) podem ser modificadas depois de inicializadas +// constantes (let) NÂO podem ser modificadas depois de inicializadas + +var myVariable = 42 +let øπΩ = "value" // nomes de variáveis em unicode +let π = 3.1415926 +let convenience = "keyword" // nome de variável contextual +let weak = "keyword"; let override = "another keyword" // expressões podem ser separadas com ';' +let `class` = "keyword" // plicals permitem que keywords sejam usadas como nomes de vartiáveis +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // interpolação de Strings + +// Valores especificos à build +// usam a configuração de build -D +#if false + print("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +print("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals são um dos recursos de Swift, Optionals tanto podem conter + um valor ou conter nil (sem valor) que indica que não existe um valor. + Adicionar um ponto de exclamção (?) após definir o tipo declara + esse valor como um Optional. + + Como Swift requere que todas as propriedades tenham um valor, até nil + tem que ser explicitamente guardado como um valor Optional. + + Optional é uma enumeração. +*/ +var someOptionalString: String? = "optional" // Pode assumir o valor nil +// Igual ao de cima, mas ? é um operando pósfixo (açúcar sintático) +var someOptionalString2: Optional = "optional" + +if someOptionalString != nil { + // Não sou nil + if someOptionalString!.hasPrefix("opt") { + print("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +/* + Tentar usar ! para aceder a Optional com valor não existente, ou seja, nil, + causa em erro de execução. + É necessário ter sempre a certeza que um Optional não tem valor nil + antes de usar ! para fazer 'force-unwrap' ao seu valor. +*/ + +// Optional implicitamente desembrulhado +var unwrappedString: String! = "Value is expected." +// O mesmo de cima, mas ! é um operando pósfixo (mais açúcar sintático) +var unwrappedString2: ImplicitlyUnwrappedOptional = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // Tem um valor diferente de nil + if !someOptionalStringConstant.hasPrefix("ok") { + // Não tem o prefixo + } +} + +// Swift tem suporte para guardar valores de qualquer tipo. +// AnyObject == id +// Ao contrátio do `id` de Objective-C, AnyObject funciona com qualquer valor (Class, Int, struct, etc.) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." + +/* + Comentar aqui + + /* + Também é possível fazer comentários aninhados + */ +*/ + +// +// MARK: Coleções (Collections) +// + +/* + Os tipos Array e Dictionary são structs e, portanto, `let` e `var` + também indicam se eles são mutáveis (var) or imutáveis (let) + na altura em que se declaram estes tipos. +*/ + +// Array +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = [String]() // let == imutável +let emptyArray2 = Array() // mesmo de cima +var emptyMutableArray = [String]() // var == mutável + + +// Dictionary +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = [String: Float]() // let == imutável +let emptyDictionary2 = Dictionary() // mesmo de cima +var emptyMutableDictionary = [String: Float]() // var == mutável + + +// +// MARK: Controlo de Fluxo (Control Flow) +// + +// for loop (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + print("One!") + } else { + print("Not one!") + } +} + +// for loop (dictionary) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// ciclo for (limite) +for i in -1...shoppingList.count { + print(i) +} +shoppingList[1...2] = ["steak", "peacons"] +// usar ..< para excluir o último número + +// ciclo while +var i = 1 +while i < 1000 { + i *= 2 +} + +// ciclo do-whie +do { + print("hello") +} while 1 == 2 + +// Switch +// Muito poderoso, imagine `if`s com açúcar sintático +// Funciona para String, instâncias de objectos e primitivas (Int, Double, etc.) +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" +default: // obrigatório (de forma a cobrir todos os possíveis inputs) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// MARK: Funções (Functions) +// + +// Funções são tipos de primeira classe, o que significa que podem ser +// aninhadas dentro de outras funções e passadas como argumento + +// Função em Swift com documentação no header + +/** + Função de cumprimento. + + - Um ponto em documentação + - Outro ponto na documentação + + :param: nome Um nome + :param: dia Um dia + :returns: Uma string com um cumprimento contendo o nome e o dia. +*/ +func greet(nome: String, dia: String) -> String { + return "Hello \(nome), today is \(dia)." +} +greet("Bob", "Tuesday") + +// Semelhante ao método de cima excepto ao comportamento dos argumentos +func greet2(#nomeObrigatório: String, nomeArgumentoExterno nomeArgumentoLocal: String) -> String { + return "Hello \(nomeObrigatório), the day is \(nomeArgumentoLocal)" +} +greet2(nomeObrigatório:"John", nomeArgumentoExterno: "Sunday") + +// Função que devolve vários itens num tuplo +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Ignorar tuplos ou outros valores usando _ (underscore) +let (_, price1, _) = pricesTuple // price1 == 3.69 +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") + +// Argumentos variáveis +func setup(numbers: Int...) { + // é um array + let number = numbers[0] + let argCount = numbers.count +} + +// Passar e devolver funções +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// Passar por referência (inout) +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closures +// +var numbers = [1, 2, 6] + +// Funções são casos especiais de closures ({}) + +// Exemplo de um Closure. +// `->` separa o argumento e o tipo de retorno. +// `in` separa o cabeçalho do closure do corpo do closure. +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Quando o tipo é conhecido, como em cima, podemos fazer o seguinte +numbers = numbers.map({ number in 3 * number }) +// Ou até mesmo isto +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Closure à direita (Trailing closure) +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super curto, pois o operador < consegue inferir o tipo + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Estruturas (Structures) +// + +// Estruturas (struct) e classes (class) têm capacidades muito semelhantes +struct NamesTable { + let names = [String]() + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Estruturas têm um inicializador implicito que é automaticamente gerado +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +print("Name is \(name)") // Name is Them + +// +// MARK: Classes +// + +// Classes, estruturas e os seus membros têm três níveis de controlo de acesso +// Nomeadamente: interno (predefinição)(internal) , público (public), privado (private) + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Todos os métodos e propriedades de uma classe são públicos. +// Se só for necessário guarda dados num +// objecto estruturado, então é melhor usar uma `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Propriedade getter e setter personalizado + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` é uma variável implicita disponível aos setters + sideLength = newValue / 4 + } + } + + // Carregar preguiçosamente uma propriedade + // subShape permanece a nil (unintialized) até o getter ser invocado + lazy var subShape = Rect(sideLength: 4) + + // Se não for necessário um getter e setter personalizado, + // mas se quiser correr o código antes e depois de modificar ou aceder + // uma propriedade, é possível usar `willSet` e `didSet` + var identifier: String = "defaultID" { + // o argumento de `willSet` é o nome da variável para o novo valor + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // invocar super.init no final do método de inicialização + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// A class `Square` estende (extends) a classe `Rect` (hierarquia) +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// Cast de uma instância de `Square` para `Shape` +let aShape = mySquare as Shape + +// Compara instâncias, não é igual a == , visto que == compara objects (igual a) +if mySquare === mySquare { + print("Yep, it's mySquare") +} + +// Inicializador (init) com Optional +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Colocar um ponto de interrpgação depois de `init` cria um inicializador + // Optional, o qual pode retornar nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +print(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // Não vai executar pois a variável myEmptyCircle é igual a nil + print("circle is not nil") +} + + +// +// MARK: Enumerações (Enums) +// + +// Enums pode opcionalmente ser um tipo especifico ou não. +// Enums podem conter métodos tal como as classes. + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum +// quando a variável é explicitamente definida. +var suitValue: Suit = .Hearts + +// Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(BookName.John.rawValue)") + +// Enum com valores associados +enum Furniture { + // Associar com um inteiro (Int) + case Desk(height: Int) + // Associar com uma String e um Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +print(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +print(chair.description()) // "Chair of Foo with 40 cm" + + +// +// MARK: Protocolos (Protocols) +// + +// Protocolos (`protcol`s) obrigam a que os tipos tenham +// propriedades de instância, métodos de instância, métodos de tipo, +// operadores e subscripts específicos. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Protocolos definidos com @objc permitem funções com optional +// que permitem verificar se existem conformidade +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + // Coloca um ponto de interrogação após uma propriedade opcional, método + // ou subscript para graciosamente ignorar um valor nil e retornar nil + // em vez de provoar um erro em tempo de execução ("optional chaining"). + if let allow = self.delegate?.canReshape?() { + // testar o delegate e depois o método + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Outro +// + +// extensões (`extension`s): Adiciona funcionalidade extra a um tipo já existente. + +// Square agora "conforma" com o protocolo `Printable` +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +print("Square: \(mySquare)") + +// Também é possível extender tipos já embutidos +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 + +// Generics: Semelhante a Java e C#. Usa a palavra-chave `where` para +// especificar requisitos do `generics`. + +func findIndex(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +print(foundAtIndex == 2) // true + +// Operadores: +// Operadores personalizados podem começar com caracteres: +// / = - + * % < > ! & | ^ . ~ +// ou +// Caracteres Unicode matemáticos, símbolos, setas, dingbat e +// caracteres de desenho linha/caixa. +operador prefixo !!! {} + +// Um operador prefixo que triplica o comprimento do lado quando usado +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// valor atual +print(mySquare.sideLength) // 4 + +// muda o comprimento deste lado usando o operador personalizado !!!, aumenta +// o comprimento 3x +!!!mySquare +print(mySquare.sideLength) // 12 + +// Operadores também podem ser generics +infix operator <-> {} +func <-> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" +``` -- cgit v1.2.3 From e65c618e29d971509a30d9395bd8341a1c52bce2 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:51:06 +0200 Subject: Update swift.html.markdown --- pt-pt/swift.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/pt-pt/swift.html.markdown b/pt-pt/swift.html.markdown index f27c3043..2a964bde 100644 --- a/pt-pt/swift.html.markdown +++ b/pt-pt/swift.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Joey Huang", "http://github.com/kamidox"] - ["Anthony Nguyen", "http://github.com/anthonyn60"] - ["Clayton Walker", "https://github.com/cwalk"] +translators: - ["João Costa", "https://github.com/joaofcosta"] lang: pt-pt --- -- cgit v1.2.3 From 75a5764000b53faf4a49e4e456591ef0cfd93b77 Mon Sep 17 00:00:00 2001 From: ditam Date: Sun, 26 Jun 2016 14:51:24 +0200 Subject: add Hungarian translation (#1874) --- hu-hu/typescript-hu.html.markdown | 174 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 hu-hu/typescript-hu.html.markdown diff --git a/hu-hu/typescript-hu.html.markdown b/hu-hu/typescript-hu.html.markdown new file mode 100644 index 00000000..88d13a9c --- /dev/null +++ b/hu-hu/typescript-hu.html.markdown @@ -0,0 +1,174 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Tamás Diószegi", "https://github.com/ditam"] +filename: learntypescript-hu.ts +--- + +A TypeScript nyelv a JavaScript nyelven írt nagy méretű alkalmazások fejlesztését kívánja megkönnyíteni. +A TypeScript olyan, más nyelvekből ismert gyakori fogalmakat ad hozzá a JavaScripthez, mint például osztályok, interfészek, generikusság, és (opcionális) statikus típusosság. +A JavaScript egy befoglaló halmazát képzi: minden JavaScript kód érvényes TypeScript kód, így könnyen hozzáadható meglévő projektekhez. A TypeScript fordító kimenetként JavaScript kódot állít elő. + +Ez a dokumentum a TypeScript által hozzáadott új szintaxissal foglalkozik, nem pedig a [Javascripttel](../javascript/). + +Hogy kipróbáld a TypeScript fordítót, látogass el a [Játszótérre avagy Playground-ra](http://www.typescriptlang.org/Playground) ahol kódot írhatsz automatikus kódkiegészítéssel, és közvetlenül láthatod az előállított JavaScript kódot. + +```js +// 3 alapvető típus létezik TypeScriptben +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Amikor nem lehet a típust előre tudni, használható az "Any" típus +var notSure: any = 4; +notSure = "talán mégis sztring lesz"; +notSure = false; // tévedtem, mégis boolean + +// Kollekciókból létezik típusos és generikus tömb +var list: number[] = [1, 2, 3]; +// ugyanez a generikus típus használatával +var list: Array = [1, 2, 3]; + +// Enumerált típusok: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Végül, "void" használható a visszatérési értékkel nem bíró függvényeknél +function bigHorribleAlert(): void { + alert("Kis idegesítő doboz vagyok!"); +} + +// A függvények elsőrangú (first-class) típusok, használható a vastag nyilas +// lambda szintaxis, +// a compiler pedig kikövetkezteti a típusokat (inferred types) + +// A következők egyenértékűek, ugyanaz a szignatúra kerül kikövetkeztetésre, és +// így ugyanaz a JavaScript kód lesz előállítva +var f1 = function(i: number): number { return i * i; } +// Következtetett visszatérési értékkel +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Következtetett visszatérési értékkel +var f4 = (i: number) => { return i * i; } +// Következtetett visszatérési értékkel, +// ebben az egysoros formában nem szükséges a return kulcsszó +var f5 = (i: number) => i * i; + +// Az interfészek szerkezeti alapon működnek, vagyis minden objektum, ahol +// jelen vannak a megfelelő mezők kompatibilis az interfésszel +interface Person { + name: string; + // Az opcionális tagokat "?" jelöli + age?: number; + // És persze függvények is: + move(): void; +} + +// Egy objektum, ami megvalósítja a "Person" interfészt +// Tekinthető Personnek, hiszen van name és move mezője +var p: Person = { name: "Bobby", move: () => {} }; +// Egy objektum, ahol az opcionális mező is jelen van: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Ez viszont nem Person, mert az age mező típusa nem szám! +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Az interfészekkel függvény típusok is leírhatóak: +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Csak a paraméterek típusai számítanak, a neveik nem. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Osztályok - a mezők alapértelmezésben publikusak +class Point { + // Mezők + x: number; + + // Konstruktor - a public/private kulcsszavak ebben a kontextusban + // legenerálják a mezőkhöz szükséges kódot a konstruktorban. + // Ebben a példában az "y" ugyanúgy definiálva lesz, mint az "x", csak + // kevesebb kóddal. + // Alapértelmezett (default) értékek is megadhatóak. + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Metódusok + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Statikus mezők + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y itt 0 lesz + +// Öröklés +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Szükséges az ősosztály konstruktorának explicit hívása + } + + // Felülírás + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modulok +// ("." használható az almodulok számára) +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Új lokális név definiálása a module számára +import G = Geometry; + +var s2 = new G.Square(10); + +// Generikus típusok +// Osztályok +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfészek +interface Pair { + item1: T; + item2: T; +} + +// és függvények +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// definíciós fájl hivatkozása: +/// + +``` + +## További források + * [TypeScript hivatalos weboldala] (http://www.typescriptlang.org/) + * [TypeScript nyelv specifikációja (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Forráskód GitHubon] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - típusdefiníciók gyűjteménye] (http://definitelytyped.org/) \ No newline at end of file -- cgit v1.2.3 From 49bc5c8f11cd2717e0dff524ca936bd18c9de11d Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:51:54 +0200 Subject: metadata fixup for #1874 --- hu-hu/typescript-hu.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hu-hu/typescript-hu.html.markdown b/hu-hu/typescript-hu.html.markdown index 88d13a9c..aedd5a64 100644 --- a/hu-hu/typescript-hu.html.markdown +++ b/hu-hu/typescript-hu.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Tamás Diószegi", "https://github.com/ditam"] filename: learntypescript-hu.ts +lang: hu-hu --- A TypeScript nyelv a JavaScript nyelven írt nagy méretű alkalmazások fejlesztését kívánja megkönnyíteni. @@ -171,4 +172,4 @@ var tuple = pairToTuple({ item1:"hello", item2:"world"}); * [TypeScript nyelv specifikációja (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) * [Forráskód GitHubon] (https://github.com/Microsoft/TypeScript) - * [Definitely Typed - típusdefiníciók gyűjteménye] (http://definitelytyped.org/) \ No newline at end of file + * [Definitely Typed - típusdefiníciók gyűjteménye] (http://definitelytyped.org/) -- cgit v1.2.3 From 59adb3cca3447c8099fb5b5dab5dd22630232094 Mon Sep 17 00:00:00 2001 From: Abhishek Jaisingh Date: Sun, 26 Jun 2016 18:22:17 +0530 Subject: Ds (#1879) * created binary search doc started contributing * Updated binary search * Added new info --- binary-search.html | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 binary-search.html diff --git a/binary-search.html b/binary-search.html new file mode 100644 index 00000000..68a54c2a --- /dev/null +++ b/binary-search.html @@ -0,0 +1,63 @@ +--- +category: Algorithms & Data Structures +name: Binary Search +contributors: + - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"] +--- + +# Binary Search + +## Why Binary Search? + +Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. + +## Introduction + +A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1. + +``` +Linear Search: O (n) Linear Time + +Binary Search: O ( log(n) ) Logarithmic Time + +``` +``` +def search(arr, x): + + for i in range(len(arr)): + + if arr[i] == x: + return i + + return -1 + +``` +## Binary Search Algorithm + +The basic requirement for binary search to work is that the data to search should be sorted (in any order). +### Algo + +``` +The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. +1) Compare x with the middle element. +2) If x matches with middle element, we return the mid index. +3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. +4) Else (x is smaller) recur for the left half. +Following is Recursive implementation of Binary Search. + +``` + +### Ending Notes + +There is another form of binary search that is very useful. + +## Books + +* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms) +* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Online Resources + +* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/) +* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) \ No newline at end of file -- cgit v1.2.3 From b76e66ed9be842c573deedbf6835f8e28685ac50 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:52:42 +0200 Subject: fixup filename for #1879 --- binary-search.html | 63 --------------------------------------------- binary-search.html.markdown | 63 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 63 deletions(-) delete mode 100644 binary-search.html create mode 100644 binary-search.html.markdown diff --git a/binary-search.html b/binary-search.html deleted file mode 100644 index 68a54c2a..00000000 --- a/binary-search.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -category: Algorithms & Data Structures -name: Binary Search -contributors: - - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"] ---- - -# Binary Search - -## Why Binary Search? - -Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. - -## Introduction - -A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1. - -``` -Linear Search: O (n) Linear Time - -Binary Search: O ( log(n) ) Logarithmic Time - -``` -``` -def search(arr, x): - - for i in range(len(arr)): - - if arr[i] == x: - return i - - return -1 - -``` -## Binary Search Algorithm - -The basic requirement for binary search to work is that the data to search should be sorted (in any order). -### Algo - -``` -The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. -1) Compare x with the middle element. -2) If x matches with middle element, we return the mid index. -3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. -4) Else (x is smaller) recur for the left half. -Following is Recursive implementation of Binary Search. - -``` - -### Ending Notes - -There is another form of binary search that is very useful. - -## Books - -* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms) -* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) -* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) - -## Online Resources - -* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/) -* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) \ No newline at end of file diff --git a/binary-search.html.markdown b/binary-search.html.markdown new file mode 100644 index 00000000..92df4875 --- /dev/null +++ b/binary-search.html.markdown @@ -0,0 +1,63 @@ +--- +category: Algorithms & Data Structures +name: Binary Search +contributors: + - ["Abhishek Jaisingh", "http://github.com/abhishekjiitr"] +--- + +# Binary Search + +## Why Binary Search? + +Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. + +## Introduction + +A simple approach to implement search is to do a linear search, but this approach takes a lot of time and this time grows linearly with the amount or number of data points. i.e., start from the leftmost element of arr[] and one by one compare x with each element of arr[], if x matches with an element, return the index. If x doesn’t match with any of elements, return -1. + +``` +Linear Search: O (n) Linear Time + +Binary Search: O ( log(n) ) Logarithmic Time + +``` +``` +def search(arr, x): + + for i in range(len(arr)): + + if arr[i] == x: + return i + + return -1 + +``` +## Binary Search Algorithm + +The basic requirement for binary search to work is that the data to search should be sorted (in any order). +### Algo + +``` +The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Logn). We basically ignore half of the elements just after one comparison. +1) Compare x with the middle element. +2) If x matches with middle element, we return the mid index. +3) Else If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half. +4) Else (x is smaller) recur for the left half. +Following is Recursive implementation of Binary Search. + +``` + +### Ending Notes + +There is another form of binary search that is very useful. + +## Books + +* [CLRS](https://mitpress.mit.edu/books/introduction-algorithms) +* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Online Resources + +* [GeeksforGeeks](http://www.geeksforgeeks.org/the-ubiquitous-binary-search-set-1/) +* [Topcoder Tutorial](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/) -- cgit v1.2.3 From eda92c01650f21ed43fea92b7e4535647defd3bd Mon Sep 17 00:00:00 2001 From: Paulo Henrique Rodrigues Pinheiro Date: Sun, 26 Jun 2016 09:55:40 -0300 Subject: Output example had a value more (#1876) * Output example had a value more * Added pt-br translation for python3 --- pt-br/python3-pt.html.markdown | 747 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 747 insertions(+) create mode 100644 pt-br/python3-pt.html.markdown diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown new file mode 100644 index 00000000..0fef2528 --- /dev/null +++ b/pt-br/python3-pt.html.markdown @@ -0,0 +1,747 @@ +--- +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"] +filename: learnpython3.py +translators: + - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] +language: pt-br +filename: learnpython3-pt-br.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. + +Suas opiniões são grandemente apreciadas. Você pode encontrar-me em +[@louiedinh](http://twitter.com/louiedinh) ou louiedinh [em] +[serviço de e-mail do google]. + +Observação: Este artigo trata de Python 3 especificamente. Verifique +[aqui](http://learnxinyminutes.com/docs/pt-br/python-pt/) se você pretende +aprender o velho Python 2.7. + +```python + +# Comentários em uma única linha começam com uma cerquilha (também conhecido por sustenido). + +""" Strings de várias linhas podem ser escritas + usando três ", e são comumente usadas + como comentários. +""" + +#################################################### +## 1. Tipos de dados primitivos e operadores +#################################################### + +# Você usa números normalmente +3 # => 3 + +# Matemática é como você espera que seja +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Números inteiros por padrão, exceto na divisão, que retorna número +# de ponto flutuante (float). +35 / 5 # => 7.0 + +# O resultado da divisão inteira arredonda para baixo tanto para números +# positivos como para negativos. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona em float também +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quando você usa um float, o resultado é float. +3 * 2.0 # => 6.0 + +# operador módulo +7 % 3 # => 1 + +# Exponenciação (x**y, x elevado à potência y) +2**4 # => 16 + +# Determine a precedência usando parêntesis +(1 + 3) * 2 # => 8 + +# Valores lógicos são primitivos (Atenção à primeira letra maiúscula) +True +False + +# negação lógica com not +not True # => False +not False # => True + +# Operadores lógicos +# Observe que "and" e "or" são sensíveis a maiúsculas e minúsculas +True and False # => False +False or True # => True + +# Observe a utilização de operadores lógicos com números inteiros +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Igualdade é == +1 == 1 # => True +2 == 1 # => False + +# Diferença é != +1 != 1 # => False +2 != 1 # => True + +# Mais comparações +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Comparações podem ser agrupadas +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (operador 'is' e operador '==') is verifica se duas referenciam um +# mesmo objeto, mas == verifica se as variáveis apontam para o +# mesmo valor. +a = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b = a # b referencia o que está referenciado por a +b is a # => True, a e b referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo +b = [1, 2, 3, 4] # Referência a uma nova lista, [1, 2, 3, 4] +b is a # => False, a e b não referenciam o mesmo objeto +b == a # => True, objetos a e b tem o mesmo conteúdo + +# Strings são criadas com " ou ' +"Isto é uma string." +'Isto também é uma string.' + +# Strings também podem ser somadas! Mas tente não fazer isso. +"Olá " + "mundo!" # => "Olá mundo!" +# Strings podem ser somadas sem usar o '+' +"Olá " "mundo!" # => "Olá mundo!" + +# Uma string pode ser manipulada como se fosse uma lista de caracteres +"Isso é uma string"[0] # => 'I' + +# .format pode ser usado para formatar strings, dessa forma: +"{} podem ser {}".format("Strings", "interpoladas") # => "Strings podem ser interpoladas" + +# Você pode repetir os argumentos para digitar menos. +"Seja ágil {0}, seja rápido {0}, salte sobre o {1} {0}".format("Jack", "castiçal") +# => "Seja ágil Jack, seja rápido Jack, salte sobre o castiçal Jack." + +# Você pode usar palavras-chave se quiser contar. +"{nome} quer comer {comida}".format(nome="Beto", comida="lasanha") # => "Beto quer comer lasanha" + +# Se você precisa executar seu código Python3 com um interpretador Python 2.5 ou acima, você pode usar a velha forma para formatação de texto: +"%s podem ser %s da forma %s" % ("Strings", "interpoladas", "antiga") # => "Strings podem ser interpoladas da forma antiga" + + +# None é um objeto +None # => None + +# Não use o operador de igualdade "==" para comparar objetos com None +# Use "is" para isso. Ele checará pela identidade dos objetos. +"etc" is None # => False +None is None # => True + +# None, 0, e strings/listas/dicionários vazios todos retornam False. +# Qualquer outra coisa retorna True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. Variáveis e coleções +#################################################### + +# Python tem uma função print +print("Eu sou o Python. Prazer em conhecer!") # => Eu sou o Python. Prazer em conhecer! + +# Por padrão a função print também imprime o caractere de nova linha ao final. +# Use o argumento opcional end para mudar o caractere final. +print("Olá, Mundo", end="!") # => Olá, Mundo! + +# Forma simples para capturar dados de entrada via console +input_string_var = input("Digite alguma coisa: ") # Retorna o que foi digitado em uma string +# Observação: Em versões antigas do Python, o método input() era chamado raw_input() + +# Não é necessário declarar variáveis antes de iniciá-las +# È uma convenção usar letras_minúsculas_com_sublinhados +alguma_variavel = 5 +alguma_variavel # => 5 + +# Acessar uma variável que não tenha sido inicializada gera uma exceção. +# Veja Controle de Fluxo para aprender mais sobre tratamento de exceções. +alguma_variavel_nao_inicializada # Gera a exceção NameError + +# Listas armazenam sequencias +li = [] +# Você pode iniciar com uma lista com alguns valores +outra_li = [4, 5, 6] + +# Adicionar conteúdo ao fim da lista com append +li.append(1) # li agora é [1] +li.append(2) # li agora é [1, 2] +li.append(4) # li agora é [1, 2, 4] +li.append(3) # li agora é [1, 2, 4, 3] +# Remover do final da lista com pop +li.pop() # => 3 e agora li é [1, 2, 4] +# Vamos colocá-lo lá novamente! +li.append(3) # li agora é [1, 2, 4, 3] novamente. + +# Acessar uma lista da mesma forma que você faz com um array +li[0] # => 1 +# Acessa o último elemento +li[-1] # => 3 + +# Acessando além dos limites gera um IndexError +li[4] # Gera o IndexError + +# Você pode acessar vários elementos com a sintaxe de limites +# (É um limite fechado, aberto pra você que gosta de matemática.) +li[1:3] # => [2, 4] +# Omitindo o final +li[2:] # => [4, 3] +# Omitindo o início +li[:3] # => [1, 2, 4] +# Selecione cada segunda entrada +li[::2] # => [1, 4] +# Tenha uma cópia em ordem invertida da lista +li[::-1] # => [3, 4, 2, 1] +# Use qualquer combinação dessas para indicar limites complexos +# li[inicio:fim:passo] + +# Faça uma cópia profunda de um nível usando limites +li2 = li[:] # => li2 = [1, 2, 4, 3] mas (li2 is li) resultará em False. + +# Apague elementos específicos da lista com "del" +del li[2] # li agora é [1, 2, 3] + +# Você pode somar listas +# Observação: valores em li e other_li não são modificados. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concatene listas com "extend()" +li.extend(other_li) # Agora li é [1, 2, 3, 4, 5, 6] + +# Verifique se algo existe na lista com "in" +1 in li # => True + +# Examine tamanho com "len()" +len(li) # => 6 + + +# Tuplas são como l istas, mas imutáveis. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Gera um TypeError + +# Observe que uma tupla de tamanho um precisa ter uma vírgula depois do +# último elemento mas tuplas de outros tamanhos, mesmo vazias, não precisa,. +type((1)) # => +type((1,)) # => +type(()) # => + +# Você pode realizar com tuplas a maior parte das operações que faz com listas +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Você pode desmembrar tuplas (ou listas) em variáveis. +a, b, c = (1, 2, 3) # a é 1, b é 2 e c é 3 +# Por padrão, tuplas são criadas se você não coloca parêntesis. +d, e, f = 4, 5, 6 +# Veja como é fácil permutar dois valores +e, d = d, e # d é 5, e é 4 + +# Dicionários armazenam mapeamentos +empty_dict = {} +# Aqui está um dicionário preenchido na definição da referência +filled_dict = {"um": 1, "dois": 2, "três": 3} + +# Observe que chaves para dicionários devem ser tipos imutáveis. Isto é para +# assegurar que a chave pode ser convertida para uma valor hash constante para +# buscas rápidas. +# Tipos imutáveis incluem inteiros, flotas, strings e tuplas. +invalid_dict = {[1,2,3]: "123"} # => Gera um TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Já os valores, podem ser de qualquer tipo. + +# Acesse valores com [] +filled_dict["um"] # => 1 + +# Acesse todas as chaves como um iterável com "keys()". É necessário encapsular +# a chamada com um list() para transformá-las em uma lista. Falaremos sobre isso +# mais adiante. Observe que a ordem de uma chave de dicionário não é garantida. +# Por isso, os resultados aqui apresentados podem não ser exatamente como os +# aqui apresentados. +list(filled_dict.keys()) # => ["três", "dois", "um"] + + +# Acesse todos os valores de um iterável com "values()". Novamente, é +# necessário encapsular ele com list() para não termos um iterável, e sim os +# valores. Observe que, como foi dito acima, a ordem dos elementos não é +# garantida. +list(filled_dict.values()) # => [3, 2, 1] + + +# Verifique a existência de chaves em um dicionário com "in" +"um" in filled_dict # => True +1 in filled_dict # => False + +# Acessar uma chave inexistente gera um KeyError +filled_dict["quatro"] # KeyError + +# Use o método "get()" para evitar um KeyError +filled_dict.get("um") # => 1 +filled_dict.get("quatro") # => None +# O método get permite um parâmetro padrão para quando não existir a chave +filled_dict.get("um", 4) # => 1 +filled_dict.get("quatro", 4) # => 4 + +# "setdefault()" insere em dicionário apenas se a dada chave não existir +filled_dict.setdefault("cinco", 5) # filled_dict["cinco"] tem valor 5 +filled_dict.setdefault("cinco", 6) # filled_dict["cinco"] continua 5 + +# Inserindo em um dicionário +filled_dict.update({"quatro":4}) # => {"um": 1, "dois": 2, "três": 3, "quatro": 4} +#filled_dict["quatro"] = 4 #outra forma de inserir em um dicionário + +# Remova chaves de um dicionário com del +del filled_dict["um"] # Remove a chave "um" de filled_dict + + +# Armazenamento em sets... bem, são conjuntos +empty_set = set() +# Inicializa um set com alguns valores. Sim, ele parece um dicionário. Desculpe. +some_set = {1, 1, 2, 2, 3, 4} # some_set agora é {1, 2, 3, 4} + +# Da mesma forma que chaves em um dicionário, elementos de um set devem ser +# imutáveis. +invalid_set = {[1], 1} # => Gera um TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Pode definir novas variáveis para um conjunto +filled_set = some_set + +# Inclua mais um item no set +filled_set.add(5) # filled_set agora é {1, 2, 3, 4, 5} + +# Faça interseção de conjuntos com & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Faça união de conjuntos com | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Faça a diferença entre conjuntos com - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Verifique a existência em um conjunto com in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Controle de fluxo e iteráveis +#################################################### + +# Iniciemos um variável +some_var = 5 + +# Aqui está uma expressão if. Indentação é significante em python! +# imprime "somevar é menor que10" +if some_var > 10: + print("some_var é absolutamente maior que 10.") +elif some_var < 10: # Esta cláusula elif é opcional. + print("some_var é menor que 10.") +else: # Isto também é opcional. + print("some_var é, de fato, 10.") + + +""" +Laços for iteram sobre listas +imprime: + cachorro é um mamífero + gato é um mamífero + rato é um mamífero +""" +for animal in ["cachorro", "gato", "rato"]: + # Você pode usar format() para interpolar strings formatadas + print("{} é um mamífero".format(animal)) + +""" +"range(número)" retorna um iterável de números +de zero até o número escolhido +imprime: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(menor, maior)" gera um iterável de números +começando pelo menor até o maior +imprime: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(menor, maior, passo)" retorna um iterável de números +começando pelo menor número até o maior númeno, pulando de +passo em passo. Se o passo não for indicado, o valor padrão é um. +imprime: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) +""" + +Laços while executam até que a condição não seja mais válida. +imprime: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Maneira mais curta para for x = x + 1 + +# Lide com exceções com um bloco try/except +try: + # Use "raise" para gerar um erro + raise IndexError("Isto é um erro de índice") +except IndexError as e: + pass # Pass é um não-operador. Normalmente você usa algum código de recuperação aqui. +except (TypeError, NameError): + pass # Varias exceções podem ser gerenciadas, se necessário. +else: # Cláusula opcional para o bloco try/except. Deve estar após todos os blocos de exceção. + print("Tudo certo!") # Executa apenas se o código em try não gera exceção +finally: # Sempre é executado + print("Nós podemos fazer o código de limpeza aqui.") + +# Ao invés de try/finally para limpeza você pode usar a cláusula with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python provê uma abstração fundamental chamada Iterável. +# Um iterável é um objeto que pode ser tratado como uma sequência. +# O objeto retornou a função range, um iterável. + +filled_dict = {"um": 1, "dois": 2, "três": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => range(1,10). Esse é um objeto que implementa nossa interface iterável. + +# Nós podemos percorrê-la. +for i in our_iterable: + print(i) # Imprime um, dois, três + +# Mas não podemos acessar os elementos pelo seu índice. +our_iterable[1] # Gera um TypeError + +# Um iterável é um objeto que sabe como criar um iterador. +our_iterator = iter(our_iterable) + +# Nosso iterador é um objeto que pode lembrar o estado enquanto nós o percorremos. +# Nós acessamos o próximo objeto com "next()". +next(our_iterator) # => "um" + +# Ele mantém o estado enquanto nós o percorremos. +next(our_iterator) # => "dois" +next(our_iterator) # => "três" + +# Após o iterador retornar todos os seus dados, ele gera a exceção StopIterator +next(our_iterator) # Gera StopIteration + +# Você pode capturar todos os elementos de um iterador aplicando list() nele. +list(filled_dict.keys()) # => Retorna ["um", "dois", "três"] + + +#################################################### +## 4. Funções +#################################################### + +# Use "def" para criar novas funções. +def add(x, y): + print("x é {} e y é {}".format(x, y)) + return x + y # Retorne valores com a cláusula return + +# Chamando funções com parâmetros +add(5, 6) # => imprime "x é 5 e y é 6" e retorna 11 + +# Outro meio de chamar funções é com argumentos nomeados +add(y=6, x=5) # Argumentos nomeados podem aparecer em qualquer ordem. + +# Você pode definir funções que pegam um número variável de argumentos +# posicionais +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Você pode definir funções que pegam um número variável de argumentos nomeados +# também +def keyword_args(**kwargs): + return kwargs + +# Vamos chamá-lo para ver o que acontece +keyword_args(peh="grande", lago="ness") # => {"peh": "grande", "lago": "ness"} + + +# Você pode fazer ambos simultaneamente, se você quiser +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) imprime: + (1, 2) + {"a": 3, "b": 4} +""" + +# Quando chamar funções, você pode fazer o oposto de args/kwargs! +# Use * para expandir tuplas e use ** para expandir dicionários! +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # equivalente a foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalente a foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalente a foo(1, 2, 3, 4, a=3, b=4) + +# Retornando múltiplos valores (com atribuição de tuplas) +def swap(x, y): + return y, x # Retorna múltiplos valores como uma tupla sem os parêntesis. + # (Observação: os parêntesis foram excluídos mas podem estar + # presentes) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Novamente, os parêntesis foram excluídos mas podem estar presentes. + +# Escopo de função +x = 5 + +def setX(num): + # A variável local x não é a mesma variável global x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # variável global x agora é 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python tem funções de primeira classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Também existem as funções anônimas +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Existem funções internas de alta ordem +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Nós podemos usar compreensão de lista para interessantes mapas e filtros +# Compreensão de lista armazena a saída como uma lista que pode ser uma lista +# aninhada +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# Nós usamos o operador "class" para ter uma classe +class Human: + + # Um atributo de classe. Ele é compartilhado por todas as instâncias dessa + # classe. + species = "H. sapiens" + + # Construtor básico, é chamado quando esta classe é instanciada. + # Note que dois sublinhados no início e no final de uma identificados + # significa objetos ou atributos que são usados pelo python mas vivem em + # um namespace controlado pelo usuário. Métodos (ou objetos ou atributos) + # como: __init__, __str__, __repr__, etc. são chamados métodos mágicos (ou + # algumas vezes chamados métodos dunder - "double underscore") + # Você não deve usar nomes assim por sua vontade. + def __init__(self, name): + @ Atribui o argumento ao atributo da instância + self.name = name + + # Um método de instância. Todos os métodos tem "self" como primeiro + # argumento + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Um método de classe é compartilhado por todas as instâncias + # Eles são chamados com a classe requisitante como primeiro argumento + @classmethod + def get_species(cls): + return cls.species + + # Um método estático é chamado sem uma referência a classe ou instância + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancie uma classe +i = Human(name="Ian") +print(i.say("oi")) # imprime "Ian: oi" + +j = Human("Joel") +print(j.say("olá")) # imprime "Joel: olá" + +# Chama nosso método de classe +i.get_species() # => "H. sapiens" + +# Altera um atributo compartilhado +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Chama o método estático +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Módulos +#################################################### + +# Você pode importar módulos +import math +print(math.sqrt(16)) # => 4 + +# Você pode importar apenas funções específicas de um módulo +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Você pode importar todas as funções de um módulo para o namespace atual +# Atenção: isso não é recomendado +from math import * + +# Você pode encurtar o nome dos módulos +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Módulos python são apenas arquivos python comuns. Você +# pode escrever os seus, e importá-los. O nome do +# módulo é o mesmo nome do arquivo. + +# Você pode procurar que atributos e funções definem um módulo. +import math +dir(math) + + +#################################################### +## 7. Avançado +#################################################### + +# Geradores podem ajudar você a escrever código "preguiçoso" +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Um gerador cria valores conforme necessário. +# Ao invés de gerar e retornar todos os valores de uma só vez ele cria um em +# cada interação. Isto significa que valores maiores que 15 não serão +# processados em double_numbers. +# Nós usamos um sublinhado ao final do nome das variáveis quando queremos usar +# um nome que normalmente colide com uma palavra reservada do python. +range_ = range(1, 900000000) +# Multiplica por 2 todos os números até encontrar um resultado >= 30 +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decoradores +# Neste exemplo beg encapsula say +# beg irá chamar say. Se say_please é verdade então ele irá mudar a mensagem +# retornada +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, "Por favor! Eu sou pobre :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Você me paga uma cerveja?" + return msg, say_please + + +print(say()) # Você me paga uma cerveja? +print(say(say_please=True)) # Você me paga uma cerveja? Por favor! Eu sou pobre :( +``` + +## Pronto para mais? + +### Free Online + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [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/) + +### Dead Tree + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From f6c68bdd0055b7c066cd707ec6f1227608fe26d8 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 14:56:03 +0200 Subject: Update python3-pt.html.markdown --- pt-br/python3-pt.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pt-br/python3-pt.html.markdown b/pt-br/python3-pt.html.markdown index 0fef2528..c5a3c020 100644 --- a/pt-br/python3-pt.html.markdown +++ b/pt-br/python3-pt.html.markdown @@ -5,11 +5,10 @@ contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] - ["Zachary Ferguson", "http://github.com/zfergus2"] -filename: learnpython3.py translators: - ["Paulo Henrique Rodrigues Pinheiro", "http://www.sysincloud.it"] language: pt-br -filename: learnpython3-pt-br.py +filename: learnpython3-pt.py --- Python foi criado por Guido Van Rossum nos anos 1990. Ele é atualmente uma -- cgit v1.2.3 From 41cf3e7421fe7547ee55ac551438c0645281de33 Mon Sep 17 00:00:00 2001 From: Akashdeep Goel Date: Sun, 26 Jun 2016 18:28:40 +0530 Subject: Feature: adds Dynamic Programming tutorial (#1885) --- dynamic-programming.html.markdown | 50 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 dynamic-programming.html.markdown diff --git a/dynamic-programming.html.markdown b/dynamic-programming.html.markdown new file mode 100644 index 00000000..95f774bf --- /dev/null +++ b/dynamic-programming.html.markdown @@ -0,0 +1,50 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] +--- + +# Dynamic Programming + +## Introduction + +Dynamic Programming is a powerful technique used for solving a particular class of problems as we will see.The idea is very simple, If you have solved a problem with the given input, then save the result for future reference, so as to avoid solving the same problem again. + +Always remember!! +"Those who can't remember the past are condemned to repeat it" + +## Ways of solving such Problems + +1.) Top-Down : Start solving the given problem by breaking it down. If you see that the problem has been solved already, then just return the saved answer. If it has not been solved, solve it and save the answer. This is usually easy to think of and very intuitive. This is referred to as Memoization. + +2.) Bottom-Up : Analyze the problem and see the order in which the sub-problems are solved and start solving from the trivial subproblem, up towards the given problem. In this process, it is guaranteed that the subproblems are solved before solving the problem. This is referred to as Dynamic Programming. + +## Example of Dynamic Programming + +The Longest Increasing Subsequence problem is to find the longest increasing subsequence of a given sequence. Given a sequence S= {a1 , a2 , a3, a4, ............., an-1, an } we have to find a longest subset such that for all j and i, j a[j] and LS[i] Date: Sun, 26 Jun 2016 10:03:09 -0300 Subject: Added typescript-pt.html.markdown (#1699) * link for learning of javascript adjusted * Added typescript-pt.html.markdown --- pt-br/typescript-pt.html.markdown | 179 ++++++++++++++++++++++++++++++++++++++ typescript.html.markdown | 2 +- 2 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 pt-br/typescript-pt.html.markdown diff --git a/pt-br/typescript-pt.html.markdown b/pt-br/typescript-pt.html.markdown new file mode 100644 index 00000000..f072b257 --- /dev/null +++ b/pt-br/typescript-pt.html.markdown @@ -0,0 +1,179 @@ +--- +language: TypeScript +filename: learntypescript-pt.ts +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +TypeScript is a language that aims at easing development of large scale applications written in JavaScript. +TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. + +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). + + +Typescript é uma linguagem que visa facilitar o desenvolvimento de aplicações em grande escala escritos em JavaScript. +Typescript acrescenta conceitos comuns como classes, módulos, interfaces, genéricos e (opcional) tipagem estática para JavaScript. +É um super conjunto de JavaScript: todo o código JavaScript é o código do texto dactilografado válido para que possa ser adicionados diretamente a qualquer projeto. O compilador emite typescript JavaScript. + +Este artigo irá se concentrar apenas em texto datilografado sintaxe extra, ao contrário de [JavaScript](javascript-pt.html.markdown). + +Para testar compilador do texto datilografado, de cabeça para o [Parque](http://www.typescriptlang.org/Playground), onde você vai ser capaz de escrever código, ter auto conclusão e ver diretamente o JavaScript emitida. + +```js +// Existem 3 tipos básicos no TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Quando é impossível saber, há o "Qualquer" tipo +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // Ok, definitivamente um boolean + +// Para coleções, não são matrizes e matrizes genéricas digitado +var list: number[] = [1, 2, 3]; +// Como alternativa, usando o tipo de matriz genérica +var list: Array = [1, 2, 3]; + +// Para enumerações: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +// Por último, "vazio" é utilizado no caso especial de uma função que não retorna nada +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +// Funções são cidadãos de primeira classe, apoiar a sintaxe lambda "seta gordura" e +// Tipo de uso inferência + +// A seguir são equivalentes, a mesma assinatura será inferido pelo +// Compilador, e mesmo JavaScript será emitido +var f1 = function(i: number): number { return i * i; } +// Tipo de retorno inferida +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Tipo de retorno inferida +var f4 = (i: number) => { return i * i; } +// Tipo de retorno inferido, one-liner significa nenhuma palavra-chave retorno necessário +var f5 = (i: number) => i * i; + +// Interfaces são estruturais, qualquer coisa que tenha as propriedades é compatível com +// A interface +interface Person { + name: string; + // Propriedades opcionais, marcado com um "?" + age?: number; + // E de funções curso + move(): void; +} + +// Objeto que implementa a "Pessoa" Interface +// 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: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Não é uma pessoa porque a idade não é um número +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Interfaces também pode descrever um tipo de função +interface SearchFunc { + (source: string, subString: string): boolean; +} +// Somente tipos dos parâmetros são importantes, os nomes não são importantes. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Classes - membros são públicos por padrão +class Point { + // Propriedades + x: number; + + // Construtor - the public/private keywords in this context will generate + // o código clichê para a propriedade e a inicialização no + // construtor. + // Neste exemplo, "y" será definida como "X" é, mas com menos código + // Os valores padrão também são suportados. + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Funções + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Membros Estáticos + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y será 0 + +// Herança +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Chamada explícita para o construtor da super classe é obrigatória + } + + // Sobrescrever + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Módulos, "." pode ser utilizado como separador de sub módulos +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Alias no local para fazer referência a um módulo +import G = Geometry; + +var s2 = new G.Square(10); + +// Genericos +// Classes +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Pair { + item1: T; + item2: T; +} + +// e funções +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Incluindo referências a um arquivo de definição: +/// + +``` + +## Leitura adicional + * [TypeScript site oficial](http://www.typescriptlang.org/) + * [TypeScript especificações de idioma (pdf)](http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Apresentando texto datilografado no Canal 9](http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Código fonte no GitHub](https://github.com/Microsoft/TypeScript) + * [Definitivamente datilografado - repositório de definições de tipo](http://definitelytyped.org/) diff --git a/typescript.html.markdown b/typescript.html.markdown index 21f1ce7d..1d712369 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -9,7 +9,7 @@ TypeScript is a language that aims at easing development of large scale applicat TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. -This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript](javascript.html.markdown). To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. -- cgit v1.2.3 From 8cd7c230aaa708dffb544887baa85de8f3377251 Mon Sep 17 00:00:00 2001 From: Jonathan Wang Date: Sun, 26 Jun 2016 09:04:11 -0400 Subject: [bash/en] basic parameter expansion, and brace expansion (#1533) * Added brace expansion as well as basic parameter expansion * frogot my name * Update bash.html.markdown Added to parameter expansion --- bash.html.markdown | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/bash.html.markdown b/bash.html.markdown index c2c3e3f1..a62bd167 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -11,6 +11,7 @@ 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" ] filename: LearnBash.sh --- @@ -54,6 +55,13 @@ echo '$Variable' # its name without $. If you want to use the variable's value, you should use $. # Note that ' (single quote) won't expand the variables! +# Parameter expansion ${ }: +echo ${Variable} +# This is a simple usage of parameter expansion +# Parameter Expansion gets a value from a variable. It "expands" or prints the value +# During the expansion time the value or parameter are able to be modified +# Below are other modifications that add onto this expansion + # String substitution in variables echo ${Variable/Some/A} # This will substitute the first occurrence of "Some" with "A" @@ -68,6 +76,12 @@ echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} # This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. # Note that it only returns default value and doesn't change variable value. +# Brace Expansion { } +# Used to generate arbitrary strings +echo {1..10} +echo {a..z} +# This will output the range from the start value to the end value + # Builtin variables: # There are some useful builtin variables, like echo "Last program's return value: $?" -- cgit v1.2.3 From 57a0ce5acc898792ea5c577fa41f5376a30c28d0 Mon Sep 17 00:00:00 2001 From: Lucas Moreira Date: Sun, 26 Jun 2016 10:05:04 -0300 Subject: =?UTF-8?q?[ruby/pt-br]=20Erros=20ortogr=C3=A1ficos.=20(#1609)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Alguns erros ortográficos foram corrigidos. * Correcting some words. --- pt-br/git-pt.html.markdown | 12 ++++++------ pt-br/ruby-pt.html.markdown | 10 +++++----- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index ea3570d6..907892b1 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -32,7 +32,7 @@ a um arquivo ou conjunto de arquivos ao longo do tempo. de arquivos. * Controle de versão distribuído foca em compartilhar alterações. Cada alteração é associada a um *id* único. -* Sistemas distribuídos não tem estrutura definida. É possivel ter um sistema +* Sistemas distribuídos não têm estrutura definida. É possivel ter um sistema centralizado ao estilo SVN usando git. [Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -56,7 +56,7 @@ referências. Pode ser descrito como uma estrutura de dados de código fonte com a particularidade de cada elemento do código fonte permitir acesso ao histórico das suas alterações, entre outras coisas. -Um repositório git é constituido pelo diretório .git e a *working tree* +Um repositório git é constituído pelo diretório .git e a *working tree* ### Diretório .git (componente do repositório) @@ -140,10 +140,10 @@ Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da # Ver rapidamente os comandos disponiveis $ git help -# Ver todos os comandos disponiveis +# Ver todos os comandos disponíveis $ git help -a -# Usar o *help* para um comando especifico +# Usar o *help* para um comando específico # git help $ git help add $ git help commit @@ -158,7 +158,7 @@ do repositório) e o *commit* da *HEAD* atual. ```bash # Apresenta o *branch*, arquivos não monitorados, alterações e outras -# difereças +# diferenças $ git status # Para aprender mais detalhes sobre git *status* @@ -400,7 +400,7 @@ perigoso quando não há certeza do que se está fazendo. ```bash # Restabelece a camada intermediária de registo para o último -# commit (o directório fica sem alterações) +# commit (o diretório fica sem alterações) $ git reset # Restabelece a camada intermediária de registo para o último commit, e diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown index 668cd25f..eeb51bec 100644 --- a/pt-br/ruby-pt.html.markdown +++ b/pt-br/ruby-pt.html.markdown @@ -101,7 +101,7 @@ caminho_para_a_raiz_do_projeto = '/bom/nome/' caminho = '/nome/ruim/' # Símbolos (são objetos) -# Símbolos são imutáveis, são constantes reutilizáveis representadadas +# Símbolos são imutáveis, são constantes reutilizáveis representados # internamente por um valor inteiro. Eles são frequentemente usados no # lugar de strings para transmitir com eficiência os valores específicos # e significativos @@ -260,7 +260,7 @@ somar 3, 4 #=> 7 somar(3,4), 5 #=> 12 # yield -# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco +# Todos os métodos possuem implicitamente um paramêtro opcional que é um bloco # ele pode ser chamado com a palavra chave 'yield' def ao_redor @@ -285,7 +285,7 @@ class Humano # Inicialização básica (contructor) def initialize(nome, idade=0) - # Atribui o argumento para a variável de instancia "nome" do objeto + # Atribui o argumento para a variável de instância "nome" do objeto @nome = nome # Se a idade não for passada, nós definimos um valor padrão na lista de argumentos @idade = idade @@ -301,7 +301,7 @@ class Humano @nome end - # Um método de classe usa a palavra chave self para se defenciar dos métodos de instância. + # Um método de classe usa a palavra chave self para se diferenciar dos métodos de instância. # Ele só pode ser chamado na classe, não na instancia def self.diz(msg) puts "#{msg}" @@ -362,7 +362,7 @@ Trabalhador.foo # 0 Humano.foo = 2 # 2 Trabalhador.foo # 2 -# Uma variável de instância não é compartilhada por suas classes decendentes. +# Uma variável de instância não é compartilhada por suas classes descendentes. class Humano @bar = 0 -- cgit v1.2.3 From b54e0f4da89f04e635d40958d74c71effea762cf Mon Sep 17 00:00:00 2001 From: Matthias Kern Date: Sun, 26 Jun 2016 16:06:36 +0300 Subject: Add german translation for python3 (#1287) --- de-de/python3-de.html.markdown | 655 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 655 insertions(+) create mode 100644 de-de/python3-de.html.markdown diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown new file mode 100644 index 00000000..ef1786c8 --- /dev/null +++ b/de-de/python3-de.html.markdown @@ -0,0 +1,655 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://ldinh.ca"] +translators: + - ["kultprok", "http:/www.kulturproktologie.de"] + - ["matthiaskern", "https://github.com/matthiaskern"] +filename: learnpython3-de.py +lang: de-de +--- + +Anmerkungen des ursprünglichen Autors: +Python wurde in den frühen Neunzigern von Guido van Rossum entworfen. Es ist heute eine der beliebtesten Sprachen. Ich habe mich in Python wegen seiner syntaktischen Übersichtlichkeit verliebt. Eigentlich ist es ausführbarer Pseudocode. + +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. + +```python + +# Einzeilige Kommentare beginnen mit einer Raute (Doppelkreuz) + +""" Mehrzeilige Strings werden mit + drei '-Zeichen geschrieben und werden + oft als Kommentare genutzt. +""" + +#################################################### +## 1. Primitive Datentypen und Operatoren +#################################################### + +# Die Zahlen +3 #=> 3 + +# Mathematik funktioniert so, wie man das erwartet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 + +# Außer Division, welche automatisch Gleitkommazahlen zurückgibt +35 / 5 # => 7.0 + +# Eine Division kann mit "//" für positive sowie negative Werte abgerundet werden. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Benutzt man eine Gleitkommazahl, ist auch das Ergebnis eine solche +3 * 2.0 # => 6.0 + +# Der Rest einer Division +7 % 3 # => 1 + +# Potenz +2**4 # => 16 + +# Rangfolge wird mit Klammern erzwungen +(1 + 3) * 2 #=> 8 + +# Boolesche Ausdrücke sind primitive Datentypen +True +False + +# Mit not wird negiert +not True #=> False +not False #=> True + +# Boolesche Operatoren +# Hinweis: "and" und "or" müssen klein geschrieben werden +True and False #=> False +False or True #=> True + +# Für die Benutzung von Booleschen Operatoren und ganzen Zahlen +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Gleichheit ist == +1 == 1 #=> True +2 == 1 #=> False + +# Ungleichheit ist != +1 != 1 #=> False +2 != 1 #=> True + +# Ein paar weitere Vergleiche +1 < 10 #=> True +1 > 10 #=> False +2 <= 2 #=> True +2 >= 2 #=> True + +# Vergleiche können verknüpft werden! +1 < 2 < 3 #=> True +2 < 3 < 2 #=> False + +# Strings werden mit " oder ' gebildet +"Das ist ein String." +'Das ist auch ein String.' + +# Strings können auch addiert werden! Vermeide dies aber lieber. +"Hallo " + "Welt!" #=> "Hallo Welt!" +# Strings können ohne "+" addiert werden +"Hallo " "welt!" # => "Hallo Welt!" + +# Ein String kann wie eine Liste von Zeichen verwendet werden +"Das ist ein String"[0] #=> 'D' + +# .format kann Strings formatieren +"{} können {} werden".format("Strings", "formatiert") + +# Schneller geht das mit Wiederholungen +"{0} mag Spagetthi, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") +#=> "Hans mag Spagetthi, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" + +# Wir können Schlüsselwörter verwenden, wenn wir nicht abzählen wollen. +"{name} will {food} essen".format(name="Bob", food="Lasagne") +#=> "Bob will Lasagne kochen" + +#Falls dein Python 3 Code auch unter Python 2.5 oder darunter laufen soll, kann das alte Format benutzt werden: +"%s können %s werden" % ("Strings", "interpoliert") + + +# None ist ein Objekt +None #=> None + +# Verwendet nicht das Symbol für Gleichheit `==`, um Objekte mit None zu vergleichen +# Benutzt stattdessen `is`. Dieser Operator testet Objektidentität +"etc" is None #=> False +None is None #=> True + + + +# None, 0, und leere Strings/Listen werden alle als False bewertet. +# Alle anderen Werte sind True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variablen und Collections +#################################################### + +# Textausgabe ist sehr einfach +print "Ich bin Python. Schön, dich kennenzulernen!" + +# Es gibt keinen Grund, Variablen vor der Zuweisung zu deklarieren. +some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm +some_var #=> 5 + +# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus. +# Unter "Kontrollstruktur" kann noch mehr über +# Ausnahmebehandlung erfahren werden. +some_unknown_var # Löst einen NameError aus + +# Listen speichern Sequenzen +li = [] +# Wir können mit einer bereits gefüllten Liste anfangen +other_li = [4, 5, 6] + +# append fügt Daten am Ende der Liste ein +li.append(1) #li ist jetzt [1] +li.append(2) #li ist jetzt [1, 2] +li.append(4) #li ist jetzt [1, 2, 4] +li.append(3) #li ist jetzt [1, 2, 4, 3] +# Vom Ende der Liste mit pop entfernen +li.pop() #=> 3 und li ist jetzt [1, 2, 4] +# und dann wieder hinzufügen +li.append(3) # li ist jetzt wieder [1, 2, 4, 3]. + +# Greife auf Listen wie auf Arrays zu +li[0] #=> 1 +# Das letzte Element ansehen +li[-1] #=> 3 + +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError +li[4] # Verursacht einen IndexError + +# Wir können uns Ranges mit Slice-Syntax ansehen +li[1:3] #=> [2, 4] +# Den Anfang auslassen +li[2:] #=> [4, 3] +# Das Ende auslassen +li[:3] #=> [1, 2, 4] +# Jeden Zweiten Eintrag auswählen +li[::2] # =>[1, 4] +# Eine umgekehrte Kopie zurückgeben +li[::-1] # => [3, 4, 2, 1] +# Jegliche Kombination dieser Syntax machen fortgeschrittene Slices möglich +# li[Start:Ende:Schritt] + +# Ein bestimmtes Element mit del aus der Liste entfernen +del li[2] # li ist jetzt [1, 2, 3] + +# Listen können addiert werden +li + other_li #=> [1, 2, 3, 4, 5, 6] - Hinweis: li und other_li werden in Ruhe gelassen + +# Listen mit extend verknüpfen +li.extend(other_li) # Jetzt ist li [1, 2, 3, 4, 5, 6] + +# Mit in auf Existenz eines Elements prüfen +1 in li #=> True + +# Die Länge der Liste mit len ermitteln +len(li) #=> 6 + + +# Tupel sind wie Listen, nur unveränderlich. +tup = (1, 2, 3) +tup[0] #=> 1 +tup[0] = 3 # Löst einen TypeError aus + +# Wir können all diese Listen-Dinge auch mit Tupeln anstellen +len(tup) #=> 3 +tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) +tup[:2] #=> (1, 2) +2 in tup #=> True + +# Wir können Tupel (oder Listen) in Variablen entpacken +a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen +d, e, f = 4, 5, 6 +# Es ist kinderleicht zwei Werte zu tauschen +e, d = d, e # d is now 5 and e is now 4 + + +# Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare +empty_dict = {} +# Hier ein gefülltes Wörterbuch +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Wir können Einträge mit [] nachschlagen +filled_dict["one"] #=> 1 + +# So holen wir alle Keys (Schlüssel) als Liste +list(filled_dict.keys()) #=> ["three", "two", "one"] +# Hinweis - Die Reihenfolge von Schlüsseln in der Liste ist nicht garantiert. +# Einzelne Resultate können anders angeordnet sein. + +# Alle Values (Werte) als Liste +list(filled_dict.values()) #=> [3, 2, 1] +# Hinweis - Hier gelten dieselben Einschränkungen für die Reihenfolge wie bei Schlüsseln. + +# Das Vorhandensein eines Schlüssels im Wörterbuch mit "in" prüfen +"one" in filled_dict #=> True +1 in filled_dict #=> False + +# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +filled_dict["four"] # KeyError + +# Mit der get-Methode verhindern wir das +filled_dict.get("one") #=> 1 +filled_dict.get("four") #=> None +# Die get-Methode unterstützt auch ein Standardargument, falls der Wert fehlt +filled_dict.get("one", 4) #=> 1 +filled_dict.get("four", 4) #=> 4 + +# Die setdefault-Methode ist ein sicherer Weg, ein neues Schlüssel-Wert-Paar anzulegen +filled_dict.setdefault("five", 5) #filled_dict["five"] wird auf 5 gesetzt +filled_dict.setdefault("five", 6) #filled_dict["five"] ist noch immer 5 + +# Einträge zu einem Wörterbuch hinzufügen +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # noch ein Weg, Werte hinzuzufügen + +# Schlüssel von einem Wörterbuch entfernen +del filled_dict["one"] # Entfert den Schlüssel "one" + + +# Sets speichern Mengen +empty_set = set() +# Initialisieren wir ein Set mit ein paar Werten +some_set = {1, 1, 2, 2, 3, 4} # some_set ist jetzt {1, 2, 3, 4} + +# Neue Variablen können einer Menge gleichgesetzt werden +filled_set = some_set + +# Mehr Elemente hinzufügen +filled_set.add(5) # filled_set ist jetzt {1, 2, 3, 4, 5} + +# Schnittmengen werden mit & gebildet +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + +# Mengen werden mit | vereinigt +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + +# Die Differenz einer Menge mit - bilden +{1,2,3,4} - {2,3,5} #=> {1, 4} + +# Auf Vorhandensein von Elementen mit in prüfen +2 in filled_set #=> True +10 in filled_set #=> False + + +#################################################### +## 3. Kontrollstruktur und Iteratoren +#################################################### + +# Erstellen wir mal eine Variable +some_var = 5 + +# Hier eine if-Anweisung. Die Einrückung ist in Python wichtig! +# gibt "some_var ist kleiner als 10" aus +if some_var > 10: + print "some_var ist viel größer als 10." +elif some_var < 10: # Dieser elif-Absatz ist optional. + print "some_var ist kleiner als 10." +else: # Das hier ist auch optional. + print "some_var ist tatsächlich 10." + + +""" +For-Schleifen iterieren über Listen +Ausgabe: + hund ist ein Säugetier + katze ist ein Säugetier + maus ist ein Säugetier +""" +for animal in ["hund", "katze", "maus"]: + # Wir können Strings mit format() formatieren + print("{} ist ein Säugetier".format(animal)) + +""" +`range(Zahl)` gibt eine null-basierte Liste bis zur angegebenen Zahl wieder +Ausgabe: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print i + +""" +"range(unten, oben)" gibt eine Liste von der unteren Zahl bis zur oberen Zahl aus +Ausgabe: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +While-Schleifen laufen, bis eine Bedingung erfüllt ist. +Ausgabe: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print x + x += 1 # Kurzform für x = x + 1 + +# Ausnahmebehandlung mit einem try/except-Block +try: + # Mit raise wird ein Fehler ausgegeben + raise IndexError("Das hier ist ein Index-Fehler") +except IndexError as e: + pass # Pass ist nur eine no-op. Normalerweise würden wir hier den Fehler klären. +except (TypeError, NameError): + pass # Mehrere Fehler können zusammen geklärt werden, falls erforderlich. +else: # Optional, hinter allen except-Blöcken + print("Keine Probleme!") # Wird nur ausgeführt, wenn keine Ausnahmen aufgetreten sind +finally: # Wird immer ausgeführt + print("Hier können wir Ressourcen aufräumen") + +# alternativ zu einem try/finally Block um Aufzuräumen: +with open("meineDatei.txt") as f: + for line in f: + print(line) + +# Python bietet ein fundamentales Konzept der Iteration. +# Das Objekt, auf das die Interation, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". +# Die range Method gibt ein solches Objekt aus. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). Dies ist ein "iterable" Objekt. + +# Über dieses können wir auch iterieren +for i in our_iterable: + print(i) # Gibt one, two, three aus + +# Allerdings können wir die einzelnen Elemente nicht mit ihrem index ausgeben +our_iterable[1] # TypeError + +# Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. +our_iterator = iter(our_iterable) + +# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es geraden hat während wir durch es gehen. +# Das jeweeils nächste Objekt bekommen wir mit "next()" +next(our_iterator) #=> "one" + +# Es hält den vorherigen Status +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Nachdem alle Daten ausgegeben worden sind, kommt eine StopIterator Ausnahme zurück +next(our_iterator) # Gibt StopIteration aus + +# Alle Elemente können mit "list()" ausgegeben werden +list(filled_dict.keys()) #=> ["one", "two", "three"] + + + +#################################################### +## 4. Funktionen +#################################################### + +# Mit def neue Funktionen erstellen +def add(x, y): + print "x ist %s und y ist %s" % (x, y) + return x + y # Werte werden mit return zurückgegeben + +# Funktionen mit Parametern aufrufen +add(5, 6) #=> Ausgabe ist "x ist 5 und y ist 6" und gibt 11 zurück + +# Ein anderer Weg des Funktionsaufrufs sind Schlüsselwort-Argumente +add(y=6, x=5) # Schlüsselwörter können in beliebiger Reihenfolge übergeben werden. + +# Wir können Funktionen mit beliebiger Anzahl von # Positionsargumenten definieren +def varargs(*args): + return args + +varargs(1, 2, 3) #=> (1,2,3) + + +# Wir können auch Funktionen mit beliebiger Anzahl +# Schlüsselwort-Argumenten definieren +def keyword_args(**kwargs): + return kwargs + +# Rufen wir es mal auf, um zu sehen, was passiert +keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} + +# Wir können beides gleichzeitig machem, wenn wir wollen +def all_the_args(*args, **kwargs): + print args + print kwargs +""" +all_the_args(1, 2, a=3, b=4) Ausgabe: + (1, 2) + {"a": 3, "b": 4} +""" + +# Beim Aufruf von Funktionen können wir das Gegenteil von varargs/kwargs machen! +# Wir benutzen dann *, um Tupel auszuweiten, und ** für kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # äquivalent zu foo(1, 2, 3, 4) +all_the_args(**kwargs) # äquivalent zu foo(a=3, b=4) +all_the_args(*args, **kwargs) # äquivalent zu foo(1, 2, 3, 4, a=3, b=4) + + +# Anwendungsbereich von Funktionen +x = 5 + +def setX(num): + # lokale Variable x ist nicht die globale Variable x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # globale Variable x ist jetzt 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python hat First-Class-Funktionen +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) #=> 13 + +# Es gibt auch anonyme Funktionen +(lambda x: x > 2)(3) #=> True + +# Es gibt auch Funktionen höherer Ordnung als Built-Ins +map(add_10, [1,2,3]) #=> [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7] + +# Wir können bei map- und filter-Funktionen auch List Comprehensions einsetzen +[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7] + +#################################################### +## 5. Klassen +#################################################### + +# Wir bilden die Unterklasse eines Objekts, um Klassen zu erhalten. +class Human(object): + + # Ein Klassenattribut. Es wird von allen Instanzen einer Klasse geteilt + species = "H. sapiens" + + # Ein simpler Konstruktor + def __init__(self, name): + # Wir weisen das Argument name dem name-Attribut der Instanz zu + self.name = name + + # Eine Instanzmethode. Alle Methoden erhalten self als erstes Argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Eine Klassenmethode wird von allen Instanzen geteilt. + # Sie werden mit der aufrufenden Klasse als erstem Argument aufgerufen + @classmethod + def get_species(cls): + return cls.species + + # Eine statische Methode wird ohne Klasse oder Instanz aufgerufen + @staticmethod + def grunt(): + return "*grunt*" + + +# Eine Instanz einer Klasse erstellen +i = Human(name="Ian") +print i.say("hi") # gibt "Ian: hi" aus + +j = Human("Joel") +print j.say("hello") #gibt "Joel: hello" aus + +# Rufen wir mal unsere Klassenmethode auf +i.get_species() #=> "H. sapiens" + +# Ändern wir mal das gemeinsame Attribut +Human.species = "H. neanderthalensis" +i.get_species() #=> "H. neanderthalensis" +j.get_species() #=> "H. neanderthalensis" + +# Aufruf der statischen Methode +Human.grunt() #=> "*grunt*" + + +#################################################### +## 6. Module +#################################################### + +# Wir können Module importieren +import math +print math.sqrt(16) #=> 4 + +# Wir können auch nur spezielle Funktionen eines Moduls importieren +from math import ceil, floor +print ceil(3.7) #=> 4.0 +print floor(3.7) #=> 3.0 + +# Wir können auch alle Funktionen eines Moduls importieren +# Warnung: Dies wird nicht empfohlen +from math import * + +# Wir können Modulnamen abkürzen +import math as m +math.sqrt(16) == m.sqrt(16) #=> True + +# Module sind in Python nur gewöhnliche Dateien. Wir +# können unsere eigenen schreiben und importieren. Der Name des +# Moduls ist der Dateiname. + +# Wir können auch die Funktionen und Attribute eines +# Moduls herausfinden. +import math +dir(math) + + +#################################################### +## 7. Fortgeschritten +#################################################### + +# Generatoren helfen um Code schnell und einfach zu schreiben +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Ein Generator erschafft Werte spontan +# Statt alle Werte auf einmal, wird bei jeder Iteration einer erschaffen. +# iteration. Das heißt, Werte größer als 15 werden nicht behandelt. +# Die range-Methode ist auch ein Generator. Im Fall einer Liste von 1-900000000 +# würde das sehr viel Zeit in Anspruch nehmen. +# Wenn wir eine variable mit einem Namen erschaffen wollen, das +# normalerweise mit einem Python - Schlüsselwort kollidieren würde, +# benutzen wir einen Unterstrich nach dem Wort. +range_ = range(1, 900000000) +# Alle Nummern bis zu einem Ergebnis von >=30 werden verdoppelt +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Dekoratoren +# In diesem Beispiel die Methode beg umwickelt say +# Beim Aufruf von beg, say wird aufgerufen +# Falls say_please true ist, ändert sich die ausgegebene Nachricht +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 :( + +``` + +## Lust auf mehr? + +### Kostenlos online (Englisch) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Totholz (Englisch) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 25f954e90ac0fc87fa24a1c018fb891544870dd6 Mon Sep 17 00:00:00 2001 From: Niels van Velzen Date: Sun, 26 Jun 2016 15:06:53 +0200 Subject: Add dutch translation of markdown (#1724) Add dutch translation of markdown --- nl-nl/markdown-nl-html.markdown | 256 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 256 insertions(+) create mode 100644 nl-nl/markdown-nl-html.markdown diff --git a/nl-nl/markdown-nl-html.markdown b/nl-nl/markdown-nl-html.markdown new file mode 100644 index 00000000..0f954715 --- /dev/null +++ b/nl-nl/markdown-nl-html.markdown @@ -0,0 +1,256 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +filename: learnmarkdown-nl.md +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +Markdown is gemaakt door John Gruber in 2004. De bedoeling was om een simpel te +lezen en schrijven syntax te creëren wat makkelijk om te zetten is naar +HTML (en tegenwoordig ook vele andere formaten). + +```markdown + + + + + + +# Dit is een

+## Dit is een

+### Dit is een

+#### Dit is een

+##### Dit is een

+###### Dit is een
+ + +Dit is een h1 +============= + +Dit is een h2 +------------- + + + + +*Deze tekst staat schuin.* +_Net als deze tekst._ + +**Deze tekst is dikgedrukt.** +__Net als deze tekst.__ + +***En deze tekst is dik en schuin.*** +**_Net als dit!_** +*__En dit!__* + + + +~~Deze tekst is doorgehaald.~~ + + + + +Dit is een paragraaf. Ik typ in een paragraaf, is dat niet leuk? + +Nu ben ik in paragraaf 2. +Nog steeds in paragraaf 2! + +Dit is paragraaf drie! + + + +Ik eindig met twee spaties (selecteer mij om het te zien). + +Er is een nieuwe regel boven mij! + + + +> Dit is een citaat. Je kan +> handmatig je lijnen laten vormen of je kan je lijnen lang laten worden en vanzelf op nieuwe regels verder laten gaan. +> Het maakt niet uit zolang je maar begint met een `>`. + +> Je kunt ook meer dan 1 level +>> uitlijning gebruiken. +> Hoe handig is dat? + + + + +* Item +* Item +* Nog een item + +of + ++ Item ++ Item ++ Nog een item + +of + +- Item +- Item +- Nog een item + + + +1. Item een +2. Item twee +3. Item drie + + + +1. Item een +1. Item twee +1. Item drie + + + + + +1. Item een +2. Item twee +3. Item drie + * Sub-item een + * Sub-item twee +4. Item vier + + + +Checkboxes hieronder zonder de 'x' zijn leeg. +- [ ] Eerste taak. +- [ ] Tweede taak +Checkboxes met een 'x' zijn klaar. +- [x] Deze taak is klaar. + + + + + Dit is code + net als dit + + + + mijn_array.each do |item| + puts item + end + + + +John wist niet eens wat de `go_to()` functie deed! + + + +\`\`\`ruby +def foobar + puts "Hallo wereld!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Klik op mij!](http://test.com/) + + + +[Klik op mij!](http://test.com/ "Link naar Test.com") + + + +[Ga naar de muziek](/music/). + + + +[Klik op deze link][link1] vor meer informatie erover! +[Bekijk deze ook eens][foobar] als je wilt. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "In orde!" + + + + + +[Dit][] is een link. + +[dit]: http://ditiseenlink.nl/ + + + + + + +![Dit is de alt attribuut van het plaatje](http://imgur.com/myimage.jpg "Een optionele titel") + + + +![Dit is de alt attribuut.][mijnplaatje] + +[mijnplaatje]: relative/urls/cool/image.jpg "Hier is de titel" + + + + + is hetzelfde als +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Ik wil *deze tekst met sterretjes typen* maar ik wil het niet schuin, dus ik doe dit: \*deze tekst met sterretjes typen\*. + + + + +Computer gecrashed? Gebruik eens +Ctrl+Alt+Del + + + + +| kolom1 | kolom2 |kolom3 | +| :--------------- | :---------: | ----------------: | +| Links-uitgelijnd | Gecentreerd | Rechts-uitgelijnd | +| blah | blah | blah | + + + +Kolom 1 | Kolom 2 | Kolom 3 +:-- | :-: | --: +Dit is zo lelijk | stop | er mee + + + +``` + +Voor meer informatie, bekijk Josn Gruber's officiele post over de syntax [hier](http://daringfireball.net/projects/markdown/syntax). Of bekijk Adam Pritchard's grote cheatsheet [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) (beide Engels). -- cgit v1.2.3 From eaee51effeaa9a6ec85f64e4cf69e79ac1b507d6 Mon Sep 17 00:00:00 2001 From: Jorge Antonio Atempa Camacho Date: Sun, 26 Jun 2016 06:07:31 -0700 Subject: [haskell/es] Spanish translation (#1309) * Add comments section * Add Strings and Characters Section * Added list and tuples Section * Add More Functions Section * Add translation of Types Signature Section * Add Haskell links * Add translation * Haskell's spanish translation, finished --- es-es/haskell-es.html.markdown | 436 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 436 insertions(+) create mode 100644 es-es/haskell-es.html.markdown diff --git a/es-es/haskell-es.html.markdown b/es-es/haskell-es.html.markdown new file mode 100644 index 00000000..a6900a2b --- /dev/null +++ b/es-es/haskell-es.html.markdown @@ -0,0 +1,436 @@ +--- +language: Haskell +contributors: + - ["Adit Bhargava", "http://adit.io"] +translators: + - ["Jorge Antonio Atempa", "http://www.twitter.com/atempa09"] +lang: es-es +--- + +Haskell fue diseñado como lenguaje de programación funcional práctico y puro. Es famoso por sus mónadas y su sistema de tipos, pero siempre regreso a él debido a su elegancia. Haskell hace la codificación una verdadera alegría para mí. + +```haskell +-- Para comentar una sola línea utiliza dos guiones. +{- Para comentar múltiples líneas puedes encerrarlas +en un bloque como este. +-} + +---------------------------------------------------- +-- 1. Tipos de datos primitivos y Operadores +---------------------------------------------------- + +-- Tienes números a tu disposición +3 -- 3 + +-- Matématicas, es lo que esperas +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Por defecto la división no devuelve un entero +35 / 4 -- 8.75 + +-- Para la división entera utiliza +35 `div` 4 -- 8 + +-- Valores booleanos +True +False + +-- Operaciones booleanas +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- En los ejemplos superiores, `not` es una función que toma un valor. +-- Haskell no necesita paréntisis para las llamadas a funciones...todos los argumentos +-- son enlistados después de la función. Entonces el patrón general es: +-- func arg1 arg2 arg3... +-- Observa la sección de funciones para obtener información de como escribir tu propia función. + +-- Cadenas y caracteres +"Esto es una cadena." +'a' -- caracter +'No puedes utilizar comillas simples para cadenas.' -- ¡error! + +-- Concatenación de cadenas +"¡Hola " ++ "mundo!" -- "¡Hola mundo!" + +-- Una cadena es una lista de caracteres +['H', 'o', 'l', 'a'] -- "Hola" +"Esto es una cadena" !! 0 -- 'E' + + +---------------------------------------------------- +-- Listas y Tuplas +---------------------------------------------------- + +-- Cada elemento en una lista debe ser del mismo tipo. +-- Estas dos listas son iguales: +[1, 2, 3, 4, 5] +[1..5] + +-- Los rangos son versátiles. +['A'..'F'] -- "ABCDEF" + +-- Puedes crear un paso en un rango. +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- Esto no funciona debido a que Haskell incrementa por defecto. +[5,4..1] -- [5, 4, 3, 2, 1] + +-- indexación en una lista +[0..] !! 5 -- 5 + +-- También tienes listas infinitas en Haskell! +[1..] -- una lista de todos los números naturales + +-- Las listas infinitas funcionan porque Haskell tiene "lazy evaluation". Esto significa +-- que Haskell solo evalúa las cosas cuando lo necesita. Así que puedes pedir +-- el elemento 1000 de tú lista y Haskell te devolverá: + +[1..] !! 999 -- 1000 + +-- Y ahora Haskell ha evaluado elementos 1 - 1000 de esta lista...pero el +-- resto de los elementos de esta lista "infinita" ¡no existen todavía! Haskell no lo hará +-- en realidad los evalúa hasta que los necesita. + +-- uniendo dos listas +[1..5] ++ [6..10] + +-- añadiendo a la cabeza de la lista +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- más operaciones con listas +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- Listas por comprensión +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- Listas por comprensión utilizando condicionales +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Cada elemento en una tupla puede ser de diferente tipo, pero una tupla tiene +-- longitud fija. +-- Ejemplo de una tupla: +("haskell", 1) + +-- acceder a los elementos (por ejemplo una tupla de longitud 2) +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +---------------------------------------------------- +-- 3. Funciones +---------------------------------------------------- +-- Una función simple que recibe dos variables +add a b = a + b + +-- Nota: Si estas utilizando ghci (el interprete de Haskell) +-- Necesitas utilizar `let`, por ejemplo +-- let add a b = a + b + +-- Utilizando la función +add 1 2 -- 3 + +-- También puedes llamar a la función enmedio de dos argumentos +-- con acentos abiertos: +1 `add` 2 -- 3 + +-- ¡También puedes definir funciones sin tener que utilizar letras! De este modo +-- ¡Tú defines tus propios operadores! Aquí esta un operador que realiza +-- una división entera +(//) a b = a `div` b +35 // 4 -- 8 + +-- Guardas: son una manera fácil para ramificar funciones +fib x + | x < 2 = 1 + | otherwise = fib (x - 1) + fib (x - 2) + +-- La coincidencia de patrones es similar. Aquí hemos dado tres diferentes +-- definiciones para fib. Haskell llamará automáticamente la primer +-- función que coincide con el patrón del valor. +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Coincidencia de patrones en tuplas: +foo (x, y) = (x + 1, y + 2) + +-- Coincidencia de patrones en listas. Aquí `x` es el primer elemento +-- en una lista, y `xs` es el resto de la lista. Podemos escribir +-- nuestra propia función map: +myMap func [] = [] +myMap func (x:xs) = func x:(myMap func xs) + +-- Funciones anónimas son creadas con una diagonal invertida seguido de +-- todos los argumentos. +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- utilizando pliegues (llamado `inject` en algunos lenguajes) con una función +-- anónima. foldl1 significa pliegue por la izquierda, y usa el primer valor +-- en la lista como el valor inicial para el acumulador. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Más funciones +---------------------------------------------------- + +-- aplicación parcial: si no quieres pasar todos los argumentos a una función, +-- esta es "parcialmente aplicada". Esto significa que retorna una función que toma +-- el resto de los argumentos. + +add a b = a + b +foo = add 10 -- foo es actualmente una función que toma un número y suma 10 a esta +foo 5 -- 15 + +-- Otra manera de escribir los mismo +foo = (+10) +foo 5 -- 15 + +-- composición de funciones +-- el (.) encadena funciones. +-- Por ejemplo, aquí foo es una función que toma un valor. Y se le suma 10, +-- posteriormente multiplica el resultado por 5, y devuelve el resultado final. +foo = (*5) . (+10) + +-- (5 + 10) * 5 = 75 +foo 5 -- 75 + +-- fijación de precedencia +-- Haskell tiene otro operador llamado `$`. Este operador aplica a una función +-- para un parámetro dado. En contraste a la aplicación de función estándar, +-- la cúal tiene prioridad más alta posible de 10 y es asociativa por la izquierda, +-- el operador `$` tiene prioridad de 0 y es asociativa por la derecha. Tal que +-- una baja prioridad significa que la expresión a su derecha es aplicada como parámetro a la función a su izquierda. + +-- antes +even (fib 7) -- false + +-- equivalentemente +even $ fib 7 -- false + +-- composición de funciones +even . fib $ 7 -- false + + +---------------------------------------------------- +-- 5. Firma de tipos +---------------------------------------------------- + +-- Haskell tiene un fuerte sistema de tipado, y cada cosa tiene una firma de tipo. + +-- Algunos tipos básicos: +5 :: Integer +"hola" :: String +True :: Bool + +-- Las funciones tienen muchos tipos. +-- `not` toma un booleano y devuelve un booleano: +-- not :: Bool -> Bool + +-- Aquí, esta función toma dos argumentos: +-- add :: Integer -> Integer -> Integer + +-- Cuando defines un valor, es una buena práctica escribir su tipo en una línea superior: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Control de flujo y Expresiones If +---------------------------------------------------- + +-- expressiones if en una sola línea +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- expressiones if en múltiples líneas, la identación es importante +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- expressiones case: Aquí se muestra como analizar los argumentos +-- desde línea de comandos +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Haskell no tiene ciclos; en lugar de esto utiliza recursión. +-- map aplica una función sobre cada elemento en un arreglo + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- tú puedes crear una función utilizando map +for array func = map func array + +-- y entonces utilizarla +for [0..5] $ \i -> show i + +-- también podríamos haberlo escrito de esta manera: +for [0..5] show + +-- Puedes utilizar foldl o foldr para reducir una lista +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- Esto es lo mismo que +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl es izquierda, foldr es derecha +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Esto es los mismo que +(2 * 1 + (2 * 2 + (2 * 3 + 4))) + +---------------------------------------------------- +-- 7. Tipos de datos +---------------------------------------------------- + +-- Por ejemplo, para crear tu propio tipo de dato en Haskell + +data Color = Rojo | Azul | Verde + +-- Ahora puedes utilizarlo en una función: + + +say :: Color -> String +say Rojo = "¡Es Rojo!" +say Azul = "¡Es Azul!" +say Verde = "¡Es Verde!" + +-- Tus tipos de datos pueden tener parámetros también: + +data Maybe a = Nothing | Just a + +-- Estos son todos de tipo Maybe +Just "hello" -- de tipo `Maybe String` +Just 1 -- de tipo `Maybe Int` +Nothing -- de tipo `Maybe a` para cualquier `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Mientras que IO no puede ser explicado plenamente sin explicar las mónadas, +-- no es difícil explicar lo suficiente para ponerse en marcha. + +-- Cuando un programa en Haskell se ejecuta, `main` es +-- llamado. Este debe devolver un valor de tipo `IO ()`. Por ejemplo: + +main :: IO () +main = putStrLn $ "¡Hola, cielo! " ++ (say Blue) +-- putStrLn tiene tipo String -> IO () + +-- Es más fácil de hacer IO si puedes implementar tu programa como +-- una función de String a String. La función +-- interact :: (String -> String) -> IO () +-- recibe como entrada un texto, ejecuta una función e imprime +-- una salida. + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Puedes pensar en el valor de tipo `IO ()` como la representación +-- de una secuencia de acciones que la computadora hace, al igual que +-- un programa escrito en un lenguaje imperativo. Podemos utilizar +-- la notación `do` para encadenar acciones. Por ejemplo: + +sayHello :: IO () +sayHello = do + putStrLn "¿Cual es tu nombre?" + name <- getLine -- obtenemos un valor y lo proporcionamos a "name" + putStrLn $ "Hola, " ++ name + +-- Ejercicio: escribe tu propia version de `interact` que solo lea +-- una linea como entrada. + +-- Nunca se ejecuta el código en `sayHello`, sin embargo. La única +-- acción que siempre se ejecuta es el valor de `main`. +-- Para ejecutar `sayHello` comenta la definición anterior de `main` +-- y sustituyela por: +-- main = sayHello + +-- Vamos a entender mejor como funciona la función `getLine` cuando +-- la utilizamos. Su tipo es: +-- getLine :: IO String +-- Puedes pensar en el valor de tipo `IO a` como la representación +-- programa que generará un valor de tipo `a` +-- cuando es ejecutado (además de cualquier otra cosa que haga). Podemos +-- almacenar y reutilizar el valor usando `<-`. También podemos +-- crear nuestra propia acción de tipo `IO String`: + +action :: IO String +action = do + putStrLn "Esta es una linea." + input1 <- getLine + input2 <- getLine + -- El tipo de la sentencia `do` es la de su última línea. + -- `return` no es una palabra clave, sino simplemente una función + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Podemos usar esto sólo como usabamos `getLine`: + +main'' = do + putStrLn "¡Volveré a repetir dos líneas!" + result <- action + putStrLn result + putStrLn "Esto es todo, ¡amigos!" + +-- El tipo `IO` es un ejemplo de una "mónada". La forma en que Haskell utiliza una monada +-- permite que sea un lenguaje puramente funcional. Cualquier función que +-- interactue con el mundo exterior (por ejemplo usar IO) obtiene una marca `IO` +-- como su firma de tipo. Esto nos permite pensar qué funciones son "puras" +-- (que no interactuan con el mundo exterior o modifican el estado) y que funciones no lo son. + +-- Esta es una poderosa característica, porque es una manera fácil de ejecutar funciones puras +-- concurrentemente; entonces, la concurrencia en Haskell es muy fácil. + + +---------------------------------------------------- +-- 9. El interprete de comandos de Haskell +---------------------------------------------------- + +-- Para comenzar escribe desde la terminal `ghci`. +-- Ahora puede escribir código en Haskell. Para cualquier valor nuevo +-- que necesites crear utiliza `let`: + +let foo = 5 + +-- Puedes inspeccionar el tipo de cualquier valor con `:t`: + +>:t foo +foo :: Integer + +-- Puedes ejecutar acciones de tipo `IO ()` + +> sayHello +¿Cual es tu nombre? +Amigo +Hola, Amigo + +``` + +Existe mucho más de Haskell, incluyendo clases de tipos y mónadas. Estas son +las grandes ideas que hacen a Haskell divertido. Te dejamos un ejemplo final +de Haskell: una implementación del algoritmo QuickSort: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Haskell es fácil de instalar. Obtenlo [aquí](http://www.haskell.org/platform/). + +Usted puede encontrar más información en: +[Learn you a Haskell](http://learnyouahaskell.com/) o +[Real World Haskell](http://book.realworldhaskell.org/) o +[Aprende Haskell por el bien de todos](http://aprendehaskell.es/) -- cgit v1.2.3 From eb15a9272f151e50397e3fdfc0cd4bced4faec53 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:08:10 +0200 Subject: #1672 metadata --- es-es/haskell-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/haskell-es.html.markdown b/es-es/haskell-es.html.markdown index a6900a2b..babb1060 100644 --- a/es-es/haskell-es.html.markdown +++ b/es-es/haskell-es.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Jorge Antonio Atempa", "http://www.twitter.com/atempa09"] +filename: haskell-es.md lang: es-es --- -- cgit v1.2.3 From 810178c3cc3e83d37efc8b73772b1a468f6117a9 Mon Sep 17 00:00:00 2001 From: Xuan-thi N Date: Sun, 26 Jun 2016 15:10:26 +0200 Subject: [Git/fr] Added translation for Git article (#1949) * Added translation for Git article * Took into account suggestions for modification * Forgot a fix --- fr-fr/git-fr.html.markdown | 583 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 583 insertions(+) create mode 100644 fr-fr/git-fr.html.markdown diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown new file mode 100644 index 00000000..7a83704d --- /dev/null +++ b/fr-fr/git-fr.html.markdown @@ -0,0 +1,583 @@ +--- +category: tool +tool: git +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Leo Rudberg" , "http://github.com/LOZORD"] + - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] +translators: + - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] +filename: LearnGit-fr-.txt +lang: fr-fr +--- + +Git est un logiciel de contrôle de versions distribué et un système de gestion +du code source. + +Il effectue sa tâche via des séries d'instantanés (snapshots) du projet, et +travaille avec ces instantanés afin de fournir les fonctionnalités de gestion +de version et de code source. + +## Concepts du versionnage + +### Qu'est ce que le contrôle de version ? + +Le contrôle de version est un système qui enregistre les changements faits sur +un ou plusieurs fichiers au fil du temps. + +### Versionnage centralisé VS Versionnage distribué + +* Le contrôle de version centralisé se concentre sur la synchronisation, le +suivi et la sauvegarde des fichiers. +* Le contrôle de version distribué se focalise sur l'échange des changements. +Chaque changement a un identifiant unique. +* Les systèmes distribués n'ont pas de structure définie. Vous pouvez aisément +avoir un système centralisé de type SVN, avec Git. + +[Informations additionnelles](http://git-scm.com/book/fr/v1/D%C3%A9marrage-rapide-%C3%80-propos-de-la-gestion-de-version) + +### Pourquoi utiliser Git ? + +* Fonctionne hors ligne. +* Travailler avec les autres devient facile ! +* Ramifier le travail (créer des branches différentes) est facile ! +* Fusionner le travail est facile ! +* Git est rapide. +* Git est flexible. + +## Architecture Git + + +### Dépôt ("repository") + +Un ensemble de fichiers, dossiers, historiques de modifications, commits +(validations de changements) et de heads (état courant, "tête"). +Représentez-vous ceci comme une structure de données de code source, avec la +particularité que chaque "élement" vous donne, entre autres, accès à son +historique des révisions. + +Un dépôt Git comprend un répertoire .git et "l'arbre de travail" (working tree). + +### Répertoire .git (composant du dépôt) + +Le répertoire .git contient toutes les configurations, logs (journaux), +branches, HEAD et plus. +[Liste détaillée (EN)](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Arbre de travail (composant du dépôt) + +Il s'agit de l'ensemble des répertoires et fichiers de votre dépôt. Il est +souvent qualifié de répertoire de travail ("working directory"). + +### Index (composant du répertoire .git) + +L'index est la zone de transit ("staging area") dans Git. Il s'agit d'une couche +séparant votre arbre de travail de votre dépôt Git. Ceci donne aux développeurs +plus de pouvoir sur ce qu'ils envoient au dépôt. + +### Commit + +Un "commit" (validation de changements) est un instantané d'un ensemble de +modifications de votre arbre de travail. Par exemple, si vous avez rajouté 5 +fichiers et enlevé 2 autres, ces changements seront contenus dans un commit +(ou "snapshot", instantané). Ce commit peut ensuite être poussé ("pushed") dans +d'autres dépôts, ou non ! + +### Branches + +Une branche consiste essentiellement en un pointeur vers le dernier commit que +vous avez fait. Au fur et à mesure de vos commits, ce pointeur se mettra +automatiquement à jour pour pointer vers le dernier commit. + +### Etiquette ("tag") + +Une étiquette est une marque sur un point spécifique de l'historique. +Typiquement, on utilise cette fonctionnalité pour marquer les états de +publication (v1.0, et ainsi de suite). + +### HEAD and head (composant du répertoire .git) + +HEAD est un pointeur pointant vers la branche courante. Un dépôt ne peut avoir +qu'un seul HEAD *actif*. +head est un pointeur pouvant pointer sur n'importe quel commit. Un dépôt peut +avoir un nombre illimité de heads. + +### Les états dans Git +* Modifié - Des changements on été faits à un fichier mais ce dernier n'a pas +encore été rajouté à l'ensemble des fichiers Git +* Indexé ("staged") - Indique qu'un fichier modifié ira dans le prochain commit +* Validé ("committed") - Les fichiers ont été validés dans l'ensemble de +fichiers + +### Ressources conceptuelles + +* [Git pour les informaticiens (EN)](http://eagain.net/articles/git-for-computer-scientists/) +* [Git pour les designers (EN)](http://hoth.entp.com/output/git_for_designers.html) + + +## Commandes + + +### init + +Créé un dépôt Git vide. Les paramètres du dépôt Git, les informations stockées +et plus sont dans un répertoire (un dossier) nommé ".git". + +```bash +$ git init +``` + +### config + +Configuration des paramètres. Que ce soit pour le dépôt, le système lui-même, +ou la configuration globale (le fichier de configuration globale +est `~/.gitconfig`). + + +```bash +# Lit et assigne quelques variables (globales) de configuration de base +$ git config --global user.email "monEmail@foo.com" +$ git config --global user.name "Mon nom" +``` + +[Apprenez-en plus à propos de git config.](https://git-scm.com/book/fr/v1/Personnalisation-de-Git-Configuration-de-Git) + +### help + +Vous donne un accès rapide à un guide extrêmement détaillé de chaque commande. +Ou juste vous donner un rappel rapide de la sémantique. + +```bash +# Vérifie rapidement les commandes disponibles +$ git help + +# Vérifie toutes les commandes disponibles +$ git help -a + +# Aide pour une commande spécifique - manuel utilisateur +# git help +$ git help add +$ git help commit +$ git help init +# ou git --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignorer des fichiers + +Ne plus suivre certains fichiers et dossiers de Git. +Habituellement fait pour les fichiers privés et temporaires qui seraient, +autrement, partagés dans le dépôt. +```bash +$ echo "temp/" >> .gitignore +$ echo "cle_privee" >> .gitignore +``` + +### status + +Montre les différences entre le fichier indexé (typiquement votre copie/dépôt +de travail) et le HEAD actuel. + + +```bash +# Affiche la branche, les fichiers non suivis, les changements et autres +différences +$ git status + +# Pour en apprendre plus sur git status +$ git help status +``` + +### add + +Rajoute des fichiers à la zone d'index. Si vous ne faites pas `git add` sur les +nouveaux fichiers, ils ne seront pas inclus dans les commits ! + +```bash +# rajoute un fichier dans votre répertoire de travail actuel +$ git add HelloWorld.java + +# rajoute un fichier dans un répertoire imbriqué +$ git add /path/to/file/HelloWorld.c + +# Gestion des expressions régulières ! +$ git add ./*.java +``` + +On ne fait que rajouter des fichiers dans la zone d'index, on ne valide pas +les changements au répertoire/dépôt de travail. + +### branch + +Gère vos branches. Vous pouvez voir, éditer, créer et supprimer des branches en +utilisant cette commande. + +```bash +# Liste les branches existantes et distantes +$ git branch -a + +# Créé une nouvelle branche +$ git branch maNouvelleBranche + +# Supprime une branche +$ git branch -d maBranche + +# Renomme une branche +# git branch -m +$ git branch -m nomDeMaBranche nouveauNomDeMaBranche + +# Edite la description d'une branche +$ git branch nomDeMaBranche --edit-description +``` + +### tag + +Gère vos étiquettes + +```bash +# Liste les étiquettes +$ git tag + +# Créé une étiquette annotée +# L'option -m spécifie un message qui sera stockée dans l'étiquette. +# Si vous ne spécifiez pas de message pour une étiquette annotée, +# Git lance votre éditeur pour que vous puissiez le saisir. +$ git tag -a v2.0 -m 'ma version 2.0' + +# Affiche des informations à propos de l'étiquette +# comprenant des informations sur l'auteur, la date du commit correspondant, +# et le message d'annotation avant d'afficher les informations du commit. +$ git show v2.0 + +# Pousse une seule étiquette dans le dépôt distant +$ git push origin v2.0 + +# Pousse beaucoup d'étiquettes dans le dépôt distant +$ git push origin --tags +``` + +### checkout + +Met à jour tous les fichiers dans l'arbre de travail afin de correspondre à la +version de la zone d'index ou de l'arbre spécifié. + +```bash +# Obtenir une copie de travail du dépôt - par défaut on prend la branche master +$ git checkout + +# Bascule vers une branche spéficiée +$ git checkout nomDeLaBranche + +# Créé une nouvelle branche et bascule sur celle-ci +# Revient à faire "git branch ; git checkout " +$ git checkout -b nouvelleBranche +``` + +### clone + +Clone (ou copie) un dépôt existant dans un nouveau répertoire. Rajoute +également les branches distantes pour chaque branche du dépôt clôné, ce qui +vous permet de pousser vers une branche distante. + +```bash +# Clone learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git + +# Clone superficiel ("shallow clone") - clone plus rapide qui récupère +seulement le dernier instantané ("snapshot") +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git + +# Clone seulement une branche spécifique +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch +``` + +### commit + +Conserve le contenu actuel de la zone d'index dans un nouveau "commit." Ce +commit contient les changements faits, accompagnés d'un message écrit par son +auteur. + +```bash +# Commit avec un message +$ git commit -m "Ajout de la fonction multiplierNombres() dans HelloWorld.c" + +# Rajoute automatiquement dans l'index les fichiers modifiés ou supprimés, +# à l'exception des nouveaux fichiers, puis commit +$ git commit -a -m "Modification de foo.php et suppression de bar.php" + +# Change le dernier commit (ceci supprime le commit précédent avec un +# nouveau commit) +$ git commit --amend -m "Message corrigé" +``` + +### diff + +Montre les différences entre un fichier dans le répertoire de travail, la zone +d'index and les commits. + +```bash +# Affiche les différences entre votre répertoire de travail et l'index +$ git diff + +# Affiche les différences entre l'index et le plus récent commit. +$ git diff --cached + +# Affiche les différences entre votre répertoire de travail et le plus récent +# commit +$ git diff HEAD +``` + +### grep + +Permet de faire une recherche rapide dans le dépôt. + +Configurations optionnelles : + +```bash +# Merci à Travis Jeffery pour ce qui suit +# Affiche les numéros des lignes dans les résultats de la recherche grep +$ git config --global grep.lineNumber true + +# Rend les résultats de recherche plus lisibles, en incluant les groupements +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Recherche de "nomDeVariable" dans tous les fichiers java +$ git grep 'nomDeVariable' -- '*.java' + +# Recherche une ligne contenant "nomDeTableau", et "rajouter" ou "enlever" +$ git grep -e 'nomDeTableau' --and \( -e rajouter -e enlever \) +``` + +Google est votre ami; pour plus d'exemples : +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Affiche les commits d'un dépôt. + +```bash +# Montre tous les commits +$ git log + +# Montre seulement les messages de commits et leur référence +$ git log --oneline + +# Montre seulement les commits commits des merges (fusions) +$ git log --merges +``` + +### merge + +Fusionne les changements provenant de commits externes dans la branche +courante. + +```bash +# Fusionne la branche spécifiée dans la branche courante. +$ git merge nomDeBranche + +# Génère toujours un commit quand on fusionne +$ git merge --no-ff branchName +``` + +### mv + +Renomme ou déplace un fichier + +```bash +# Renomme un fichier +$ git mv HelloWorld.c HelloNewWorld.c + +# Déplace un fichier +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Force le renommage ou le déplacement +# Si "fichierExistant" existe déjà dans le répertoire, il sera écrasé +$ git mv -f monFichier fichierExistant +``` + +### pull + +Récupère la version d'un dépôt et la fusionne avec une autre branche. + +```bash +# Met à jour votre dépôt local en y intégrant les changements +# depuis la branche "master" du dépôt distant "origin". +# git pull +$ git pull origin master + +# Par défaut, git pull mettra à jour votre branche actuelle +# en y intégrant les nouveaux changements venant de sa branche distante suivie +$ git pull + +# Intègre les changements de la branche distante et "rebase" +# les commits de la branche dans votre dépôt local, comme ceci: +#"git pull , git rebase " +$ git pull origin master --rebase +``` + +### push + +Pousse et fusionne les changements d'une dépôt local vers une branche distante. + +```bash +# Pousse et fusionne les changements d'un dépôt local vers la branche +# appelée "master" du dépôt distant "master". +# git push +$ git push origin master + +# Par défaut, git push poussera et fusionnera les changements de la branche +# courante vers sa branche distante suivie. +$ git push + +# Pour faire le lien entre la branche locale courante et sa branche distante, +# rajouter l'option -u : +$ git push -u origin master +# Dorénavant, à chaque fois que vous voulez pousser depuis cette même branche +# locale, utilisez ce raccourci : +$ git push +``` + +### stash + +Sauvegarde ("stash") l'état actuel de votre espace de travail et le garde dans +pile de changements non finis que vous pouvez réappliquer n'importe quand. + +Supposons que vous avez effectué du travail dans votre dépôt git, mais que vous +voulez récupérer la version de la branche distante. Depuis que vous avez des +changements "malpropres" (non commités) à quelques fichiers, vous ne pouvez pas +faire de `git pull`. A la place, vous pouvez utiliser `git stash` afin de +sauvegarder votre travail dans la pile ! + +```bash +$ git stash +Saved working directory and index state \ + "WIP on master: 049d078 added the index file" + HEAD is now at 049d078 added the index file + (To restore them type "git stash apply") +``` + +Vous pouvez maintenant pull ! + +```bash +git pull +``` +`...changes apply...` + +Vérifiez maintenant que tout est OK + +```bash +$ git status +# On branch master +nothing to commit, working directory clean +``` + +Vous pouvez constater quels "morceaux" vous avez stash jusque là en +utilisant `git stash list`. +Puisque les changements sont gardés dans une pile Last-In-First-Out, notre +changement le plus récent sera en premier. + +```bash +$ git stash list +stash@{0}: WIP on master: 049d078 rajout du fichier index +stash@{1}: WIP on master: c264051 annulation de "rajout de la taille_fichier" +stash@{2}: WIP on master: 21d80a5 ajout des chiffres aux logs +``` + +Appliquons maintenant les changements en les enlevant de notre pile. + +```bash +$ git stash pop +# On branch master +# Changes not staged for commit: +# (use "git add ..." to update what will be committed) +# +# modified: index.html +# modified: lib/simplegit.rb +# +``` + +`git stash apply` effectue le même travail + +Vous êtes maintenant prêt à retourner sur vos tâches de travail ! + +[Lecture additionelle.](https://git-scm.com/book/fr/v1/Utilitaires-Git-Le-remisage) + +### rebase (attention) + +Prend tous les changements qui ont été commités sur une branche, et les +ré-applique sur une autre branche. +*Ne rebasez pas les commits que vous avez poussés sur un dépôt publique*. + +```bash +# Expérimentation d'un rebase dans la branche "master" +# git rebase +$ git rebase master brancheExperience +``` + +[Lecture additionelle.](https://git-scm.com/book/fr/v1/Les-branches-avec-Git-Rebaser) + +### reset (attention) + +Réinitialise le pointeur HEAD courant à l'état spécifié. Ceci vous permet +d'annuler des fusions, des pulls, commits, ajouts et autres. C'est une commande +puissante mais également dangereuse si vous ne savez pas ce que vous faites. + +```bash +# Réinitialise la zone d'index afin de correspondre au dernier commit (laisse +# le répertoire inchangé). +$ git reset + +# Réinitialise la zone d'index afin de correspondre au dernier commit et +# réécrit le répertoire de travail. +$ git reset --hard + +# Déplace le pointeur de la branche courante au commit spécifié (laisse +# le répertoire inchangé). Tous les changements existents toujours dans +# le répertoire. +$ git reset 31f2bb1 + +# Déplace le pointeur de la branche courante en arrière, au commit spécifié +# et fait correspondre le répertoire de travail (supprime les changements +# non commités et tous les commits après le commit spécifié). +$ git reset --hard 31f2bb1 +``` + +### rm + +Le contraire de git add, git rm supprime les fichiers de l'arbre de travail +courant. + +```bash +# Supprime HelloWorld.c +$ git rm HelloWorld.c + +# Enlève un fichier d'un répertoire imbriqué. +$ git rm /chemin/vers/le/fichier/HelloWorld.c +``` + +## Informations complémentaires + +* [tryGit - A fun interactive way to learn Git (EN)](http://try.github.io/levels/1/challenges/1) + +* [Udemy Git Tutorial: A Comprehensive Guide (EN)](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [git-scm - Tutoriaux vidéos](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutoriaux et Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet (EN)](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [GitGuys (EN)](http://www.gitguys.com/) + +* [Git - the simple guide (EN)](http://rogerdudler.github.io/git-guide/index.html) + +* [Livre Pro Git](http://www.git-scm.com/book/fr/v1) + +* [Une introduction à Git et GitHub pour les débutants (tutoriel) (EN)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) -- cgit v1.2.3 From cf309475adf6e26ec3977c81d58d033551361e18 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:10:59 +0200 Subject: #1949 metadata fix --- fr-fr/git-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown index 7a83704d..510459fe 100644 --- a/fr-fr/git-fr.html.markdown +++ b/fr-fr/git-fr.html.markdown @@ -8,7 +8,7 @@ contributors: - ["Bruno Volcov", "http://github.com/volcov"] translators: - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] -filename: LearnGit-fr-.txt +filename: LearnGit-fr.txt lang: fr-fr --- -- cgit v1.2.3 From b7e57907b97582c5adc4f4cbf4c0fbee6e56a6ef Mon Sep 17 00:00:00 2001 From: Jacopo Andrea Giola Date: Sun, 26 Jun 2016 15:11:52 +0200 Subject: Add Italian translation for Markdown (#1663) --- it-it/markdown.html.markdown | 244 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 244 insertions(+) create mode 100644 it-it/markdown.html.markdown diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown new file mode 100644 index 00000000..2560c5b1 --- /dev/null +++ b/it-it/markdown.html.markdown @@ -0,0 +1,244 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Jacopo Andrea Giola", "http://geekpanda.net"] +filename: markdown.md +lang: it-it +--- + +Markdown è stato creato da John Gruber nel 2004. Il suo scopo è quello di essere una sintassi facile da leggere e scrivere, e che può essere convertita in HTML (ad oggi anche in molti altri formati). + +Mandate tutto il feedback che volete! / Sentitevi liberi di forkare o di mandare pull request! + + +```markdown + + + + + + +# Questo è un

+## Questo è un

+### Questo è un

+#### Questo è un

+##### Questo è un

+###### Questo è un
+ + +Questo è un h1 +============== + +Questo è un h2 +-------------- + + + + +*Questo testo è in corsivo.* +_Come pure questo._ + +**Questo testo è in grassetto.** +__Come pure questo.__ + +***Questo testo è stilizzato in entrabmi i modi.*** +**_Come questo!_** +*__E questo!__* + + + +~~Questo testo è barrato.~~ + + + +Qeusto è un paragrafo. Sto scrivendo in un paragrafo, non è divertente? + +Ora sono nel paragrafo 2. +Anche questa linea è nel paragrafo 2! + + +Qui siamo nel paragrafo 3! + + + +Questa frase finisce con due spazi (evidenziatemi per vederli). + +C'è un
sopra di me! + + + +> Questa è una citazione. Potete +> mandare a capo manualmente le linee e inserire un `>` prima di ognuna, oppure potete usare una sola linea e lasciare che vada a capo automaticamente. +> Non c'è alcuna differenza, basta che iniziate ogni riga con `>`. + +> Potete utilizzare anche più di un livello +>> di indentazione! +> Quanto è comodo? + + + + +* Oggetto +* Oggetto +* Altro oggetto + +oppure + ++ Oggetto ++ Oggetto ++ Un altro oggetto + +oppure + +- Oggetto +- Oggetto +- Un ultimo oggetto + + + +1. Primo oggetto +2. Secondo oggetto +3. Terzo oggetto + + + +1. Primo oggetto +1. Secondo oggetto +1. Terzo oggetto + + + + +1. Primo oggetto +2. Secondo oggetto +3. Terzo oggetto + * Sotto-oggetto + * Sotto-oggetto +4. Quarto oggetto + + + +I box senza la 'x' sono checkbox HTML ancora da completare. +- [ ] Primo task da completare. +- [ ] Secondo task che deve essere completato. +Il box subito sotto è una checkbox HTML spuntata. +- [x] Questo task è stato completato. + + + + + Questa è una linea di codice + Come questa + + + + my_array.each do |item| + puts item + end + + + +Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! + + + +\`\`\`ruby +def foobar + puts "Hello world!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Cliccami!](http://test.com/) + + + +[Cliccami!](http://test.com/ "Link a Test.com") + + + +[Vai a musica](/music/). + + + +[Apri questo link][link1] per più informazioni! +[Guarda anche questo link][foobar] se ti va. + +[link1]: http://test.com/ "Bello!" +[foobar]: http://foobar.biz/ "Va bene!" + + + + + +[Questo][] è un link. + +[Questo]: http://thisisalink.com/ + + + + + + +![Qeusto è il testo alternativo per l'immagine](http://imgur.com/myimage.jpg "Il titolo opzionale") + + + +![Questo è il testo alternativo.][myimage] + +[myimage]: relative/urls/cool/image.jpg "Se vi serve un titolo, lo mettete qui" + + + + + è equivalente ad +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga renderizzato in corsivo, quindi lo inserirò così: \*questo testo è circondato da asterischi\*. + + + + +Il tuo computer è crashato? Prova a premere +Ctrl+Alt+Canc + + + + +| Col1 | Col2 | Col3 | +| :------------------- | :------: | -----------------: | +| Allineato a sinistra | Centrato | Allineato a destra | +| blah | blah | blah | + + + +Col 1 | Col2 | Col3 +:-- | :-: | --: +È una cosa orrenda | fatela | finire in fretta + + + +``` + +Per altre informazioni, leggete il post ufficiale di John Gruber sulla sintassi [qui](http://daringfireball.net/projects/markdown/syntax) e il magnifico cheatsheet di Adam Pritchard [qui](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From 4604870dc36e9603c563826224d13af881c7e132 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:12:36 +0200 Subject: metadata fix --- it-it/markdown.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index 2560c5b1..b006dbb4 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Jacopo Andrea Giola", "http://geekpanda.net"] -filename: markdown.md +filename: markdown-it.md lang: it-it --- -- cgit v1.2.3 From 19ac1e8eeb92115b1af90ea1aa9181a8f6d48211 Mon Sep 17 00:00:00 2001 From: s-webber Date: Sun, 26 Jun 2016 14:20:28 +0100 Subject: [kotlin/en] Add examples of sequences (#2214) * minor capitalization and punctuation changes * examples of sequences * corrected comment --- kotlin.html.markdown | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 7b1475a8..605b1a63 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -5,7 +5,7 @@ contributors: filename: LearnKotlin.kt --- -Kotlin is a Statically typed programming language for the JVM, Android and the +Kotlin is a statically typed programming language for the JVM, Android and the browser. It is 100% interoperable with Java. [Read more here.](https://kotlinlang.org/) @@ -72,7 +72,7 @@ fun helloWorld(val name : String) { A variable can be specified as nullable by appending a ? to its type. We can access a nullable variable by using the ?. operator. We can use the ?: operator to specify an alternative value to use - if a variable is null + if a variable is null. */ var fooNullable: String? = "abc" println(fooNullable?.length) // => 3 @@ -137,7 +137,7 @@ fun helloWorld(val name : String) { println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") } - //The "class" keyword is used to declare classes. + // The "class" keyword is used to declare classes. class ExampleClass(val x: Int) { fun memberFunction(y: Int) : Int { return x + y @@ -194,7 +194,7 @@ fun helloWorld(val name : String) { println(fooList.size) // => 3 println(fooList.first()) // => a println(fooList.last()) // => c - // elements can be accessed by index + // Elements of a list can be accessed by their index. println(fooList[1]) // => b // A mutable list can be created using the "mutableListOf" function. @@ -213,12 +213,37 @@ fun helloWorld(val name : String) { // Map values can be accessed by their key. println(fooMap["a"]) // => 8 + /* + Sequences represent lazily-evaluated collections. + We can create a sequence using the "generateSequence" function. + */ + val fooSequence = generateSequence(1, {it + 1}) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // An example of using a sequence to generate Fibonacci numbers: + fun fibonacciSequence() : Sequence { + var a = 0L + var b = 1L + + fun next() : Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + // Kotlin provides higher-order functions for working with collections. - val x = (1..9).map {it * 3} + val z = (1..9).map {it * 3} .filter {it < 20} .groupBy {it % 2 == 0} .mapKeys {if (it.key) "even" else "odd"} - println(x) // => {odd=[3, 9, 15], even=[6, 12, 18]} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} // A "for" loop can be used with anything that provides an iterator. for (c in "hello") { -- cgit v1.2.3 From 273fa8606b662dbec5b3b0b2fd0d3dfd648e00ab Mon Sep 17 00:00:00 2001 From: Geoffrey Liu Date: Sun, 26 Jun 2016 21:21:13 +0800 Subject: [racket/en] Add more details about Racket (#2278) * Add let* and letrec reference * More elaboration on structs * Add code about predefined car, cdr functions * Mention explicit typing, int to real conversion --- racket.html.markdown | 34 ++++++++++++++++++++++++++++++++++ standard-ml.html.markdown | 8 ++++++++ 2 files changed, 42 insertions(+) diff --git a/racket.html.markdown b/racket.html.markdown index 0fe3f030..96dcaf25 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -114,18 +114,42 @@ some-var ; => 5 "Alice" me) ; => "Bob" +;; let* is like let, but allows you to use previous bindings in creating later bindings +(let* ([x 1] + [y (+ x 1)]) + (* x y)) + +;; finally, letrec allows you to define recursive and mutually recursive functions +(letrec ([is-even? (lambda (n) + (or (zero? n) + (is-odd? (sub1 n))))] + [is-odd? (lambda (n) + (and (not (zero? n)) + (is-even? (sub1 n))))]) + (is-odd? 11)) + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 3. Structs and Collections ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Structs +; By default, structs are immutable (struct dog (name breed age)) (define my-pet (dog "lassie" "collie" 5)) my-pet ; => # +; returns whether the variable was constructed with the dog constructor (dog? my-pet) ; => #t +; accesses the name field of the variable constructed with the dog constructor (dog-name my-pet) ; => "lassie" +; You can explicitly declare a struct to be mutable with the #:mutable option +(struct rgba-color (red green blue alpha) #:mutable) +(define burgundy + (rgba-color 144 0 32 1.0)) +(set-color-green! burgundy 10) +(color-green burgundy) ; => 10 + ;;; Pairs (immutable) ;; `cons' constructs pairs, `car' and `cdr' extract the first ;; and second elements @@ -143,6 +167,16 @@ my-pet ; => # ;; and a quote can also be used for a literal list value '(1 2 3) ; => '(1 2 3) +;; Racket has predefined functions on top of car and cdr, to extract parts of a list +(cadr (list 1 2 3)) ; => 2 +(car (cdr (list 1 2 3))) ; => 2 + +(cddr (list 1 2 3)) ; => '(3) +(cdr (cdr (list 1 2 3))) ; => '(3) + +(caddr (list 1 2 3)) ; => 3 +(car (cdr (cdr (list 1 2 3)))) ; => 3 + ;; Can still use `cons' to add an item to the beginning of a list (cons 4 '(1 2 3)) ; => '(4 1 2 3) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index 143980e7..133e4f54 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -24,6 +24,12 @@ val phone_no = 5551337 val pi = 3.14159 val negative_number = ~15 (* Yeah, unary minus uses the 'tilde' symbol *) +(* Optionally, you can explicitly declare types. This is not necessary as + ML will automatically figure out the types of your values. *) +val diameter = 7926 : int +val e = 2.718 : real +val name = "Bobby" : string + (* And just as importantly, functions: *) fun is_large(x : int) = if x > 37 then true else false @@ -31,6 +37,8 @@ fun is_large(x : int) = if x > 37 then true else false val tau = 2.0 * pi (* You can multiply two reals *) val twice_rent = 2 * rent (* You can multiply two ints *) (* val meh = 1.25 * 10 *) (* But you can't multiply an int and a real *) +val yeh = 1.25 * (Real.fromInt 10) (* ...unless you explicitly convert + one or the other *) (* +, - and * are overloaded so they work for both int and real. *) (* The same cannot be said for division which has separate operators: *) -- cgit v1.2.3 From a7015a0f8592d49f62bbafae1dcffcf1619ec92d Mon Sep 17 00:00:00 2001 From: Adam Heins Date: Sun, 26 Jun 2016 06:21:27 -0700 Subject: Minor formatting and wording change in rust doc. (#2277) --- rust.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index d0c56b4a..440cd9eb 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -281,7 +281,7 @@ fn main() { println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); // var = 5; // this would not compile because `var` is borrowed - // *ref_var = 6; // this would not too, because `ref_var` is an immutable reference + // *ref_var = 6; // this would not either, because `ref_var` is an immutable reference // Mutable reference // While a value is mutably borrowed, it cannot be accessed at all. @@ -289,8 +289,9 @@ fn main() { let ref_var2: &mut i32 = &mut var2; *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2 - 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 + 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. } ``` -- cgit v1.2.3 From 6069ef6dc36baa14eda997591031c1eaf78b6481 Mon Sep 17 00:00:00 2001 From: Arlindo Pereira Date: Sun, 26 Jun 2016 10:22:21 -0300 Subject: fixing typos (#2228) --- pt-br/bash-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/bash-pt.html.markdown b/pt-br/bash-pt.html.markdown index a604e7b8..ae18435a 100644 --- a/pt-br/bash-pt.html.markdown +++ b/pt-br/bash-pt.html.markdown @@ -161,11 +161,11 @@ echo "#helloworld" > output.out echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out > /dev/null -# Limpa os arquivos temporarios detalhando quais foram deletados (use '-i' para confirmar exlusão) +# Limpa os arquivos temporários detalhando quais foram deletados (use '-i' para confirmar exclusão) rm -v output.out error.err output-and-error.log -# Comando podem ser substituidos por outros comandos usando $( ): -# O comand oa seguir mostra o número de arquivos e diretórios no diretorio atual +# Comando podem ser substituídos por outros comandos usando $( ): +# O comando a seguir mostra o número de arquivos e diretórios no diretorio atual echo "Existem $(ls | wc -l) itens aqui." # O mesmo pode ser feito usando crase `` mas elas não podem ser aninhadas - dá se -- cgit v1.2.3 From ec15a36de7bcc56708d7e6d52fabe0296b8cc466 Mon Sep 17 00:00:00 2001 From: Arlindo Pereira Date: Sun, 26 Jun 2016 10:22:34 -0300 Subject: Removing untranslated duplicated text (#2227) --- pt-br/javascript-pt.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index 59c6890e..e337f4bc 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -197,7 +197,6 @@ myObj.myFourthKey; // = undefined // A sintaxe para essa seção é quase idêntica a maioria das linguagens. -// The `if` structure works as you'd expect. // A estrutura `if` funciona como deveria ser. var count = 1 if (count == 3){ @@ -219,9 +218,6 @@ do { input = getInput(); } while (!isValid(input)) -// The `for` loop is the same as C and Java: -// initialisation; continue condition; iteration. - // O loop `for` é o mesmo de C e Java: // inicialização, condição para continuar; iteração for (var i = 0; i < 5; i++){ -- cgit v1.2.3 From e72c849556dd7ae9cd1333229b4c007a7229225f Mon Sep 17 00:00:00 2001 From: Alexandre Constantino Date: Sun, 26 Jun 2016 14:22:47 +0100 Subject: Python3/en: multiple inheritance (#2217) * Add __name__ check to make testing easier * Update say to call print. Add more usage examples * Move Modules section before Classes Makes more sense for when explaining inheritance * Add multiple inheritance example * Add examples for multiple inheritance * Add instance check examples * Fix multiple inheritance example * Add note on the __name__ variable --- python3.html.markdown | 197 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 147 insertions(+), 50 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 0f5da8f1..7f3702e6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -601,10 +601,47 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + #################################################### -## 5. Classes +## 5. Modules #################################################### +# You can import modules +import math +print(math.sqrt(16)) # => 4.0 + +# You can get specific functions from a module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + + +#################################################### +## 6. Classes +#################################################### # We use the "class" operator to get a class class Human: @@ -627,7 +664,11 @@ class Human: # An instance method. All methods take "self" as the first argument def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) + print ("{name}: {message}".format(name=self.name, message=msg)) + + # Another instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' # A class method is shared among all instances # They are called with the calling class as the first argument @@ -658,71 +699,127 @@ class Human: del self._age -# Instantiate a class -i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +# When a Python interpreter reads a source file it executes all its code. +# This __name__ check makes sure this code block is only executed when this +# module is the main program. +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + i.say("hi") # "Ian: hi" + j = Human("Joel") + j.say("hello") # "Joel: hello" + # i and j are instances of type Human, or in other words: they are Human objects + + # Call our class method + i.say(i.get_species()) # "Ian: H. sapiens" + # Change the shared attribute + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Call the static method + print(Human.grunt()) # => "*grunt*" + print(i.grunt()) # => "*grunt*" + + # Update the property for this instance + i.age = 42 + # Get the property + i.say(i.age) # => 42 + j.say(j.age) # => 0 + # Delete the property + del i.age + # i.age # => this would raise an AttributeError -j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" -# Call our class method -i.get_species() # => "H. sapiens" +#################################################### +## 6.1 Multiple Inheritance +#################################################### -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +# Another class definition +class Bat: -# Call the static method -Human.grunt() # => "*grunt*" + species = 'Baty' -# Update the property -i.age = 42 + def __init__(self, can_fly=True): + self.fly = can_fly -# Get the property -i.age # => 42 + # This class also has a say method + def say(self, msg): + msg = '... ... ...' + return msg -# Delete the property -del i.age -i.age # => raises an AttributeError + # And its own method as well + def sonar(self): + return '))) ... (((' +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) -#################################################### -## 6. Modules -#################################################### +# from "filename-without-extension" import "function-or-class" +from human import Human +from bat import Bat -# You can import modules -import math -print(math.sqrt(16)) # => 4.0 +# Batman inherits from both Human and Bat +class Batman(Human, Bat): -# You can get specific functions from a module -from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 + # Batman has its own value for the species class attribute + species = 'Superhero' -# You can import all functions from a module. -# Warning: this is not recommended -from math import * + def __init__(self, *args, **kwargs): + # Typically to inherit attributes you have to call super: + #super(Batman, self).__init__(*args, **kwargs) + # However we are dealing with multiple inheritance here, and super() + # only works with the next base class in the MRO list. + # So instead we explicitly call __init__ for all ancestors. + # The use of *args and **kwargs allows for a clean way to pass arguments, + # with each parent "peeling a layer of the onion". + Human.__init__(self, 'anonymous', *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # override the value for the name attribute + self.name = 'Sad Affleck' -# You can shorten module names -import math as m -math.sqrt(16) == m.sqrt(16) # => True + def sing(self): + return 'nan nan nan nan nan batman!' -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. -# You can find out which functions and attributes -# defines a module. -import math -dir(math) +if __name__ == '__main__': + sup = Batman() + + # Instance type checks + if isinstance(sup, Human): + print('I am human') + if isinstance(sup, Bat): + print('I am bat') + if type(sup) is Batman: + print('I am Batman') + + # Get the Method Resolution search Order used by both getattr() and super(). + # This attribute is dynamic and can be updated + print(Batman.__mro__) # => (, , , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhero + + # Calls overloaded method + print(sup.sing()) # => nan nan nan nan nan batman! + + # Calls method from Human, because inheritance order matters + sup.say('I agree') # => Sad Affleck: I agree + + # Call method that exists only in 2nd ancestor + print(sup.sonar()) # => ))) ... ((( + + # Inherited class attribute + sup.age = 100 + print(sup.age) + + # Inherited attribute from 2nd ancestor whose default value was overriden + print('Can I fly? ' + str(sup.fly)) + -# If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. -# This happens because the local folder has priority -# over Python's built-in libraries. #################################################### ## 7. Advanced -- cgit v1.2.3 From 5068509640591a47a47169687757fc996c88d60a Mon Sep 17 00:00:00 2001 From: Voltinus Date: Sun, 26 Jun 2016 16:24:58 +0300 Subject: [json/pl] Translated JSON tutorial (#2079) * Create json-pl.html.markdown * Update json-pl.html.markdown * Added -pl to file name --- pl-pl/json-pl.html.markdown | 85 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 pl-pl/json-pl.html.markdown diff --git a/pl-pl/json-pl.html.markdown b/pl-pl/json-pl.html.markdown new file mode 100644 index 00000000..872455de --- /dev/null +++ b/pl-pl/json-pl.html.markdown @@ -0,0 +1,85 @@ +--- +language: json +filename: learnjson-pl.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] +translators: + - ["Michał Mitrosz", "https://github.com/Voltinus"] +lang: pl-pl +--- + +JSON to bardzo prosty format wymiany danych. Jak jest napisane na [json.org](http://json.org), jest łatwy do pisania i czytania dla ludzi i do parsowania i generowania dla maszyn. + +Kod JSON musi zawierać któreś z poniższych: +* Zbiór par nazwa/wartość (`{ }`). W różnych językach jest to obiekt, rekord, struktura, słownik, tablica mieszająca, lista z kluczami, lub tablica asocjacyjna. +* Uporządkowana lista wartości (`[ ]`). W różnych językach jest to tablica, wektor, lista, lub sekwencja. + tablica/lista/sekwencja (`[ ]`) lub słownik/obiekt/tablica asocjacyjna (`{ }`). + +JSON w swojej czystej postaci nie ma komentarzy, ale większość parserów akceptuje komentarze w stylu C (`//`, `/* */`). Niektóre parsery pozwalają także na końcowy przecinek (np. przecinek po ostatnim elemencie w tablicy lub po ostatiej własności obiektu), ale powinien on być omijany dla lepszej kompatybilności. + +Dla celów tego poradnika wszystko będzie 100% kodem JSON. Na szczęście, to samo mówi za siebie. + +Wspierane typy danych: + +* Łańcuchy znaków: `"witaj"`, `"\"Cytat.\""`, `"\u0abe"`, `"Nowa linia.\n"` +* Liczby: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Obiekty: `{ "klucz": "wartość" }` +* Tablice: `["Wartości"]` +* Inne: `true`, `false`, `null` + +```json +{ + "klucz": "wartość", + + "klucze": "muszą być zawsze zamknięte w podwójnych cudzysłowach", + "liczby": 0, + "łańcuchy": "Hellø, wørld. Wszystkie znaki unicode są dozwolone, razem z \"sekwencjami escape\".", + "wartości logiczne?": true, + "nic": null, + + "duża liczba": 1.2e+100, + + "obiekty": { + "komentarz": "Większość twojej struktury będzie zbudowana z obiektów.", + + "tablica": [0, 1, 2, 3, "Tablice mogą mieć wewnątrz cokolwiek", 5], + + "inny obiekt": { + "komentarz": "Elementy mogą się w sobie zawierać, bardzo użyteczne" + } + }, + + "głupota": [ + { + "źródła potasu": ["banany"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "styl alternatywny": { + "komentarz": "sprawdź to!" + , "pozycja przecinka": "nie ma znaczenia, o ile jest przed następnym kluczem, jest poprawnie" + , "następny komentarz": "jak ładnie" + }, + + + + "znaki białe": "nie mają znaczenia", + + + + "to było krótkie": "I gotowe. Wiesz już wszystko o formacie JSON." +} +``` + +## Dalsza lektura + +* [JSON.org](http://json.org) Cały JSON pięknie wytłumaczony na podstawie grafik przypominających schematy blokowe. -- cgit v1.2.3 From 0bb3ed5f870025a14e07cd9ff7eb00277cd14e19 Mon Sep 17 00:00:00 2001 From: Tasya Aditya Rukmana Date: Sun, 26 Jun 2016 21:29:20 +0800 Subject: Added id-id translation for markdown (#1476) --- id-id/markdown.html.markdown | 263 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 263 insertions(+) create mode 100644 id-id/markdown.html.markdown diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown new file mode 100644 index 00000000..5e28aba9 --- /dev/null +++ b/id-id/markdown.html.markdown @@ -0,0 +1,263 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +filename: markdown.md +--- + +Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax yang mudah dibaca dan ditulis yang dapat berubah menjadi HTML (dan sekarang berbagai format lainnya) dengan mudah. + +Beri masukan sebanyak-banyaknya! / Jangan sungkan untuk melakukan fork dan pull request! + + +```markdown + + + + + + +# Ini adalah

+## Ini adalah

+### Ini adalah

+#### Ini adalah

+##### Ini adalah

+###### Ini adalah
+ + +Ini adalah h1 +============= + +Ini adalah h2 +------------- + + + + +*Ini adalah teks miring.* +_Dan juga teks ini._ + +**Ini adalah teks tebal.** +__Dan juga teks ini.__ + +***Ini adalah teks dengan keduanya.*** +**_Dan juga ini!_** +*__Dan ini!__* + + + +~~Teks ini dirender dengan coretan.~~ + + + +Ini adalah paragraf. Saya mengetik dalam paragraf, bukankah ini menyenangkan? + +Sekarang saya ada di paragraf 2. +Saya juga masih ada dalam paragraf 2! + + +Saya ada di paragraf 3! + + + +Aku diakhiri dua spasi (soroti aku untuk melihatnya). + +Ada sebuah
diatasku! + + + +> Ini adalah kutipan. Anda dapat +> membungkusnya secara manual dan meletakkan `>` sebelum tiap baris atau Anda dapat membuat baris yang sangat panjang dan membuatnya membungkus secara otomatis. +> Tidak ada masalah selama ia diawali dengan `>`. + +> Anda juga dapat menggunakan lebih dari satu level +>> indentasi! +> Sangat rapi bukan? + + + + +* Item +* Item +* Item lainnya + +atau + ++ Item ++ Item ++ Satu lagi item + +or + +- Item +- Item +- Item terakhir + + + +1. Item satu +2. Item dua +3. Item tiga + + + +1. Item satu +1. Item dua +1. Item tida + + + + +1. Item satu +2. Item dua +3. Item tiga + * Sub-item + * Sub-item +4. Item empat + + + +Kotak di bawah tanpa 'x' adalah kotak centang HTML yang belum diisi. +- [ ] Tugas pertama selesai. +- [ ] Tugas kedua yang harus diselesaikan +Kotak centang HTML berikut telah diisi. +- [x] Tugas ini telah diselesaikan + + + + + Ini adalah kode + Dan ini juga + + + + array_ku.each do |item| + puts item + end + + + +John bahkan tidak tahu apa fungsi dari `go_to()` ! + + + +\`\`\`ruby +def foobar + puts "Halo Dunia!" +end +\`\`\` + + + + + + +*** +--- +- - - +**************** + + + + +[Klik aku!](http://test.com/) + + + +[Klik aku!](http://test.com/ "Link to Test.com") + + + +[Pergi ke musik](/music/). + + + +[Klik link ini][link1] untuk info lebih banyak! +[Juga cek link ini][foobar] jika Anda mau. + +[link1]: http://test.com/ "Keren!" +[foobar]: http://foobar.biz/ "OK!" + + + + + +[Ini][] adalah tautan. + +[ini]: http://thisisalink.com/ + + + + + + +![Ini adalah atribut alt dari gambar saya](http://imgur.com/myimage.jpg "Judul opsional") + + + +![Ini adalah atribut alt.][myimage] + +[myimage]: relative/urls/cool/image.jpg "jika Anda membutuhkan judul, disini" + + + + + sama dengan +[http://testwebsite.com/](http://testwebsite.com/) + + + + + + + +Saya ingin mengetik *teks ini dikelilingi tanda bintang* tapi saya tidak mau teksnya menjadi +miring, jadi saya melakukan: \*teks ini dikelilingi tanda bintang\*. + + + + +Komputer Anda hang? Coba kirim sebuah +Ctrl+Alt+Del + + + + +| Kol1 | Kol2 | Kol3 | +| :----------- | :------: | ------------: | +| Rata-kiri | Tengah | Rata-Kanan | +| blah | blah | blah | + + + +Kol 1 | Kol2 | Kol3 +:-- | :-: | --: +Ugh ini sangat jelek | buat ia | berhenti + + + +``` + +Untuk info lebih lanjut, cek post syntax resmi John Gruber [di sini](http://daringfireball.net/projects/markdown/syntax) dan contekan hebat Adam Pritchard's [di sini](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). -- cgit v1.2.3 From c6ba8c1f3f9401907236da73a3eddcf77b05bf2e Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:29:40 +0200 Subject: #1476 metadata --- id-id/markdown.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown index 5e28aba9..9a7c18cc 100644 --- a/id-id/markdown.html.markdown +++ b/id-id/markdown.html.markdown @@ -3,8 +3,8 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] -filename: markdown.md + - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +filename: markdown-id.md --- Markdown dibuat oleh John Gruber pada tahun 2004. Tujuannya untuk menjadi syntax yang mudah dibaca dan ditulis yang dapat berubah menjadi HTML (dan sekarang berbagai format lainnya) dengan mudah. -- cgit v1.2.3 From d9c2b9a9c26ecb387b50660e71855691c0995e1d Mon Sep 17 00:00:00 2001 From: fontealpina Date: Sun, 26 Jun 2016 15:30:05 +0200 Subject: Add matlab italian translation (#1454) --- it-it/matlab-it.html.markdown | 525 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 525 insertions(+) create mode 100644 it-it/matlab-it.html.markdown diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown new file mode 100644 index 00000000..b1e8777b --- /dev/null +++ b/it-it/matlab-it.html.markdown @@ -0,0 +1,525 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] +translators: + - ["Samuele Gallerani", "http://github.com/fontealpina"] +lang: it-it +--- + +MATLAB sta per MATrix LABoratory ed è un potente linguaggio per il calcolo numerico comunemente usato in ingegneria e matematica. + +```matlab +% I commenti iniziano con il segno percentuale. + +%{ +I commenti multilinea +assomigliano a +qualcosa +del genere +%} + +% i comandi possono essere spezzati su più linee, usando '...': + a = 1 + 2 + ... + + 4 + +% i comandi possono essere passati al sistema operativo +!ping google.com + +who % Mostra tutte le variabili in memoria +whos % Mostra tutte le variabili in memoria, con i loro tipi +clear % Cancella tutte le tue variabili dalla memoria +clear('A') % Cancella una particolare variabile +openvar('A') % Apre la variabile in un editor di variabile + +clc % Cancella il contenuto della Command Window +diary % Attiva il log della Command Window su file +ctrl-c % Interrompe il calcolo corrente + +edit('myfunction.m') % Apre la funzione/script nell'editor +type('myfunction.m') % Stampa il codice della funzione/script sulla Command Window + +profile on % Attiva la profilazione del codice +profile off % Disattiva la profilazione del codice +profile viewer % Apre il profilatore + +help comando % Mostra la documentazione di comando sulla Command Window +doc comando % Mostra la documentazione di comando sulla Help Window +lookfor comando % Cerca comando nella prima linea di commento di tutte le funzioni +lookfor comando -all % Cerca comando in tutte le funzioni + + +% Formattazione dell'output +format short % 4 decimali in un numero float +format long % 15 decimali +format bank % Solo due cifre decimali - per calcoli finaziari +fprintf('text') % Stampa "text" a terminale +disp('text') % Stampa "text" a terminale + +% Variabili ed espressioni +miaVariabile = 4 % Il pannello Workspace mostra la nuova variabile creata +miaVariabile = 4; % Il punto e virgola evita che l'output venga stampato sulla Command Window +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% La chiamata di funzioni può essere fatta in due modi differenti: +% Sintassi standard di una funzione: +load('myFile.mat', 'y') % argomenti tra parentesi, separati da virgole +% Sintassi di tipo comando: +load myFile.mat y % Non ci sono parentesi e gli argometi sono separati da spazi +% Notare la mancanza di apici nella sintassi di tipo comando: gli input sono sempre passati come +% testo letterale - non è possibile passare valori di variabili. Inoltre non può ricevere output: +[V,D] = eig(A); % Questa non ha una forma equivalente con una sintassi di tipo comando +[~,D] = eig(A); % Se si vuole solo D e non V + + + +% Operatori logici +1 > 5 % ans = 0 +10 >= 10 % ans = 1 +3 ~= 4 % Not equal to -> ans = 1 +3 == 3 % equal to -> ans = 1 +3 > 1 && 4 > 1 % AND -> ans = 1 +3 > 1 || 4 > 1 % OR -> ans = 1 +~1 % NOT -> ans = 0 + +% Gli operatori logici possono essere applicati alle matrici: +A > 5 +% Per ogni elemento, se la condizione è vera, quell'elemento vale 1 nella matrice risultante +A( A > 5 ) +% Restituisce un vettore contenente gli elementi in A per cui la condizione è vera + +% Stringhe +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString + + +% Celle +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - ritorna una cella +char(a(1)) % ans = one - ritorna una stringa + +% Strutture +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; + +% Vettori +x = [4 32 53 7 1] +x(2) % ans = 32, gli indici in Matlab iniziano da 1, non da 0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Vettore colonna + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrici +A = [1 2 3; 4 5 6; 7 8 9] +% Le righe sono separate da punto e virgola, mentre gli elementi sono separati da spazi +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6, A(row, column) +A(6) % ans = 8 +% (implicitamente concatena le colonne in un vettore, e quindi gli indici sono riferiti al vettore) + + +A(2,3) = 42 % Aggiorna riga 2 colonna 3 con 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Crea una nuova matrice a partire da quella precedente +%ans = + +% 5 42 +% 8 9 + +A(:,1) % Tutte le righe nella colonna 1 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % Tutte le colonne in riga 1 +%ans = + +% 1 2 3 + +[A ; A] % Concatenazione di matrici (verticalmente) +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% è equivalente a +vertcat(A,A); + + +[A , A] % Concatenazione di matrici (orrizontalmente) + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% è equivalente a +horzcat(A,A); + + +A(:, [3 1 2]) % Ripristina le colonne della matrice originale +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % ans = 3 3 + +A(1, :) =[] % Rimuove la prima riga della matrice +A(:, 1) =[] % Rimuove la prima colonna della matrice + +transpose(A) % Traspone la matrice, equivale a: +A one +ctranspose(A) % Trasposizione hermitiana della matrice +% (ovvero il complesso coniugato di ogni elemento della matrice trasposta) + + + + +% Aritmetica Elemento per Elemento vs. Artimetica Matriciale +% Gli operatori aritmetici da soli agliscono sull'intera matrice. Quando sono preceduti +% da un punto, allora agiscono su ogni elemento. Per esempio: +A * B % Moltiplicazione matriciale +A .* B % Moltiplica ogni elemento di A per il corrispondente elemento di B + +% Ci sono diverse coppie di funzioni, in cui una agisce su ogni elemento, e +% l'altra (il cui nome termina con m) agisce sull'intera matrice. +exp(A) % Calcola l'esponenziale di ogni elemento +expm(A) % Calcola la matrice esponenziale +sqrt(A) % Calcola la radice quadrata di ogni elementotake the square root of each element +sqrtm(A) % Trova la matrice di cui A nè è la matrice quadrata + + +% Plot di grafici +x = 0:.10:2*pi; % Crea un vettore che inizia a 0 e termina 2*pi con incrementi di .1 +y = sin(x); +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x range da 0 a 2*pi, y range da -1 a 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % Per stampare più funzioni in unico plot +legend('Line 1 label', 'Line 2 label') % Aggiunge un etichetta con il nome delle curve + +% Metodo alternativo per stampare funzioni multiple in un unico plot. +% mentre 'hold' è on, i comandi sono aggiunti al grafico esistene invece di sostituirlo +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % Un plot di tipo log-log +semilogx(x, y) % Un plot con asse x logaritmico +semilogy(x, y) % Un plot con asse y logaritmico + +fplot (@(x) x^2, [2,5]) % Stampa la funzione x^2 da x=2 a x=5 + +grid on % Mostra la griglia, disattivare con 'grid off' +axis square % Rende quadrata la regione individuata dagli assi +axis equal % Iposta l'aspetto del grafico in modo che le unità degli assi siano le stesse + +scatter(x, y); % Scatter-plot +hist(x); % Istogramma + +z = sin(x); +plot3(x,y,z); % Stampa una linea 3D + +pcolor(A) % Heat-map di una matrice: stampa una griglia di rettangoli, colorati in base al valore +contour(A) % Contour plot di una matrice +mesh(A) % Stampa come una superfice di mesh + +h = figure % Crea un nuovo oggetto figura, con handle f +figure(h) % Rende la figura corrispondente al handle h la figura corrente +close(h) % Chiude la figura con handle h +close all % Chiude tutte le figure +close % Chiude la figura corrente + +shg % Riutilizza una finestra grafica già esistente, o se necessario ne crea una nuova +clf clear % Pulisce la figura corrente, e resetta le proprietà della figura + +% Le proprietà possono essere impostate e modificate attraverso l'handle della figura. +% Si può salvare l'handle della figura quando viene creata. +% La funzione gcf restituisce un handle alla figura attuale. +h = plot(x, y); % Si può salvare un handle della figura quando viene creata +set(h, 'Color', 'r') +% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black +set(h, 'LineStyle', '--') + % '--' linea continua, '---' tratteggiata, ':' puntini, '-.' trattino-punto, 'none' nessuna linea +get(h, 'LineStyle') + + +% La funzione gca restituisce un handle degli assi della figura corrente +set(gca, 'XDir', 'reverse'); % Inverte la direzione dell'asse x + +% Per creare una figura che contiene diverse sottofigure, usare subplot +subplot(2,3,1); % Seleziona la prima posizione in una griglia 2 per 3 di sottofigure +plot(x1); title('First Plot') % Stampa qualcosa in questa posizione +subplot(2,3,2); % Seleziona la seconda posizione nella griglia +plot(x2); title('Second Plot') % Stampa qualcosa in questa posizione + + +% Per usare funzioni o script, devono essere nel tuo path o nella directory corrente +path % Mostra il path corrente +addpath /path/to/dir % Aggiunge al path +rmpath /path/to/dir % Rimuove dal path +cd /path/to/move/into % Cambia directory + + +% Le variabili possono essere salvate in file .mat +save('myFileName.mat') % Salva le variabili nel tuo Workspace +load('myFileName.mat') % Carica variabili salvate nel tuo Workspace + +% M-file Scripts +% I file di script sono file esterni che contengono una sequenza di istruzioni. +% Permettono di evitare di scrivere ripetutamente lo stesso codice nella Command Window +% Hanno estensione .m + +% M-file Functions +% Come gli script, hanno la stessa estensione .m +% Ma possono accettare argomenti di input e restituire un output. +% Inoltre, hanno un proprio workspace (differente scope delle variabili). +% Il nome della funzione dovrebbe coincidere con il nome del file (quindi salva questo esempio come double_input.m). +% 'help double_input.m' restituisce i commenti sotto alla linea iniziale della funzione +function output = double_input(x) + %double_input(x) restituisce il doppio del valore di x + output = 2*x; +end +double_input(6) % ans = 12 + + +% Si possono anche avere sottofunzioni e funzioni annidate. +% Le sottofunzioni sono nello stesso file della funzione primaria, e possono solo essere +% chiamate da funzioni nello stesso file. Le funzioni annidate sono definite dentro ad altre +% funzioni, e hanno accesso ad entrambi i workspace. + +% Se si vuole creare una funzione senza creare un nuovo file si può usare una +% funzione anonima. Utile quando si vuole definire rapidamente una funzione da passare ad +% un'altra funzione (es. stampa con fplot, valutare un integrale indefinito +% con quad, trovare le radici con fzenzro, o trovare il minimo con fminsearch). +% Esempio che restituisce il quadrato del proprio input, assegnato all'handle sqr: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % scopri di più + +% Input dell'utente +a = input('Enter the value: ') + +% Ferma l'esecuzione del file e cede il controllo alla tastiera: l'utente può esaminare +% o cambiare variabili. Digita 'return' per continuare l'esecuzione, o 'dbquit' per uscire +keyboard + +% Importarare dati (anche xlsread/importdata/imread per excel/CSV/image file) +fopen(filename) + +% Output +disp(a) % Stampa il valore della variabile a +disp('Hello World') % Stampa una stringa +fprintf % Stampa sulla Command Window con più controllo + +% Istruzioni condizionali (le parentesi sono opzionali, ma un buon stile) +if (a > 15) + disp('Maggiore di 15') +elseif (a == 23) + disp('a è 23') +else + disp('nessuna condizione verificata') +end + +% Cicli +% NB. Ciclare su elementi di vettori/matrici è lento! +% Dove possibile, usa funzioni che agiscono sull'intero vettore/matrice +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Misurare la durata dell'esecuzione del codice: 'toc' stampa il tempo trascorso da quando 'tic' è stato chiamato +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Connessione a un Database MySQL +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); +% xx dipende dalla versione, download disponibile all'indirizzo http://dev.mysql.com/downloads/connector/j/ +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % Esempio istruzione sql +a = fetch(conn, sql) % conterra i tuoi dati + + +% Funzioni matematiche comuni +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % Numeri pseudocasuali uniformemente distribuiti +randi % Numeri interi pseudocasuali uniformemente distrubuiti +randn % Numeri pseudocasuali distrbuiti normalmente + +% Costanti comuni +pi +NaN +inf + +% Risolvere equazioni matriciali +% Gli operatori \ e / sono equivalenti alle funzioni mldivide e mrdivide +x=A\b % Risolve Ax=b. Più veloce e più accurato numericamente rispetto ad usare inv(A)*b. +x=b/A % Risolve xA=b + +inv(A) % Calcola la matrice inversa +pinv(A) % Calcola la matrice pseudo-inversa + +% Funzioni comuni su matrici +zeros(m,n) % Matrice m x n di zeri +ones(m,n) % Matrice m x n di uni +diag(A) % Estrae gli elementi della diagonale della matrice A +diag(x) % Costruisce una matrice con elementi diagonali uguali agli elementi di x, e zero negli altri elementi +eye(m,n) % Matrice identità +linspace(x1, x2, n) % Ritorna n punti equamente distanziati, con minimo x1 e massimo x2 +inv(A) % Matrice inversa di A +det(A) % Determinante di A +eig(A) % Autovalori e autovettori di A +trace(A) % Traccia della matrice - equivalente a sum(diag(A)) +isempty(A) % Verifica se l'array è vuoto +all(A) % Verifica se tutti gli elementi sono nonzero o veri +any(A) % Verifica se almento un elemento è nonzero o vero +isequal(A, B) % Verifica l'uguaglianza di due array +numel(A) % Numero di elementi nella matrice +triu(x) % Ritorna la parte triangolare superiore di x +tril(x) % Ritorna la parte triangolare inferiore di x +cross(A,B) % Ritorna il prodotto vettoriale dei vettori A e B +dot(A,B) % Ritorna il prodotto scalare di due vettori (devono avere la stessa lunghezza) +transpose(A) % Ritorna la trasposta di A +fliplr(A) % Capovolge la matrice da sinistra a destra +flipud(A) % Capovolge la matrice da sopra a sotto + +% Fattorizzazione delle matrici +[L, U, P] = lu(A) % Decomposizione LU: PA = LU, L è il triangolo inferiore, U è il triangolo superiore, P è la matrice di permutazione +[P, D] = eig(A) % Auto-decomposizione: AP = PD, le colonne di P sono autovettori e gli elementi sulle diagonali di D sono autovalori +[U,S,V] = svd(X) % SVD: XV = US, U e V sono matrici unitarie, S ha gli elementi della diagonale non negativi in ordine decrescente + +% Funzioni comuni su vettori +max % elemento più grande +min % elemento più piccolo +length % lunghezza del vettore +sort % ordina in modo crescente +sum % somma degli elementi +prod % prodotto degli elementi +mode % valore moda +median % valore mediano +mean % valore medio +std % deviazione standard +perms(x) % lista tutte le permutazioni di elementi di x + + +% Classi +% Matlab supporta la programmazione orientata agli oggetti. +% La classe deve essere messa in un file con lo stesso nome della classe e estensione .m +% Per iniziare, creiamo una semplice classe per memorizzare waypoint GPS +% Inizio WaypointClass.m +classdef WaypointClass % Il nome della classe. + properties % Le proprietà della classe funzionano come Strutture + latitude + longitude + end + methods + % Questo metodo che ha lo stesso nome della classe è il costruttore + function obj = WaypointClass(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Altre funzioni che usano l'oggetto Waypoint + function r = multiplyLatBy(obj, n) + r = n*[obj.latitude]; + end + + % Se si vuole aggiungere due oggetti Waypoint insieme senza chiamare + % una funzione speciale si può sovradefinire una funzione aritmetica di Matlab come questa: + function r = plus(o1,o2) + r = WaypointClass([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End WaypointClass.m + +% Si può creare un oggetto della classe usando un costruttore +a = WaypointClass(45.0, 45.0) + +% Le proprietà della classe si comportano esattamente come una Struttura Matlab. +a.latitude = 70.0 +a.longitude = 25.0 + +% I metodi possono essere chiamati allo stesso modo delle funzioni +ans = multiplyLatBy(a,3) + +% Il metodo può anche essere chiamato usando una notazione con punto. In questo caso, l'oggetto +% non necessita di essere passato al metodo. +ans = a.multiplyLatBy(a,1/3) + +% Le funzioni Matlab possono essere sovradefinite per gestire oggetti. +% Nel metodo sopra, è stato sovradefinito come Matlab gestisce +% l'addizione di due oggetti Waypoint. +b = WaypointClass(15.0, 32.0) +c = a + b + +``` + +## Di più su Matlab + +* Sito ufficiale [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* Forum ufficiale di MATLAB: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) -- cgit v1.2.3 From 9b51e703c57c77bfe29c390d9d1dbe398e1ce5b8 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:30:19 +0200 Subject: Update matlab-it.html.markdown --- it-it/matlab-it.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/it-it/matlab-it.html.markdown b/it-it/matlab-it.html.markdown index b1e8777b..aeb42658 100644 --- a/it-it/matlab-it.html.markdown +++ b/it-it/matlab-it.html.markdown @@ -7,6 +7,7 @@ contributors: translators: - ["Samuele Gallerani", "http://github.com/fontealpina"] lang: it-it +filename: matlab-it.md --- MATLAB sta per MATrix LABoratory ed è un potente linguaggio per il calcolo numerico comunemente usato in ingegneria e matematica. -- cgit v1.2.3 From 13bddecbe44f424436f5c9c838c5c9c633b6c5b4 Mon Sep 17 00:00:00 2001 From: Rodrigo Muniz Date: Sun, 26 Jun 2016 10:31:09 -0300 Subject: =?UTF-8?q?Tradu=C3=A7=C3=A3o=20do=20Elixir=20para=20pt=5Fbr=20(#1?= =?UTF-8?q?421)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pt-br/elixir.html.markdown | 411 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 411 insertions(+) create mode 100644 pt-br/elixir.html.markdown diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown new file mode 100644 index 00000000..55a8df86 --- /dev/null +++ b/pt-br/elixir.html.markdown @@ -0,0 +1,411 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Rodrigo Muniz", "http://github.com/muniz95"] +filename: learnelixir.ex +--- + +Elixir é uma linguagem funcional moderna construída no topo da Erlang VM. +É totalmente compatível com Erlang, porém conta com uma sintaxe mais padronizada +e muitos outros recursos. + +```elixir + +# Comentários de linha única começam com um símbolo de número. + +# Não há comentários de múltiplas linhas, +# mas você pode empilhar os comentários. + +# Para usar o shell do elixir use o comando `iex`. +# Compile seus módulos com o comando `elixirc`. + +# Ambos devem estar em seu path se você instalou o Elixir corretamente. + +## --------------------------- +## -- Tipos Básicos +## --------------------------- + +# Há números +3 # integer +0x1F # integer +3.0 # float + +# Atoms, que são literais, uma constante com nome. Elas começam com `:`. +:hello # atom + +# Tuplas que são guardadas contiguamente em memória. +{1,2,3} # tupla + +# Podemos acessar um elemento de uma tupla om a função `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Listas que são implementadas como listas ligadas. +[1,2,3] # lista + +# Podemos acessar a primeira posição (head) e o resto (tail) de uma lista como a seguir: +[head | tail] = [1,2,3] +head #=> 1 +tail #=> [2,3] + +# Em elixir, bem como em Erlang, o sinal `=` denota pattern match, +# e não uma atribuição. +# +# Isto significa que o que estiver à esquerda (pattern) é comparado com o que +# estiver à direita. +# +# É assim que o exemplo acima de acesso à head e tail de uma lista funciona. + +# Um pattern match retornará erro quando os lados não conferem, como neste exemplo +# onde as tuplas tem diferentes tamanhos. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Também há binários +<<1,2,3>> # binary + +# Strings e char lists +"hello" # string +'hello' # char list + +# Strings de múltiplas linhas +""" +Strings +de múltiplas +linhas. +""" +#=> "Strings\nde múltiplas\nlinhas" + +# Strings são sempre codificadas em UTF-8: +"héllò" #=> "héllò" + +# Strings são de fato apenas binários, e char lists apenas listas. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` em elixir retorna o valor ASCII para a letra `a` +?a #=> 97 + +# Para concatenar listas use `++`, para binários use `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" + +# Ranges são representados como `início..fim` (ambos inclusivos) +1..10 #=> 1..10 +menor..maior = 1..10 # Pattern matching pode ser usada em ranges também +[lower, upper] #=> [1, 10] + +## --------------------------- +## -- Operadores +## --------------------------- + +# Matemática básica +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# Em elixir o operador `/` sempre retorna um float. + +# Para divisão de inteiros use `div` +div(10, 2) #=> 5 + +# Para obter o resto da divisão use `rem` +rem(10, 3) #=> 1 + +# Há também operadores booleanos: `or`, `and` e `not`. +# Estes operadores esperam um booleano como primeiro argumento. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir também fornece `||`, `&&` e `!` que aceitam argumentos de qualquer tipo. +# Todos os valores exceto `false` e `nil` serão avaliados como true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Para comparações temos: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` e `!==` são mais estritos ao comparar integers e floats: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Podemos comparar também dois tipos de dados diferentes: +1 < :hello #=> true + +# A regra de ordenação no geral é definida abaixo: +# number < atom < reference < functions < port < pid < tuple < list < bit string + +# Ao citar Joe Armstrong nisto: "A ordem de fato não é importante, +# mas que uma ordem total esteja bem definida é importante." + +## --------------------------- +## -- Fluxo de Controle +## --------------------------- + +# expressão `if` +if false do + "Isso nunca será visto" +else + "Isso será" +end + +# Também há `unless` +unless true do + "Isso nunca será visto" +else + "Isso será" +end + +# Lembra do patter matching? Muitas estruturas de fluxo de controle em elixir contam com ela. + +# `case` nos permite comparar um valor com muitos patterns: +case {:um, :dois} do + {:quatro, :cinco} -> + "Isso não corresponde" + {:um, x} -> + "Isso corresponde e vincula `x` a `:dois`" + _ -> + "Isso corresponde a qualquer valor" +end + +# É comum vincular o valor a `_` se não precisamos dele. +# Por exemplo, se apenas a head de uma lista nos interessa: +[head | _] = [1,2,3] +head #=> 1 + +# Para melhor legibilidade podemos fazer o seguinte: +[head | _tail] = [:a, :b, :c] +head #=> :a + +# `cond` nos permite verificar várias condições ao mesmo tempo. +# Use `cond` em vez de aninhar vários `if`'s. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + 1 + 2 == 3 -> + "Mas eu serei" +end + +# É comum definir a última condição igual a `true`, que sempre irá corresponder. +cond do + 1 + 1 == 3 -> + "Nunca serei visto" + 2 * 5 == 12 -> + "Nem eu" + true -> + "Mas eu serei (isso é essencialmente um else)" +end + +# `try/catch` é usado para capturar valores que são lançados, também suporta uma +# cláusula `after` que é invocada havendo um valor capturado ou não. +try do + throw(:hello) +catch + message -> "Deu #{mensagem}." +after + IO.puts("Sou o after.") +end +#=> Sou o after +# "Deu :hello" + +## --------------------------- +## -- Módulos e Funções +## --------------------------- + +# Funções Anônimas (repare o ponto) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Elas também aceitam várias cláusulas e guards. +# Guards permitem ajustes finos de pattern matching, +# sendo indicados pela palavra `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir também fornece várias funções embutidas. +# Estas estão disponíveis no escopo atual. +is_number(10) #=> true +is_list("ola") #=> false +elem({1,2,3}, 0) #=> 1 + +# Você pode agrupar algumas funções em um módulo. Dentro de um módulo use `def` +# para definir suas funções. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# Para compilar o módulo Math salve-o como `math.ex` e use `elixirc` +# em seu terminal: elixirc math.ex + +# Dentro de um módulo podemos definir funções com `def` e funções privadas com `defp`. +# Uma função definida com `def` pode ser invocada por outros módulos, +# já uma função privada pode ser invocada apenas localmente. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Declarações de funções também suportam guards cláusulas múltiplas: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +# Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 + +# Devido à imutabilidade, recursão é uma grande parte do elixir +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Módulos do elixir suportam atributos, hpa atributos embutidos e você +# pode também adicionar os seus próprios. +defmodule MyMod do + @moduledoc """ + Este é um atributo embutido em um módulo de exemplo. + """ + + @my_data 100 # Este é um atributo customizado. + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- Structs e Exceptions +## --------------------------- + +# Structs são extensões no topo de mapas que trazem valores padrão, +# garantias em tempo de compilação e polimorfismo para o Elixir. +defmodule Pessoa do + defstruct nome: nil, idade: 0, peso: 0 +end + +joe_info = %Pessoa{ nome: "Joe", idade: 30, peso: 180 } +#=> %Pessoa{idade: 30, peso: 180, nome: "Joe"} + +# Acessa o valor de nome +joe_info.name #=> "Joe" + +# Atualiza o valor de idade +older_joe_info = %{ joe_info | idade: 31 } +#=> %Pessoa{idade: 31, peso: 180, nome: "Joe"} + +# O bloco `try` com a palavra `rescue` é usado para manipular exceções +try do + raise "algum erro" +rescue + RuntimeError -> "resgatado um erro em tempo de execução" + _error -> "isso resgatará qualquer erro" +end + +# Toda exceção possui uma mensagem +try do + raise "algum erro" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concorrência +## --------------------------- + +# Elixir conta com o modelo de ator para concorrência. Tudo o que precisamos para +# escrever programas concorrentes em elixir são três primitivos: spawning processes, +# sending messages e receiving messages. + +# Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função +# como argumento. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` retorna um pid (process identifier), você pode usar esse pid para enviar +# mensagens ao processo. Para envio de mensagens usamos o operador `send`. +# Para tudo isso ser útil precisamos estar aptos a receber mensagens. Isto é +# realizado com o mecanismo `receive`: +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Compile o módulo e crie um processo que avalie `area_loop` no shell +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Envia uma mensagem ao `pid` correspondente a um pattern na declaração de recebimento +send pid, {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# O shell também é um processo, você pode usar `self` para obter o pid atual +self() #=> #PID<0.27.0> +``` + +## Referências + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) da [página do elixir](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) por Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) por Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) por Joe Armstrong -- cgit v1.2.3 From 0827434afa6e0f9ac7371a7b51a6a055a794aaf3 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:31:27 +0200 Subject: #1421 --- pt-br/elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown index 55a8df86..b4ca8a52 100644 --- a/pt-br/elixir.html.markdown +++ b/pt-br/elixir.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] translators: - ["Rodrigo Muniz", "http://github.com/muniz95"] -filename: learnelixir.ex +filename: learnelixir-pt.ex --- Elixir é uma linguagem funcional moderna construída no topo da Erlang VM. -- cgit v1.2.3 From 6419fa49074df3b24e8225f457cb462aededcc01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juraj=20Kostolansk=C3=BD?= Date: Sun, 26 Jun 2016 15:32:29 +0200 Subject: [bash/sk] Slovak translation for Bash (#1517) --- sk-sk/bash.html.markdown | 286 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 sk-sk/bash.html.markdown diff --git a/sk-sk/bash.html.markdown b/sk-sk/bash.html.markdown new file mode 100644 index 00000000..ba67b699 --- /dev/null +++ b/sk-sk/bash.html.markdown @@ -0,0 +1,286 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Juraj Kostolanský", "http://www.kostolansky.sk"] +lang: sk-sk +filename: LearnBash.sh +--- + +Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol +tiež distribuovaný ako shell pre GNU operačné systémy a ako predvolený +shell pre Linux a Mac OS X. +Takmer všetky príklady uvedené nižšie môžu byť súčasťou shell skriptu alebo +vykonané priamo v shelli. + +[Viac informácií tu.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Prvý riadok skriptu je tzv. shebang, ktorý systému povie ako skript vykonať: +# http://en.wikipedia.org/wiki/Shebang_(Unix) +# Komentáre začínajú znakom #. Shebang je tiež komentár. + +# Jednoduchý príklad: +echo Ahoj svet! + +# Každý príkaz začína na novom riadku alebo za bodkočiarkou: +echo 'Toto je prvý riadok'; echo 'Toto je druhý riadok' + +# Deklarácia premenných vyzerá takto: +Premenna="Nejaky retazec" + +# Ale nie takto: +Premenna = "Nejaky retazec" +# Bash si bude myslieť, že Premenna je príkaz, ktorý musí vykonať. +# Výsledkom bude chyba, pretože taký príkaz nenájde. + +# Alebo takto: +Premenna= 'Nejaky retazec' +# Bash zistí, že 'Nejaky retazec' je príkaz, ktorý musí vykonať. +# Výsledkom je opäť chyba, lebo taký príkaz neexistuje. + +# Používanie premenných: +echo $Premenna +echo "$Premenna" +echo '$Premenna' +# Keď je premenná použitá samostatne - priradenie, exportovanie a pod. - jej +# meno sa píše bez znaku $. Keď sa používa hodnota premennej, pred názov sa +# dáva znak $. Pozor však pri použití ' (apostrof), ktorý nenahradí premennú +# hodnotou! + +# Nahradenie reťazca v premennej +echo ${Premenna/Nieco/A} +# Toto nahradí prvý výskyt reťazca "Nieco" za "A" + +# Podreťazec z premennej +Dlzka=7 +echo ${Premenna:0:Dlzka} +# Toto vráti iba prvých 7 znakov z hodnoty premennej + +# Predvolená hodnota premennej +echo ${Foo:-"PredvolenaHodnotaAkFooChybaAleboJePrazdna"} +# Toto funguje pre null (Foo=) a prázdny reťazec (Foo=""); +# nula (Foo=0) vráti 0. Všimni si, že toto iba vráti predvolenú hodnotu, +# ale nezmení hodnotu premennej. + +# Štandardné premenné: +# Existujú aj užitočné "vstavané" premenné, ako +echo "Hodnota vrátená posledným programom: $?" +echo "PID skriptu: $$" +echo "Počet argumentov: $#" +echo "Argumeny skriptu: $@" +echo "Argumeny skriptu oddelené do rôznych premenných: $1 $2..." + +# Čítanie hodnoty zo vstupu: +echo "Ako sa voláš?" +read Meno # Premenná nemusí byť deklarovaná skôr +echo Ahoj, $Meno! + +# Klasická if štruktúra: +# použi 'man test' Pre viac informácií o podmienkach +if [ $Meno -ne $USER ] +then + echo "Meno nie je tvoje používateľské meno" +else + echo "Meno je tvoje používateľské meno" +fi + +# Existuje aj podmienené vykonanie +echo "Vykonané vždy" || echo "Vykonané iba ak prvý príkaz zlyhá" +echo "Vykonané vždy" && echo "Vykonané iba ak prvý príkaz uspeje" + +# Pre použitie && a || s if-podmienkou je potrebné použiť zátvorky: +if [ $Meno == "Steve" ] && [ $Vek -eq 15 ] +then + echo "Toto sa spustí ak $Meno je Steve a $Vek je 15." +fi + +if [ $Meno == "Daniya" ] || [ $Meno == "Zach" ] +then + echo "Toto sa spustí ak $Meno je Daniya alebo Zach." +fi + +# Pre výrazy sa používa nasledovný formát: +echo $(( 10 + 5 )) + +# Na rozdiel od programovacích jazykov shell pracuje v kontexte aktuálneho +# adresára. Môžeš si prehliadať súbory a adresáre v aktuálnom adresári pomocou +# príkazu ls: +ls + +# Tieto príkazy majú aj argumenty pre úpravu ich správania: +ls -l # Vypíše zoznam súborov a priečinkov, každý na samostatnom riadku + +# Výsledok predchádzajúceho príkazu môže byť využitý priamo ako vstup pre +# ďalší príkaz. +# Príkaz grep filtruje vstupvyužitím poskytnutého vzoru. Takto môžeme vypísať +# iba .txt súbory: +ls -l | grep "\.txt" + +# Vstup a výstup príkazu (stdin, stdout, stderr) môžu byť presmerované. +# Toto číta stdin až po ^EOF$ a prepíše hello.py riadkami medzi "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Spustí hello.py s rôznymi presmerovaniami pre stdin, stdout a stderr: +python hello.py < "vstup.in" +python hello.py > "vystup.out" +python hello.py 2> "chyby.err" +python hello.py > "vystup-a-chyby.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Chybový výstup prepíše uvedený súbor, ak už existuje. +# Ak chceš výstup pridať za existujúci obsah, použi ">>": +python hello.py >> "vystup.out" 2>> "chyby.err" + +# Prepíše vystup.out, pripojí k chyby.err a spočíta riadky: +info bash 'Basic Shell Features' 'Redirections' > vystup.out 2>> chyby.err +wc -l vystup.out chyby.err + +# Spustí príkaz a vypíše deskriptor súboru (napr. /dev/fd/123) +# pozri: man fd +echo <(echo "#ahojsvet") + +# Prepíše vystup.out s "#ahojsvet": +cat > vystup.out <(echo "#ahojsvet") +echo "#ahojsvet" > vystup.out +echo "#ahojsvet" | cat > vystup.out +echo "#ahojsvet" | tee vystup.out >/dev/null + +# Potichu odstráni dočasné súbory (pridaj '-i' pre interaktivitu) +rm -v vystup.out chyby.err vystup-a-chyby.log + +# Príkazy môžu byť nahradené v iných príkazoch použitím $( ): +# Nasledujúci príkaz vypíše počet súborov a adresárov v aktuálnom adresári +echo "Je tu $(ls | wc -l) súborov a priečinkov." + +# To isté sa dá spraviť pomocou spätného apostrofu ``, tie však nemôžu byť +# vhniezdené - preferovaný spôsob je preto $( ). +echo "Je tu `ls | wc -l` súborov a priečinkov." + +# Bash používa case, ktorý funguje podobne ako switch v Jave a C++: +case "$Premenna" in + #Zoznam vzorov pre podmienky + 0) echo "Je to nula.";; + 1) echo "Je to jednotka.";; + *) echo "Nie je to null.";; +esac + +# for-cyklus iteruje cez všetky argumenty: +# Obsah premennej $Premenna sa vypíše trikrát. +for Premenna in {1..3} +do + echo "$Premenna" +done + +# Alebo "tradičným" spôsobom: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Môžu sa použiť aj na súbory.. +# Toto spustí príkaz 'cat' na subor1 a subor2 +for Premenna in subor1 subor2 +do + cat "$Premenna" +done + +# ..alebo na výstup príkazu. +# Toto použije príkaz cat na výstup z ls. +for Vystup in $(ls) +do + cat "$Vystup" +done + +# while-cykklus: +while [ true ] +do + echo "telo cyklu..." + break +done + +# Môžeš tiež definovať funkice +# Definícia: +function foo () +{ + echo "Argumenty fungujú rovnako ako pri skriptoch: $@" + echo "A: $1 $2..." + echo "Toto je funkcia" + return 0 +} + +# alebo jednoducho +bar () +{ + echo "Iný spôsob definície funkcií" + return 0 +} + +# Volanie funkcie +foo "Moje meno je" $Meno + +# Existuje veľa užitočných príkazov, ktoré sa oplatí naučiť: +# vypíše posledných 10 riadkov zo subor.txt +tail -n 10 subor.txt +# vypíše prvých 10 riadkov zo subor.txt +head -n 10 subor.txt +# zotriedi riadky zo subor.txt +sort subor.txt +# vypíše alebo vynechá opakované riadky, použitím -d ich vypíše +uniq -d subor.txt +# vypíše iba prvý stĺpecpred znakom ',' +cut -d ',' -f 1 subor.txt +# nahradí každý výskyt 'oukej' za 'super' v subor.txt (možnosť použiť regex) +sed -i 's/oukej/super/g' subor.txt +# vypíše všetky riadky zo subor.txt ktoré vyhovujú regexu +# ukážka vypíše riadky ktoré začínajú s "foo" a končia s "bar" +grep "^foo.*bar$" subor.txt +# pre výpis počtu riadkov vyhovujúcich regexu slúži "-c" +grep -c "^foo.*bar$" subor.txt +# pre vyhľadávanie reťazca bez regexu slúži fgrep (alebo grep -F) +fgrep "^foo.*bar$" subor.txt + + +# Prečítaj si dokumentáciu k Bash shellu použitím príkazu 'help': +help +help help +help for +help return +help source +help . + +# Prečítaj si Bash manpage dokumentáciu príkazom 'man' +apropos bash +man 1 bash +man bash + +# Prečítaj si info dokumentáciu pomocou 'info' (? pre help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Prečítaj si bash info dokumentáciu: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From 095d2e2405ced6a6e42b5f270d44a6ec6e9e3cb4 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:32:45 +0200 Subject: #1517 --- sk-sk/bash.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sk-sk/bash.html.markdown b/sk-sk/bash.html.markdown index ba67b699..e9d1490c 100644 --- a/sk-sk/bash.html.markdown +++ b/sk-sk/bash.html.markdown @@ -14,7 +14,7 @@ contributors: translators: - ["Juraj Kostolanský", "http://www.kostolansky.sk"] lang: sk-sk -filename: LearnBash.sh +filename: LearnBash-sk.sh --- Bash je pomenovanie pre unix shell (príkazový interpreter), ktorý bol -- cgit v1.2.3 From be12f2009759514fdcf6bfc70cc62f4cc60c651b Mon Sep 17 00:00:00 2001 From: Martin Damien Date: Sun, 26 Jun 2016 15:34:16 +0200 Subject: [en/RST] Add RST introduction (#1723) * [en/RST] Add RST introduction * Fix @ in username --- rst.html.markdown | 107 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 rst.html.markdown diff --git a/rst.html.markdown b/rst.html.markdown new file mode 100644 index 00000000..161a0610 --- /dev/null +++ b/rst.html.markdown @@ -0,0 +1,107 @@ +--- +language: restructured text +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] +filename: restructuredtext.rst +--- + +RST is file format formely created by Python community to write documentation (and so, is part of Docutils). + +RST files are simple text files with lightweight syntaxe (comparing to HTML). + + +## Installation + +To use Restructured Text, you will have to install [Python](http://www.python.org) and the `docutils` package. + +`docutils` can be installed using the commandline: + +```bash +$ easy_install docutils +``` + +If your system have `pip`, you can use it too: + +```bash +$ pip install docutils +``` + + +## File syntaxe + +A simple example of the file syntax: + +```rst +.. Line with two dotes are special commands. But if no command can be found, the line is considered as a comment + +========================================================= +Main titles are written using equals signs over and under +========================================================= + +Note that theire must be as many equals signs as title characters. + +Title are underlined with equals signs too +========================================== + +Subtitles with dashes +--------------------- + +And sub-subtitles with tilde +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can put text in *italic* or in **bold**, you can "mark" text as code with double backquote ``: ``print()``. + +Lists are as simple as markdown: + +- First item +- Second item + - Sub item + +or + +* First item +* Second item + * Sub item + +Tables are really easy to write: + +=========== ======== +Country Capital +=========== ======== +France Paris +Japan Tokyo +=========== ======== + +More complexe tabless can be done easily (merged columns and/or rows) but I suggest you to read the complete doc for this :) + +Their is multiple ways to make links: + +- By adding an underscore after a word : Github_ and by adding the target after the text (this have the advantage to not insert un-necessary URL inside the readed text). +- By typing a full comprehensible URL : https://github.com/ (will be automatically converted in link) +- By making a more "markdown" link: `Github `_ . + +.. _Github https://github.com/ + +``` + + +## How to use it + +RST comes with docutils in which you have `rst2html` for exemple: + +```bash +$ rst2html myfile.rst output.html +``` + +*Note : On some systems the command could be rst2html.py* + +But their is more complexe applications that uses RST file format: + +- [Pelican](http://blog.getpelican.com/), a static site generator +- [Sphinx](http://sphinx-doc.org/), a documentation generator +- and many others + + +## Readings + +- [Official quick reference](http://docutils.sourceforge.net/docs/user/rst/quickref.html) -- cgit v1.2.3 From 6b3f99a4131665670c58a2ad5ab90254f365f83c Mon Sep 17 00:00:00 2001 From: Tommaso Date: Sun, 26 Jun 2016 15:35:10 +0200 Subject: [go/it] Add first italian translation of go language (#1630) --- it-it/go-it.html.markdown | 454 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 454 insertions(+) create mode 100644 it-it/go-it.html.markdown diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown new file mode 100644 index 00000000..3f17fe1f --- /dev/null +++ b/it-it/go-it.html.markdown @@ -0,0 +1,454 @@ +--- +name: Go +category: language +language: Go +filename: learngo-it.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] +lang: it-it +--- + +Go è stato creato per avere tra le mani uno strumento in grado di arrivare +al punto, nel modo più veloce ed efficiente possibile. Non è all'ultima +moda tra i linguaggi di programmazione, ma è una delle migliori soluzioni +per risolvere in maniera efficace i problemi di tutti i giorni. + +Go presenta alcuni concetti già presenti nei linguaggi imperativi con +tipizzazione statica. Compila velocemente ed esegue altrettanto veloce. +Aggiunge la concorrenza in maniera diretta e semplice da capire, per far +forza sulle CPU multi-core di oggigiorno. Presenta caratteristiche utili +per la programmazione in larga scala. + +Go comes with a great standard library and an enthusiastic community. + +```go +// Commento su riga singola +/* Commento + su riga multipla */ + +// In cima a ogni file è necessario specificare il package. +// Main è un package speciale che identifica un eseguibile anziché una libreria. +package main + +// Con import sono dichiarate tutte le librerie a cui si fa riferimento +// all'interno del file. +import ( + "fmt" // Un package nella libreria standard di Go. + "io/ioutil" // Implementa alcune funzioni di utility per l'I/O. + m "math" // Libreria matematica, con alias locale m + "net/http" // Sì, un web server! + "strconv" // Package per la conversione di stringhe. +) + +// Una definizione di funzione. Il main è speciale: è il punto di ingresso +// per il programma. Amalo o odialo, ma Go usa le parentesi graffe. +func main() { + // Println stampa una riga a schermo. + // Questa funzione è all'interno del package fmt. + fmt.Println("Ciao mondo!") + + // Chiama un'altra funzione all'interno di questo package. + oltreIlCiaoMondo() +} + +// Le funzioni ricevono i parametri all'interno di parentesi tonde. +// Se la funzione non riceve parametri, vanno comunque messe le parentesi (vuote). +func oltreIlCiaoMondo() { + var x int // Dichiarazione di una variabile. Ricordati di dichiarare sempre le variabili prima di usarle! + x = 3 // Assegnazione di una variabile. + // E' possibile la dichiarazione "rapida" := per inferire il tipo, dichiarare e assegnare contemporaneamente. + y := 4 + // Una funzione che ritorna due valori. + somma, prod := imparaMoltepliciValoriDiRitorno(x, y) + fmt.Println("somma:", somma, "prodotto:", prod) // Semplice output. + imparaTipi() // < y minuti, devi imparare ancora! +} + +/* <- commento su righe multiple +Le funzioni possono avere parametri e ritornare (molteplici!) valori. +Qua, x e y sono gli argomenti, mentre somma e prod sono i valori ritornati. +Da notare il fatto che x e somma vengono dichiarati come interi. +*/ +func imparaMoltepliciValoriDiRitorno(x, y int) (somma, prod int) { + return x + y, x * y // Ritorna due valori. +} + +// Ecco alcuni tipi presenti in Go +func imparaTipi() { + // La dichiarazione rapida di solito fa il suo lavoro. + str := "Impara il Go!" // Tipo stringa. + + s2 := `Una stringa letterale +puo' includere andata a capo.` // Sempre di tipo stringa. + + // Stringa letterale non ASCII. I sorgenti Go sono in UTF-8. + g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode. + + f := 3.14195 // float64, un numero in virgola mobile a 64-bit (IEEE-754) + + c := 3 + 4i // complex128, rappresentato internamente con due float64. + + // Inizializzare le variabili con var. + var u uint = 7 // Senza segno, ma la dimensione dipende dall'implementazione (come l'int) + var pi float32 = 22. / 7 + + // Sintassi per la conversione. + n := byte('\n') // Il tipo byte è un alias per uint8. + + // I vettori hanno dimensione fissa, stabilita durante la compilazione. + var a4 [4]int // Un vettore di 4 interi, tutti inizializzati a 0. + a3 := [...]int{3, 1, 5} // Un vettore inizializzato con una dimensione fissa pari a 3, i cui elementi sono 3, 1 e 5. + + // Gli slice hanno dimensione variabile. Vettori e slice hanno pro e contro, + // ma generalmente si tende a usare più spesso gli slice. + s3 := []int{4, 5, 9} // La differenza con a3 è che qua non ci sono i 3 punti all'interno delle parentesi quadre. + s4 := make([]int, 4) // Alloca uno slice di 4 interi, tutti inizializzati a 0. + var d2 [][]float64 // Semplice dichiarazione, non vengono fatte allocazioni. + bs := []byte("uno slice") // Sintassi per la conversione. + + // Poiché gli slice sono dinamici, è possibile aggiungere elementi + // quando è necessario. Per farlo, si usa la funzione append(). Il primo + // argomento è lo slice a cui stiamo aggiungendo elementi. Di solito + // lo slice viene aggiornato, senza fare una copia, come nell'esempio: + s := []int{1, 2, 3} // Il risultato è uno slice di dimensione 3. + s = append(s, 4, 5, 6) // Aggiunge 3 elementi: lo slice ha dimensione 6. + fmt.Println(s) // Lo slice aggiornato è [1 2 3 4 5 6] + // Per aggiungere un altro slice, invece che elencare gli elementi uno ad + // uno, è possibile passare alla funzione append un riferimento ad uno + // slice, oppure uno slice letterale: in questo caso si usano i tre punti, + // dopo lo slice, a significare "prendi ciascun elemento dello slice": + s = append(s, []int{7, 8, 9}...) // Il secondo argomento è uno slice letterale. + fmt.Println(s) // Lo slice aggiornato è [1 2 3 4 5 6 7 8 9] + + p, q := imparaLaMemoria() // Dichiara due puntatori a intero: p e q. + fmt.Println(*p, *q) // * dereferenzia un puntatore. Questo stampa due interi. + + // Una variabile di tipo map è un vettore associativo di dimensione variabile, + // e funzionano come le tabelle di hash o i dizionari in altri linguaggi. + m := map[string]int{"tre": 3, "quattro": 4} + m["uno"] = 1 + + // Le variabili dichiarate e non usate sono un errore in Go. + // L'underscore permette di "usare" una variabile, scartandone il valore. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Stampare a schermo ovviamente significa usare una variabile. + fmt.Println(s, c, a4, s3, d2, m) + + imparaControlloDiFlusso() // Torniamo in carreggiata. +} + +// In Go è possibile associare dei nomi ai valori di ritorno di una funzione. +// Assegnare un nome al tipo di dato ritornato permette di fare return in vari +// punti all'interno del corpo della funzione, ma anche di usare return senza +// specificare in modo esplicito che cosa ritornare. +func imparaValoriDiRitornoConNome(x, y int) (z int) { + z = x * y + return // z è implicito, perchè compare nella definizione di funzione. +} + +// Go è dotato di garbage collection. Ha i puntatori, ma non l'aritmetica dei +// puntatori. Puoi fare errori coi puntatori a nil, ma non puoi direttamente +// incrementare un puntatore. +func imparaLaMemoria() (p, q *int) { + // I valori di ritorno (con nome) p e q sono puntatori a int. + p = new(int) // La funzione new si occupa di allocare memoria. + // L'int allocato viene inizializzato a 0, dunque p non è più nil. + s := make([]int, 20) // Alloca 20 int come un singolo blocco di memoria. + s[3] = 7 // Ne assegna uno. + r := -2 // Dichiara un'altra variabile locale + return &s[3], &r // & "prende" l'indirizzo di un oggetto. +} + +func calcoloCostoso() float64 { + return m.Exp(10) +} + +func imparaControlloDiFlusso() { + // L'istruzione if richiede parentesi graffe per il corpo, mentre non ha + // bisogno di parentesi tonde per la condizione. + if true { + fmt.Println("te l'ho detto") + } + // Eseguendo "go fmt" da riga di comando, il codice viene formattato + // in maniera standard. + if false { + // :( + } else { + // :D + } + // L'istruzione switch serve ad evitare tanti if messi in cascata. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Quando è soddisfatta la condizione all'interno di un case, il + // programma esce dal switch senza che siano specificate istruzioni + // di tipo "break". In Go infatti di default non è presente il + // cosiddetto "fall through" all'interno dell'istruzione switch. + // Tuttavia, il linguaggio mette a disposizione la parola chiave + // fallthrough per permettere, in casi particolari, questo comportamento. + case 43: + // Non si arriva qua. + default: + // Il caso di default è opzionale. + } + // Come l'if, anche il for non usa parentesi tonde per la condizione. + // Le variabili dichiarate all'interno di if/for sono locali al loro scope. + for x := 0; x < 3; x++ { // ++ è un'istruzione! + fmt.Println("ciclo numero", x) + } + // x == 42 qua. + + // Il for è l'unica istruzione per ciclare in Go, ma ha varie forme. + for { // Ciclo infinito. + break // Scherzavo. + continue // Non si arriva qua. + } + + // Puoi usare range per ciclare su un vettore, slice, stringa, mappa o canale. + // range ritorna uno (per i canali) o due valori (vettore, slice, stringa, mappa). + for chiave, valore := range map[string]int{"uno": 1, "due": 2, "tre": 3} { + // per ogni coppia dentro la mappa, stampa chiave e valore + fmt.Printf("chiave=%s, valore=%d\n", chiave, valore) + } + + // Come nel for, := dentro la condizione dell'if è usato per dichiarare + // e assegnare y, poi testare se y > x. + if y := calcoloCostoso(); y > x { + x = y + } + // Le funzioni letterali sono closure. + xGrande := func() bool { + return x > 10000 // Si riferisce a x dichiarata sopra al switch (vedi sopra). + } + fmt.Println("xGrande:", xGrande()) // true (abbiamo assegnato e^10 a x). + x = 1.3e3 // Adesso x == 1300 + fmt.Println("xGrande:", xGrande()) // false ora. + + // Inoltre le funzioni letterali possono essere definite e chiamate + // inline, col ruolo di parametri di funzione, a patto che: + // a) la funzione letterale venga chiamata subito (), + // b) il valore ritornato è in accordo con il tipo dell'argomento. + fmt.Println("Somma e raddoppia due numeri: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Chiamata con argomenti 10 e 2 + // => Somma e raddoppia due numeri: 24 + + // Quando ti servirà, lo amerai. + goto amore +amore: + + imparaFabbricaDiFunzioni() // Una funzione che ritorna un'altra funzione è divertente! + imparaDefer() // Un tour veloce di una parola chiave importante. + imparaInterfacce() // Arriva la roba buona! +} + +func imparaFabbricaDiFunzioni() { + // Questi due blocchi di istruzioni sono equivalenti, ma il secondo è più semplice da capire. + fmt.Println(fabbricaDiFrasi("estate")("Una bella giornata", "giornata!")) + + d := fabbricaDiFrasi("estate") + fmt.Println(d("Una bella", "giornata!")) + fmt.Println(d("Un pigro", "pomeriggio!")) +} + +// I decoratori sono comuni in alcuni linguaggi. Si può fare lo stesso in Go +// con le funzioni letterali che accettano argomenti. +func fabbricaDiFrasi(miaStringa string) func(prima, dopo string) string { + return func(prima, dopo string) string { + return fmt.Sprintf("%s %s %s", prima, miaStringa, dopo) // Nuova stringa + } +} + +func imparaDefer() (ok bool) { + // Le istruzioni dette "deferred" (rinviate) sono eseguite + // appena prima che la funzione ritorni. + defer fmt.Println("le istruzioni 'deferred' sono eseguite in ordine inverso (LIFO).") + defer fmt.Println("\nQuesta riga viene stampata per prima perché") + // defer viene usato di solito per chiudere un file, così la funzione che + // chiude il file viene messa vicino a quella che lo apre. + return true +} + +// Definisce Stringer come un'interfaccia con un metodo, String. +type Stringer interface { + String() string +} + +// Definisce coppia come una struct con due campi interi, chiamati x e y. +type coppia struct { + x, y int +} + +// Definisce un metodo sul tipo coppia, che adesso implementa Stringer. +func (p coppia) String() string { // p viene definito "ricevente" + // Sprintf è un'altra funzione del package ftm. + // La notazione con il punto serve per richiamare i campi di p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func imparaInterfacce() { + // Brace syntax is a "struct literal". It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + // Le parentesi graffe sono usate per le cosiddette "struct letterali". + // Con :=, p viene dichiarata e inizializzata a questa struct. + p := coppia{3, 4} + fmt.Println(p.String()) // Chiama il metodo String di p, che è di tipo coppia. + var i Stringer // Dichiara i come interfaccia Stringer. + i = p // Valido perchè coppia implementa Stringer. + // Chiama il metodo String di i, che è di tipo Stringer. Output uguale a sopra. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + // Le funzioni dentro al package fmt chiamano il metodo String per + // chiedere ad un oggetto una rappresentazione in stringhe di sé stesso. + fmt.Println(p) // Output uguale a sopra. Println chiama il metodo String. + fmt.Println(i) // Output uguale a sopra. + + imparaParametriVariadici("grande", "imparando", "qua!") +} + +// Le funzioni possono avere parametri variadici (ovvero di lunghezza variabile). +func imparaParametriVariadici(mieStringhe ...interface{}) { + // Cicla su ogni valore variadico. + // L'underscore serve a ignorare l'indice del vettore. + for _, param := range mieStringhe { + fmt.Println("parametro:", param) + } + + // Passa un valore variadico come parametro variadico. + fmt.Println("parametri:", fmt.Sprintln(mieStringhe...)) + + imparaGestioneErrori() +} + +func imparaGestioneErrori() { + // La sintassi ", ok" è usata per indicare se qualcosa ha funzionato o no. + m := map[int]string{3: "tre", 4: "quattro"} + if x, ok := m[1]; !ok { // ok sarà false perchè 1 non è dentro la mappa. + fmt.Println("qua non c'è nessuno!") + } else { + fmt.Print(x) // x sarebbe il valore che corrisponde alla chiave 1, se fosse nella mappa. + } + // Un errore non riporta soltanto "ok" ma è più specifico riguardo al problema. + if _, err := strconv.Atoi("non_intero"); err != nil { // _ scarta il valore + // stampa 'strconv.ParseInt: parsing "non_intero": invalid syntax' + fmt.Println(err) + } + // Approfondiremo le interfacce un'altra volta. Nel frattempo, + imparaConcorrenza() +} + +// c è un canale, un oggetto per comunicare in modo concorrente e sicuro. +func inc(i int, c chan int) { + c <- i + 1 // <- è l'operatore di "invio" quando un canale sta a sinistra. +} + +// Useremo inc per incrementare alcuni numeri in modo concorrente. +func imparaConcorrenza() { + // Stessa funzione usata prima per creare uno slice. Make alloca e + // inizializza slice, mappe e canali. + c := make(chan int) + // Lancia tre goroutine. I numeri saranno incrementati in modo concorrente, + // forse in parallelo se la macchina lo supporta. Tutti e tre inviano dati + // sullo stesso canale. + go inc(0, c) // go è un'istruzione che avvia una goroutine. + go inc(10, c) + go inc(-805, c) + // Legge tre risultati dal canale e li stampa a schermo. + // Non si conosce a priori l'ordine in cui i risultati arriveranno! + fmt.Println(<-c, <-c, <-c) // <- è l'operatore di "ricevuta" quando + // un canale sta a destra. + + cs := make(chan string) // Un altro canale, gestisce le stringhe. + ccs := make(chan chan string) // Un canale che gestisce canali di stringhe. + go func() { c <- 84 }() // Lancia una goroutine, solo per inviare un valore. + go func() { cs <- "parolina" }() // Stessa cosa ma per cs. + // select è simile a switch, ma ogni case riguarda un'operazione su un + // canale. Seleziona, in modo random, uno tra i canali che sono pronti + // a comunicare. + select { + case i := <-c: // Il valore ricevuto può essere assegnato a una variabile, + fmt.Printf("E' un %T", i) + case <-cs: // oppure il valore ricevuto può essere scartato. + fmt.Println("E' una stringa.") + case <-ccs: // Canale vuoto, non pronto per comunicare. + fmt.Println("Non succede niente.") + } + // A questo punto un valore è stato preso da c o cs. Una delle tue goroutine + // cominciate sopra ha completato l'esecuzione, l'altra rimarrà bloccata. + + imparaProgrammazioneWeb() // Se lo fa Go, lo puoi fare anche tu. +} + +// Una funzione all'interno del package http avvia un webserver. +func imparaProgrammazioneWeb() { + + // Il primo parametro di ListenAndServe è l'indirizzo TCP su cui ascoltare. + // Il secondo parametro è un'interfaccia, precisamente http.Handler. + go func() { + err := http.ListenAndServe(":8080", coppia{}) + fmt.Println(err) // Non ignorare gli errori. + }() + + richiediServer() +} + +// Per rendere coppia un http.Handler basta implementare il metodo ServeHTTP. +func (p coppia) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Il server fornisce dati con un metodo di http.ResponseWriter. + w.Write([]byte("Hai imparato Go in Y minuti!")) +} + +func richiediServer() { + risposta, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer risposta.Body.Close() + corpo, err := ioutil.ReadAll(risposta.Body) + fmt.Printf("\nIl webserver dice: `%s`", string(corpo)) +} +``` + +## Letture consigliate + +La risorsa più importante per imparare il Go è il [sito ufficiale di Go](http://golang.org/). +Qui puoi seguire i tutorial, scrivere codice in modo interattivo, e leggere tutti i dettagli. +Oltre al tour, [la documentazione](https://golang.org/doc/) contiene informazioni su +come scrivere ottimo codice in Go, documentazione sui package e sui comandi, e +la cronologia delle release. + +Anche il documento che definisce il linguaggio è un'ottima lettura. E' semplice +da leggere e incredibilmente corto (rispetto ad altri documenti riguardanti +la creazione di linguaggi). + +Puoi giocare con il codice visto finora nel [Go playground](https://play.golang.org/p/Am120Xe7qf). +Prova a cambiarlo e ad eseguirlo dal browser! +Osserva che puoi usare [https://play.golang.org](https://play.golang.org) come +una [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per scrivere +codice all'interno del browser, senza neanche installare Go! + +Una lettura importante per capire Go in modo più profondo è il [codice +sorgente della libreria standard](http://golang.org/src/pkg/). Infatti è +molto ben documentato e costituisce quanto più chiaro e conciso ci sia riguardo +gli idiomi e le buone pratiche del Go. Inoltre, clickando sul nome di una +funzione [nella documentazione](http://golang.org/pkg/) compare il relativo +codice sorgente! + +Un'altra ottima risorsa per imparare è [Go by example](https://gobyexample.com/). + +Go Mobile aggiunge il supporto per lo sviluppo mobile (Android e iOS). +In questo modo è possibile scrivere un'app mobile nativa in Go, oppure +una libreria che contiene binding da un package scritto in Go, e che può +essere richiamata da Java(Android) e Objective-C(iOS). Visita la pagina di +[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. \ No newline at end of file -- cgit v1.2.3 From 80e4a8375dcaa89ddbe2b40840f968d6e632185a Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 15:35:51 +0200 Subject: #1630 --- it-it/go-it.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index 3f17fe1f..e005f2dc 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -1,6 +1,5 @@ --- name: Go -category: language language: Go filename: learngo-it.go contributors: @@ -451,4 +450,4 @@ Go Mobile aggiunge il supporto per lo sviluppo mobile (Android e iOS). In questo modo è possibile scrivere un'app mobile nativa in Go, oppure una libreria che contiene binding da un package scritto in Go, e che può essere richiamata da Java(Android) e Objective-C(iOS). Visita la pagina di -[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. \ No newline at end of file +[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. -- cgit v1.2.3 From 8eac984e808014de68082b125b98091f3d50901e Mon Sep 17 00:00:00 2001 From: phbo85 Date: Sun, 26 Jun 2016 17:11:24 +0200 Subject: Added suffix to filename and changed minor content errors (#2291) --- de-de/sass-de.html.markdown | 450 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 450 insertions(+) create mode 100644 de-de/sass-de.html.markdown diff --git a/de-de/sass-de.html.markdown b/de-de/sass-de.html.markdown new file mode 100644 index 00000000..20266d17 --- /dev/null +++ b/de-de/sass-de.html.markdown @@ -0,0 +1,450 @@ +--- +language: sass +filename: learnsass.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] + - ["Kyle Mendes", "https://github.com/pink401k"] +translators: + - ["Philipp Bochmann", "https://github.com/phbo85"] +lang: de-de +--- +Sass ist eine CSS-erweiternde Sprache, welche Features wie Variablen, Verschachtelung, Mixins und mehr hinzufügt. +Sass (und andere Präprozessoren wie [Less](http://lesscss.org/)) helfen Entwicklern dabei ihren Code wartbar und DRY (Don't Repeat Yourself - wiederhole dich nicht) zu schreiben. + +Sass hat zwei verschiedene Syntax-Optionen. SCSS, mit der gleichen Syntax wie CSS aber mit den zusätzlichen Features von Sass. Oder Sass (die originale Syntax), welche Einrückung statt geschweiften Klammern und Semikolons benutzt. +Dieses Tutorial wurde mit SCSS geschrieben. + +Wenn du bereits mit CSS3 vertraut bist, wirst du dir Sass relativ schnell aneignen. Es bietet keine neuen Styling-Eigenschaft, sondern Werkzeuge mit denen du dein CSS effizienter schreiben kannst und die Wartung viel einfacher machst. + + +```scss + + +//Einzeilige Kommentare werden entfernt, wenn Sass zu CSS kompiliert wird. + +/* Mehrzeilige Kommentare bleiben bestehen. */ + + + +/* Variablen +============================== */ + + + +/* Du kannst einen CSS-Wert (wie eine Farbe) in einer Variable speichern. +Benutze das '$'-Zeichen um eine Variable zu erstellen. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Du kannst die Variablen überall in deinem Stylesheet verwenden. +Wenn du nun eine Farbe ändern willst, musst du das nur einmal tun. */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Das wird kompiliert zu: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* Dies ist viel besser wartbar als die Farbe +an jeder Stelle im Stylesheet einzeln ändern zu müssen. */ + + + +/* Mixins +============================== */ + + + +/* Wenn du merkst, dass du den gleichen Code für mehr als ein +Element schreiben musst, kannst du ihn in einem mixin speichern. + +Dazu benutzt du '@mixin' plus einem Namen für dein mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Du kannst das mixin mit '@include' und dem Namen des mixin benutzen. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Das kompiliert zu: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Du kannst Mixins benutzen, um shorthand Eigenschaften zu erstellen. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* Diese kannst du aufrufen und width und height als Parameter übergeben. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Compiles to: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/* Funktionen +============================== */ + + + +/* Sass bietet Funktionen, welche benutzt werden können um eine Reihe + von Aufgaben zu bewältigen. Berücksichtige das Folgende: */ + +/* Funktionen können aufgerufen werden indem du ihren Namen benutzt + und die benötigten Parameter übergibst. */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Kompiliert: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Du kannst auch deine eigenen Funktionen definieren. Funktionen ähneln + Mixins. Wenn du zwischen Funktionen und Mixins auswählen musst, denke + daran, dass Mixins am besten zur Generierung von CSS eignen, während + Funktionen besser für Logik in deinem Sass Code genutzt werden. Die + Beispiele mit in der Sektion "Mathematische Operatoren" sind ideale + Kandidaten für wiederverwendbare Funktionen. */ + +/* Diese Funktion errechnet den Prozentwert aus target-size und parent-size + und gibt diesen zurück. */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Kompiliert: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Extend (Vererbung) +============================== */ + + + +/* Extend ist ein Weg um Eigenschaften eines Selektoren mit einem anderem + zu teilen. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Kompiliert: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Aufgrund der Art wie Sass die Klassen zusammen gruppiert, welche + alle das gleiche Grund-Styling haben, ist Extend der Erstellung + eines Mixins vorzuziehen. Wenn dies mit einem Mixin gemacht worden + wäre, würden width, height und border für jedes Element dupliziert + werden, welches das Mixin aufruft. Dies beeinflusst zwar nicht + deinen Workflow, bläht aber die vom Sass-Compiler erzeugten Dateien + unnötige auf. */ + + + +/* Nesting (Verschachtelung) +============================== */ + + + +/* Sass erlaubt es Selektoren in Selektoren zu verschachteln. */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' wird durch den übergeordneten Selektor ersetzt. */ +/* Du kannst auch Pseudo-Klassen verschachteln. */ +/* Denk daran, dass zu viel Verschachtelung deinen Code schlechter + wartbar macht. + Die Best Practices empfehlen nicht mehr als 3 Ebenen zu verschachteln. + Zum Beispiel: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Kompiliert: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/* Partials und Imports +============================== */ + + + +/* Sass erlaubt dir das Erstellen partieller Dateien (partials). + Das hilft dir modularisierten Sass Code zu schreiben. + Partielle Dateien fangen mit einem '_' an, z.B. _reset.css. + Partielle Dateien werden nicht zu CSS generiert. */ + +/* Schau dir folgendes CSS an, was wir in einer Datei namens _reset.css haben */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Mit @import kannst du in Sass partielle Dateien importieren. + Dies unterscheidet sich vom traditionellen CSS @import Statement + welches einen neuen HTTP Request macht, um die zu importierende Datei + zu holen. Sass nimmt die importierte Datei und kombiniert sie mit + dem kompilierten Code. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Kompiliert: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/* Platzhalter Selektoren +============================== */ + + + +/* Platzhalter sind nützlich, um ein CSS Statement zum Erweitern zu + erstellen. Wenn du ein CSS Statement erstellst, welches du ausschließlich + zur Verwendung mit @extend nutzen willst, kannst du das mit einem + Platzhalter tun. Platzhalter fangen mit einem '%' statt einem '.' + oder '#' an und erscheinen nicht im kompilierten CSS. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Kompiliert: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/* Mathematische Operationen +============================== */ + + + +/* Sass bietet die folgenden Operatoren: +, -, *, /, und %. Diese können + nützlich sein, wenn du Werte direkt in Sass berechnen willst, anstatt + vorher manuell errechnete Werte zu verwenden. Unten folgt ein Beispiel + für ein einfaches zweispaltiges Design. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + +``` + +## SASS oder Sass? +Hast du dich jemals gefragt, ob Sass ein Akronym ist oder nicht? Hast du wahrscheinlich nicht, aber ich sage es dir trotzdem. Der Name der Sprache ist ein Wort, "Sass", und kein Akronym. +Da die Leute durchgehend "SASS" geschrieben haben, hat der Ersteller der Sprache es scherzhaft "Syntactically Awesome StyleSheets" genannt. + +## Sass üben +Wenn du mit Sass in deinem Browser spielen willst, schau dir [SassMeister](http://sassmeister.com/) an. +Du kannst beide Syntax-Optionen benutzen, gehe einfach in die Einstellungen und wähle entweder Sass oder SCSS. + +## Kompatibilität +Sass kann in jedem Projekt verwendet werden, solange du ein Programm hast, um es in CSS zu kompilieren. +Du solltest verifizieren, dass das CSS, was du verwendest, mit deinen Ziel-Browsern kompatibel ist. + +[QuirksMode CSS](http://www.quirksmode.org/css/) und [CanIUse](http://caniuse.com) sind gute Resourcen um die Kompatibilät zu überpüfen. + + +## Literaturhinweise +* [Offizielle Dokumentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) bietet Tutorials (Anfänger bis Fortgeschritten) und Artikel. -- cgit v1.2.3 From 5ec0aba7783f7900bc97dda4a0ce68814442b6e4 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 17:11:50 +0200 Subject: fix #2291 metadata --- de-de/sass-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/sass-de.html.markdown b/de-de/sass-de.html.markdown index 20266d17..0c14e249 100644 --- a/de-de/sass-de.html.markdown +++ b/de-de/sass-de.html.markdown @@ -1,6 +1,6 @@ --- language: sass -filename: learnsass.scss +filename: learnsass-de.scss contributors: - ["Laura Kyle", "https://github.com/LauraNK"] - ["Sean Corrales", "https://github.com/droidenator"] -- cgit v1.2.3 From 5d39704b57bc3e163df6f9ac510ea7e56439db0e Mon Sep 17 00:00:00 2001 From: Kyle Mendes Date: Sun, 26 Jun 2016 15:46:16 -0400 Subject: [rust/en] Updating comment examples (#1883) --- rust.html.markdown | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 440cd9eb..cce91683 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -2,6 +2,7 @@ language: rust contributors: - ["P1start", "http://p1start.github.io/"] + - ["Pink401k", "http://github.com/Pink401k"] filename: learnrust.rs --- @@ -27,8 +28,15 @@ concepts that are generally found in higher-level languages. This makes Rust not only fast, but also easy and efficient to code in. ```rust -// This is a comment. Single-line look like this... -/* ...and multi-line comment look like this */ +// This is a comment. Line comments look like this... +// and extend multiple lines like this. + +/// Documentation comments look like this and support markdown notation. +/// # Examples +/// +/// ``` +/// let five = 5 +/// ``` /////////////// // 1. Basics // -- cgit v1.2.3 From 5977df5be45c0f3468abf402921cf925c996a472 Mon Sep 17 00:00:00 2001 From: ven Date: Sun, 26 Jun 2016 21:46:57 +0200 Subject: Update rust.html.markdown --- rust.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index cce91683..4aa9ca7c 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -2,7 +2,6 @@ language: rust contributors: - ["P1start", "http://p1start.github.io/"] - - ["Pink401k", "http://github.com/Pink401k"] filename: learnrust.rs --- -- cgit v1.2.3 From 281ba5b37a9e4e42d33442b0d3a062d99c964a95 Mon Sep 17 00:00:00 2001 From: Ankush goyal Date: Mon, 27 Jun 2016 02:19:51 +0530 Subject: Containers Added (#1942) * Containers Added * Text Formatting Added required spaces between text and // --- c++.html.markdown | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/c++.html.markdown b/c++.html.markdown index a02e7e5b..6b81f95f 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Matt Kline", "https://github.com/mrkline"] - ["Geoff Liu", "http://geoffliu.me"] - ["Connor Waters", "http://github.com/connorwaters"] + - ["Ankush Goyal", "http://github.com/ankushg07"] lang: en --- @@ -985,6 +986,99 @@ cout << get<0>(concatenated_tuple) << "\n"; // prints: 10 cout << get<3>(concatenated_tuple) << "\n"; // prints: 15 cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' + +///////////////////// +// CONTAINERS +///////////////////// + +// Containers or the Standard Template Library are some predefined templates +// They manages the storage space for its elements and provide +// member functions to access and manipulate them + +// Few containers are as follows:- + +// Vectors (Dynamic arrays) +// Allow us to Define the Array or list of objects at run time +#include // will include the header file for vector +vector< Data_Type > Vector_name; // used to initialize the vector +cin>>val; +Vector_name.push_back(val); // will push the value of variable into array + +// To iterate through vector, we have 2 choices +// using normal looping +for(int i=0; i::iterator it; // initialize the iteartor for vector +for(it=vector_name.begin(); it!=vector_name.end();++it) + +// For accessing the element of the vector +// Operator [] +var= vector_name[index]; //will assign value at that index to var + + +// Set +// Sets are containers that store unique elements following a specific order +// Very useful container to store unique values in sorted order +// without any other functions or code + +#include // Will include the header file for sets +set< int > ST; // Will initialize the set of int data type +ST.insert(30); // Will insert the value 30 in set ST +ST.insert(10); // Will insert the value 10 in set ST +ST.insert(20); // Will insert the value 20 in set ST +ST.insert(30); // Will insert the value 30 in set ST +// Now elements of sets are as follows +// 10 20 30 + +// To erase an element +ST.erase(20); // Will erase element with value 20 +// Set ST: 10 30 +// To iterate through Set we use iterators +set< int >::iterator it; +for(it=ST.begin();it // Will include the header file for map +map< char, int >mymap; // Will initalize the map with key as char and value as int + +mymap.insert ( pair('A',1) ); +// Will insert value 1 for key A +mymap.insert ( pair('Z',26) ); +// Will insert value 26 for key Z + +// To iterate +map::iterator it; +for (it=mymap.begin(); it!=mymap.end(); ++it) + std::cout << it->first << "->" << it->second <<'\n'; +// Output: +// A->1 +// Z->26 + +// To find the value correponsing to a key +it = mymap.find('Z'); +cout<second; + +// OUTPUT: 26 + + ``` Further Reading: -- cgit v1.2.3 From f98cbd3653bd0b83bdfb4cb8afae529afd3bc8bc Mon Sep 17 00:00:00 2001 From: Oleksii Kholovchuk Date: Mon, 27 Jun 2016 00:10:37 +0300 Subject: Added document about Qt framework (#1444) * Added document about Qt framework * Removed qt.cpp file and made some corrections in the markdown file --- qt.html.markdown | 157 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 qt.html.markdown diff --git a/qt.html.markdown b/qt.html.markdown new file mode 100644 index 00000000..71d12909 --- /dev/null +++ b/qt.html.markdown @@ -0,0 +1,157 @@ +--- +category: tool +tool: Qt Framework +language: c++ +filename: learnqt.cpp +contributors: + - ["Aleksey Kholovchuk", "https://github.com/vortexxx192"] +lang: en +--- + +**Qt** is a widely-known framework for developing cross-platform software that can be run on various software and hardware platforms with little or no change in the code, while having the power and speed of native applications. Though **Qt** was originally written in *C++*, there are its ports to other languages: *PyQt*, *QtRuby*, *PHP-Qt*, etc. + +**Qt** is beautiful for creating applications with graphical user interface (GUI). This tutorial is how to do it in *C++*. + +```c++ +/* + * Let's start clasically + */ + +// all headers from Qt framework start with capital letter 'Q' +#include +#include + +int main(int argc, char *argv[]) { + // create an object to manage application-wide resources + QApplication app(argc, argv); + + // create line edit widget and show it on screen + QLineEdit lineEdit("Hello world!"); + lineEdit.show(); + + // start the application's event loop + return app.exec(); +} +``` + +GUI-related part of **Qt** is all about *widgets* and *connections* between them. + +[READ MORE ABOUT WIDGETS](http://doc.qt.io/qt-5/qtwidgets-index.html) + +```c++ +/* + * Let's create a label and a button. + * A label should appear when a button is pressed. + * + * Qt code is speaking for itself. + */ + +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + // add vertical layout + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + QLabel textLabel("Thanks for pressing that button"); + layout.addWidget(&textLabel); + textLabel.hide(); + + QPushButton button("Press me"); + layout.addWidget(&button); + + // show hidden label when the button is pressed + QObject::connect(&button, &QPushButton::pressed, + &textLabel, &QLabel::show); + + return app.exec(); +} +``` + +Notice that *QObject::connect* part. This method is used to connect *SIGNALS* of one objects to *SLOTS* of another. + +**Signals** are being emited when certain things happen with objects, like *pressed* signal is emited when user presses on QPushButton object. + +**Slots** are *actions* that might be performed in response to received signals. + +[READ MORE ABOUT SLOTS AND SIGNALS](http://doc.qt.io/qt-4.8/signalsandslots.html) + + +Next, let's learn that we can not only use standard widgets but also extend their behaviour using inheritance. Let's create a button and count how many times it was pressed. For this purpose we define our own class *CounterLabel*. It must be declared in separate file because of specific Qt architecture. + +```c++ +// counterlabel.hpp + +#ifndef COUNTERLABEL +#define COUNTERLABEL + +#include + +class CounterLabel : public QLabel { + Q_OBJECT // Qt-defined macros that must be present in every custom widget + +public: + CounterLabel() : counter(0) { + setText("Counter has not been increased yet"); // method of QLabel + } + +public slots: + // action that will be called in response to button press + void increaseCounter() { + setText(QString("Counter value: %1").arg(QString::number(++counter))); + } + +private: + int counter; +}; + +#endif // COUNTERLABEL +``` + +```c++ +// main.cpp +// Almost the same as in previous example + +#include +#include +#include +#include +#include +#include "counterlabel.hpp" + +int main(int argc, char *argv[]) { + QApplication app(argc, argv); + + QDialog dialogWindow; + dialogWindow.show(); + + QVBoxLayout layout; + dialogWindow.setLayout(&layout); + + CounterLabel counterLabel; + layout.addWidget(&counterLabel); + + QPushButton button("Push me once more"); + layout.addWidget(&button); + QObject::connect(&button, &QPushButton::pressed, + &counterLabel, &CounterLabel::increaseCounter); + + return app.exec(); +} +``` + +## Furter reading +That's it! Of course Qt framework is much much larger than the part that was covered in this tutorial, so be ready to read and practice. + +[READ MORE ABOUT QT](http://doc.qt.io/qt-4.8/tutorials.html) + +Good luck and have fun -- cgit v1.2.3 From 95870a3aa2a05542ef2e9356127bafe2eeeb535f Mon Sep 17 00:00:00 2001 From: WinChris Date: Mon, 27 Jun 2016 10:00:38 +0200 Subject: Create HTML-fr.html.markdown (#1843) * Create HTML-fr.html.markdown What is HTML ? Tutorial to understand HTML * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown Corrections de divers points * Update HTML-fr.html.markdown Corrections * Update HTML-fr.html.markdown Corrections d'un commentaire * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown * Update HTML-fr.html.markdown --- HTML-fr.html.markdown | 115 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 HTML-fr.html.markdown diff --git a/HTML-fr.html.markdown b/HTML-fr.html.markdown new file mode 100644 index 00000000..fdde9107 --- /dev/null +++ b/HTML-fr.html.markdown @@ -0,0 +1,115 @@ +--- +language: html +filename: learnhtml-fr.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +lang: fr-fr +--- +HTML signifie HyperText Markup Language. +C'est un langage (format de fichiers) qui permet d'écrire des pages internet. +C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). +Les fichiers HTML sont en réalité de simple fichier texte. +Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. +Ce balisage sert à donner une signification au texte ainsi entouré. +Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. + +**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. +Cet article porte principalement sur la syntaxe et quelques astuces. + + +```HTML + + + + + + + + + + + Mon Site + + +

Hello, world!

+ Venez voir ce que ça donne +

Ceci est un paragraphe

+

Ceci est un autre paragraphe

+
    +
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • +
  • Ceci est un autre item
  • +
  • Et ceci est le dernier item de la liste
  • +
+ + + + + + + + + + + + + + + + + + + + Mon Site + + + + + + + +

Hello, world!

+ + Venez voir ce que ça donne +

Ceci est un paragraphe

+

Ceci est un autre paragraphe

+
    + +
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • +
  • Ceci est un autre item
  • +
  • Et ceci est le dernier item de la liste
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
First Header Second Header
Première ligne, première cellule Première ligne, deuxième cellule
Deuxième ligne, première celluleDeuxième ligne, deuxième cellule
+ +## Utilisation + +Le HTML s'écrit dans des fichiers `.html`. + +## En savoir plus + +* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 46844f8e8e9b55148910256e149f510ae43cf757 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20D=C3=A4hnert?= Date: Mon, 27 Jun 2016 10:09:58 +0200 Subject: [java/de] Initial translation added. (#1391) * DE-Translation for Java added. * Handled hints from vendethiel. --- de-de/java-de.html.markdown | 497 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 497 insertions(+) create mode 100644 de-de/java-de.html.markdown diff --git a/de-de/java-de.html.markdown b/de-de/java-de.html.markdown new file mode 100644 index 00000000..001c6888 --- /dev/null +++ b/de-de/java-de.html.markdown @@ -0,0 +1,497 @@ +--- +language: java +filename: LearnJavaDe.java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] +translators: + - ["Michael Dähnert", "http://github.com/JaXt0r"] +lang: de-de +--- + +Java ist eine Programmiersprache für vielfältige Aufgaben. Sie ist imperative und objektorientiert. +Oftmals wird sie für Desktop- Webapplikationen sowie als Programmiersprache im Betriebssystem Android verwendet. +[Weitere Informationen \(Englisch\](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Einzeilige Kommentare starten mit // +/* +Mehrzeilige Kommentare sehen so aus. +*/ +/** +JavaDoc Kommentare haben dieses Format. Sie werden verwendet um Klassen, Attribute sowie Methoden zu beschreiben. +*/ + +// Importieren der Klasse ArrayList aus dem Paket java.util +import java.util.ArrayList; +// Importieren aller Klassen innerhalb des Paketes java.security +import java.security.*; + +// Jede .java Datei besteht aus einer äußeren öffentlichen (public) Klasse. +// Der Name der Klasse muss identisch des Dateinamens sein. +public class LearnJavaDe { + + // Ein Programm muss eine main Methode als Eintrittspunkt besitzen. + public static void main (String[] args) { + + // System.out.println() wird zum Schreiben von zeilenweisen Ausgaben verwendet. + System.out.println("Hello World!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Zum Schreiben von Ausgaben ohne Zeilenumbruch wird System.out.print() verwendet. + System.out.print("Hello "); + System.out.print("World"); + + + /////////////////////////////////////// + // Typen & Variablen + /////////////////////////////////////// + + // Zum Deklarieren einer Variable nutze + // Byte - 8-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-128 <= byte <= 127) + byte fooByte = 100; + + // Short - 16-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-32,768 <= short <= 32,767) + short fooShort = 10000; + + // Integer - 32-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-2,147,483,648 <= int <= 2,147,483,647) + int fooInt = 1; + + // Long - 64-bit vorzeichenbehaftete (signed), binäre Ganzzahl + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long fooLong = 100000L; + // L wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ long ist. + // Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt. + + // Hinweis: Java besitzt keine vorzeichenlosen (unsigned) Typen. + + // Float - Typ mit einfacher Genauigkeit (Single-precision), 32-bit IEEE 754 Fließkommazahl + float fooFloat = 234.5f; + // f wird verwendet um zu kennzeichnen, dass ein Variablenwert vom Typ float ist; + // Ohne diesen Buchstaben wird die Zahl automatisch als Integer behandelt. + + // Double - Typ mit doppelter Genauigkeit (Double-precision), 64-bit IEEE 754 Fließkommazahl + double fooDouble = 123.4; + + // Boolean - Wahr & Falsch (true & false) + boolean fooBoolean = true; + boolean barBoolean = false; + + // Char - Ein einfacher 16-bit Unicode Buchstabe + char fooChar = 'A'; + + // final Variablen können von einem anderen Objekt nicht erneut zugeordnet werden. + final int HOURS_I_WORK_PER_WEEK = 9001; + + // Zeichenketten (Strings) + String fooString = "My String Is Here!"; + + // \n ist ein Escape Zeichen welcher eine neue Zeile startet. + String barString = "Schreiben auf einer neuen Zeile?\nKein Problem!"; + // \t ist ein Escape Zeichen welcher einen Tab-Zeichen anhängt. + String bazString = "Möchtest du einen Tabulator anhängen?\tKein Problem!"; + System.out.println(fooString); + System.out.println(barString); + System.out.println(bazString); + + // Arrays + // Die Arraygröße muss bei Instanziierung entschieden werden. + // Das folgende Format funktioniert bei Deklaration eines Arrays + // [] = new []; + // [] = new []; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Eine weitere Möglichkeit ein Array zu deklarieren & initialisieren. + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Indexierung eines Arrays - Zugriff auf ein Element + System.out.println("intArray @ 0: " + intArray[0]); + + // Arrays sind 0-indexiert und veränderbar. + intArray[1] = 1; + System.out.println("intArray @ 1: " + intArray[1]); // => 1 + + // Weitere nennenswerte Typen + // ArrayLists - Ähnlich Arrays, allerdings werden mehr Funktionen geboten, + // ebenso ist die Arraygröße verwänderbar + // LinkedLists - Implementierung einer doppelt verlinkten Liste. + // Alle Operationen funktioneren so, wie es von einer doppelt verlinkten Liste erwartet wird. + // Weitere Informationen: https://de.wikipedia.org/wiki/Liste_(Datenstruktur)#Doppelt_.28mehrfach.29_verkettete_Liste + // Maps - Eine Sammlung von Objekten, welche eine Verknüpfung von Schlüsseln zu Werten (key => value) vornimmt. + // Eine Map kann keine Duplikate enthalten; Jeder Schlüssel kann genau einen Wert beinhalten. + // HashMaps - Diese Klasse nutzt eine Hashtabelle zur Implementierung eines Map Interfaces. + // Dies erlaubt es zur Laufzeit Standardoperationen wie gib (get) und einfügen (insert) + // selbst für große Mengen in einer konstanten Zeit auszuführen (Laufzeitverhalten O(n)). + + /////////////////////////////////////// + // Operatoren + /////////////////////////////////////// + System.out.println("\n->Operatoren"); + + int i1 = 1, i2 = 2; // Kurform zur Deklaration mehrerer Variablen. + + // Arithmetische Operationen sind einfach nutzbar. + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 Nachkommazahl abgeschnitten) + + // Modulo + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Vergleichsoperationen + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise Operatoren! + /* + ~ Unäres (unary) bitweise Komplement + << Vorzeichenbehaftete (signed) linke Verschiebung + >> Vorzeichenbehaftete (signed) rechte Verschiebung + >>> Vorzeichenlose (unsigned) linke Verschiebung + & Bitweise UND (AND) + ^ Bitweise exklusive ODER (OR) + | Bitweise inklusive ODER (OR) + */ + + // Inkrementierungen + int i = 0; + System.out.println("\n->Inc/Dec-rementierung"); + // Die ++ und -- operatoren inkrementieren und dekrementieren jeweils um 1. + // Werden sie vor die Variable gesetzt, ink-/dekrementieren sie und geben anschließend ihren Wert zurück. + // Hinter der Variable geben sie ihren Wert zurück und ändern ihn anschließend. + System.out.println(i++); // i = 1, schreibt 0 (post-increment) + System.out.println(++i); // i = 2, schreibt 2 (pre-increment) + System.out.println(i--); // i = 1, schreibt 2 (post-decrement) + System.out.println(--i); // i = 0, schreibt 0 (pre-decrement) + + /////////////////////////////////////// + // Kontrollstrukturen + /////////////////////////////////////// + System.out.println("\n->Kontrollstrukturen"); + + // If Bedingungen sind wie in den C-Sprachen aufgebaut + int j = 10; + if (j == 10){ + System.out.println("Ich wurde geprinted"); + } else if (j > 10) { + System.out.println("Ich nicht"); + } else { + System.out.println("Ich auch nicht"); + } + + // While Schleife + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Den Zähler inkrementieren + // 100x iterieren, fooWhile 0,1,2...99 + fooWhile++; + } + System.out.println("fooWhile Wert: " + fooWhile); + + // Do While Schleife + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Den Zähler inkrementieren + // 99x iterieren, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("fooDoWhile Wert: " + fooDoWhile); + + // For Schleife + int fooFor; + // for Schleifenstruktur => for(; ; ) + for (fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // 10x iterieren, fooFor 0->9 + } + System.out.println("fooFor Wert: " + fooFor); + + // For Each Schleife + // The for Schleife kann verwendet werden um über Arrays ebenso wie Objekte, + // welche das Interface Iterable implementieren zu iterieren. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // for each Schleifenstruktur => for ( : ) + // Wird gelesen als: Iteriere für jedes Element im Iterable + // Hinweis: Der Objekttyp muss dem Elementtyp des Iterable entsprechen. + + for (int bar : fooList) { + System.out.println(bar); + //9x iterieren und die Werte 1-9 auf jeweils einer neuen Zeile schreiben + } + + // Switch Case + // A Schalter (switch) funktioniert mit den Datentypen byte, short, char und int. + // Ebenso kann er für Aufzählungen (Enums) verwendet werden (Enum Typen folgen weiter unten) + // der String Klasse (ab Java SE7) und ein paar spezielle Klassen, welche die primitiven Typen ummanteln (wrap): + // Character, Byte, Short, and Integer. + int monat = 3; + String monatsString; + switch (monat) { + case 1: monatsString = "Januar"; + break; + case 2: monatsString = "Februar"; + break; + case 3: monatsString = "März"; + break; + default: monatsString = "Ein anderer Monat"; + break; + } + System.out.println("Switch Case Ergebnis: " + monatsString); + + // Bedingungsoperator (Conditional Shorthand) + // Der Operator '?' kann für schnelle Zuweisungen oder logische Verzweigungen genutzt werden. + // Er ist wie folgt zu lesen: Wenn die Bedingung wahr ist, nutze + // ansonsten nutze + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Schreibt A, denn die Bedingung ist wahr. + + + //////////////////////////////////////// + // Typkonvertierung und Type-Casting + //////////////////////////////////////// + + // Konvertierung von Daten + + // Konvertiere String nach Integer + Integer.parseInt("123");// Gibt die Integer Repräsentation von "123" zurück + + // Konvertiere String nach Integer + Integer.toString(123);// Gibt die String Repräsentation von 123 zurück + + // Für andere Konvertierungen sind die folgenden Klassen zu betrachten: + // Double + // Long + // String + + // Tpe-Casting + // Java Objekte können benfalls konvertiert werden, hierbei gibt es vielfältige Konzepte. + // Weitere Informationen finden sich hier (englisch): + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Klassen und Funktionen + /////////////////////////////////////// + + System.out.println("\n->Klassen & Funktionen"); + + // (Die Definition der Klasse Fahrrad folgt) + + // Verwendung einer neuen Klasseninstanz + Fahrrad trek = new Fahrrad(); + + // Aufruf von Methoden des Objektes + trek.erhöheGeschwindigkeit(3); // Es sollten immer getter- und setter- Methoden verwendet werden + trek.setTrittfrequenz(100); + + // toString gibt die StringRepräsentation des Objektes zurück. + System.out.println("trek info: " + trek.toString()); + + } // Ende der Main Methode +} // Ende der LearnJavaDe Klasse + + +// In einer .java-Datei können zusätzliche nicht öffentliche (non-public) äüßere Klassen vorhanden sein. + + +// Syntax der Klassendeklaration: +// class { +// // Es folgen Datenfelder, Konstruktoren, Funktionen. +// // Funktionen werden in Java Methoden genannt. +// } + +class Fahrrad { + + // Felder/Variablen der Klasse Fahrrad + public int trittfrequenz; // Public: Kann von überall her angesprochen werden + private int geschwindigkeit; // Private: Nur innerhalb der Klasse sichtbar + protected int gang; // Protected: Erreichbar innerhalb der Klasse oder Subklassen (sub classes) + String name; // default: Nur innerhalb des Paketes verwendbar + + // Eine Klasse kann mittelst Konstruktoren erstellt werden. + // Das ist ein Konstruktor + public Fahrrad() { + gang = 1; + trittfrequenz = 50; + geschwindigkeit = 5; + name = "Bontrager"; + } + + // Das ist ein Konstruktor mit Argumenten + public Bicycle(int initialTrittfrequenz, int initialGeschwindigkeit, int initialGang, + String name) { + this.gang = initialGang; + this.trittfrequenz = initialTrittfrequenz; + this.geschwindigkeit = initialGeschwindigkeit; + this.name = name; + } + + // Syntax von Methoden (Funktionen): + // () + + // Java Klassen implementieren oftmals getter- und setter-Methoden ihrer Felder + + // Syntax von Methodendeklarationen: + // () + public int getTrittfrequenz() { + return tri; + } + + // void Methoden benötigen kein return Statement. + public void setCadence(int newValue) { + cadence = newValue; + } + + public void setGear(int newValue) { + gear = newValue; + } + + public void erhöheGeschwindigkeit(int increment) { + speed += increment; + } + + public void verringereGeschwindigkeit(int decrement) { + speed -= decrement; + } + + public void setName(String newName) { + name = newName; + } + + public String getName() { + return name; + } + + //Methode zur Darstellung der Attributwerte des Objektes. + @Override + public String toString() { + return "Gang: " + gang + " Trittfrequenz: " + trittfrequenz + " Geschwindigkeit: " + geschwindigkeit + + " name: " + name; + } +} // Ende der Klasse Fahrrad + +// Hochrad ist eine Subklasse von Fahrrad +class Hochrad extends Fahrrad { + // (Hochräder sind Fahrräder mit einem extrem großen Vorderrad. + // Sie haben keine Gänge.) + + public Hochrad(int initialTrittfrequenz, int initialGeschwindigkeit){ + // Aufruf des Vater-Konstruktors (parent constructor) mit dem Wort super. + super(initialTrittfrequenz, initialGeschwindigkeit, 0, "Hochrad"); + } + + // Überschriebene Methoden sollten die Annotation @Override besitzen. + // Mehr zu Annotationen und deren Verwendungszwecken kann hier nachgelesen werden: + // (englisch) http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setGang(int gang) { + gang = 0; + } +} + +// Schnittstellen (Interfaces) +// Interface Deklaration +// interface extends { +// // Konstanten +// // Methodendeklarationen +// } + +// Beispiel - Nahrung: +public interface Essbar { + public void essen(); // Jede Klasse, die dieses Interface implementiert + // muss auch diese Methode implementieren. +} + + +public interface Verdaulich { + public void verdauen(); +} + + +// Nun können wir eine Klasse erstellen, die beide Interfaces implementiert. +public class Frucht implements Essbar, Verdaulich { + @Override + public void essen() { + // ... + } + + @Override + public void verdauen() { + // ... + } +} + +// Mit Java kann man nur eine Klasse erweitern (extends) jedoch mehrere Interfaces implementieren. +// z.B.: +public class BeispielKlasse extends ParentBeispielKlasse implements InterfaceEins, + InterfaceZwei { + @Override + public void methodeInterfaceEins() { + } + + @Override + public void methodeInterfaceZwei() { + } +} +``` + +## Weitere Informationen (in englisch) + +Die folgenden Links dienen lediglich dazu Verständnis für die Kapitel aufzubauen. +Für tiefergreifende Fragen ist Google der beste Startpunkt. + +**Offizielle Oracle Guides**: + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) + +**Online Tutorials** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Bücher**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From c50ff9299651ba3c856ee23cbdabeda2784b864c Mon Sep 17 00:00:00 2001 From: Jatin Dhankhar Date: Mon, 27 Jun 2016 19:00:07 +0530 Subject: Added the Logical and bitwise operators section, fixes merge issue with #1817 (#2292) * Added the Logical and bitwise operators section * Added a note for Short Circuit evaluation Excerpt from https://en.wikipedia.org/wiki/Short-circuit_evaluation C++ uses minimal evaluation, or McCarthy evaluation (after John McCarthy (computer scientist)) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true. In some programming languages (Lisp), the usual Boolean operators are short-circuit. --- c++.html.markdown | 57 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 6b81f95f..290633f3 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Geoff Liu", "http://geoffliu.me"] - ["Connor Waters", "http://github.com/connorwaters"] - ["Ankush Goyal", "http://github.com/ankushg07"] + - ["Jatin Dhankhar", "https://github.com/jatindhankhar"] lang: en --- @@ -1005,7 +1006,7 @@ cin>>val; Vector_name.push_back(val); // will push the value of variable into array // To iterate through vector, we have 2 choices -// using normal looping +// using normal looping for(int i=0; i // Will include the header file for sets @@ -1031,7 +1032,7 @@ ST.insert(20); // Will insert the value 20 in set ST ST.insert(30); // Will insert the value 30 in set ST // Now elements of sets are as follows // 10 20 30 - + // To erase an element ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 @@ -1041,7 +1042,7 @@ for(it=ST.begin();it('A',1) ); mymap.insert ( pair('Z',26) ); // Will insert value 26 for key Z -// To iterate +// To iterate map::iterator it; for (it=mymap.begin(); it!=mymap.end(); ++it) std::cout << it->first << "->" << it->second <<'\n'; -// Output: +// Output: // A->1 // Z->26 @@ -1078,6 +1079,50 @@ cout<second; // OUTPUT: 26 +/////////////////////////////////// +// Logical and Bitwise operators +////////////////////////////////// + +// Most of the operators in C++ are same as in other languages + +// Logical operators + +// C++ uses Short - circuit evaluation for boolean expressions, i.e, the second argument is executed or +// evaluated only if the first argument does not suffice to determine the value of the expression + +true && false // Performs **logical and** to yield false +true || false // Performs **logical or** to yield true +! true // Performs **logcical not** to yield + +// Instead of using symbols equivalent keywords can be used +true and false // Performs **logical and** to yield false +true or false // Performs **logical or** to yield true +not true // Performs **logcical not** to yield + +// Bitwise operators + +// **<<** Left Shift Operator +// << shifts bits to the left +4 << 1 // Shifts bits of 4 to left by 1 to give 8 +// x << n can be thought as x * 2^n + + +// **>>** Right Shift Operator +// << shifts bits to the right +4 >> 1 // Shifts bits of 4 to right by 1 to give 2 +// x << n can be thought as x / 2^n + +~4 // Performs a bitwise not +4 | 3 // Performs bitwise or +4 & 3 // Performs bitwise and +4 ^ 3 // Performs bitwise xor + +// Equivalent keywords are +compl 4 // Performs a bitwise not +4 bitor 3 // Performs bitwise or +4 bitand 3 // Performs bitwise and +4 xor 3 // Performs bitwise xor + ``` Further Reading: -- cgit v1.2.3 From c0577fece6b2862a7198b61ec1855b504cf43d47 Mon Sep 17 00:00:00 2001 From: Durant Schoon Date: Mon, 27 Jun 2016 23:53:25 -0700 Subject: Correct "Bycles" to "Bicycles"" (#2293) "DidWeCreateEnoughBycles" -> "DidWeCreateEnoughBicycles" --- csharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/csharp.html.markdown b/csharp.html.markdown index 69aef257..4c9e8411 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -826,7 +826,7 @@ on a new line! ""Wow!"", the masses cried"; } // Methods can also be static. It can be useful for helper methods - public static bool DidWeCreateEnoughBycles() + public static bool DidWeCreateEnoughBicycles() { // Within a static method, we only can reference static class members return BicyclesCreated > 9000; -- cgit v1.2.3 From d3a31e9a7d2752e67e452a28f318710448444ba8 Mon Sep 17 00:00:00 2001 From: Adam Heins Date: Mon, 27 Jun 2016 23:54:00 -0700 Subject: Remove obsolete utf-8 options. (#2294) These options are no longer valid in recent versions of tmux. See https://github.com/tmux/tmux/issues/230. --- tmux.html.markdown | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index c9e3db6b..ae73d912 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -122,10 +122,6 @@ like how .vimrc or init.el are used. ### General ########################################################################### -# Enable UTF-8 -setw -g utf8 on -set-option -g status-utf8 on - # Scrollback/History limit set -g history-limit 2048 -- cgit v1.2.3 From 7812b99ff8f649595a57ef86577c7567cd1c8166 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 28 Jun 2016 18:06:06 +0200 Subject: Manually merge #1780 fixes #1780 --- java.html.markdown | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index fb0913f1..f65c484e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -8,6 +8,7 @@ contributors: - ["Zachary Ferguson", "http://github.com/zfergus2"] - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Michael Dähnert", "http://github.com/JaXt0r"] filename: LearnJava.java --- @@ -171,6 +172,29 @@ public class LearnJava { System.out.println(barString); System.out.println(bazString); + // String Building + // #1 - with plus operator + // That's the basic way to do it (optimized under the hood) + String plusConcatenated = "Strings can " + "be concatenated " + "via + operator."; + System.out.println(plusConcatenated); + // Output: Strings can be concatenated via + operator. + + // #2 - with StringBuilder + // This way doesn't create any intermediate strings. It just stores the string pieces, and ties them together + // when toString() is called. + // Hint: This class is not thread safe. A thread-safe alternative (with some impact on performance) is StringBuffer. + StringBuilder builderConcatenated = new StringBuilder(); + builderConcatenated.append("You "); + builderConcatenated.append("can use "); + builderConcatenated.append("the StringBuilder class."); + System.out.println(builderConcatenated.toString()); // only now is the string built + // Output: You can use the StringBuilder class. + + // #3 - with String formatter + // Another alternative way to create strings. Fast and readable. + String.format("%s may prefer %s.", "Or you", "String.format()"); + // Output: Or you may prefer String.format(). + // Arrays // The array size must be decided upon instantiation // The following formats work for declaring an array -- cgit v1.2.3 From e07de13721a6f434473839454fe161ed2cff3a6e Mon Sep 17 00:00:00 2001 From: Xuan-thi N Date: Wed, 29 Jun 2016 11:26:11 +0200 Subject: [fr/tmux] Tmux translated in French (#1861) * tmux article translated in French * Small typos * Added change suggestions --- fr-fr/tmux-fr.html.markdown | 261 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 fr-fr/tmux-fr.html.markdown diff --git a/fr-fr/tmux-fr.html.markdown b/fr-fr/tmux-fr.html.markdown new file mode 100644 index 00000000..d353af3b --- /dev/null +++ b/fr-fr/tmux-fr.html.markdown @@ -0,0 +1,261 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Xuan-thi Nguyen", "https://github.com/mellenguyen"] +filename: LearnTmux-fr.txt +lang: fr-fr +--- + + +[Tmux](http://tmux.sourceforge.net) est un multiplexeur de terminal: il permet +de créer plusieurs terminaux, accédés et contrôlés depuis un seul écran. Tmux +peut être détaché de l'écran tout en continuant de fonctionner en tâche de +fond, puis rattaché de nouveau. + + +``` + + tmux [command] # Exécute une commande + # 'tmux' sans commande créé une nouvelle session + + new # Créé une nouvelle session + -s "Session" # Créé une session nommée "Session" + -n "Window" # Créé une fenêtre nommée "Window" + -c "/dir" # Démarre dans le dossier cible "/dir" + + attach # S'attache à la dernière session ou la session disponible + -t "#" # S'attache à la session cible + -d # Détache la session des autres instances + + ls # Liste les sessions ouvertes + -a # Liste toutes les sessions ouvertes + + lsw # Liste les fenêtres de la session courante + -a # Liste toutes les fenêtres + -s # Liste toutes les fenêtres en session + + lsp # Liste les panels + -a # Liste tous les panels + -s # Liste tous les panels en session + -t # Liste tous les panels dans la cible + + kill-window # Tue la fenêtre courante + -t "#" # Tue la fenêtre cible + -a # Tue toutes les fenêtres + -a -t "#" # Tue toutes les fenêtres sauf la cible + + kill-session # Tue la session courante + -t "#" # Tue la session cible + -a # Tue toutes les sessions + -a -t "#" # Tue toutes les sessions sauf la cible + +``` + + +### Raccourcis clavier + +Afin de contrôler une session tmux attachée, on utilise une combinaison de +touches appelées 'Préfixe'. Elle doit être pressée afin d'utiliser les +raccourcis. + +``` +-------------------------------------------------------------------------------- + (C-b) = Ctrl + b # Combinaison 'Préfixe' requise pour utiliser les raccourcis + + (M-1) = Meta + 1 -ou- Alt + 1 +-------------------------------------------------------------------------------- + + ? # Liste tous les raccourcis + : # Entre dans l'invite de commande de tmux + r # Force la redéfinition du client attaché + c # Créé une nouvelle fenêtre + + ! # Sépare le panel courant de sa fenêtre + % # Sépare le panel courant en deux, gauche et droite + " # Sépare le panel courant en deux, haut et bas + + n # Changer vers la fenêtre suivante + p # Changer vers la fenêtre précédente + { # Echange le panel courant avec le panel précédent + } # Echange le panel courant avec le panel suivant + + s # Sélectionne une nouvelle session pour le client attaché + # de manière interactive + w # Choisi la fenêtre courante de manière interactive + 0 to 9 # Sélectionne la fenêtre de 0 à 9 + + d # Détache le client courant + D # Choisi un client à détacher + + & # Tue la fenêtre courante + x # Tue le panel courant + + Up, Down # Change vers le panel au dessus, en dessous, à gauche + Left, Right # ou à droite + + M-1 to M-5 # Arrange les panels: + # 1) égaliser sur l'horizontale + # 2) égaliser sur la verticale + # 3) panel principal en haut et le reste en bas + # de gauche à droite + # 4) panel principal à gauche et le reste à droite + # de haut en bas + # 5) "tiled" : égalise les panels + # sur la hauteur et la largeur + + C-Up, C-Down # Redimensionne le panel courant par pas de une cellule + C-Left, C-Right + + M-Up, M-Down # Redimensionne le panel courant par pas de cinq cellules + M-Left, M-Right + +``` + + +### Configuration de ~/.tmux.conf + +tmux.conf peut être utilisé pour fixer les options automatiquement au +démarrage, comme .vimrc ou init.el. + +``` +# Exemple de tmux.conf +# 2014.10 + + +### Général +########################################################################### + +# Active UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Limite de l'historique +set -g history-limit 2048 + +# Indice de début du nombre de panels +set -g base-index 1 + +# Souris +set-option -g mouse-select-pane on + +# Force le rechargement du fichier de configuration +unbind r +bind r source-file ~/.tmux.conf + + +### Raccourcis clavier +########################################################################### + +# Annule C-b en tant que préfixe par défaut +unbind C-b + +# Définit un nouveau préfixe par défaut +set-option -g prefix ` + +# Retourne à la fenêtre précédente quand le préfixe est pressé deux fois +bind C-a last-window +bind ` last-window + +# Permet d'échanger C-a et ` en utilisant F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Préférences de raccourcis clavier +setw -g mode-keys vi +set-option -g status-keys vi + +# Navigue entre les panels avec les raccourcis clavier de vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Navigation entre les fenêtres +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Commandes simples de séparation des panels +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Active la session la plus imbriquée (en faisant de l'imbrication sous tmux) +# pour envoyer des commandes +bind a send-prefix + + +### Thème +########################################################################### + +# Palette de couleurs pour la barre de statuts +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Palette de couleurs pour les bordures des panels +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Palette de couleurs pour les messages +set-option -g message-fg black +set-option -g message-bg green + +# Palette de couleurs pour les fenêtres +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notification +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Définir automatiquement des titres de fenêtres +set-option -g set-titles on +# Numéro de fenêtre, nom du programme, actif (ou non) +set-option -g set-titles-string '#H:#S.#I.#P #W #T' + +# Réglages de la barre de statuts +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Présente des indicateurs de performance dans la barre de statuts +# Recquiert https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Références + +[Tmux | Home](http://tmux.sourceforge.net) + +[Page du manuel Tmux](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Montrer le pourcentage CPU/MEM dans la barre de statuts](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Gère des sessions tmux complexes](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From df4dbee36f5a3b9b63292a2346327f8b7d282a28 Mon Sep 17 00:00:00 2001 From: Xuan-thi N Date: Wed, 29 Jun 2016 11:26:53 +0200 Subject: [fr/ruby-ecosytem] Translated ruby-ecosytem article in French (#1857) * Translated ruby-ecosytem article in French * Added change suggestions --- fr-fr/ruby-ecosystem-fr.html.markdown | 154 ++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 fr-fr/ruby-ecosystem-fr.html.markdown diff --git a/fr-fr/ruby-ecosystem-fr.html.markdown b/fr-fr/ruby-ecosystem-fr.html.markdown new file mode 100644 index 00000000..9b52069a --- /dev/null +++ b/fr-fr/ruby-ecosystem-fr.html.markdown @@ -0,0 +1,154 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Xuan-thi Nguyen", "http://github.com/mellenguyen"] +lang: fr-fr + +--- + +Les gens utilisant Ruby adoptent généralement un gestionnaire pour installer +différentes versions de Ruby, gérer leurs paquets (ou gems), et gérer les +dépendances des gems. + +## Ruby Managers + +Quelques plateformes possèdent Ruby pré-installé ou disponible en tant que +paquet. La plupart des rubyists ne les utilisent pas, ou si c'est le cas, ne +les utilise que pour faire démarrer un autre installateur ou implémentation de +Ruby. Les rubyists tendent plutôt à installer un manager Ruby pour installer +et changer entre les différentes et nombreuses versions de Ruby et les +environnements de leurs projets Ruby. + +Les gestionnaires d'environnement Ruby les plus populaires sont : + +* [RVM](https://rvm.io/) - Installe et navigue entre les rubies. RVM possède + églement le concept des gemsets pour isoler les environnements de projets + complètement. +* [ruby-build](https://github.com/sstephenson/ruby-build) - Installe seulement + les rubies. Utilisez-le pour un contrôle plus fin des installations des + rubies. +* [rbenv](https://github.com/sstephenson/rbenv) - Navigue seulement entre les + rubies. Utilisé avec ruby-build. Utilisez-le pour un contrôle plus fin des + chargements des rubies. +* [chruby](https://github.com/postmodern/chruby) - Navigue seulement entre les + rubies. Similaire à rbenv. Neutre sur comment les rubies sont installés. + +## Versions de Ruby + +Ruby a été créé par Yukihiro "Matz" Matsumoto, qui reste quelque peu un +[BDFL](https://fr.wikipedia.org/wiki/Benevolent_Dictator_for_Life), bien que +cela soit récemment en changement. Jusqu'à la standardisation du langage en +2011, l'implémentation de référence de Ruby était appelé MRI (Matz' Reference +Implementation). + +Les trois versions majeures de Ruby actuellement utilisées sont : + +* 2.0.0 - Sortie en février 2013. La plupart des librairies et frameworks + gèrent la versions 2.0.0. +* 1.9.3 - Sortie en octobre 2011. Il s'agit de la version que la majorité des + rubyists utilisent actuellement. [Fin de vie](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Sortie en juin 2006. [Fin de vie](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Les changements entre 1.8.7 à 1.9.x sont bien plus grands qu'entre 1.9.3 +jusqu'à 2.0.0. Par exemple, les versions 1.9 ont introduit le support des +encodages et d'une VM bytecode ([YARV](https://fr.wikipedia.org/wiki/YARV)). +Il y a toujours des projets sur 1.8.7, mais ils deviennent minoritaires, étant +donné que la majorité de la communauté a migré vers au moins 1.9.2 ou 1.9.3. + +## Implémentations Ruby + +L'écosystème Ruby comprend de nombreuses implémentations de Ruby, chacune avec +des points forts uniques et différents degrés de compatibilité. Les différentes +implémentations sont écrites dans différents languages. +Chaque implémentation a des "hooks" et des fonctionnalités spécifiques, elles +exécutent cependant très bien des fichiers Ruby classiques. +Par exemple, JRuby est écrit en Java, mais vous n'avez pas besoin de connaître +le Java pour l'utiliser. + +Très mature/compatible: + +* [MRI](https://github.com/ruby/ruby) - Ecrite en C, c'est l'implémentation de + référence de Ruby. Elle est par définition 100% compatible (avec elle-même). + Tous les autres rubies maintiennent la compatibilité avec MRI + (voir [RubySpec](#rubyspec) à la suite). +* [JRuby](http://jruby.org/) - Écrite en Java et Ruby, cette robuste + implémentation est assez rapide. + La force de JRuby réside surtout sur l'interopérabilité JVM/Java, faisant + levier sur des outils JVM, des projets et des langages existants. +* [Rubinius](http://rubini.us/) - Ecrite principalement en Ruby avec une VM + bytecode en C++. Egalement mature et rapide. Etant donné qu'elle est + implémentée en Ruby, elle couvre beaucoup de fonctionnalités de la + VM dans Ruby. + +Mpyennement mature/compatible: + +* [Maglev](http://maglev.github.io/) - Basée sur Gemstone, une VM Smalltalk. + Smalltalk possède quelques outils impressionnants, et ce projet tente + de les apporter dans le développement Ruby. +* [RubyMotion](http://www.rubymotion.com/) - Ruby pour développement iOS. +* [Opal](http://opalrb.org/) - Compile le Ruby en Javascript + +Les implémentations de Ruby peuvent avoir leurs propres numéros de versions, +mais elles ciblent toujours une versions spéficique de MRI pour la +compatibilité. +Beaucoup d'implémentations ont la capacité d'entrer dans différents modes +(par exemple, la version 1.8 ou 1.9) afin de spécifier quelle version de MRI +cibler. + +Une liste non exhaustive d'implémentations peut être trouvée [ici (EN)](https://github.com/cogitator/ruby-implementations/wiki/List-of-Ruby-implementations). + +## RubySpec + +La plupart des implémentations Ruby s'appuient fortement sur [RubySpec](http://rubyspec.org/). +Ruby n'a pas de spécification officielle, c'est pourquoi la commaunité a écrit +des spécifications exécutables en Ruby pour tester la compatibilité de leur +implémentation avec MRI. + +## RubyGems + +[RubyGems](http://rubygems.org/) est un gestionnaire de paquets communautaire +pour Ruby. +RubyGems est livré avec Ruby, il n'y a donc pas besoin de le télécharger +séparément. + +Les paquets Ruby sont appelés des "gems", et peuvent être hébergés par la +communauté à RubyGems.org. Chaque gem contient son code source et quelques +métadatas, includant des choses comme la version, les dépendances, +l(es) auteur(s) et la/les licence(s). + +## Bundler + +[Bundler](http://bundler.io/) est un résolveur de dépendances des gems. Il +utilise le Gemfile d'un projet ppur trouver les dépendances, et récupère +ensuite les dépendances de ces dépendances récursivement. Il déroule cet +algorithme jusqu'à ce que toutes les dépendances soient résolues et +téléchargées, ou s'arrête si un conflit est trouvé. + +Bundler lèvera une erreur s'il trouve des conflits de dépendances. Par exemple, +si la gem A recquiert la version 3 ou plus de gem Z, mais que gem B recquiert +seulement la version 2, Bundler vous notifiera ce conflict. Cela devient +extrêmement utile, étant donné que beaucoup de gems font référence à d'autres +gems (qui se réfèrent à d'autres gems), ce qui peut former un large graphe de +dépendance à résoudre. + +# Les tests + +Tester fait partie intégrante de la culture Ruby. Ruby fournit son propre +framework de tests unitaires appelé minitest (ou TestUnit pour Ruby +version 1.8.x). Il existe beaucoup de librairies de tests avec des buts +différents. + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Framework de tests intégré de Ruby version 1.8 style "Unit" +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Framework de tests intégré de Ruby version 1.9/2.0 +* [RSpec](http://rspec.info/) - Un framework de tests qui se focalise sur l'expressivité +* [Cucumber](http://cukes.info/) - Un framework de tests BDD ([behaviour-driven development](https://fr.wikipedia.org/wiki/Behavior_driven_development)) qui parse les tests formatés de Gherkin. + +## Soyez gentil + +La communauté Ruby est fière d'être une communauté ouverte, riche et +accueillante. Matz lui-même est extrêmement sociable, et la générosité des +rubyists est généralement remarquable. -- cgit v1.2.3 From a7eed36c1da2a16c7ced96e4d5fb0fb03bd94716 Mon Sep 17 00:00:00 2001 From: ven Date: Sat, 2 Jul 2016 12:43:15 +0200 Subject: fix #2295 --- elm.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/elm.html.markdown b/elm.html.markdown index fa10671f..dab2ab34 100644 --- a/elm.html.markdown +++ b/elm.html.markdown @@ -156,6 +156,7 @@ List.map (\a -> a * 2) [1..4] -- [2, 4, 6, 8] -- You can pattern match in function definitions when there's only one case. -- This function takes one tuple rather than two arguments. +-- This is the way you'll usually unpack/extract values from tuples. area (width, height) = width * height -- cgit v1.2.3 From 5dee671bfef8c4ab253a1992f03176b72948f226 Mon Sep 17 00:00:00 2001 From: Edmilson Lima Date: Sat, 2 Jul 2016 11:02:38 -0300 Subject: Update Dict and Set Syntax (#2296) --- julia.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/julia.html.markdown b/julia.html.markdown index 23d834f4..5b3f6fd8 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -255,7 +255,7 @@ e, d = d, e # => (5,4) # d is now 5 and e is now 4 empty_dict = Dict() # => Dict{Any,Any}() # You can create a dictionary using a literal -filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +filled_dict = Dict("one"=> 1, "two"=> 2, "three"=> 3) # => Dict{ASCIIString,Int64} # Look up values with [] @@ -305,7 +305,7 @@ in(10, filled_set) # => false other_set = Set([3, 4, 5, 6]) # => Set{Int64}(6,4,5,3) intersect(filled_set, other_set) # => Set{Int64}(3,4,5) union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) +setdiff(Set([1,2,3,4]),Set([2,3,5])) # => Set{Int64}(1,4) #################################################### @@ -346,7 +346,7 @@ end # cat is a mammal # mouse is a mammal -for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] +for a in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") println("$(a[1]) is a $(a[2])") end # prints: @@ -354,7 +354,7 @@ end # cat is a mammal # mouse is a mammal -for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] +for (k,v) in Dict("dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal") println("$k is a $v") end # prints: @@ -445,7 +445,7 @@ end # You can define functions that take keyword arguments function keyword_args(;k1=4,name2="hello") # note the ; - return ["k1"=>k1,"name2"=>name2] + return Dict("k1"=>k1,"name2"=>name2) end keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] -- cgit v1.2.3 From e053806775d18e14bb5de2adcdf8369d6566ce45 Mon Sep 17 00:00:00 2001 From: "J. Ryan Rembert" Date: Sun, 3 Jul 2016 01:47:57 -0700 Subject: [python/en] Set, dict, and generator comprehensions (#2298) * Add set and dict comprehensions for python 2 and 3 * Clean up formatting and generator explanation * Include documentation for generator comprehensions --- python.html.markdown | 50 ++++++++++++++++++++++++++++++++------------------ python3.html.markdown | 38 ++++++++++++++++++++++++-------------- 2 files changed, 56 insertions(+), 32 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 6c9da9a9..55f56071 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -8,21 +8,21 @@ contributors: filename: learnpython.py --- -Python was created by Guido Van Rossum in the early 90s. It is now one of the -most popular languages in existence. I fell in love with Python for its +Python was created by Guido Van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its syntactic clarity. It's basically executable pseudocode. -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) +Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reaching end of life and will stop being -maintained in 2020, it is though recommended to start learning Python with +Note: This article applies to Python 2.7 specifically, but should be applicable +to Python 2.x. Python 2.7 is reaching end of life and will stop being +maintained in 2020, it is though recommended to start learning Python with Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). -It is also possible to write Python code which is compatible with Python 2.7 +It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports -allow you to write Python 3 code that will run on Python 2, so check out the +allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. ```python @@ -549,6 +549,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + #################################################### ## 5. Classes @@ -668,10 +672,10 @@ import math dir(math) # If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. # This happens because the local folder has priority -# over Python's built-in libraries. +# over Python's built-in libraries. #################################################### @@ -679,44 +683,54 @@ dir(math) #################################################### # Generators -# A generator "generates" values as they are requested instead of storing +# A generator "generates" values as they are requested instead of storing # everything up front -# The following method (*NOT* a generator) will double all values and store it +# The following method (*NOT* a generator) will double all values and store it # in `double_arr`. For large size of iterables, that might get huge! def double_numbers(iterable): double_arr = [] for i in iterable: double_arr.append(i + i) -# Running the following would mean we'll double all values first and return all +# Running the following would mean we'll double all values first and return all # of them back to be checked by our condition for value in double_numbers(range(1000000)): # `test_non_generator` print value if value > 5: break -# We could instead use a generator to "generate" the doubled value as the item +# We could instead use a generator to "generate" the doubled value as the item # is being requested def double_numbers_generator(iterable): for i in iterable: yield i + i # Running the same code as before, but with a generator, now allows us to iterate -# over the values and doubling them one by one as they are being consumed by -# our logic. Hence as soon as we see a value > 5, we stop break out of the +# over the values and doubling them one by one as they are being consumed by +# our logic. Hence as soon as we see a value > 5, we break out of the # loop and don't need to double most of the values sent in (MUCH FASTER!) for value in double_numbers_generator(xrange(1000000)): # `test_generator` print value if value > 5: break -# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? +# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? # Just as `double_numbers_generator` is the generator version of `double_numbers` # We have `xrange` as the generator version of `range` # `range` would return back and array with 1000000 values for us to use # `xrange` would generate 1000000 values for us as we request / iterate over those items +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +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 diff --git a/python3.html.markdown b/python3.html.markdown index 7f3702e6..6b3486a6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -601,6 +601,10 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x 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 @@ -816,7 +820,7 @@ if __name__ == '__main__': sup.age = 100 print(sup.age) - # Inherited attribute from 2nd ancestor whose default value was overriden + # Inherited attribute from 2nd ancestor whose default value was overridden. print('Can I fly? ' + str(sup.fly)) @@ -825,29 +829,35 @@ if __name__ == '__main__': ## 7. Advanced #################################################### -# Generators help you make lazy code +# Generators help you make lazy code. def double_numbers(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -range_ = range(1, 900000000) -# will double all numbers until a result >=30 found -for i in double_numbers(range_): +# Generators are memory-efficient because they only load the data needed to +# process the next value in the iterable. This allows them to perform +# operations on otherwise prohibitively large value ranges. +# NOTE: `range` replaces `xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. print(i) if i >= 30: break +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +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 -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# In this example `beg` wraps `say`. If say_please is True then it +# will change the returned message. from functools import wraps -- cgit v1.2.3 From 1cab710b058b9a84bf13913263c26968098d3b10 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 6 Jul 2016 12:09:20 +0200 Subject: Attempt at #2299 --- ro-ro/bf-ro.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ro-ro/bf-ro.html.markdown b/ro-ro/bf-ro.html.markdown index 61b555ed..686dd39d 100644 --- a/ro-ro/bf-ro.html.markdown +++ b/ro-ro/bf-ro.html.markdown @@ -1,10 +1,11 @@ --- -language: brainfuck +language: bf contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Petru Dimitriu", "http://petru-dimitriu.github.io"] +filename: bf-ro.html lang: ro-ro --- @@ -87,4 +88,4 @@ Așadar acesta este limbajul brainfuck. Nu e atât de greu, nu? Pentru amuzament, puteți să scrieți propriile dumneavoastră limbaje, sau puteți scrie un interpretor pentru brainfuck într-un alt limbaj. Interpretorul este destul de ușor de implementat, dar dacă sunteți masochist, încercați -să implementați un interpretor de brainfuck… în brainfuck. \ No newline at end of file +să implementați un interpretor de brainfuck… în brainfuck. -- cgit v1.2.3 From b8e496eba15314e581c1280b1f55cd6e56740956 Mon Sep 17 00:00:00 2001 From: Nimit Shah Date: Fri, 8 Jul 2016 15:03:11 +0530 Subject: [Java/en] Adding a reference for treemap (#2300) * Adding a reference for treemap Adding reference for a treemap * Removing my name from the contributors list Removing my name from the contributors list as it requires a significant contribution to add my name to it. --- java.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index f65c484e..1f7d4115 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -232,6 +232,9 @@ public class LearnJava { // interface. This allows the execution time of basic // operations, such as get and insert element, to remain // constant even for large sets. + // TreeMap - This class is a sorted tree structure. It implements a red + // black tree and sorts the entries based on the key value or + // the comparator provided while creating the object /////////////////////////////////////// // Operators -- cgit v1.2.3 From 36ab227827c371721066ebfbc954ce3eaeaf2aa3 Mon Sep 17 00:00:00 2001 From: Nimit Shah Date: Fri, 8 Jul 2016 23:42:03 +0530 Subject: [CSS/en] Adding border related styleguides (#2301) * Adding border related styleguides Adding border related styleguides. Most of the modern designs have borders for their elements. * Spacing the comments like the rest of the file --- css.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/css.html.markdown b/css.html.markdown index 5dae06ca..fc07fce4 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -169,6 +169,13 @@ selector { 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 */ + border-width:5px; + 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 */ /* Images as backgrounds of elements */ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ -- cgit v1.2.3 From f1ac2a78aeca0c26f190dc2f79f4b3d29fe74b9f Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Sun, 10 Jul 2016 02:00:47 +0800 Subject: [java/id-id] ID translation (#2304) --- id-id/java-id.html.markdown | 801 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 801 insertions(+) create mode 100644 id-id/java-id.html.markdown diff --git a/id-id/java-id.html.markdown b/id-id/java-id.html.markdown new file mode 100644 index 00000000..a5455952 --- /dev/null +++ b/id-id/java-id.html.markdown @@ -0,0 +1,801 @@ +--- +language: java +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] +filename: LearnJava-id.java +translators: + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] +lang: id-id +--- + +Java adalah bahasa pemrograman yang memiliki tujuan umum dan berorientasi kelas dan objek. +[Baca lebih lanjut.](http://docs.oracle.com/javase/tutorial/java/) + +```java +// Komentar satu baris diawali dengan // (dua garis miring) +/* +Ini adalah contoh komentar banyak-baris. +*/ +/** +Ini adalah contoh komentar JavaDoc. Digunakan untuk mendeskripsikan sebuah kelas, +atau beberapa sifat dari kelas tersebut. +*/ + +// Menyertakan kelas ArrayList dalam paket java.util +import java.util.ArrayList; +// Menyertakan semua kelas yang ada dalam paket java.security +import java.security.*; + +// Setiap dokumen .java sebuah kelas publik dengan nama yang sama dengan nama kelas. +public class BelajarJava { + + // Untuk menjalankan program java, program harus memiliki sebuah method utama (main) sebagai awalan. + public static void main (String[] args) { + + // System.out.println() digunakan untuk menampilkan satu baris teks. + System.out.println("Halo Dunia!"); + System.out.println( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // System.out.print() hanya menampilkan teks tanpa baris baru. + System.out.print("Halo "); + System.out.print("Dunia"); + + // System.out.printf() memudahkan dalam mengatur format penampilan. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 + + /////////////////////////////////////// + // Variabel + /////////////////////////////////////// + + /* + * Deklarasi Variabel + */ + // Deklarasi variabel menggunakan format + int nilai; + // Deklarasi banyak variabel menggunakan format yang sama , , + int nilai1, nilai2, nilai3; + + /* + * Inisialisasi Variabel + */ + + // Inisialisasi sebuah variabel menggunakan = + int nilai = 1; + // Inisialisasi banyak variabel menggunakan format yang sama , , = + int nilai1, nilai2, nilai3; + nilai1 = nilai2 = nilai3 = 1; + + /* + * Tipe Variabel + */ + // Byte - 8 bit signed untuk bilangan bulat komplemen 2 + // (-128 <= byte <= 127) + byte nilaiByte = 100; + + // Short - 8 bit signed untuk bilangan bulat komplemen 2 + // (-32,768 <= short <= 32,767) + short nilaiShort = 10000; + + // Integer - 32 bit signed untuk bilangan bulat komplemen 2 + // (-2,147,483,648 <= int <= 2,147,483,647) + int nilaiInt = 1; + + // Long - 64 bit signed untuk bilangan bulat komplemen 2 + // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + long nilaiLong = 100000L; + // Karakter "L" pada akhir nilai menyatakan tipe Long; + // selainnya akan dianggap sebagai nilai bilangan bulat. + + // Catatan: Java tidak memiliki tipe unsigned. + + // Float - Presisi-satu 32-bit standar IEEE 754 untuk Floating Point + // 2^-149 <= float <= (2-2^-23) * 2^127 + float nilaiFloat = 234.5f; + // Karakter "f" atau "F" pada akhir nilai menyatakan tipe Float; + // selainnya akan dianggap sebagai nilai double. + + // Double - Presisi-dua 64-bit standar IEEE 754 untuk Floating Point + // 2^-1074 <= x <= (2-2^-52) * 2^1023 + double nilaiDouble = 123.4; + + // Boolean - true & false + boolean nilaiBoolean = true; + boolean nilaiBoolean = false; + + // Char - Sebuah karakter Unicode 16-bit + char nilaiChar = 'A'; + + // Variabel "final" tidak dapat di-set kembali nilainya pada objek lain, + final int WAKTU_SAYA_BEKERJA_TIAP_MINGGU = 9001; + // tapi dapat dilakukan inisialisasi diwaktu yang lain. + final double E; + E = 2.71828; + + + // BigInteger - Bilangan bulat yang memiliki presisi dinamis + // + // BigInteger adalah tipe data yang memungkinkan pembuat program untuk memanipulasi + // bilangan bulat lebih panjang dari 64-bit. Bilangan bulat tersebut tersimpan dalam + // bentuk kumpulan byte (array) dan dimanipulasi menggunakan fungsi yang sudah tersedia + // pada BigInteger + // + // BigInteger dapat diinisialisasi menggunakan kumpulan byte atau teks. + + BigInteger nilaiBigInteger = new BigInteger(kumpulanByte); + + + // BigDecimal - Bilangan signed desimal yang memiliki presisi dinamis + // + // Tipe BigDecimal memiliki dua bagian: sebuah bilangan bulat dengan nilai presisi + // dinamis tanpa skala dan sebuah bilangan bulat skala 32-bit. + + // BigDecimal memungkinkan pembuat program untuk memegang kontrol penuh + // terhadap batas desimal. BigDecimal baik digunakan untuk nilai tukar mata uang + // dimana sangat mementingkan presisi nilai desimal. + // + // BigDecimal dapat diinisialisasi dengan int, long, double, String, + // atau dengan melakukan inisialisasi nilai tanpa skala (BigInteger) + // dan nilai dengan skala (int). + + BigDecimal nilaiBigDecimal = new BigDecimal(nilaiBigInteger, nilaiInt); + + // Perlu diperhatikan konstruktor yang digunakan apakah float atau double + // karena dapat mengakibatkan ketidak-akurasian float/double yang akan digunakan + // dalam BigDecimal. Sebaiknya gunakan nilai String pada konstruktor + // jika membutuhkan nilai pasti. + + BigDecimal sepuluhSen = new BigDecimal("0.1"); + + + // Strings + String nilaiString1 = "Ini adalah contoh String!"; + + // Karakter \n berfungsi untuk membuat baris baru + String nilaiString2 = "Menampilkan baris baru?\nTidak masalah!"; + // Karakter \t berfungsi untuk membuat tab antar karakter + String nilaiString3 = "Ingin menambahkan sebuah tab?\tTidak masalah!"; + System.out.println(nilaiString1); + System.out.println(nilaiString2); + System.out.println(nilaiString3); + + // Larik (array) + // Ukuran array harus ditentukan ketika instansiasi + // Format berikut adalah beberapa cara deklarasi array + // [] = new []; + // [] = new []; + int[] barisAngka = new int[10]; + String[] barisString = new String[1]; + boolean barisBoolean[] = new boolean[100]; + + // Cara lain untuk mendeklarasikan dan menginisialisasi sebuah array + int[] y = {9000, 1000, 1337}; + String nama[] = {"Andi", "Budi", "Agus"}; + boolean bools[] = new boolean[] {true, false, false}; + + // Indeks sebuah array - Mengakses sebuah elemen + System.out.println("barisAngka @ 0: " + barisAngka[0]); + + // Array menggunakan indeks 0 yang tetap. + barisAngka[1] = 1; + System.out.println("barisAngka @ 1: " + barisAngka[1]); // => 1 + + // Lainnya yang perlu diketahui + // ArrayLists - Sama seperti array biasa, namum penggunaannya sudah ditentukan, + // dan ukurannya dapat berubah-ubah. + // LinkedLists - Implementasi dari doubly-linked list. Semua operasi yang digunakan + // hampir sama dengan operasi yang dimiliki oleh sebuah doubly-linked list. + // Maps - Sebuah kumpulan objek yang menyatakan hubungan antara kunci dan nilai. Map merupakan + // sebuah interface sehingga tidak dapat diinstansiasi. Jenis kunci dan nilai yang digunakan + // pada Map harus spesifik pada saat instansiasi ketika diimplementasikan pada sebuah kelas. + // Setiap kunci hanya memiliki sebuah nilai, dan hanya muncul sekali. + // HashMaps - Kelas ini menggunakan tabel-hash untuk mengimplementasikan interface Map. + // Hal ini memungkinkan waktu eksekusi ketika melakukan operasi dasar (mengakses + // dan menambahkan elemen) menjadi konstan, meskipun memiliki banyak set data. + + /////////////////////////////////////// + // Operator + /////////////////////////////////////// + System.out.println("\n->Operator"); + + int i1 = 1, i2 = 2; // Cara singkat untuk deklarasi banyak nilai + + // Kemudahan dalam artimatika + System.out.println("1+2 = " + (i1 + i2)); // => 3 + System.out.println("2-1 = " + (i2 - i1)); // => 1 + System.out.println("2*1 = " + (i2 * i1)); // => 2 + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int menghasilkan int juga) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 + + // Modulus + System.out.println("11%3 = "+(11 % 3)); // => 2 + + // Operator Perbandingan + System.out.println("3 == 2? " + (3 == 2)); // => false + System.out.println("3 != 2? " + (3 != 2)); // => true + System.out.println("3 > 2? " + (3 > 2)); // => true + System.out.println("3 < 2? " + (3 < 2)); // => false + System.out.println("2 <= 2? " + (2 <= 2)); // => true + System.out.println("2 >= 2? " + (2 >= 2)); // => true + + // Operator Boolean + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + + // Operator Bitwise + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed/Arithmetic right shift + >>> Unsigned/Logical right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Peningkatan + int i = 0; + System.out.println("\n->Pengurangan/Peningkatan"); + // Operator ++ dan -- masing-masing melakukan peningkatan dan penurunan 1 nilai. + // Jika diletakkan sebelum variabel, maka akan di tambah/kurang 1 sebelum dilakukan perintah lainnya; + // jika setelah variabel, maka akan ditambah/kurang 1 setelah dilakukan perintah lainnya; + System.out.println(i++); // i = 1, prints 0 (peningkatan setelahnya) + System.out.println(++i); // i = 2, prints 2 (peningkatan sebelumnya) + System.out.println(i--); // i = 1, prints 2 (pengurangan setelahnya) + System.out.println(--i); // i = 0, prints 0 (pengurangan sebelumnya) + + /////////////////////////////////////// + // Struktur Kontrol + /////////////////////////////////////// + System.out.println("\n->Struktur Kontrol"); + + // Perintah "if" hampir sama dengan bahasa C + int j = 10; + if (j == 10) { + System.out.println("Saya ditampilkan"); + } else if (j > 10) { + System.out.println("Saya tidak ditampilkan"); + } else { + System.out.println("Saya juga tidak ditampilkan"); + } + + // Perulangan "while" + int fooWhile = 0; + while(fooWhile < 100) { + System.out.println(fooWhile); + // Tingkatkan penghitung + // 100 kali iterasi, fooWhile 0,1,3,...,99 + fooWhile++; + } + System.out.println("Nilai fooWhile: " + fooWhile); + + // Perulangan "do...while" + int fooDoWhile = 0; + do { + System.out.println(fooDoWhile); + // Tingkatkan penghitung + // 99 kali iterasi, fooDoWhile 0->99 + fooDoWhile++; + } while(fooDoWhile < 100); + System.out.println("Nilai fooDoWhile: " + fooDoWhile); + + // Perulangan "for" + // Struktur perulangan "for" => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // 10 kali iterasi, foofor 0-9 + } + System.out.println("Nilai fooFor: " + fooFor); + + // Perulangan "for" bertingkat dengan label "exit" + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // Menghentikan semua perulangan, tidak hanya perulangan bagian dalam saja + } + } + } + + // Perulangan "for each" + // Perulangan "for" juga dapat melakukan iterasi terhadap larik (array) dari objek + // yang mana mengimplementasikan interface Ieterable. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // Struktur perulangan "for each" => for ( : ) + // dibaca: setiap elemen dalam iterable + // catatan: tipe objek harus sama dengan tipe iterable + + for (int bar : fooList) { + System.out.println(bar); + // Melakukan interasi sebanyak 9 kali dan menampilkan 1-9 tiap baris + } + + // "switch case" + // "switch" dapat digunakan pada byte, short, char, dan tipe data bilangan bulat (int). + // "switch" juga dapat digunakan pada tipe "enum" (dijelaskan nanti), kelas String, + // dan beberapa kelas khusus yang mengandung tipe data primitif: + // Character, Byte, Short, dan Integer. + int bulan = 3; + String bulanString; + switch (bulan) { + case 1: bulanString = "Januari"; + break; + case 2: bulanString = "Februari"; + break; + case 3: bulanString = "Maret"; + break; + default: bulanString = "Bulan lainnya"; + break; + } + System.out.println("Hasil switch case: " + bulanString); + + // Mulai dari Java 7 keatas, "switch" memiliki format: + String jawabanSaya = "mungkin"; + switch(jawabanSaya) { + case "ya": + System.out.println("Anda menjawab ya."); + break; + case "tidak": + System.out.println("Anda menjawab tidak."); + break; + case "mungkin": + System.out.println("Anda menjawab mungkin."); + break; + default: + System.out.println("Anda menjawab " + jawabanSaya); + break; + } + + // Pengkondisian dengan cara singkat + // Karakter '?' dapat digunakan untuk penilaian atau logika secara cepat antara dua pernyataan. + // Dibaca "Jika (pernyataan) adalah benar, gunakan , sisanya gunakan + int foo = 5; + String bar = (foo < 10) ? "A" : "B"; + System.out.println(bar); // Menampilkan A, karena pernyataannya benar + + + //////////////////////////////////////// + // Konversi Data dan Tipe Data (Typecasting) + //////////////////////////////////////// + + // Konversi Data + + // Konversi String ke Integer + Integer.parseInt("123"); // menghasilkan nilai versi Integer dari "123" + + // Konversi Integer ke String + Integer.toString(123); // menghasilkan nilai versi String dari 123 + + // Untuk konversi lainnya silakan coba kelas berikut: + // Double + // Long + // String + + // Typecasting + // Objek dalam Java juga dapat dikonversi, banyak penjelasan dan aturan + // dengan beberapa konsep sederhana. Silakan cek di alamat berikut: + // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html + + + /////////////////////////////////////// + // Kelas dan Fungsi + /////////////////////////////////////// + + System.out.println("\n->Kelas & Fungsi"); + + // (penjelasan mengenai kelas "Sepeda" ada dibawah) + + // Gunakan "new" untuk melakukan instansiasi pada kelas + Sepeda laju = new Sepeda(); + + // Memanggil method objek + laju.tambahKecepatan(3); // Dapat juga digunakan "setter" dan "getter" method + laju.setIrama(100); + + // Method "toString()" menghasilkan representasi string dari objek. + System.out.println("informasi jalur: " + laju.toString()); + + // Dua Pasang Inisialisasi + // Bahasa Java tidak memiliki sintaks untuk membuat koleksi dari "static" sekaligus + // dengan mudah, kecuali dengan cara berikut: + + private static final Set NEGARA = new HashSet(); + static { + validCodes.add("INDONESIA"); + validCodes.add("MALAYSIA"); + validCodes.add("SINGAPURA"); + } + + // Terdapat cara yang baik untuk menulis skrip dengan mudah, + // dengan menggunakan Dua-Kurung Kurawal Inisialisasi (Double Brace Initialization) + + private static final Set NEGARA = new HashSet() {{ + add("INDONESIA"); + add("MALAYSIA"); + add("SINGAPURA"); + }} + + // Kurung kurawal yang pertama membuat sebuah AnonymousInnerClas + // dan kurung kurawal yang kedua mendeklarasikan instance dari blok + // inisialisasi. Blok ini kemudian dipanggil ketika InnerClass dibentuk. + // Cara ini tidak hanya berfungsi pada koleksi data, juga dapat digunakan + // pada semua kelas bukan-"final". + + } // Akhir dari method utama +} // Akhir dari kelas BelajarJava + + +// Kelas bukan-"public" lainnya dapat dimasukkan kedalam satu dokumen .java, +// namun tidak dianjurkan, sebaiknya memisahkan menjadi beberapa dokumen terpisah. + +// Sintaks pendeklarasian kelas: +// class { +// // isi data, konstruktor, dan fungsi. +// // dalam Java, fungsi biasa disebut juga "method" +// } + +class Sepeda { + + // Variabel dari kelas Sepeda + public int irama; // Public: dapat diakses dari manapun + private int kecepatan; // Private: hanya dapat diakses dari dalam kelas + protected int rodaGigi; // Protected: dapat diakses dari dalam kelas dan turunan kelas + String nama; // Default: hanya dapat diakses kelas yang berada dalam paket yang sama + + static String namaKelas; // Variabel "static" + + // Blok Static + // Java tidak memiliki implementasi untuk konstruktor "static", namun + // memiliki blok status yang dapat digunakan untuk inisialisasi variabel + // dalam kelas (variabel "static"). + // Blok ini akan dipanggil secara otomatis ketika kelas dijalankan. + static { + namaKelas = "Sepeda"; + } + + // Konstruktor adalah salah satu cara untuk membuat kelas + // Ini adalah bagian konstruktor + public Sepeda() { + // Dapat juga dipanggil konstruktor lainnya: + // this(1, 50, 5, "Bontrager"); + rodaGigi = 1; + irama = 50; + kecepatan = 5; + nama = "Bontrager"; + } + + // Ini adalah bagian konstruktor yang menggunakan argumen (parameter) + public Sepeda(int iramaAwal, int kecepatanAwal, int rodaGigiAwal, + String nama) { + this.rodaGigi = rodaGigiAwal; + this.irama = iramaAwal; + this.kecepatan = kecepatanAwal; + this.nama = nama; + } + + // Sintaks untuk method: + // () + + // Kelas Java terkadang mengimplementasikan "getters" dan "setters" untuk data. + + // Sintaks untuk deklarasi method: + // () + public int getIrama() { + return irama; + } + + // Tipe "void" tidak memiliki kembalian (return) nilai + public void setIrama(int nilaiBaru) { + irama = nilaiBaru; + } + + public void setRodaGigi(int nilaiBaru) { + rodaGigi = nilaiBaru; + } + + public void tambahKecepatan(int nilaiTambahan) { + kecepatan += nilaiTambahan; + } + + public void kurangiKecepatan(int nilaiPengurangan) { + kecepatan -= nilaiPengurangan; + } + + public void setNama(String namaBaru) { + nama = namaBaru; + } + + public String getNama() { + return nama; + } + + // Method untuk menampilkan nilai dari tiap atribut yang dimiliki objek Sepeda. + @Override // Diturunkan dari kelas "Object" (Pustaka Java). + public String toString() { + return "roda gigi: " + rodaGigi + " irama: " + irama + " kecepatan: " + kecepatan + + " nama: " + nama; + } +} // akhir dari kelas Sepeda + +// PennyFarthing adalah kelas turunan dari Sepeda +class PennyFarthing extends Sepeda { + // (Penny Farthings adalah sepeda dengan roda depan yang besar, + // dan tidak memiliki roda gigi.) + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + public PennyFarthing(int startCadence, int startSpeed) { + // Call the parent constructor with super + super(startCadence, startSpeed, 0, "PennyFarthing"); + } + + // You should mark a method you're overriding with an @annotation. + // To learn more about what annotations are and their purpose check this + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ + @Override + public void setRodaGigi(int rodaGigi) { + roda rodaGigi = 0; + } +} + +// Interfaces +// Sintaks untuk deklarasi Interface +// interface extends { +// // Konstan +// // Deklarasi method +// } + +// Contoh - Makanan: +public interface dapatDimakan { + public void makan(); // Setiap kelas yang menggunakan interface "dapatDimakan", + // harus mengimplementasikan method "makan". +} + +public interface dapatDicerna { + public void cerna(); +} + + +// Membuat kelas dengan mengimplementasikan dua interface dalam satu waktu. +public class Buah implements dapatDimakan, dapatDicerna { + + @Override + public void makan() { + // ... + } + + @Override + public void cerna() { + // ... + } +} + +// Dalam Java, kelas hanya dapat diturunkan sekali, tapi dapat mengimplementasikan +// banyak interface. Contoh: +public class ContohKelas extends ContohKelasInduk implements InterfaceSatu, + InterfaceDua { + + @Override + public void MethodInterfaceSatu() { + } + + @Override + public void MethodInterfaceDua() { + } + +} + +// Kelas Abstrak (Abstract) +// Sintaks untuk deklarasi kelas abstrak +// Abstract Class declaration syntax +// abstract extends { +// // Konstan dan variabel +// // Deklarasi method + +// Menjadikan kelas sebagai abstrak adalah memungkinkan kelas berisi method abstrak +// yang harus didefinisikan pada kelas turunannya. Mirip dengan Interface, kelas abstrak +// tidak dapat dilakukan instansiasi, namun harus diturunkan pada kelas lain dan method abstrak +// harus didefinisikan. Perbedaannya dengan Interface ialah kelas abstrak dapat berisi method +// kongkrit dan method abstrak. Pada Interface method tidak dapat memiliki isi, artinya hanya +// method statis, dan variabel langsung ditentukan menjadi final, tidak seperti kelas abstrak. +// Kelas abstrak juga dapat memiliki method "main". + +public abstract class Hewan +{ + public abstract void bersuara(); + + // Method biasa dapat memiliki isi + public void makan() + { + System.out.println("Saya adalah hewan dan Saya makan."); + // Catatan: Kita dapat mengakses variabel private yang ada disini. + umur = 30; + } + + // Tidak perlu dilakukan inisialisasi, berbeda dengan Interface + // sebuah variabel adalah final dan harus dilakukan inisialisasi. + protected int umur; + + public void tampilkanUmur() + { + System.out.println(umur); + } + + // Kelas abstrak dapat memiliki fungsi utama (main). + public static void main(String[] args) + { + System.out.println("Saya adalah kelas abstrak!"); + } +} + +class Kucing extends Hewan +{ + // Catatan: kelas ini harus melakukan override method abstrak + // yang ada pada kelas abstrak (induk). + @Override + public void bersuara() + { + System.out.println("Moe"); + // umur = 30; ==> ERROR! umur merupakan variabel private pada abstrak Hewan + } + + // CATATAN: Akan muncul error jika menggunakan + // keterangan @Override pada method utama (main), + // Java tidak mengizinkan hal tersebut. + // Kejadian ini sering disebut sebagai METHOD HIDING. + // Pertanyaan-jawaban yang menarik dapat dilihat: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Kucing moe = new Kucing(); + noe.bersuara(); + moe.makan(); + moe.tampilkanUmur(); + } +} + +// Kelas Final + +// Sintaks untuk deklarasi kelas Final +// final { +// // Konstann dan variabel +// // Deklarasi method +// } + +// Kelas Final merupakan kelas yang tidak dapat diturunkan sehingga menjadikan +// method tersebut turunan method terakhir. Disisi lain, kelas final merupakan +// lawan dari kelas abstrak karena kelas abstrak dapat diturunkan lagi, sedangkan +// kelas final tidak dapat diturunkan lagi. +public final class Serigala extends Hewan +{ + // Catatan: method abstrak harus di-override pada kelas abstrak. + @Override + public void bersuara() + { + System.out.println("Auuww"); + } +} + +// Method Final +public abstract class Mamalia() +{ + // Sintaks untuk method final: + // final () + + // Method final, seperti kelas final tidak dapat di-override oleh kelas turunan, + // sehingga menjadikannya implementasi terakhir dari method. + public final boolean apakahBerdarahDingin() + { + return true; + } +} + + +// Tipe Enum +// +// Tipe Enum merupakan tipe data spesial yang memungkinkan sebuah nilai dijadikan +// konstan awal (predefined). Variabel setidaknya harus memiliki nilai yang sama +// dengan salah satu dari enum-enum yang telah ditentukan. Karena nilainya merupakan +// konstan, untuk itu penamaannya menggunakan huruf kapital (uppercase). Dalam Java, +// Enum didefinisikan dengan kata kunci "enum". Contohnya nama-nama hari dalam semunggu: + +public enum Hari { + SENIN, SELASA, RABU, KAMIS, + JUMAT, SABTU, MUNGGU +} + +// Cara menggunakan Enum: +public class CobaEnum { + + // Variabel Enum + Hari hari; + + // Konstruktor + public CobaEnum(Hari hari) { + this.hari = hari; + } + + public void tampilkanKeterangan() { + switch (day) { + case SENIN: + System.out.println("Senin adalah hari yang menyebalkan."); + break; + + case JUMAT: + System.out.println("Jumat adalah hari yang singkat."); + break; + + case SABTU: + case MINGGU: + System.out.println("Akhir pekan adalah hari yang menyenangkan."); + break; + + default: + System.out.println("Hari kerja yang biasa saja."); + break; + } + } + + public static void main(String[] args) { + CobaEnum hariPertama = new CobaEnum(Hari.SENIN); + hariPertama.tampilkanKeterangan(); // Senin adalah hari yang menyebalkan. + CobaEnum hariKetiga = new CobaEnum(Hari.RABU); + hariPertama.tampilkanKeterangan(); // Hari kerja yang biasa saja. + } +} + +// Tipe enum memiliki banyak kegunaan selain yang dicontohkan diatas. +// Tipe enum dapat memiliki isi seperti method dan variabel. +// Penjelasan lebih detail di https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + +``` + +## Referensi Lainnya + +Link-link berikut hanya menyediakan pemahaman lebih lanjut mengenai topik diatas. +Tip, trik, dan contoh lainnya dapat melakukan pencarian melalui Google atau mesin pencari yang lain. + +**Panduan resmi Oracle** + +* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html) + +* [Java Access level modifiers](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) + +* [Object-Oriented Programming Concepts](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): + * [Inheritance](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) + * [Polymorphism](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) + * [Abstraction](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) + +* [Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) + +* [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) + +* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) + +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) + +**Tutorial dan Praktik Online** + +* [Learneroo.com - Learn Java](http://www.learneroo.com) + +* [Codingbat.com](http://codingbat.com/java) + + +**Buku**: + +* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) + +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + +* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) + +* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) -- cgit v1.2.3 From 56b3d98321eb4f48ffd06077d07e5208d8481ea2 Mon Sep 17 00:00:00 2001 From: Ahmad Zafrullah Date: Sun, 10 Jul 2016 02:39:03 +0800 Subject: [json/id-id] update changes for ID translation (#2305) * [json/id-id] update changes for ID translation * [json/id-id] update reference info --- id-id/json-id.html.markdown | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown index ca346f6c..eef48c63 100644 --- a/id-id/json-id.html.markdown +++ b/id-id/json-id.html.markdown @@ -1,20 +1,32 @@ --- language: json -filename: learnjson-id.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] -translators: +filename: learnjson-id.json +translators - ["Rizky Luthfianto", "https://github.com/rilut"] + - ["Ahmad Zafrullah", "https://github.com/23Pstars"] lang: id-id --- -JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar, -ini adalah "Learn X in Y Minutes" yang paling singkat. +JSON adalah format pertukaran data yang sangat sederhana. Sebagaimana dikutip dari [json.org](http://json.org), JSON mudah untuk dibaca atau ditulis oleh manusia, dan mudah diuraikan dan diproses oleh mesin. + +Sebuah format JSON setidaknya memiliki: +* Sebuah pasangan nama atau nilai dinyatakan dengan karakter (`{ }`). Dibeberapa bahasa pemrograman, karakter ini sering digunakan sebagai object, record, struct, dictionary, hash table, keyed list, atau associative array. +* Daftar nilai dinyatakan dengan karakter (`[ ]`). Dibeberapa bahasa pemrograman, karakter ini sering digunakan sebagai array, vector, list, atau sequence. + +Format JSON murni tidak memiliki komentar, namun beberapa pengurai (parser) dapat mengenali komentar seperti yang digunakan oleh bahasa C (`//`, `/**/`). Beberapa pengurai lainnya juga memiliki toleransi terhadap akhiran sisa koma (seperti koma yang terdapat pada akhir elemen dari larik atau properti terakhir dari objek), tapi koma tersebut memang seharusnya diabaikan untuk dukungan yang lebih baik. -Murninya, JSON tidak mempunyai fitur komentar, tapi kebanyakan parser akan -menerima komentar bergaya bahasa C (`//`, `/* */`). Namun, pada halaman ini, -hanya dicontohkan JSON yang 100% valid. +Dalam tutorial ini, semuanya menggunakan format JSON murni. + +Tipe data yang didukung oleh JSON: + +* Teks: `"halo"`, `"\"tanda petik.\""`, `"\u0abe"`, `"baris baru.\n"` +* Angka: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Objek: `{ "kunci": "nilai" }` +* Larik: `["nilai"]` +* Lainnya: `true`, `false`, `null` ```json { @@ -59,3 +71,7 @@ hanya dicontohkan JSON yang 100% valid. "singkat": "Dan Anda selesai! Sekarang Anda tahu apa saja yang disediakan oleh JSON." } ``` + +## Referensi lebih labjut + +* [JSON.org](http://json.org/json-id.html) semua keindahan JSON dijelaskan dalam bentuk alur-grafis (bahasa indonesia). -- cgit v1.2.3 From b16c7ee2d8b41b5db4f713360280c284ca9b1a80 Mon Sep 17 00:00:00 2001 From: Leo Rudberg Date: Sun, 10 Jul 2016 02:04:08 -0500 Subject: [bash/en] Addition to bash (#2302) * Added bash intro edits * Fixed page header * Finalizing updates Implemented my changes in the main bash code chunk instead of as an out-of-code prologue * Final touches * Added citation for John and mkdir content * Added removed original intro back in * Update bash.html.markdown Moved "hard way" link to top of article Fixed spacing Grouped `rm` commands * Fixed typos --- bash.html.markdown | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/bash.html.markdown b/bash.html.markdown index a62bd167..b1a14bdb 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -11,7 +11,10 @@ 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"] filename: LearnBash.sh --- @@ -20,6 +23,8 @@ Nearly all examples below can be a part of a shell script or executed directly i [Read more here.](http://www.gnu.org/software/bash/manual/bashref.html) +Another recommened link: [The Command Line Crash Course](http://cli.learncodethehardway.org/book/) + ```bash #!/bin/bash # First line of the script is shebang which tells the system how to execute @@ -90,6 +95,21 @@ echo "Number of arguments passed to script: $#" echo "All arguments passed to script: $@" echo "Script's arguments separated into different variables: $1 $2..." +# Now that we know how to echo and use variables, +# let's learn some of the other basics of bash! + +# Getting our current directory is available through the command `pwd`. +# `pwd` stands for "print working directory". +# We can also use the builtin variable `$PWD`. +# Observer that the following are equivalent: +echo "I'm in $(pwd)" # execs `pwd` and interpolates output +echo "I'm in $PWD" # interpolates the variable + +# If you get too much output in your terminal, or from a script, the command +# `clear` clears your screen +clear +# Ctrl-L also works for clearing output + # Reading a value from input: echo "What's your name?" read Name # Note that we didn't need to declare a new variable @@ -138,12 +158,37 @@ ls # These commands have options that control their execution: ls -l # Lists every file and directory on a separate line +ls -t # Sort the directory contents by last-modified date (descending) +ls -R # Recursively `ls` this directory and all of its subdirectories # Results of the previous command can be passed to the next command as input. # grep command filters the input with provided patterns. That's how we can list # .txt files in the current directory: ls -l | grep "\.txt" +# Use `cat` to print files to stdout: +cat file.txt + +# We can also read the file using `cat`: +Contents=$(cat file.txt) +echo "START OF FILE\n$Contents\nEND OF FILE" + +# Use `cp` to copy files or directories from one place to another. +# `cp` creates NEW versions of the sources, +# so editing the copy won't affect the original (and vice versa). +# Note that it will overwrite the destination if it already exists. +cp srcFile.txt clone.txt +cp -r srcDirectory/ dst/ # recursively copy + +# Look into `scp` or `sftp` if you plan on exchanging files between computers. +# `scp` behaves very similarly to `cp`. +# `sftp` is more interactive. + +# Use `mv` to move files or directories from one place to another. +# `mv` is similar to `cp`, but it deletes the source. +# `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 # run your command in some other directory. We have cd for changing location: cd ~ # change to home directory @@ -152,6 +197,14 @@ cd .. # go up one directory cd /home/username/Documents # change to specified directory cd ~/Documents/.. # still in home directory..isn't it?? +# Use subshells to work across directories +(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD") +pwd # still in first directory + +# Use `mkdir` to create new directories. +mkdir myNewDir +# The `-p` flag causes new intermediate directories to be created as necessary. +mkdir -p myNewDir/with/intermediate/directories # You can redirect command input and output (stdin, stdout, and stderr). # Read from stdin until ^EOF$ and overwrite hello.py with the lines @@ -191,7 +244,9 @@ echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out >/dev/null # Cleanup temporary files verbosely (add '-i' for interactive) +# WARNING: `rm` commands cannot be undone rm -v output.out error.err output-and-error.log +rm -r tempDir/ # recursively delete # Commands can be substituted within other commands using $( ): # The following command displays the number of files and directories in the @@ -282,6 +337,13 @@ sed -i 's/okay/great/g' file.txt grep "^foo.*bar$" file.txt # pass the option "-c" to instead print the number of lines matching the regex grep -c "^foo.*bar$" file.txt +# Other useful options are: +grep -r "^foo.*bar$" someDir/ # recursively `grep` +grep -n "^foo.*bar$" file.txt # give line numbers +grep -rI "^foo.*bar$" someDir/ # recursively `grep`, but ignore binary files +# perform the same initial search, but filter out the lines containing "baz" +grep "^foo.*bar$" file.txt | grep -v "baz" + # if you literally want to search for the string, # and not the regex, use fgrep (or grep -F) fgrep "foobar" file.txt @@ -290,6 +352,11 @@ fgrep "foobar" file.txt # Here trap command will execute rm if any one of the three listed signals is received. trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM +# `sudo` is used to perform commands as the superuser +$NAME1=$(whoami) +$NAME2=$(sudo whoami) +echo "Was $NAME1, then became more powerful $NAME2" + # Read Bash shell builtins documentation with the bash 'help' builtin: help help help -- cgit v1.2.3 From e249d12ee6fdc9366e6d13b869f2ca2ccff6ee56 Mon Sep 17 00:00:00 2001 From: Ryan Plant Date: Tue, 12 Jul 2016 18:07:38 +1000 Subject: Elixir agents/maps, Ruby conventions/docs (#2116) * Add name to contributors list * Fix typo * Note convention on curly-braced blocks * Replace hardcoded link to 2.1.1 documentation with generic current link * Add notes on Elixir agents * Add explanation of maps * Add name to contributors list * Fix code fence that was obscuring markdown * Fix syntax error * Remove disputed comment * Remove from contributors list --- elixir.html.markdown | 26 ++++++++++++++++++++++++++ ruby.html.markdown | 4 ++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index eb708576..26a547c3 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -3,6 +3,7 @@ language: elixir contributors: - ["Joao Marques", "http://github.com/mrshankly"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Ryan Plant", "https://github.com/ryanplant-au"] filename: learnelixir.ex --- @@ -96,6 +97,14 @@ string. lower..upper = 1..10 # Can use pattern matching on ranges as well [lower, upper] #=> [1, 10] +# Maps are key-value pairs +genders = %{"david" => "male", "gillian" => "female"} +genders["david"] #=> "male" + +# Maps with atom keys can be used like this +genders = %{david: "male", gillian: "female"} +genders.gillian #=> "female" + ## --------------------------- ## -- Operators ## --------------------------- @@ -407,6 +416,23 @@ send pid, {:circle, 2} # The shell is also a process, you can use `self` to get the current pid self() #=> #PID<0.27.0> + +## --------------------------- +## -- Agents +## --------------------------- + +# An agent is a process that keeps track of some changing value + +# Create an agent with `Agent.start_link`, passing in a function +# The initial state of the agent will be whatever that function returns +{ok, my_agent} = Agent.start_link(fn -> ["red, green"] end) + +# `Agent.get` takes an agent name and a `fn` that gets passed the current state +# Whatever that `fn` returns is what you'll get back +Agent.get(my_agent, fn colors -> colors end) #=> ["red, "green"] + +# Update the agent's state the same way +Agent.update(my_agent, fn colors -> ["blue" | colors] end) ``` ## References diff --git a/ruby.html.markdown b/ruby.html.markdown index adf5ce81..a1532855 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -210,7 +210,7 @@ array.push(6) #=> [1, 2, 3, 4, 5, 6] # Check if an item exists in an array array.include?(1) #=> true -# Hashes are Ruby's primary dictionary with keys/value pairs. +# Hashes are Ruby's primary dictionary with key/value pairs. # Hashes are denoted with curly braces: hash = { 'color' => 'green', 'number' => 5 } @@ -612,7 +612,7 @@ Something.new.qux # => 'qux' - [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. - [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials. -- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Official Documentation](http://ruby-doc.org/core) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) - [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. -- cgit v1.2.3 From 8f99c7ab7ef071979d6143ad0cf53576c1a970e0 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 12 Jul 2016 19:14:38 +0200 Subject: fix #2308 --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index e41e71c3..2b599378 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -20,7 +20,7 @@ Multi-line comments look like this */ // XCode supports pragma mark directive that improve jump bar readability -#pragma mark Navigation Functions // New tag o@"Third number = %@", thirdNumber); // prin jump bar named 'Navigation Functions' +#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions' #pragma mark - Navigation Functions // Same tag, now with a separator // Imports the Foundation headers with #import -- cgit v1.2.3 From c1a258ba9f64f648f529b8ab4ac3f5560675d322 Mon Sep 17 00:00:00 2001 From: Chris Warren-Smith Date: Sat, 16 Jul 2016 20:59:31 +1000 Subject: [smallbasic/en] New article about SmallBASIC (#2311) * [smallbasic/en] new article * [smallbasic/en] new article --- smallbasic.html.markdown | 124 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 124 insertions(+) create mode 100644 smallbasic.html.markdown diff --git a/smallbasic.html.markdown b/smallbasic.html.markdown new file mode 100644 index 00000000..007f9591 --- /dev/null +++ b/smallbasic.html.markdown @@ -0,0 +1,124 @@ +--- +language: SmallBASIC +filename: learnsmallbasic.bas +contributors: + - ["Chris Warren-Smith", "http://smallbasic.sourceforge.net"] +--- + +## About + +SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for everyday calculations, scripts and prototypes. SmallBASIC includes trigonometric, matrices and algebra functions, a built in IDE, a powerful string library, system, sound, and graphic commands along with structured programming syntax. + +## Development + +SmallBASIC was originally developed by Nicholas Christopoulos in late 1999 for the Palm Pilot. Project development has been continued by Chris Warren-Smith since around 2005. + +Versions of SmallBASIC have been made for a number of early hand held devices including Franklin eBookman and the Nokia 770. Also various desktop releases have been released based on a variety of GUI tool-kits, some of which have become defunct. The current supported platforms are Linux and Windows based on SDL2 and Android based on NDK. + +In late 2000's a large corporation released a BASIC like programming environment with a similar sounding name. SmallBASIC is not related to this other project. + +``` +REM This is a comment +' and this is also a comment + +REM print text +print "hello" +? "? is short for PRINT" + +REM Control structures +FOR index = 0 TO 10 STEP 2 + ? "This is line number "; index +NEXT +J=0 +REPEAT + J++ +UNTIL J=10 +WHILE J>0 + J-- +WEND + +REM Select case statement +Select Case "Cool" + Case "null", 1,2,3,4,5,6,7,8,"Cool","blah" + Case "Not cool" + PRINT "Epic fail" + Case Else + PRINT "Fail" +End Select + +REM catching errors with TRY/CATCH +Try + fn = Freefile + Open filename For Input As #fn +Catch err + Print "failed to open" +End Try + +REM User defined subs and functions +func add2(x,y) + ' variables may be declared as local within the scope of a SUB or FUNC + local K + k = "k will cease to exist when this FUNC returns" + add2=x+y +end +Print add2(5,5) +sub print_it(it) + print it +end +print_it "IT...." + +REM Display lines and pixels +At 0,ymax/2+txth("Q") +Color 1: ? "sin(x)": +Color 8: ? "cos(x)": +Color 12: ? "tan(x)" +Line 0,ymax/2,xmax,ymax/2 +For i=0 to xmax + Pset i,ymax/2-sin(i*2*pi/ymax)*ymax/4 color 1 + Pset i,ymax/2-cos(i*2*pi/ymax)*ymax/4 color 8 + Pset i,ymax/2-tan(i*2*pi/ymax)*ymax/4 color 12 +Next +showpage + +REM SmallBASIC is great for experimenting with fractals and other interesting effects +Delay 3000 +Randomize +ff = 440.03 +For j = 0 to 20 + r = rnd * 1000 % 255 + b = rnd * 1000 % 255 + g = rnd * 1000 % 255 + c = rgb(r,b,g) + ff += 9.444 + for i=0 to 25000 + f += ff + x = min(xmax, -x + cos(f*i)) + y = min(ymax, -y + sin(f*i)) + pset x, y color c + if (i%1000==0) then + showpage + fi + next +Next j + +REM For computer historians, SmallBASIC can run programs +REM found in early computer books and magazines, for example: +10 LET A=9 +20 LET B=7 +30 PRINT A*B +40 PRINT A/B + +PAUSE + +``` + +## Articles + +* [Getting started](http://smallbasic.sourceforge.net/?q=node/1573) +* [Welcome to SmallBASIC](http://smallbasic.sourceforge.net/?q=node/838) + +## GitHub + +* [Source code](https://github.com/smallbasic/SmallBASIC) +* [Reference snapshot](http://smallbasic.github.io/) + -- cgit v1.2.3 From a4db2f20120aa1efcbccc42ec78f95948f56fbde Mon Sep 17 00:00:00 2001 From: Chris Warren-Smith Date: Sun, 17 Jul 2016 09:51:57 +1000 Subject: [smallbasic/en] minor fact check fix (#2312) --- smallbasic.html.markdown | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/smallbasic.html.markdown b/smallbasic.html.markdown index 007f9591..9244525e 100644 --- a/smallbasic.html.markdown +++ b/smallbasic.html.markdown @@ -13,9 +13,9 @@ SmallBASIC is a fast and easy to learn BASIC language interpreter ideal for ever SmallBASIC was originally developed by Nicholas Christopoulos in late 1999 for the Palm Pilot. Project development has been continued by Chris Warren-Smith since around 2005. -Versions of SmallBASIC have been made for a number of early hand held devices including Franklin eBookman and the Nokia 770. Also various desktop releases have been released based on a variety of GUI tool-kits, some of which have become defunct. The current supported platforms are Linux and Windows based on SDL2 and Android based on NDK. +Versions of SmallBASIC have been made for a number of early hand held devices including Franklin eBookman and the Nokia 770. Also various desktop versions have been released based on a variety of GUI tool-kits, some of which have become defunct. The current supported platforms are Linux and Windows based on SDL2 and Android based on NDK. A desktop command line version is also available, although not typically released in binary form. -In late 2000's a large corporation released a BASIC like programming environment with a similar sounding name. SmallBASIC is not related to this other project. +In around 2008 a large corporation released a BASIC like programming environment with a similar sounding name. SmallBASIC is not related to this other project. ``` REM This is a comment @@ -108,6 +108,13 @@ REM found in early computer books and magazines, for example: 30 PRINT A*B 40 PRINT A/B +REM SmallBASIC also has support for a few modern concepts such as JSON +aa = array("{\"cat\":{\"name\":\"harry\"},\"pet\":\"true\"}") +If (ismap(aa) == false) Then + throw "not an map" +End If +Print aa + PAUSE ``` -- cgit v1.2.3 From 50c8f7b4dd78df0e4db95ab2cad42373d25f3021 Mon Sep 17 00:00:00 2001 From: Abhijeet Mohan Date: Sat, 30 Jul 2016 21:58:27 +0530 Subject: Fix typo (#2317) --- lua.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lua.html.markdown b/lua.html.markdown index 2cd4d7bb..1e2d4366 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -190,7 +190,7 @@ end -------------------------------------------------------------------------------- -- A table can have a metatable that gives the table operator-overloadish --- behaviour. Later we'll see how metatables support js-prototypey behaviour. +-- behaviour. Later we'll see how metatables support js-prototype behaviour. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} -- cgit v1.2.3 From a186508d6f4c57dba8f1f573b476741a45f7895f Mon Sep 17 00:00:00 2001 From: LuJimin Date: Sun, 31 Jul 2016 13:04:45 +0800 Subject: =?UTF-8?q?=E5=88=9B=E5=BB=BAKotlin=E7=9A=84=E4=B8=AD=E6=96=87?= =?UTF-8?q?=E7=BF=BB=E8=AF=91=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 创建Kotlin的中文翻译版本 --- zh-cn/kotlin-cn.html.markdown | 346 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 zh-cn/kotlin-cn.html.markdown diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown new file mode 100644 index 00000000..ac15c564 --- /dev/null +++ b/zh-cn/kotlin-cn.html.markdown @@ -0,0 +1,346 @@ +--- +language: kotlin +contributors: + - ["S Webber", "https://github.com/s-webber"] +translators: + - ["Jimin Lu", "https://github.com/lujimin"] +filename: LearnKotlin-cn.kt +--- + +Kotlin是一门适用于JVM、Android和浏览器的静态类型编程语言。它100%兼容Java。 +[了解更多。](https://kotlinlang.org/) + +```java +// 单行注释从 // 开始 +/* +多行注释看起来像这样。 +*/ + +// "package" 关键字的工作方式与Java相同。 +package com.learnxinyminutes.kotlin + +/* +Kotlin程序的入口点是一个"main"函数 +该函数传递一个包含任何命令行参数的数组。 +*/ +fun main(args: Array) { + /* + 使用"var"或"val"来声明一个值。 + "val"声明的值不能被重新赋值,而"vars"声明的值可以。 + */ + val fooVal = 10 // 以后我们不能再次给fooVal赋值 + var fooVar = 10 + fooVar = 20 // fooVar可以被再次赋值 + + /* + 在大多数情况下,Kotlin可以确定变量的类型是什么, + 所以我们不必要每次都去明确指定它。 + 我们可以像这样明确地声明一个变量的类型: + */ + val foo : Int = 7 + + /* + 可以采取和Java类似的方法来表示一个字符串。 + 用反斜杠来转义字符。 + */ + val fooString = "My String Is Here!"; + val barString = "Printing on a new line?\nNo Problem!"; + val bazString = "Do you want to add a tab?\tNo Problem!"; + println(fooString); + println(barString); + println(bazString); + + /* + 原始字符串用三重引号(""")来定义。 + 原始字符串可以包含新的行以及其他任何字符。 + */ + val fooRawString = """ +fun helloWorld(val name : String) { + println("Hello, world!") +} +""" + println(fooRawString) + + /* + 字符串可以包含模板表达式。 + 模板表达式从一个美元符号($)开始。 + */ + val fooTemplateString = "$fooString has ${fooString.length} characters" + println(fooTemplateString) + + /* + 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。 + 在变量声明处的类型后面加上?来标识它是可为空的。 + 我们可以用?.操作符来访问可为空的变量。 + 我们可以用?:操作符来指定一个替代值在变量为空的时候使用。 + */ + var fooNullable: String? = "abc" + println(fooNullable?.length) // => 3 + println(fooNullable?.length ?: -1) // => 3 + fooNullable = null + println(fooNullable?.length) // => null + println(fooNullable?.length ?: -1) // => -1 + + /* + 使用"fun"关键字来声明一个函数。 + 函数的参数在函数名后面的括号内指定。 + 函数的参数可以设定一个默认值。 + 如果需要的话,函数的返回值类型可以在参数后面指定。 + */ + fun hello(name: String = "world") : String { + return "Hello, $name!" + } + println(hello("foo")) // => Hello, foo! + println(hello(name = "bar")) // => Hello, bar! + println(hello()) // => Hello, world! + + /* + 用"vararg"关键字来修饰一个函数的参数 + 来允许可变参数传递给该函数 + */ + fun varargExample(vararg names: Int) { + println("Argument has ${names.size} elements") + } + varargExample() // => Argument has 0 elements + varargExample(1) // => Argument has 1 elements + varargExample(1, 2, 3) // => Argument has 3 elements + + /* + 当函数只包含一个单独的表达式时,大括号可以被省略。 + 函数体可以被指定在一个=符号后面。 + */ + fun odd(x: Int): Boolean = x % 2 == 1 + println(odd(6)) // => false + println(odd(7)) // => true + + // 如果返回值类型可以被推断,那么我们不需要指定它。 + fun even(x: Int) = x % 2 == 0 + println(even(6)) // => true + println(even(7)) // => false + + // 函数可以用函数作为参数并且可以返回函数。 + fun not(f: (Int) -> Boolean) : (Int) -> Boolean { + return {n -> !f.invoke(n)} + } + // 命名函数可以被指定为参数使用::操作符。 + val notOdd = not(::odd) + val notEven = not(::even) + // 匿名函数可以被指定为参数。 + val notZero = not {n -> n == 0} + /* + 如果一个匿名函数只有一个参数 + 那么它的声明可以被省略(连同->)。 + 这个参数的名字是"it"。 + */ + val notPositive = not {it > 0} + for (i in 0..4) { + println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") + } + + // "class"关键字用来声明类。 + class ExampleClass(val x: Int) { + fun memberFunction(y: Int) : Int { + return x + y + } + + infix fun infixMemberFunction(y: Int) : Int { + return x * y + } + } + /* + 我们调用构造方法来创建一个新的实例。 + 注意,Kotlin没有"new"关键字。 + */ + val fooExampleClass = ExampleClass(7) + // 可以使用一个点号来调用成员函数。 + println(fooExampleClass.memberFunction(4)) // => 11 + /* + 如果使用"infix"关键字来标记一个函数 + 那么可以使用中缀表示法来调用该函数。 + */ + println(fooExampleClass infixMemberFunction 4) // => 28 + + /* + 数据类是创建只包含数据的类的一个简洁的方法。 + "hashCode"、"equals"和"toString"方法将被自动生成。 + */ + data class DataClassExample (val x: Int, val y: Int, val z: Int) + val fooData = DataClassExample(1, 2, 4) + println(fooData) // => DataClassExample(x=1, y=2, z=4) + + // 数据类有一个"copy"函数 + val fooCopy = fooData.copy(y = 100) + println(fooCopy) // => DataClassExample(x=1, y=100, z=4) + + // 对象可以被解构成为多个变量 + val (a, b, c) = fooCopy + println("$a $b $c") // => 1 100 4 + + // "with"函数类似于JavaScript中的"with"用法。 + data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) + val fooMutableDate = MutableDataClassExample(7, 4, 9) + with (fooMutableDate) { + x -= 2 + y += 2 + z-- + } + println(fooMutableDate) // => MutableDataClassExample(x=5, y=6, z=8) + + /* + 我们可以使用"listOf"函数来创建一个list。 + 这个list是不可变的 - 元素不可以被添加或删除。 + */ + val fooList = listOf("a", "b", "c") + println(fooList.size) // => 3 + println(fooList.first()) // => a + println(fooList.last()) // => c + // 可以通过索引来访问list中的元素。 + println(fooList[1]) // => b + + // 可以使用"mutableListOf"函数来创建一个可变的list。 + val fooMutableList = mutableListOf("a", "b", "c") + fooMutableList.add("d") + println(fooMutableList.last()) // => d + println(fooMutableList.size) // => 4 + + // 我们可以使用"setOf"函数来创建一个set。 + val fooSet = setOf("a", "b", "c") + println(fooSet.contains("a")) // => true + println(fooSet.contains("z")) // => false + + // 我们可以使用"mapOf"函数来创建一个map。 + val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) + // 可以通过键来访问map中的值。 + println(fooMap["a"]) // => 8 + + /* + 序列表示惰性求值集合。 + 我们可以使用"generateSequence"函数来创建一个序列。 + */ + val fooSequence = generateSequence(1, {it + 1}) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // 一个用序列来生成斐波那契数列的例子。 + fun fibonacciSequence() : Sequence { + var a = 0L + var b = 1L + + fun next() : Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + + // Kotlin为集合提供高阶函数。 + val z = (1..9).map {it * 3} + .filter {it < 20} + .groupBy {it % 2 == 0} + .mapKeys {if (it.key) "even" else "odd"} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} + + // 任何提供迭代器的都可以使用"for"循环。 + for (c in "hello") { + println(c) + } + + // "while"循环的用法和其他语言一样。 + var ctr = 0 + while (ctr < 5) { + println(ctr) + ctr++ + } + do { + println(ctr) + ctr++ + } while (ctr < 10) + + // "when"可以用来替代"if-else if"链。 + val i = 10 + when { + i < 7 -> println("first block") + fooString.startsWith("hello") -> println("second block") + else -> println("else block") + } + + // "when"可以带参数。 + when (i) { + 0, 21 -> println("0 or 21") + in 1..20 -> println("in the range 1 to 20") + else -> println("none of the above") + } + + // "when"可以作为一个函数,提供返回值。 + var result = when (i) { + 0, 21 -> "0 or 21" + in 1..20 -> "in the range 1 to 20" + else -> "none of the above" + } + println(result) + + /* + 我们可以通过使用"is"操作符来检查一个对象是否是特定类型的。 + 如果对象通过了类型检查那么它可以作为该类型使用而不需要强制转换它。 + */ + fun smartCastExample(x: Any) : Boolean { + if (x is Boolean) { + // x自动转换为Boolean + return x + } else if (x is Int) { + // x自动转换为Int + return x > 0 + } else if (x is String) { + // x自动转换为String + return x.isNotEmpty() + } else { + return false + } + } + println(smartCastExample("Hello, world!")) // => true + println(smartCastExample("")) // => false + println(smartCastExample(5)) // => true + println(smartCastExample(0)) // => false + println(smartCastExample(true)) // => true + + /* + 扩展是用来添加新的功能到一个类的。 + 它类似于C#的扩展方法。 + */ + fun String.remove(c: Char): String { + return this.filter {it != c} + } + println("Hello, world!".remove('l')) // => Heo, word! + + println(EnumExample.A) // => A + println(ObjectExample.hello()) // => hello +} + +// 枚举类和Java的枚举类型类似。 +enum class EnumExample { + A, B, C +} + +/* +"object"关键字用来创建单例对象。 +我们不能把它赋给一个变量,但我们可以通过它的名字引用它。 +这类似于Scala的单例对象。 +*/ +object ObjectExample { + fun hello() : String { + return "hello" + } +} + +``` + +### 进一步阅读 + +* [Kotlin教程](https://kotlinlang.org/docs/tutorials/) +* [在您的浏览器中使用Kotlin](http://try.kotlinlang.org/) +* [Kotlin资源列表](http://kotlin.link/) -- cgit v1.2.3 From 7645f54e5eb3be229ed05bc99f1fc0c5db4c90fb Mon Sep 17 00:00:00 2001 From: LuJimin Date: Sun, 31 Jul 2016 13:13:44 +0800 Subject: fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改bug --- zh-cn/kotlin-cn.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown index ac15c564..5998f33f 100644 --- a/zh-cn/kotlin-cn.html.markdown +++ b/zh-cn/kotlin-cn.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Jimin Lu", "https://github.com/lujimin"] filename: LearnKotlin-cn.kt +lang: zh-cn --- Kotlin是一门适用于JVM、Android和浏览器的静态类型编程语言。它100%兼容Java。 -- cgit v1.2.3 From 83bca498968c24262780de32e5b5e2d2ac0318bc Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Sun, 31 Jul 2016 13:37:09 +0800 Subject: [bash/zh-tw] add zh-tw translation --- zh-tw/bash-tw.html.markdown | 376 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 376 insertions(+) create mode 100644 zh-tw/bash-tw.html.markdown diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown new file mode 100644 index 00000000..f195d273 --- /dev/null +++ b/zh-tw/bash-tw.html.markdown @@ -0,0 +1,376 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] + - ["Jonathan Wang", "https://github.com/Jonathansw"] + - ["Leo Rudberg", "https://github.com/LOZORD"] + - ["Betsy Lorton", "https://github.com/schbetsy"] + - ["John Detter", "https://github.com/jdetter"] +translators: + - ["Jinchang Ye", "https://github.com/Alwayswithme"] + - ["Chunyang Xu", "https://github.com/XuChunyang"] + - ["Weihang Lo", "https://github.com/weihanglo"] +filename: LearnBash-tw.sh +lang: zh-tw +--- + +Bash 是一個爲 GNU 計劃編寫的 Unix shell,是 Linux 和 Mac OS X 下預設的 shell。 +以下大多數例子可以作爲腳本的一部分運行,也可直接在 shell 下互動執行。 + +[更多資訊](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# 腳本的第一行叫 shebang,用來告知系統如何執行該腳本: +# 參見: http://en.wikipedia.org/wiki/Shebang_(Unix) +# 如你所見,註釋以 # 開頭,shebang 也是註釋。 + +# 顯示 “Hello world!” +echo Hello world! + +# 每一句指令以換行或分號隔開: +echo 'This is the first line'; echo 'This is the second line' + +# 宣告一個變數: +Variable="Some string" + +# 下面是錯誤的做法: +Variable = "Some string" +# Bash 會把 Variable 當做一個指令,由於找不到該指令,因此這裡會報錯。 + +# 也不可以這樣: +Variable= 'Some string' +# Bash 會認爲 'Some string' 是一條指令,由於找不到該指令,這裡會再次報錯。 +# (這個例子中 'Variable=' 這部分會被當作僅對 'Some string' 起作用的賦值。) + +# 使用變數: +echo $Variable +echo "$Variable" +echo '$Variable' +# 當你賦值 (assign) 、匯出 (export),或者以其他方式使用變數時,變數名前不加 $。 +# 如果要使用變數的值, 則要加 $。 +# 注意: ' (單引號) 不會展開變數。 + +# 參數展開式 ${}: +echo ${Variable} +# 這是一個參數展開的簡單用法 +# 使用參數展開會得到該變數的值,也就是會「展開」或印出該值。 +# 在展開期間,可以修改該值或該參數。 +# 以下是修改參數展開式的範例: + +# 在變數內部進行字串代換 +echo ${Variable/Some/A} +# 會把 Variable 中首次出現的 "some" 替換成 “A”。 + +# 變數的截取 +Length=7 +echo ${Variable:0:Length} +# 這樣僅會返回變數值的前7個字元 + +# 變數的預設值 +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# 對 null (Foo=) 和空字串 (Foo="") 起作用; 零(Foo=0)時返回0 +# 注意這僅返回預設值而不是改變變數的值 + +# 括號展開 { } +# 用以產生任意的字串 +echo {1..10} +echo {a..z} +# 這將會輸出該範圍內的起始值到最終值。 + +# 內建變數: +# 下面的內建變數很有用 +echo "Last program's return value: $?" +echo "Script's PID: $$" +echo "Number of arguments: $#" +echo "Scripts arguments: $@" +echo "Scripts arguments separated in different variables: $1 $2..." + +# 現在,我們知道變數如何使用與印出 +# 讓我們開始學習其他Bash基礎吧! + +# 使用 `pwd` 指令,可以得知當前工作目錄 +# `pwd` 意指 「印出工作目錄」(print working directory)。 +# 我們也可使用內建變數 `$PWD`。 +# 下列兩行指令等價: +echo "I'm in $(pwd)" # 執行 `pwd` 且將該值內插至輸出中 +echo "I'm in $PWD" # 直接內插 `$PWD` 變數 + +# 如果終端機上有太多輸出,`clear` 指令可以清除螢幕先前的輸出 +clear +# Ctrl-L 也有相同的效果 + +# 讀取輸入: +echo "What's your name?" +read Name # 這裡不需要宣告新變數 +echo Hello, $Name! + +# 一般 if 結構看起來像這樣: +# 'man test' 可查看更多的信息 +if [ $Name != $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# 注意: 如果 $Name 為空,bash會將該條件式解讀成: +if [ != USER ] +# 這是一個錯誤的語法 +# 所以,安全避免空變數的方法如下: +if [ "$Name" != $USER ] ... +# 如果 $Name 為空,該條件式將被視為: +if [ "" != $USER] +# 此條件式可正常運作 + + +# 根據上一個指令執行結果決定是否執行下一個指令 +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# 在 if 語句中使用 && 和 || 需要多對方括號 +if [ $Name == "Steve" ] && [ $Age -eq 15 ] +then + echo "This will run if $Name is Steve AND $Age is 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "This will run if $Name is Daniya OR Zach." +fi + +# 表達式的格式如下: +echo $(( 10 + 5 )) + +# 與其他程式語言不同的是,bash 運行時依賴上下文。比如,使用 ls 時,列出當前目錄。 +ls + +# 指令可以帶有選項: +ls -l # 列出文件和目錄的詳細信息 +ls -t # 以最後修改時間,對文件與目錄排序 +ls -R # 遞迴列出目錄與次目錄的內容 + +# 前一個指令的輸出可以當作後一個指令的輸入。grep 用來匹配字串。 +# 用下面的指令列出當前目錄下所有的 txt 文件: +ls -l | grep "\.txt" + +# 使用 `cat` 將檔案印出在標準輸出中: +cat file.txt + +# 使用 `cat` 讀取檔案 +Contents=$(cat file.txt) +echo "START OF FILE\n$Contents\nEND OF FILE" + +# 使用 `cp` 複製檔案或目錄,`cp` 會創建新版本的來源檔案/目錄 +# 所以,編輯副本不會影響到初始來源(反之亦然)。 +# 注意,如果目的地已存在該檔案/目錄,該檔案/目錄將會被覆寫 +cp srcFile.txt clone.txt +cp -r srcDirectory/ dst/ # 遞迴複製 + +# `scp` or `sftp` if you plan on exchanging files between computers. +# 如需在兩台電腦間交換檔案,請查看 `scp` 或 `sftp`。 +# `scp` 與 `cp` 相似。 +# `sftp` 則有更高的互動性(與 `ftp` 相似)。 + +# 使用 `mv` 來移動目錄與檔案。 +# `mv` 與 `cp` 相似,但會刪除來源。 +# `mv` 也可以用來重新命名檔案/目錄! +mv s0urc3.txt dst.txt + +# 由於 bash 運行時依賴當前目錄的上下文, +# 需要在其他目錄執行指令時,可使用 `cd` 改變當前目錄: +cd ~ # 到家目錄 +cd .. # 到上一層目錄 + # (^^例如, 從 /home/username/Downloads 到 /home/username) +cd /home/username/Documents # 到指定目錄 +cd ~/Documents/.. # 仍位於家目錄,不是嗎? + +# 使用子殼程式 (subshells) 在不同目錄間工作 +(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD") +pwd # 仍在第一個目錄 + +# 使用 `mkdir` 來建立新的目錄 +mkdir myNewDir +# 使用 `-p` 選項參數,將會自動創建路徑中不存在的目錄 +mkdir -p myNewDir/with/intermediate/directories + +# 將指令的輸出輸入重新導向(標準輸入、標準輸出、標準錯誤輸出)。 +# 從標準輸入讀取資料,直到 ^EOF$ (End-of-file),且將讀取的資料覆寫至hello.py +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 + +# 重新導向可以到標準輸出(stdout),標準輸入(stdin)和標準錯誤輸出(stderr)。 +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# `>` 會覆蓋已存在的文件, `>>` 會以累加的方式輸出文件中。 +python hello.py >> "output.out" 2>> "error.err" + +# 覆蓋 output.out , 追加 error.err 並統計行數 +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# 運行指令並印出文件描述 (比如 /dev/fd/123) +# 具體可查看: man fd +echo <(echo "#helloworld") + +# 以 "#helloworld" 覆蓋 output.out: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# 清理臨時文件並顯示詳情(增加 '-i' 選項啓用互動模式) +rm -v output.out error.err output-and-error.log + +# 一個指令可用 $( ) 嵌套在另一個指令內部: +# 以下的指令會印出當前目錄下的目錄和文件總數 +echo "There are $(ls | wc -l) items here." + +# 反引號 `` 起相同作用,但不允許嵌套 +# 優先使用 $( ). +echo "There are `ls | wc -l` items here." + +# Bash 的 case 語句與 Java 和 C++ 中的 switch 語句類似: +case "$Variable" in + # 列出需要匹配的字串 + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# 循環遍歷給定的參數序列: +# 變數$Variable 的值會被印出 3 次。 +for Variable in {1..3} +do + echo "$Variable" +done + +# 或傳統的 “for循環” : +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# 也可以用於文件 +# 用 cat 輸出 file1 和 file2 內容 +for Variable in file1 file2 +do + cat "$Variable" +done + +# 或作用於其他命令的輸出 +# 對 ls 輸出的文件執行 cat 指令。 +for Output in $(ls) +do + cat "$Output" +done + +# while 循環: +while [ true ] +do + echo "loop body here..." + break +done + +# 你也可以使用函數 +# 定義函數: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# 更簡單的方法 +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# 呼叫函數 +foo "My name is" $Name + +# 有很多有用的指令需要學習: +# 打印 file.txt 的最後 10 行 +tail -n 10 file.txt +# 印出 file.txt 的前 10 行 +head -n 10 file.txt +# 將 file.txt 按行排序 +sort file.txt +# 報告或忽略重複的行,用選項 -d 印出重複的行 +uniq -d file.txt +# 打印每行中 ',' 之前內容 +cut -d ',' -f 1 file.txt +# 將 file.txt 文件所有 'okay' 替換爲 'great', (兼容正規表達式) +sed -i 's/okay/great/g' file.txt +# 將 file.txt 中匹配正則的行打印到標準輸出 +# 這裡印出以 "foo" 開頭, "bar" 結尾的行 +grep "^foo.*bar$" file.txt +# 使用選項 "-c" 統計行數 +grep -c "^foo.*bar$" file.txt +# 其他實用的選項參數 +grep -r "^foo.*bar$" someDir/ # 遞迴的 `grep` +grep -n "^foo.*bar$" file.txt # 顯示行數 +grep -rI "^foo.*bar$" someDir/ # 遞迴的 `grep`, 但忽略二進位檔案 +# 同樣的搜尋,再過濾包含「baz」的行 +grep "^foo.*bar$" file.txt | grep -v "baz" + +# 如果要搜尋字面上的字串而不是用正規表達式,使用 `fgrep` 或 `grep -F` +fgrep "foobar" file.txt + +# trap command allows you to execute a command when a signal is received by your script. +# `trap` 可以在一個script運行,接收到特定信號時,執行對應的指令 +# `trap` 接收到 `SIGHUP`、`SIGINT`、`SIGTERM` 信號時,會移除 $TEMP_FILE +trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM + +# `sudo` 可用於以superuser的身分執行指令 +$NAME1=$(whoami) +$NAME2=$(sudo whoami) +echo "Was $NAME1, then became more powerful $NAME2" + +# 以 bash 內建的 'help' 指令閱讀 Bash 內建文件: +help +help help +help for +help return +help source +help . + +# 用 man 指令閱讀相關的 Bash 手冊 +apropos bash +man 1 bash +man bash + +# 用 info 指令查閱命令的 info 文件 (info 中按 ? 顯示幫助信息) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# 閱讀 Bash 的 info 文件: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` -- cgit v1.2.3 From dce4fefd20c025d1dd7b05781e587a6c7997da91 Mon Sep 17 00:00:00 2001 From: tiaan Date: Sun, 31 Jul 2016 14:52:41 +0200 Subject: Fix inconsistencies and add resource links --- less.html.markdown | 150 ++++++++++++++++++++++++++++------------------------- 1 file changed, 80 insertions(+), 70 deletions(-) diff --git a/less.html.markdown b/less.html.markdown index a1018ca3..f4887947 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -3,6 +3,7 @@ language: less filename: learnless.less contributors: - ["Saravanan Ganesh", "http://srrvnn.me"] + - ["Tiaan du Plessis", "https://github.com/tidupls"] --- Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. @@ -24,8 +25,8 @@ Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help develo /* You can store a CSS value (such as a color) in a variable. Use the '@' symbol to create a variable. */ -@primary-color: #A3A4FF; -@secondary-color: #51527F; +@primary-color: #a3a4ff; +@secondary-color: #51527f; @body-font: 'Roboto', sans-serif; /* You can use the variables throughout your stylesheet. @@ -39,7 +40,7 @@ body { /* This would compile to: */ body { - background-color: #A3A4FF; + background-color: #a3a4ff; color: #51527F; font-family: 'Roboto', sans-serif; } @@ -86,7 +87,7 @@ div { margin-right: auto; left: 0; right: 0; - background-color: #A3A4FF; + background-color: #a3a4ff; } /* You can omit the mixin code from being compiled by adding parenthesis @@ -112,7 +113,66 @@ div { margin-right: auto; left: 0; right: 0; - background-color: #A3A4FF; + background-color: #a3a4ff; +} + + +/*Nesting +==============================*/ + + + +/*Less allows you to nest selectors within selectors */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #f00; + } +} + +/* '&' will be replaced by the parent selector. */ +/* You can also nest pseudo-classes. */ +/* Keep in mind that over-nesting will make your code less maintainable. +Best practices recommend going no more than 3 levels deep when nesting. +For example: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compiles to: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; } @@ -130,8 +190,12 @@ body { width: round(10.25px); } +.header { + background-color: lighten(#000, 0.5); +} + .footer { - background-color: fadeout(#000000, 0.25) + background-color: fadeout(#000, 0.25) } /* Compiles to: */ @@ -140,6 +204,10 @@ body { width: 10px; } +.header { + background-color: #010101; +} + .footer { background-color: rgba(0, 0, 0, 0.75); } @@ -155,12 +223,12 @@ body { and return the percentage */ .average(@x, @y) { - @average_result: ((@x + @y) / 2); + @average-result: ((@x + @y) / 2); } div { .average(16px, 50px); // "call" the mixin - padding: @average_result; // use its "return" value + padding: @average-result; // use its "return" value } /* Compiles to: */ @@ -202,67 +270,6 @@ div { add unnecessary bloat to the files created by the Less compiler. */ - -/*Nesting -==============================*/ - - - -/*Less allows you to nest selectors within selectors */ - -ul { - list-style-type: none; - margin-top: 2em; - - li { - background-color: #FF0000; - } -} - -/* '&' will be replaced by the parent selector. */ -/* You can also nest pseudo-classes. */ -/* Keep in mind that over-nesting will make your code less maintainable. -Best practices recommend going no more than 3 levels deep when nesting. -For example: */ - -ul { - list-style-type: none; - margin-top: 2em; - - li { - background-color: red; - - &:hover { - background-color: blue; - } - - a { - color: white; - } - } -} - -/* Compiles to: */ - -ul { - list-style-type: none; - margin-top: 2em; -} - -ul li { - background-color: red; -} - -ul li:hover { - background-color: blue; -} - -ul li a { - color: white; -} - - - /*Partials and Imports ==============================*/ @@ -365,7 +372,9 @@ body { ## Practice Less -If you want to play with Less in your browser, check out [LESS2CSS](http://lesscss.org/less-preview/). +If you want to play with Less in your browser, check out: +* [Codepen](http://codepen.io/) +* [LESS2CSS](http://lesscss.org/less-preview/) ## Compatibility @@ -377,3 +386,4 @@ with your target browsers. ## Further reading * [Official Documentation](http://lesscss.org/features/) +* [Less CSS - Beginner's Guide](http://www.hongkiat.com/blog/less-basic/) -- cgit v1.2.3 From 47679dfcbe82811b7042a5994baab448adc15dd4 Mon Sep 17 00:00:00 2001 From: Valery Cherepanov Date: Tue, 2 Aug 2016 16:32:38 +0300 Subject: Some minor (mostly stylistic) fixes in C++ --- c++.html.markdown | 98 +++++++++++++++++++++++++++---------------------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 290633f3..5dc1af59 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -808,8 +808,8 @@ void doSomethingWithAFile(const std::string& filename) // have default comparators, but you can override it. class Foo { public: - int j; - Foo(int a) : j(a) {} + int j; + Foo(int a) : j(a) {} }; struct compareFunction { bool operator()(const Foo& a, const Foo& b) const { @@ -948,7 +948,7 @@ f1 = f2; #include -// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members, // its elements are accessed by their order in the tuple. // We start with constructing a tuple. @@ -958,10 +958,10 @@ const int maxN = 1e9; const int maxL = 15; auto second = make_tuple(maxN, maxL); -// printing elements of 'first' tuple +// Printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A -// printing elements of 'second' tuple +// Printing elements of 'second' tuple cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 // Unpacking tuple into variables @@ -989,43 +989,43 @@ cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' ///////////////////// -// CONTAINERS +// Containers ///////////////////// -// Containers or the Standard Template Library are some predefined templates -// They manages the storage space for its elements and provide -// member functions to access and manipulate them +// Containers or the Standard Template Library are some predefined templates. +// They manage the storage space for its elements and provide +// member functions to access and manipulate them. -// Few containers are as follows:- +// Few containers are as follows: -// Vectors (Dynamic arrays) +// Vector (Dynamic array) // Allow us to Define the Array or list of objects at run time -#include // will include the header file for vector -vector< Data_Type > Vector_name; // used to initialize the vector -cin>>val; +#include +vector Vector_name; // used to initialize the vector +cin >> val; Vector_name.push_back(val); // will push the value of variable into array -// To iterate through vector, we have 2 choices -// using normal looping +// To iterate through vector, we have 2 choices: +// Normal looping for(int i=0; i::iterator it; // initialize the iteartor for vector for(it=vector_name.begin(); it!=vector_name.end();++it) // For accessing the element of the vector // Operator [] -var= vector_name[index]; //will assign value at that index to var +var = vector_name[index]; // Will assign value at that index to var // Set -// Sets are containers that store unique elements following a specific order -// Very useful container to store unique values in sorted order -// without any other functions or code +// Sets are containers that store unique elements following a specific order. +// Set is a very useful container to store unique values in sorted order +// without any other functions or code. -#include // Will include the header file for sets -set< int > ST; // Will initialize the set of int data type +#include +set ST; // Will initialize the set of int data type ST.insert(30); // Will insert the value 30 in set ST ST.insert(10); // Will insert the value 10 in set ST ST.insert(20); // Will insert the value 20 in set ST @@ -1037,47 +1037,47 @@ ST.insert(30); // Will insert the value 30 in set ST ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 // To iterate through Set we use iterators -set< int >::iterator it; -for(it=ST.begin();it::iterator it; +for(it=ST.begin();it // Will include the header file for map -map< char, int >mymap; // Will initalize the map with key as char and value as int +#include +map mymap; // Will initalize the map with key as char and value as int -mymap.insert ( pair('A',1) ); +mymap.insert(pair('A',1)); // Will insert value 1 for key A -mymap.insert ( pair('Z',26) ); +mymap.insert(pair('Z',26)); // Will insert value 26 for key Z // To iterate map::iterator it; for (it=mymap.begin(); it!=mymap.end(); ++it) - std::cout << it->first << "->" << it->second <<'\n'; + std::cout << it->first << "->" << it->second << '\n'; // Output: // A->1 // Z->26 // To find the value correponsing to a key it = mymap.find('Z'); -cout<second; +cout << it->second; + +// Output: 26 -// OUTPUT: 26 /////////////////////////////////// // Logical and Bitwise operators @@ -1087,17 +1087,17 @@ cout<second; // Logical operators -// C++ uses Short - circuit evaluation for boolean expressions, i.e, the second argument is executed or +// C++ uses Short-circuit evaluation for boolean expressions, i.e, the second argument is executed or // evaluated only if the first argument does not suffice to determine the value of the expression true && false // Performs **logical and** to yield false true || false // Performs **logical or** to yield true -! true // Performs **logcical not** to yield +! true // Performs **logical not** to yield false // Instead of using symbols equivalent keywords can be used true and false // Performs **logical and** to yield false -true or false // Performs **logical or** to yield true -not true // Performs **logcical not** to yield +true or false // Performs **logical or** to yield true +not true // Performs **logical not** to yield false // Bitwise operators @@ -1108,20 +1108,20 @@ not true // Performs **logcical not** to yield // **>>** Right Shift Operator -// << shifts bits to the right +// >> shifts bits to the right 4 >> 1 // Shifts bits of 4 to right by 1 to give 2 -// x << n can be thought as x / 2^n +// x >> n can be thought as x / 2^n -~4 // Performs a bitwise not +~4 // Performs a bitwise not 4 | 3 // Performs bitwise or 4 & 3 // Performs bitwise and 4 ^ 3 // Performs bitwise xor // Equivalent keywords are -compl 4 // Performs a bitwise not -4 bitor 3 // Performs bitwise or +compl 4 // Performs a bitwise not +4 bitor 3 // Performs bitwise or 4 bitand 3 // Performs bitwise and -4 xor 3 // Performs bitwise xor +4 xor 3 // Performs bitwise xor ``` -- cgit v1.2.3 From bc158cba137307ff34f4ef4b6b3e7fde1afb9179 Mon Sep 17 00:00:00 2001 From: LuJimin Date: Tue, 2 Aug 2016 23:51:15 +0800 Subject: fix bug MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改一些小问题。 --- zh-cn/kotlin-cn.html.markdown | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown index 5998f33f..1fd12f5b 100644 --- a/zh-cn/kotlin-cn.html.markdown +++ b/zh-cn/kotlin-cn.html.markdown @@ -27,7 +27,7 @@ Kotlin程序的入口点是一个"main"函数 fun main(args: Array) { /* 使用"var"或"val"来声明一个值。 - "val"声明的值不能被重新赋值,而"vars"声明的值可以。 + "val"声明的值不能被重新赋值,而"var"声明的值可以。 */ val fooVal = 10 // 以后我们不能再次给fooVal赋值 var fooVar = 10 @@ -53,7 +53,7 @@ fun main(args: Array) { /* 原始字符串用三重引号(""")来定义。 - 原始字符串可以包含新的行以及其他任何字符。 + 原始字符串可以包含换行符以及其他任何字符。 */ val fooRawString = """ fun helloWorld(val name : String) { @@ -73,7 +73,7 @@ fun helloWorld(val name : String) { 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。 在变量声明处的类型后面加上?来标识它是可为空的。 我们可以用?.操作符来访问可为空的变量。 - 我们可以用?:操作符来指定一个替代值在变量为空的时候使用。 + 我们可以用?:操作符来指定一个在变量为空时使用的替代值。 */ var fooNullable: String? = "abc" println(fooNullable?.length) // => 3 @@ -96,8 +96,7 @@ fun helloWorld(val name : String) { println(hello()) // => Hello, world! /* - 用"vararg"关键字来修饰一个函数的参数 - 来允许可变参数传递给该函数 + 用"vararg"关键字来修饰一个函数的参数来允许可变参数传递给该函数 */ fun varargExample(vararg names: Int) { println("Argument has ${names.size} elements") @@ -123,7 +122,7 @@ fun helloWorld(val name : String) { fun not(f: (Int) -> Boolean) : (Int) -> Boolean { return {n -> !f.invoke(n)} } - // 命名函数可以被指定为参数使用::操作符。 + // 命名函数可以用::运算符被指定为参数。 val notOdd = not(::odd) val notEven = not(::even) // 匿名函数可以被指定为参数。 @@ -286,7 +285,7 @@ fun helloWorld(val name : String) { println(result) /* - 我们可以通过使用"is"操作符来检查一个对象是否是特定类型的。 + 我们可以通过使用"is"操作符来检查一个对象是否是某个类型的。 如果对象通过了类型检查那么它可以作为该类型使用而不需要强制转换它。 */ fun smartCastExample(x: Any) : Boolean { @@ -310,7 +309,7 @@ fun helloWorld(val name : String) { println(smartCastExample(true)) // => true /* - 扩展是用来添加新的功能到一个类的。 + 扩展是用来给一个类添加新的功能的。 它类似于C#的扩展方法。 */ fun String.remove(c: Char): String { -- cgit v1.2.3 From fdc1cf944dbafd7ee89c421c871e70f57e5aacb5 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Wed, 3 Aug 2016 01:45:22 +0800 Subject: [bash/zh-tw] add missing line for rm command --- zh-tw/bash-tw.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown index f195d273..3210f001 100644 --- a/zh-tw/bash-tw.html.markdown +++ b/zh-tw/bash-tw.html.markdown @@ -239,7 +239,9 @@ echo "#helloworld" | cat > output.out echo "#helloworld" | tee output.out >/dev/null # 清理臨時文件並顯示詳情(增加 '-i' 選項啓用互動模式) +# 警告: `rm` 指令無法復原 rm -v output.out error.err output-and-error.log +rm -r tempDir/ # 遞迴刪除 # 一個指令可用 $( ) 嵌套在另一個指令內部: # 以下的指令會印出當前目錄下的目錄和文件總數 -- cgit v1.2.3 From 7d585f8174d4abbe9dd3f4707f937c23ad8c5d51 Mon Sep 17 00:00:00 2001 From: Weihang Lo Date: Wed, 3 Aug 2016 02:05:09 +0800 Subject: [bash/zh-tw] delete extra line --- zh-tw/bash-tw.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown index 3210f001..78b39f2d 100644 --- a/zh-tw/bash-tw.html.markdown +++ b/zh-tw/bash-tw.html.markdown @@ -176,7 +176,6 @@ echo "START OF FILE\n$Contents\nEND OF FILE" cp srcFile.txt clone.txt cp -r srcDirectory/ dst/ # 遞迴複製 -# `scp` or `sftp` if you plan on exchanging files between computers. # 如需在兩台電腦間交換檔案,請查看 `scp` 或 `sftp`。 # `scp` 與 `cp` 相似。 # `sftp` 則有更高的互動性(與 `ftp` 相似)。 -- cgit v1.2.3 From 959d95dd78ffa939f876bd559d0331f29b64e075 Mon Sep 17 00:00:00 2001 From: Joakim Lahtinen Date: Thu, 4 Aug 2016 09:10:00 +0200 Subject: [json/sv-se] Synced with english version. (#2324) * [json/sv-se] Synced with english version. * [json/sv-se] Added swedish link. --- sv-se/json-sv.html.markdown | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown index c2ee36dd..002aec2e 100644 --- a/sv-se/json-sv.html.markdown +++ b/sv-se/json-sv.html.markdown @@ -4,18 +4,30 @@ filename: learnjson-sv.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] translators: - ["Lari Kovanen", "https://github.com/larkov"] + - ["Joakim Lahtinen", "https://github.com/VibyJocke"] lang: sv-se --- -Eftersom JSON är ett extremt lätt data-utbytes format så kommer detta -förmodligen att vara den lättaste "Learn X in Y Minutes" någonsin. +JSON är ett extremt enkelt datautbytesformat. Som [json.org](http://json.org) beskriver så är det lätt för människor att läsa och skriva, och för datorer att tolka och generera. -JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar -C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa -100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. +En bit av JSON måste representera antingen: +* En samling av namn/värde-par (`{ }`). I olika språk kan denna realiseras som ett objekt, struct, dictionary, hash-tabell, nyckellista eller en associativ array. +* En ordnad lista av värden (`[ ]`). I olika språk kan denna realiseras som en array, vektor, lista eller sekvens. +JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar C-stils (`//`, `/* */`) kommentarer. Vissa tolkar tolererar även komman efter sista elementet i en array, eller det sista attributet av ett objekt, men dessa bör undvikas för bättre kompabilitet. + +Detta dokument kommer dock att tillämpa 100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. + +Följande datatyper stöds: +* Strängar: `"hello"`, `"\"A quote.\""`, `"\u0abe"`, `"Newline.\n"` +* Nummer: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Objekt: `{ "key": "value" }` +* Arrayer: `["Values"]` +* Övriga: `true`, `false`, `null` ```json { @@ -57,6 +69,16 @@ C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa , "en kommentar till": "vad fint" }, + + + "blanksteg": "Spelar ingen roll.", + + + "det var kort": "Nu är du klar och kan allt vad JSON har att erbjuda." } ``` + +## Fortsatt läsning + +* [JSON.org](http://json.org/json-sv.html) Allt du kan tänkas vilja veta om JSON, och lite därtill. -- cgit v1.2.3 From 25aa41467a13fbc98de3a0a058bd5ecc2f03b5c3 Mon Sep 17 00:00:00 2001 From: robochat Date: Thu, 4 Aug 2016 10:33:58 +0200 Subject: [fortran/en] Adding a Fortran (95) Tutorial (#2318) * adding fortran tutorial * [fortran/en] fixing some typos * [fortran/en] changed a word * [fortran/en] changed another word * [fortran/en] typos and improvements. * [fortran/en] moving comments around * [fortran/en] moving print statement introduction to appropriate section * [fortran/en] changing exit code to generic error code * [fortran/en] changing bessel_j0 (available from fortran 2008) to log10 (available since fortran 77). * [fortran/en] being explicit about using cleaner Fortran 2003 notation * [fortran/en] code whitespace consistency * [fortran/en] adding examples on implied-DO loops. * [fortran/en] small adjustment to implied-DO loop example to make it more idiomatic --- fortran95.html.markdown | 452 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 452 insertions(+) create mode 100644 fortran95.html.markdown diff --git a/fortran95.html.markdown b/fortran95.html.markdown new file mode 100644 index 00000000..8479fef8 --- /dev/null +++ b/fortran95.html.markdown @@ -0,0 +1,452 @@ +--- +language: Fortran +contributors: + - ["Robert Steed", "https://github.com/robochat"] +filename: learnfortran.f95 +--- + +Fortran is one of the oldest computer languages. It was developed in the 1950s +by IBM for numeric calculations (Fortran is an abreviation of "Formula +Translation"). Despite its age, it is still used for high-performance computing +such as weather prediction. However, the language has changed considerably over +the years, although mostly maintaining backwards compatibility; well known +versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008 and +Fortran 2015. + +This overview will discuss the features of Fortran 95 since it is the most +widely implemented of the more recent specifications and the later versions are +largely similar (by comparison FORTRAN 77 is a very different language). + +```fortran + +! This is a comment. + + +program example !declare a program called example. + + ! Code can only exist inside programs, functions, subroutines or modules. + ! Using indentation is not required but it is recommended. + + + ! Declaring Variables + ! =================== + + ! All declarations must come before statements and expressions. + + implicit none !prevents dynamic declaration of variables (recommended!) + ! Implicit none must be redeclared in every function/program/module... + + ! IMPORTANT - Fortran is case insensitive. + real z + REAL Z2 + + real :: v,x ! WARNING: default initial values are compiler dependent! + real :: a = 3, b=2E12, c = 0.01 + integer :: i, j, k=1, m + real, parameter :: PI = 3.1415926535897931 !declare a constant. + logical :: y = .TRUE. , n = .FALSE. !boolean type. + complex :: w = (0,1) !sqrt(-1) + character (len=3) :: month !string of 3 characters. + + real :: array(6) !declare an array of 6 reals. + real, dimension(4) :: arrayb !another way to declare an array. + integer :: arrayc(-10:10) !an array with a custom index. + real :: array2d(3,2) !multidimensional array. + + ! The '::' separators are not always necessary but are recommended. + + ! many other variable attributes also exist: + real, pointer :: p !declare a pointer. + + integer, parameter :: LP = selected_real_kind(20) + real (kind = LP) :: d !long precision variable. + + ! WARNING: initialising variables during declaration causes problems + ! in functions since this automatically implies the 'save' attribute + ! whereby values are saved between function calls. In general, separate + ! declaration and initialisation code except for constants! + + + ! Strings + ! ======= + + character :: a_char = 'i' + character (len = 6) :: a_str = "qwerty" + character (len = 30) :: str_b + character (len = *), parameter :: a_long_str = "This is a long string." + !can have automatic counting of length using (len=*) but only for constants. + + str_b = a_str // " keyboard" !concatenate strings using // operator. + + + ! Assignment & Arithmetic + ! ======================= + + Z = 1 !assign to variable z declared above (case insensitive). + j = 10 + 2 - 3 + a = 11.54 / (2.3 * 3.1) + b = 2**3 !exponentiation + + + ! Control Flow Statements & Operators + ! =================================== + + ! Single-line if statement + if (z == a) b = 4 !condition always need surrounding parentheses. + + if (z /= a) then !z not equal to a + ! Other symbolic comparisons are < > <= >= == /= + b = 4 + else if (z .GT. a) then !z greater than a + ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE. + b = 6 + else if (z < a) then !'then' must be on this line. + b = 5 !execution block must be on a new line. + else + b = 10 + end if !end statement needs the 'if' (or can use 'endif'). + + + if (.NOT. (x < c .AND. v >= a .OR. z == z)) then !boolean operators. + inner: if (.TRUE.) then !can name if-construct. + b = 1 + endif inner !then must name endif statement. + endif + + + i = 20 + select case (i) + case (0) !case i == 0 + j=0 + case (1:10) !cases i is 1 to 10 inclusive. + j=1 + case (11:) !all cases where i>=11 + j=2 + case default + j=3 + end select + + + month = 'jan' + ! Condition can be integer, logical or character type. + ! Select constructions can also be named. + monthly: select case (month) + case ("jan") + j = 0 + case default + j = -1 + end select monthly + + + do i=2,10,2 !loops from 2 to 10 (inclusive) in increments of 2. + innerloop: do j=1,3 !loops can be named too. + exit !quits the loop. + end do innerloop + cycle !jump to next loop iteration. + enddo + + + ! Goto statement exists but it is heavily discouraged though. + goto 10 + stop 1 !stops code immediately (returning specified condition code). +10 j = 201 !this line is labeled as line 10 + + + ! Arrays + ! ====== + array = (/1,2,3,4,5,6/) + array = [1,2,3,4,5,6] !using Fortran 2003 notation. + arrayb = [10.2,3e3,0.41,4e-5] + array2d = reshape([1.0,2.0,3.0,4.0,5.0,6.0], [3,2]) + + ! Fortran array indexing starts from 1. + ! (by default but can be defined differently for specific arrays). + v = array(1) !take first element of array. + v = array2d(2,2) + + print *, array(3:5) !print all elements from 3rd to 5th (inclusive). + print *, array2d(1,:) !print first column of 2d array. + + array = array*3 + 2 !can apply mathematical expressions to arrays. + array = array*array !array operations occur element-wise. + !array = array*array2d !these arrays would not be compatible. + + ! There are many built-in functions that operate on arrays. + c = dot_product(array,array) !this is the dot product. + ! Use matmul() for matrix maths. + c = sum(array) + c = maxval(array) + print *, minloc(array) + c = size(array) + print *, shape(array) + m = count(array > 0) + + ! Loop over an array (could have used Product() function normally). + v = 1 + do i = 1, size(array) + v = v*array(i) + end do + + ! Conditionally execute element-wise assignments. + array = [1,2,3,4,5,6] + where (array > 3) + array = array + 1 + elsewhere (array == 2) + array = 1 + elsewhere + array = 0 + end where + + ! Implied-DO loops are a compact way to create arrays. + array = [ (i, i = 1,6) ] !creates an array of [1,2,3,4,5,6] + array = [ (i, i = 1,12,2) ] !creates an array of [1,3,5,7,9,11] + array = [ (i**2, i = 1,6) ] !creates an array of [1,4,9,16,25,36] + array = [ (4,5, i = 1,3) ] !creates an array of [4,5,4,5,4,5] + + + ! Input/Output + ! ============ + + print *, b !print the variable 'b' to the command line + + ! We can format our printed output. + print "(I6)", 320 !prints ' 320' + print "(I6.4)", 3 !prints ' 0003' + print "(F6.3)", 4.32 !prints ' 4.320' + + ! The letter indicates the expected type and the number afterwards gives + ! the number of characters to use for printing the value. + ! Letters can be I (integer), F (real), E (engineering format), + ! L (logical), A (characters) ... + print "(I3)", 3200 !print '***' since the number doesn't fit. + + ! we can have multiple format specifications. + print "(I5,F6.2,E6.2)", 120, 43.41, 43.41 + print "(3I5)", 10, 20, 30 !3 repeats of integers (field width = 5). + print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 !repeated grouping of formats. + + ! We can also read input from the terminal. + read *, v + read "(2F6.2)", v, x !read two numbers + + ! To read a file. + open(unit=11, file="records.txt", status="old") + ! The file is referred to by a 'unit number', an integer that you pick in + ! the range 9:99. Status can be one of {'old','replace','new'}. + read(unit=11, fmt="(3F10.2)") a, b, c + close(11) + + ! To write a file. + open(unit=12, file="records.txt", status="replace") + write(12, "(F10.2,F10.2,F10.2)") c, b, a + close(12) + + ! There are more features available than discussed here and alternative + ! variants due to backwards compatability with older Fortran versions. + + + ! Built-in Functions + ! ================== + + ! Fortran has around 200 functions/subroutines intrinsic to the language. + ! Examples - + call cpu_time(v) !sets 'v' to a time in seconds. + k = ior(i,j) !bitwise OR of 2 integers. + v = log10(x) !log base 10. + i = floor(b) !returns the closest integer less than or equal to x. + v = aimag(w) !imaginary part of a complex number. + + + ! Functions & Subroutines + ! ======================= + + ! A subroutine runs some code on some input values and can cause + ! side-effects or modify the input values. + + call routine(a,c,v) !subroutine call. + + ! A function takes a list of input parameters and returns a single value. + ! However the input parameters may still be modified and side effects + ! executed. + + m = func(3,2,k) !function call. + + ! Function calls can also be evoked within expressions. + Print *, func2(3,2,k) + + ! A pure function is a function that doesn't modify its input parameters + ! or cause any side-effects. + m = func3(3,2,k) + + +contains ! Zone for defining sub-programs internal to the program. + + ! Fortran has a couple of slightly different ways to define functions. + + integer function func(a,b,c) !a function returning an integer value. + implicit none !best to use implicit none in function definitions too. + integer :: a,b,c !type of input parameters defined inside the function. + if (a >= 2) then + func = a + b + c !the return variable defaults to the function name. + return !can return the current value from the function at any time. + endif + func = a + c + ! Don't need a return statement at the end of a function. + end function func + + + function func2(a,b,c) result(f) !return variable declared to be 'f'. + implicit none + integer, intent(in) :: a,b !can declare and enforce that variables + !are not modified by the function. + integer, intent(inout) :: c + integer :: f !function return type declared inside the function. + integer :: cnt = 0 !GOTCHA - initialisation implies variable is + !saved between function calls. + f = a + b - c + c = 4 !altering the value of an input variable. + cnt = cnt + 1 !count number of function calls. + end function func2 + + + pure function func3(a,b,c) !a pure function can have no side-effects. + implicit none + integer, intent(in) :: a,b,c + integer :: func3 + func3 = a*b*c + end function func3 + + + subroutine routine(d,e,f) + implicit none + real, intent(inout) :: f + real, intent(in) :: d,e + f = 2*d + 3*e + f + end subroutine routine + + +end program example ! End of Program Definition ----------------------- + + +! Functions and Subroutines declared externally to the program listing need +! to be declared to the program using an Interface declaration (even if they +! are in the same source file!) (see below). It is easier to define them within +! the 'contains' section of a module or program. + +elemental real function func4(a) result(res) +! An elemental function is a Pure function that takes a scalar input variable +! but can also be used on an array where it will be separately applied to all +! of the elements of an array and return a new array. + real, intent(in) :: a + res = a**2 + 1.0 +end function func4 + + +! Modules +! ======= + +! A module is a useful way to collect related declarations, functions and +! subroutines together for reusability. + +module fruit + real :: apple + real :: pear + real :: orange +end module fruit + + +module fruity + ! Declarations must be in the order: modules, interfaces, variables. + ! (can declare modules and interfaces in programs too). + + use fruit, only: apple, pear ! use apple and pear from fruit module. + implicit none !comes after module imports. + + private !make things private to the module (default is public). + ! Declare some variables/functions explicitly public. + public :: apple,mycar,create_mycar + ! Declare some variables/functions private to the module (redundant here). + private :: func4 + + ! Interfaces + ! ========== + ! Explicitly declare an external function/procedure within the module + ! (better in general to put functions/procedures in the 'contains' section). + interface + elemental real function func4(a) result(res) + real, intent(in) :: a + end function func4 + end interface + + ! Overloaded functions can be defined using named interfaces. + interface myabs + ! Can use 'module procedure' keyword to include functions already + ! defined within the module. + module procedure real_abs, complex_abs + end interface + + ! Derived Data Types + ! ================== + ! Can create custom structured data collections. + type car + character (len=100) :: model + real :: weight !(kg) + real :: dimensions(3) !i.e. length-width-height (metres). + character :: colour + end type car + + type(car) :: mycar !declare a variable of your custom type. + ! See create_mycar() routine for usage. + + ! Note: There are no executable statements in modules. + +contains + + subroutine create_mycar(mycar) + ! Demonstrates usage of a derived data type. + implicit none + type(car),intent(out) :: mycar + + ! Access type elements using '%' operator. + mycar%model = "Ford Prefect" + mycar%colour = 'r' + mycar%weight = 1400 + mycar%dimensions(1) = 5.0 !default indexing starts from 1! + mycar%dimensions(2) = 3.0 + mycar%dimensions(3) = 1.5 + + end subroutine + + real function real_abs(x) + real :: x + if (x<0) then + real_abs = -x + else + real_abs = x + end if + end function real_abs + + real function complex_abs(z) + complex :: z + ! long lines can be continued using the continuation character '&' + complex_abs = sqrt(real(z)**2 + & + aimag(z)**2) + end function complex_abs + + +end module fruity + +``` + +### More Resources + +For more information on Fortran: + ++ [wikipedia](https://en.wikipedia.org/wiki/Fortran) ++ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features) ++ [fortranwiki.org](http://fortranwiki.org) ++ [www.fortran90.org/](http://www.fortran90.org) ++ [list of Fortran 95 tutorials](http://www.dmoz.org/Computers/Programming/Languages/Fortran/FAQs%2C_Help%2C_and_Tutorials/Fortran_90_and_95/) ++ [Fortran wikibook](https://en.wikibooks.org/wiki/Fortran) ++ [Fortran resources](http://www.fortranplus.co.uk/resources/fortran_resources.pdf) ++ [Mistakes in Fortran 90 Programs That Might Surprise You](http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html) -- cgit v1.2.3 From 2f28300d10505c294ae1d805514c7d01636925f2 Mon Sep 17 00:00:00 2001 From: Wim Date: Thu, 4 Aug 2016 14:41:16 +0200 Subject: [fsharp/en] Explain the cons pattern, and introduce recursion keyword (#2310) * [fsharp/en] Explain the cons pattern, and introduce recursion keyword Was confused when reading the sieve function and thought it could be explained a little more. I got some help from http://hestia.typepad.com/flatlander/2010/07/f-pattern-matching-for-beginners-part-4-lists-and-recursion.html * Forgot the word 'notation' --- fsharp.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index e345201d..69f4eb60 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -175,7 +175,12 @@ module ListExamples = // list comprehensions (aka generators) let squares = [for i in 1..10 do yield i * i] - // prime number generator + // A prime number generator + // - this is using a short notation for the pattern matching syntax + // - (p::xs) is 'first :: tail' of the list, could also be written as p :: xs + // this means this matches 'p' (the first item in the list), and xs is the rest of the list + // this is called the 'cons pattern' + // - uses 'rec' keyword, which is necessary when using recursion let rec sieve = function | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] | [] -> [] -- cgit v1.2.3 From f6c353eb37b553ae18e659eb5b6eb883e43e4b00 Mon Sep 17 00:00:00 2001 From: tiaan Date: Thu, 4 Aug 2016 23:05:29 +0200 Subject: Remove name from contributors list. --- less.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/less.html.markdown b/less.html.markdown index f4887947..d88b6ee9 100644 --- a/less.html.markdown +++ b/less.html.markdown @@ -3,7 +3,6 @@ language: less filename: learnless.less contributors: - ["Saravanan Ganesh", "http://srrvnn.me"] - - ["Tiaan du Plessis", "https://github.com/tidupls"] --- Less is a CSS pre-processor, that adds features such as variables, nesting, mixins and more. @@ -26,7 +25,7 @@ Less (and other preprocessors, such as [Sass](http://sass-lang.com/) help develo Use the '@' symbol to create a variable. */ @primary-color: #a3a4ff; -@secondary-color: #51527f; +@secondary-color: #51527f; @body-font: 'Roboto', sans-serif; /* You can use the variables throughout your stylesheet. -- cgit v1.2.3 From 804261b9e5d6c0686d7cbc236b239afe853db57f Mon Sep 17 00:00:00 2001 From: Alexander Salamanca Date: Sun, 7 Aug 2016 02:32:44 -0500 Subject: [ps/es] Added initial version of powershell Spanish guide (based on the latest English version) (#2325) * progress in translating to spanish the powershell guide * traducido todo * fixed reported issues in powershell spanish file --- es-es/powershell-es.html.markdown | 329 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 es-es/powershell-es.html.markdown diff --git a/es-es/powershell-es.html.markdown b/es-es/powershell-es.html.markdown new file mode 100644 index 00000000..dd92eb97 --- /dev/null +++ b/es-es/powershell-es.html.markdown @@ -0,0 +1,329 @@ +--- +category: tool +tool: powershell +contributors: + - ["Wouter Van Schandevijl", "https://github.com/laoujin"] +translators: + - ["Alexander Salamanca", "https://github.com/alexitosrv"] +filename: LearnPowershell-es.ps1 +lang: es-es +--- + +PowerShell es el lenguaje de automatización y gestión de configuraciones de Windows hecho por Microsoft basado en .NET Framework. Desde Windows 7 en adelante, esos sistemas operativos incluyen un intérprete de PowerShell. +Casi todos los ejemplos a continuación pueden ser parte de un script o ejecutados directamente en la consola de PowerShell. + +Una diferencia clave con respecto a Bash es que en PowerShell casi todo son manipulaciones de objetos en vez de análisis sobre flujos de texto plano. + +[Leer más acá.](https://technet.microsoft.com/en-us/library/bb978526.aspx) (EN) + +Si no está seguro sobre el ambiente de ejecución en su sistema: + +``` +Get-ExecutionPolicy -List +Set-ExecutionPolicy AllSigned +# Otras opciones de políticas de ejecución son: +# - Restricted: Los scripts no correrán. +# - RemoteSigned: Los scripts que se hayan descargado sólo correrán si han sido firmados por un editor de confianza. +# - AllSigned: Los scripts requieren ser firmados por un editor de confianza. +# - Unrestricted: Ejecuta cualquier script. +help about_Execution_Policies # para obtener más ayuda sobre políticas de ejecución. + +# Versión instalada de PowerShell: +$PSVersionTable +``` + +Para obtener ayuda: + +``` +# Si necesita encontrar algún comando +Get-Command about_* # tiene por abreviación (o alias): gcm +Get-Command -Verb Add # lista todos los comandos que tienen por verbo 'Add' +Get-Alias ps +Get-Alias -Definition Get-Process + +Get-Help ps | less # alias: help +ps | Get-Member # alias: gm + +Show-Command Get-EventLog # Muestra un formulario para llenar los parámetros del comando Get-EventLog + +Update-Help # Actualiza la ayuda (debe ser ejecutado en una consola elevada como admin) +``` + +Acá inicia el tutorial: + +``` +# Como ya lo notó, los comentarios empiezan con # + +# Ejemplo de un simple hola mundo: +echo Hola mundo! +# echo es el alias del comando Write-Output (a los comandos también se les dice cmdlets) +# La mayoría de los cmdlets y funciones siguen la convención de llamarse de la forma: Verbo-Sustantivo + +# Cada comando inicia en una nueva línea, o después de un punto y coma: +echo 'Esta es la primer línea'; echo 'Esta es la segunda' + +# La declaración de una variable se ve así: +$unaCadena ="Algún texto" +# O así: +$unNumero = 5 -as [double] +$unaLista = 1,2,3,4,5 +$unaCadena = $unaLista -join '--' # también existe el parámetro -split +$unaTablaHash = @{nom1='val1'; nom2='val2'} + +# Uso de variables: +echo $unaCadena +echo "Interpolación: $unaCadena" +echo "`$unaCadena tiene longitud de $($unaCadena.Length)" +echo '$unaCadena' +echo @" +Esta es una Here-String +$otraVariable +"@ +# Note que una ' (comilla simple) no expande las variables! +# Las Here-Strings también funcionan con comilla simple + +# Variables Automáticas: +# Hay algunas variables previamente definidas en el ambiente que le pueden servir, tales como +echo "Booleanos: $TRUE y $FALSE" +echo "Valor vacío: $NULL" +echo "Valor de retorno del último programa: $?" +echo "Código de salida del último programa en Windows: $LastExitCode" +echo "El último token en la última línea de la sesión activa: $$" +echo "El primer token: $^" +echo "PID del script: $PID" +echo "Ruta completa del directorio dónde está el script actual: $PSScriptRoot" +echo 'Ruta completa de script actual: ' + $MyInvocation.MyCommand.Path +echo "Ruta completa de directorio actual: $Pwd" +echo "Argumentos pasados a la invocación de una función, script o bloque de código: $PSBoundParameters" +echo "Argumentos no predefinidos: $($Args -join ', ')." +# Para saber más sobre variables automáticas: `help about_Automatic_Variables` + +# Para enlazar otro archivo (operador punto) +. .\otroNombreDeScript.ps1 + + +### Control de Flujo +# Tenemos la estructura de if como es usual: +if ($Edad -is [string]) { + echo 'Pero... si $Edad no puede ser una cadena de texto!' +} elseif ($Edad -lt 12 -and $Edad -gt 0) { + echo 'Niño (Menor de 12. Mayor que 0)' +} else { + echo 'Adulto' +} + +# Sentencias switch de PS son más poderosas comparadas con otros lenguajes +$val = "20" +switch($val) { + { $_ -eq 42 } { "La respuesta es 42"; break } + '20' { "Exactamente 20"; break } + { $_ -like 's*' } { "No distingue entre mayúsculas/minúsculas"; break } + { $_ -clike 's*'} { "clike, ceq, cne para ser diferenciar el caso entre mayúsculas/minúsculas"; break } + { $_ -notmatch '^.*$'} { "Emparejamiento de expresiones regulares. cnotmatch, cnotlike, ..."; break } + { 'x' -contains 'x'} { "FALSO! -contains es para listas!"; break } + default { "Otros" } +} + +# El for clásico +for($i = 1; $i -le 10; $i++) { + "Número de ciclo $i" +} +# O más corto +1..10 | % { "Número de ciclo $_" } + +# PowerShell también incluye +foreach ($var in 'valor1','valor2','valor3') { echo $var } +# while () {} +# do {} while () +# do {} until () + +# Manejo de excepciones +try {} catch {} finally {} +try {} catch [System.NullReferenceException] { + echo $_.Exception | Format-List -Force +} + + +### Proveedores +# Lista de archivos y directorios en la ubicación actual +ls # o el alias `dir` +cd ~ # ir al directorio principal del usuario + +Get-Alias ls # -> Get-ChildItem +# ¿¡Eh!? Estos cmdlets tienen nombres genéricos porque a diferencia de otros lenguajes de scripting, +# PowerShell no opera únicamente en el directorio actual. +cd HKCU: # se dirige a la rama HKEY_CURRENT_USER del registro de Windows + +# Para hacer un listado de todos los proveedores disponibles +Get-PSProvider + + +### Tuberías +# Los Cmdlets tienen parámetros que controlan su ejecución: +Get-ChildItem -Filter *.txt -Name # Se obtiene sólo el nombre de todos los archivos txt +# Sólo se necesita escribir caracteres de un parámetro hasta que deja de ser ambiguo +ls -fi *.txt -n # -f no se puede porque también existe -Force +# Use `Get-Help Get-ChildItem -Full` para un tratado más completo + +# Los results del cmdlet anterior se le pueden pasar como entrada al siguiente. +# `$_` representa el objeto actual en el objeto de tubería. +ls | Where-Object { $_.Name -match 'c' } | Export-CSV exportado.txt +ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File exportado.html + +# Si se confunde con la tubería use `Get-Member` para revisar +# los métodos y propiedades de los objetos de la tubería: +ls | Get-Member +Get-Date | gm + +# ` es el caracter de continuación de línea. O termine la línea con un | +Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM ` + | Stop-Process -WhatIf + +Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List + +# Use % como una abreviación de ForEach-Object +(a,b,c) | ForEach-Object ` + -Begin { "Iniciando"; $counter = 0 } ` + -Process { "Procesando $_"; $counter++ } ` + -End { "Terminando: $counter" } + +# El siguiente comando ps (alias de Get-Process) devuelve una tabla con 3 columnas +# La tercera columan es el valor de memoria virtual en MB y usando 2 dígitos decimales +# Las columnas calculadas pueden escribirse más extensamente como: +# `@{name='lbl';expression={$_}` +ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize + + +### Funciones +# El atributo [string] es opcional. +function foo([string]$nombre) { + echo "Hey $nombre, aquí tiene una función" +} + +# Llamando una función +foo "Diga mi nombre" + +# Funciones con parámetros nombrados, atributos de parámetros y documentación analizable +<# +.SYNOPSIS +Establecer un nuevo sitio web +.DESCRIPTION +Crea todo lo que su sitio necesite +.PARAMETER siteName +El nombre para el nuevo sitio web +.EXAMPLE +Crear-SitioWeb -Nombre SitioBonito -Po 5000 +Crear-SitioWeb SiteWithDefaultPort +Crear-SitioWeb nombreSitio 2000 # ERROR! No se pudo validar arguemento de puerto +('nombre1','nombre2') | Crear-SitioWeb -Verbose +#> +function Crear-SitioWeb() { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [Alias('nombre')] + [string]$nombreSitio, + [ValidateSet(3000,5000,8000)] + [int]$puerto = 3000 + ) + BEGIN { Write-Verbose 'Creando nuevo(s) sitio(s) web' } + PROCESS { echo "nombre: $nombreSitio, puerto: $puerto" } + END { Write-Verbose 'Sitio(s) web creado(s)' } +} + + +### Todo es .NET +# Una cadena PS es, de hecho, una cadena tipo System.String de .NET +# Todos los métodos y propiedades de .NET están disponibles +'cadena'.ToUpper().Replace('E', 'eee') +# O más powershellezco +'cadena'.ToUpper() -replace 'E', 'eee' + +# ¿No recuerda cómo es que se llama cierto método .NET? +'cadena' | gm + +# Sintaxis para ejecutar métodos .NET estáticos +[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') + +# Nótese que cualquier función que proviene de .NET Framework REQUIERE paréntesis para ser invocada +# al contrario de las funciones definidas desde PS, las cuales NO PUEDEN ser invocadas con paréntesis. +# Si se invoca una función/cmdlet de PS usando paréntesis, +# es equivalente a que le estuviera pasando un parámetro de tipo lista +$writer = New-Object System.IO.StreamWriter($ruta, $true) +$writer.Write([Environment]::NewLine) +$writer.Dispose() + +### Entrada/Salida +# Leyendo una variable +$Nombre = Read-Host "¿Cómo se llama?" +echo "¡Hola $Nombre!" +[int]$Edad = Read-Host "¿Cuál es su edad?" + +# Test-Path, Split-Path, Join-Path, Resolve-Path +# Get-Content filename # devuelve un string[] +# Set-Content, Add-Content, Clear-Content +Get-Command ConvertTo-*,ConvertFrom-* + + +### Material útil +# Actualizar la ruta de ejecuciones (PATH) +$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") + +# Encontrar Python en el path +$env:PATH.Split(";") | Where-Object { $_ -like "*python*"} + +# Cambiar el directorio de trabajo sin tener que memorizar la ruta anterior +Push-Location c:\temp # se cambia el directorio de trabajo a c:\temp +Pop-Location # revierte el cambio y se devuelve a donde estaba al principio +# Los aliases son : pushd y popd + +# Desbloquear un archivo después de descargarlo de Internet +Get-ChildItem -Recurse | Unblock-File + +# Abre Windows Explorer en la ruta actual (usando el alias ii de Invoke-Item) +ii . + +# Pulse cualquier tecla para salir +$host.UI.RawUI.ReadKey() +return + +# Para crear un acceso directo +$WshShell = New-Object -comObject WScript.Shell +$Shortcut = $WshShell.CreateShortcut($link) +$Shortcut.TargetPath = $file +$Shortcut.WorkingDirectory = Split-Path $file +$Shortcut.Save() +``` + + +Configurando el shell + +``` +# $Profile es la ruta completa para su `Microsoft.PowerShell_profile.ps1` +# Todo el código alojado allí será ejecutado cuando se ejecuta una nueva sesión de PS +if (-not (Test-Path $Profile)) { + New-Item -Type file -Path $Profile -Force + notepad $Profile +} +# Más información en: `help about_profiles` +# Para un shell más productivo, asegúrese de verifivar el proyecto PSReadLine descrito abajo +``` + +Proyectos interesantes (EN) + +* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) Tutoriales de PowerShell +* [PSGet](https://github.com/psget/psget) NuGet para PowerShell +* [PSReadLine](https://github.com/lzybkr/PSReadLine/) Una implementación inspirada en bash para PowerShell (¡Es tan buena que ahora viene con Windows10 por defecto!) +* [Posh-Git](https://github.com/dahlbyk/posh-git/) Un intérprete bonito de Git (¡Recomendado!) +* [PSake](https://github.com/psake/psake) Herramienta de automatización de compilaciones +* [Pester](https://github.com/pester/Pester) Framework de pruebas BDD +* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` que lee su mente + + +Material no cubierto en esta guía + +* WMI: Windows Management Intrumentation (Get-CimInstance) +* Multitarea: Start-Job -scriptBlock {...}, +* Firmas de código +* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command) -- cgit v1.2.3 From c0183a42cd8e52e5ee8d46645a41ab7c86f7a134 Mon Sep 17 00:00:00 2001 From: freesoftwareneedsfreetools Date: Sun, 7 Aug 2016 16:21:54 -0500 Subject: [elisp/en] Fix tiny typo (#2327) --- elisp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elisp.html.markdown b/elisp.html.markdown index da86cab3..c88d97f0 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -194,7 +194,7 @@ filename: learn-emacs-lisp.el ;; And evaluate it: (greeting "you") -;; Some function are interactive: +;; Some functions are interactive: (read-from-minibuffer "Enter your name: ") ;; Evaluating this function returns what you entered at the prompt. -- cgit v1.2.3 From a0b6af45345b957c749dd2cd2e54117006af08be Mon Sep 17 00:00:00 2001 From: "J. Ryan Rembert" Date: Tue, 16 Aug 2016 03:42:20 -0700 Subject: [rust/fr] - French translation for Rust tutorial (#2297) * Initial pass at a fr translation of Rust tutorial * Clean up formatting * Add GFM rust modifer to code black * Final pre-PR fixes * Edit YAML front-matter * Grammar and typo fixes --- fr-fr/rust-fr.html.markdown | 319 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 319 insertions(+) create mode 100644 fr-fr/rust-fr.html.markdown diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown new file mode 100644 index 00000000..0fa16075 --- /dev/null +++ b/fr-fr/rust-fr.html.markdown @@ -0,0 +1,319 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Ryan Rembert", "http://jrrembert.github.io"] +filename: learnrust-fr.rs +lang: fr-fr +--- + +Rust est un langage de programmation développé par Mozilla Research. Rust combine le contrôle de bas niveau sur la performance avec la commodité et la sécurité garanties de haut niveau. + +Il atteint ces objectifs sans avoir besoin d'un ramasse-miettes ou environnement d'exécution, ce qui rend possible l'utilisation de bibliothèques Rust comme une substitution directe pour C. + +La première version de Rust, 0.1, est sortie en janvier 2012 et a tellement évolué rapidement que jusqu'à récemment, l'utilisation de versions stables était déconseillée - à la place ce était conseillé d'utiliser les nightly builds. + +Le 15 mai 2015, Rust 1.0 a été libéré avec une garantie complète de compatibilité ascendante. Améliorations aux temps de compilation et d'autres aspects du compilateur sont actuellement disponibles dans la nightly builds. Rust a adopté un modèle de libération à bord du train avec les versions régulières toutes les six semaines. Rust 1.1 beta a été mis à la disposition dans le même temps de la libération de Rust 1.0. + +Bien que Rust soit un langage relativement bas niveau, Rust a quelques concepts fonctionnels qui se trouvent généralement dans les langues de niveau supérieur. Cela rend Rust non seulement rapide, mais aussi efficace et facile à coder. + +```rust +// Ceci est un commentaire. commentaires de ligne ressemblent à ceci ... +// Et prolonger plusieurs lignes comme celle-ci. + +/// Les commentaires de documentation ressemblent à ceci et à soutenir +/// la notation de démarques. +/// # Exemples +/// +/// ``` +/// let cinq = 5 +/// ``` + +/////////////// +// 1. Basics // +/////////////// + +// Les fonctions +// `I32` est le type 32 bits entiers signés +fn add2(x: i32, y: i32) -> i32 { +    // Retour implicite (pas virgule) +    x + y +} + +// Fonction principale +fn main() { +    // Nombres // + +    // Reliures immutable +    let x: i32 = 1; + +    // Entier suffixes/float +    let y: I32 = 13i32; +    let f: f64 = 1.3f64; + +    // Type Inférence +    // La plupart du temps, le compilateur Rust peut déduire le type de variable + // est, donc vous ne devez pas écrire une annotation de type explicite. +    // Tout au long de ce tutoriel, les types sont explicitement annotées dans + // de nombreux endroits, mais seulement à des fins de démonstration. + // L'inférence de type peut gérer cela pour vous la plupart du temps. +    let implicit_x = 1; +    let implicit_f = 1,3; + +    // Arithmétique +    let somme = x + y + 13; + +    // Variable Mutable +    let mut mutable = 1; +    let mutable = 4; +    let mutable += 2; + +    // Chaînes // + +    // Littéraux chaîne +    let x: &str = "Bonjour tout le monde!"; + +    // Impression +    println!("{} {}", f, x); // 1.3 Bonjour tout le monde + +    // A `Chaîne` - une chaîne de tas alloué +    let s: String = "Bonjour tout le monde".to_string(); + +    // Une tranche de chaîne - une vue immutable dans une else chaîne. +    // Ceci est essentiellement un pointeur immutable à une chaîne - il n'a pas +    // contient effectivement le contenu d'une chaîne, juste un pointeur vers +    // quelque chose qui fait(dans ce cas, `s`). +    let s_slice: &str = &s; + +    println!("{} {}", s, s_slice); // Bonjour monde Bonjour tout le monde + +    // Vecteurs/tableau // + +    // Un tableau de taille fixe +    let four_ints: [i32; 4] = [1, 2, 3, 4]; + +    // Un tableau dynamique(vecteur) +    let mut vecteur: Vec = vec![1, 2, 3, 4]; +    vecteur.push(5); + +    // Une tranche - une vue immutable dans un vecteur ou un tableau. +    // Ceci est un peu comme une tranche de chaîne, mais pour les vecteurs. +    let tranche: &[i32] = &vecteur; + +    // Utiliser `{:?}` pour imprimer quelque chose de débogage de style +    println!("{:?} {:?}", vecteur, tranche); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + +    // Tuples // + +    // Un tuple est un ensemble de valeurs de peut-être différents types. + // de taille fixe +    let x:(i32, &str, f64) = (1, "bonjour", 3.4); + +    // Déstructurante `let` +    let (a, b, c) = x; +    println!("{} {} {}", a, b, c); // 1 bonjour 3.4 + +    // indexation +    println!("{}", x.1); // Bonjour + +    ////////////// +    // 2. Types // +    ////////////// + +    // Struct +    struct Point { +        x: i32, +        y: i32, +    } + +    let origine: Point = Point { x: 0, y: 0 }; + +    // Un struct avec des champs sans nom, appelé 'tuple struct'. +    struct Point2(i32, i32); + +    let origine2 = Point2(0, 0); + +    // Basic C-like enum +    enum Direction { +        Àgauche, +        Droite, +        En_Haut, +        Vers_Le_Bas, +    } + +    let en_haut = Direction::En_Haut; + +    // Enum avec des champs +    enum OptionnelI32 { +        AnI32(I32), +        Rien, +    } + +    let deux: OptionnelI32 = OptionnelI32::AnI32(2); +    let rien = OptionnelI32::Rien; + +    // Generics // + +    struct Foo { bar: T } + +    // Ceci est défini dans la bibliothèque standard comme `Option`. +    enum Optionnel { +        SomeVal(T), +        NoVal, +    } + +    // Méthodes // + +    impl Foo { +        // Méthodes prennent un paramètre explicite `de self`. +        fn get_bar(self) -> T { +            self.bar +        } +    } + +    let a_foo = Foo { bar: 1 }; +    println!("{}", a_foo.get_bar()); // 1 + +    // Traits (connu sous le nom des interfaces ou des classes de types dans + // d'elses langues). + +    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. Motif correspondant // +    ///////////////////////// + +    let foo = OptionnelI32::AnI32(1); +    match foo { +        OptionnelI32::AnI32(n) => println!("Il est un i32: {}", n), +        OptionnelI32::Rien => println!("Il n'y a rien!"), +    } + +    // Motif avancé correspondant +    struct FooBar { x: i32, y: OptionnelI32 } +    let bar = FooBar { x: 15, y: OptionnelI32::AnI32(32) }; + +    match bar { +        FooBar { x: 0, y: OptionnelI32 :: AnI32(0)} => +            println!("Les chiffres sont nuls!"), +        FooBar { x: n, y: OptionnelI32 :: AnI32(m)} if n == m => +            println!("Les chiffres sont les mêmes"), +        FooBar { x: n, y: OptionnelI32 :: AnI32(m)} => +            println!("Différents numéros: {} {}", n, m)!, +        FooBar { x: _, y: OptionnelI32 :: Rien} => +            println!("Le deuxième numéro est rien!"), +    } + +    ///////////////////// +    // 4. Flux de contrôle // +    ///////////////////// + +    // `for` boucles / itération +    let array = [1, 2, 3]; +    for i in array.iter() { +        println!("{}", i); +    } + +    // Ranges +    for i in 0u32..10 { +        print!("{}", i); +    } +    println!(""); +    // imprime `0 1 2 3 4 5 6 7 8 9` + +    // `if` +    if 1 == 1 { +        println!("Maths est travaille!"); +    } else { +        println!("Oh non ...!"); +    } + +    // `if` comme expression +    let valeur = if true { +        "bien" +    } else { +        "mal" +    }; + +    // `while` boucle +    while 1 == 1 { +        println!("L'univers fonctionne normalement."); +    } + +    // Boucle infinie +    loop { +        println!("Bonjour!"); +    } + +    ///////////////////////////////// +    // 5. Sécurité & pointeurs mémoire // +    ///////////////////////////////// + + // Pointeur occasion - une seule chose peut "posséder" pointeur à un moment. +    // Cela signifie que lorsque le `Box` laisse son champ d'application, il + // peut être automatiquement libérée en toute sécurité. +    let mut mien: Box = Box::new(3); +    *mien = 5; // déréférencer +    // Ici, `now_its_mine` prend possession de` mine`. En d'elses termes, + // `mien` est déplacé. +    let mut now_its_mine = mien; +    *now_its_mine += 2; + +    println!("{}", now_its_mine); // 7 +    // println!("{}", de la mine); // Cela ne compile pas parce + // que `now_its_mine` possède maintenant le pointeur + +    // Référence - un pointeur immutable qui fait référence à d'elses données. +    // Quand une référence est prise à une valeur, nous disons que la valeur + // a été "emprunté". +    // Même si une valeur est emprunté immutablement, il ne peut pas être + // muté ou déplacé. +    // Un emprunt dure jusqu'à la fin de la portée, il a été créé. +    let mut var = 4; +    var = 3; +    let ref_var: &i32 = &var; + +    println!("{}", var); // Contrairement `box`, `var` peut encore être utilisé +    println!("{}", *ref_var); +    // Var = 5; // Cela ne compile pas parce que `var` est emprunté. +    // *ref_var = 6; // Ce ne serait pas non plus, parce que `ref_var` est une + // référence immutable. + +    // Référence Mutable +    // Même si une valeur est mutably emprunté, il ne peut pas être + // accessible à tous. +    let mut var2 = 4; +    let ref_var2: &mut i32 = &mut var2; + // '*' est utilisé pour pointer vers le var2 mutably emprunté. + *ref_var2 += 2; + + println!("{}", * ref_var2); // 6, // var2 ne serait pas compiler. +    // ref_var2 est de type &mut i32 donc stocke il référence à i32, + // pas la valeur. +    // var2 = 2; // Cela ne compile pas parce que `var2` est emprunté. +} +``` + +## Autres lectures + +Il y a beaucoup plus à Rust -- ce est juste l'essentiel de Rust afin que vous puissiez comprendre +les choses les plus importantes. Pour en savoir plus sur Rust, lire [La Programmation Rust +Langue](http://doc.rust-lang.org/book/index.html) et etudier la +[/r/rust](http://reddit.com/r/rust) subreddit. Les gens sur le canal de #rust sur +irc.mozilla.org sont aussi toujours prêts à aider les nouveaux arrivants. + +Vous pouvez également essayer caractéristiques de Rust avec un compilateur en ligne sur le fonctionnaire +[Rust parc](http://play.rust-lang.org) ou sur la principale +[Site Rust](http://rust-lang.org). -- cgit v1.2.3 From 21c4be47790c230cf5a321aeabb5c07ad57f0522 Mon Sep 17 00:00:00 2001 From: Ryan Date: Wed, 17 Aug 2016 13:25:32 -0600 Subject: Remove undefined behavior (#2332) --- c.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/c.html.markdown b/c.html.markdown index babf0954..92f07fe2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -449,7 +449,8 @@ int main (int argc, char** argv) int size = 10; int *my_arr = malloc(sizeof(int) * size); // Add an element to the array - my_arr = realloc(my_arr, ++size); + size++; + my_arr = realloc(my_arr, sizeof(int) * size); my_arr[10] = 5; // Dereferencing memory that you haven't allocated gives -- cgit v1.2.3 From 12e1739706da8ead292f1c21c4cf54afbd4f4087 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Sun, 21 Aug 2016 15:51:29 +0800 Subject: go: [zh-cn] fix a typo. --- zh-cn/go-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 49224085..fa4540a2 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -129,7 +129,7 @@ func learnFlowControl() { fmt.Println("told ya") } // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了, - // 也不用容忍被人的代码风格。 + // 也不用容忍别人的代码风格。 if false { // pout } else { -- cgit v1.2.3 From 6f20dea30740479fd0f0d7e2221490eaffb9a0d5 Mon Sep 17 00:00:00 2001 From: Chris Martin Date: Sun, 21 Aug 2016 15:55:49 -0400 Subject: Added info on Java generics in Spanish. (#2213) --- es-es/java-es.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/es-es/java-es.html.markdown b/es-es/java-es.html.markdown index b34dca8d..e48a3b73 100644 --- a/es-es/java-es.html.markdown +++ b/es-es/java-es.html.markdown @@ -279,6 +279,19 @@ public class AprendeJava { // 'toString' es una convención para mostrar los valores de este objeto. System.out.println("informacion de la excursion: " + excursion.toString()); + /////////////////////////////////////// + // Genéricos + /////////////////////////////////////// + + // Utilizando genéricos (a partir de Java 1.5) es posible detectar en tiempo de + // compilación errores de tipado (en versiones anteriores se detectarían como error + // de ejecución) + + List v = new ArrayList(); + v.add("test"); + String s = v.get(0); // Si intentamos recuperar s como otro tipo diferente a String + // (por ejemplo, un Integer) obtendríamos un error de compilación + } // Fin del método 'main' } // Fin de la clase AprendeJava -- cgit v1.2.3 From 34456d988c627a58ce8fca141cfb488c6d7998d4 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Mon, 22 Aug 2016 06:06:57 +0800 Subject: java: In Java 8, interfaces can have default method. (#2337) --- java.html.markdown | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 1f7d4115..56bffd88 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -585,10 +585,14 @@ public interface Edible { public interface Digestible { public void digest(); + // In Java 8, interfaces can have default method. + // public void digest() { + // System.out.println("digesting ..."); + // } } // We can now create a class that implements both of these interfaces. -public class Fruit implements Edible, Digestible { +public class Fruit implements Edible, Digestible { @Override public void eat() { // ... @@ -636,7 +640,7 @@ public abstract class Animal // Method can have a body public void eat() { - System.out.println("I am an animal and I am Eating."); + System.out.println("I am an animal and I am Eating."); // Note: We can access private variable here. age = 30; } -- cgit v1.2.3 From c6bfd82aa098ed8ef0c4d78e925f14a589940d59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Roun?= Date: Tue, 23 Aug 2016 21:36:57 +0200 Subject: added missing modulo division (#2339) --- cs-cz/javascript.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index 0b053595..b4596c40 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] @@ -59,6 +59,11 @@ delejNeco() // Včetně dělení 5 / 2; // = 2.5 +// A také dělení modulo +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + // Bitové operace také fungují; když provádíte bitové operace, desetinné číslo // (float) se převede na celé číslo (int) se znaménkem *do* 32 bitů 1 << 2; // = 4 -- cgit v1.2.3 From fc7ec89cee90d6e97d64fe3efd0b55979151ba11 Mon Sep 17 00:00:00 2001 From: "Ole Mathias Aa. Heggem" Date: Wed, 24 Aug 2016 08:59:57 +0200 Subject: Added NO version for JSON (#1532) --- no-nb/JSON-no.html.markdown | 59 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 no-nb/JSON-no.html.markdown diff --git a/no-nb/JSON-no.html.markdown b/no-nb/JSON-no.html.markdown new file mode 100644 index 00000000..6e63eb43 --- /dev/null +++ b/no-nb/JSON-no.html.markdown @@ -0,0 +1,59 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Ole Mathias Heggem", "https://github.com/msbone"] + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +--- + +JSON er en enkel tekstbasert standard for datautveksling. +Den er opprinnelig avledet fra JavaScript for å representere enkle datastrukturer. +Standarden er imidlertid uavhengig av JavaScript eller andre programmeringsspråk. + +JSON i sin reneste form har ingen faktiske kommentarer, men de fleste parsere vil akseptere +C-stil (`//`, `/* */`) kommentarer. + +```json +{ + "nøkkel": "verdi", + + "nøkler": "må alltid være i doble anførselstegn", + "tall": 0, + "strings": "Hellø, wørld. Alt unicode er godkjent, også \"escaping\".", + "har bools?": true, + "ingenting": null, + + "stort tall": 1.2e+100, + + "objekt": { + "kommentar": "Meste av strukturen kommer ifra objekt.", + + "array": [0, 1, 2, 3, "Arrays kan inneholde alt.", 5], + + "nytt object": { + "comment": "Ny kommentar" + } + }, + + "tull": [ + { + "Kilde til Kalium": ["bananer"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "Alternativ": { + "Kommentar": "Sjekk ut ditta!" + , "plassering av komma": "Sålenge den er før verdien er det gyldig" + , "Enda en kommentar": "TØFT!" + }, + + "Ferdig": "Da er den korte innledninga til JSON ferdig" +} +``` -- cgit v1.2.3 From 8032dbccc9e2a1b551079c39b0adb40fcdc0f2ab Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 24 Aug 2016 09:00:23 +0200 Subject: fixup for #1532 --- no-nb/JSON-no.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/no-nb/JSON-no.html.markdown b/no-nb/JSON-no.html.markdown index 6e63eb43..6c8c3c79 100644 --- a/no-nb/JSON-no.html.markdown +++ b/no-nb/JSON-no.html.markdown @@ -1,6 +1,7 @@ --- language: json -filename: learnjson.json +filename: learnjson-no.json +lang: no-nb contributors: - ["Ole Mathias Heggem", "https://github.com/msbone"] - ["Anna Harren", "https://github.com/iirelu"] -- cgit v1.2.3 From e89fded52b67bc3afd1036f2aa977d24dd2185ed Mon Sep 17 00:00:00 2001 From: Martin Schimandl Date: Wed, 24 Aug 2016 18:32:01 +0200 Subject: Fix some typos --- de-de/perl-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown index 016c273f..fd8fb3c4 100644 --- a/de-de/perl-de.html.markdown +++ b/de-de/perl-de.html.markdown @@ -16,7 +16,7 @@ Perl 5 läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainfra # Einzeilige Kommentare beginnen mit dem # Symbol. -#### Perl variablen typen +#### Perl Variablen Typen # Variablen beginnen mit einem Sigil, das ist ein Symbol das den Typ anzeigt. # Ein erlaubter Variablen-Name beginnt mit einem Buchstaben oder einem @@ -109,7 +109,7 @@ print for @elements; #### Reguläre Ausdrücke # Die Unterstützung von Perl für reguläre Ausdrücke ist weit und tiefgreifend. -# Sie ist ausführlichst in perlrequick, perlretut und sonstwo dokumentiert. +# Sie ist ausführlich in perlrequick, perlretut und sonstwo dokumentiert. # Die Kurzfassung: # Einfaches Vergleichen @@ -122,7 +122,7 @@ $a =~ s/foo/bar/; # Ersetzt foo mit bar in $a $a =~ s/foo/bar/g; # Ersetzt ALLE VORKOMMNISSE von foo mit bar in $a -#### Datien und Ein-/Ausgabe +#### Dateien und Ein-/Ausgabe # Dateien werden mit der "open()" Funktion zur Ein- oder Ausgabe geöffnet. @@ -150,14 +150,14 @@ sub logger { print $logfile $logmessage; } -# Nun könnne wir die Subroutine genau wie eine eingebaute Funktion verwenden: +# Nun können wir die Subroutine genau wie eine eingebaute Funktion verwenden: logger("We have a logger subroutine!"); ``` #### Verwenden von Perl Modulen -Perl Module lieferen eine Menge an Funktionen die dabei Helfen das Rad nicht neu erfinden zu müssen. Perl Module können von CPAN (http://www.cpan.org/) heruntergeladen werden. Einige populäre Module sind in der Perl Distribution selbst bereits enthalten. +Perl Module liefern eine Menge an Funktionen die dabei Helfen das Rad nicht neu erfinden zu müssen. Perl Module können von CPAN (http://www.cpan.org/) heruntergeladen werden. Einige populäre Module sind in der Perl Distribution selbst bereits enthalten. Perlfaq enthält Fragen und Antworten zu häufig vorkommenden Aufgaben. Sehr oft sind auch Vorschläge enthalten welches CPAN module am besten geeignet ist. -- cgit v1.2.3 From 6996dcf3e3304a60655fea1968ce0ee90d3eff77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Roun?= Date: Wed, 24 Aug 2016 18:49:07 +0200 Subject: added missing js examples for czech translation --- cs-cz/javascript.html.markdown | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index b4596c40..e781db3e 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -105,6 +105,10 @@ false; // nepravda // Řetězce znaků se spojují pomocí + "Ahoj " + "světe!"; // = "Ahoj světe!" +// ... což funguje nejenom s řetězci +"1, 2, " + 3; // = "1, 2, 3" +"Ahoj " + ["světe", "!"] // = "Ahoj světe,!" + // a porovnávají se pomocí < nebo > "a" < "b"; // = true @@ -131,7 +135,7 @@ null === undefined; // = false // Existují také typy `null` a `undefined`. null; // značí, že žádnou hodnotu -undefined; // značí, že hodnota nebyla definovaná definovaná (ikdyž +undefined; // značí, že hodnota nebyla definovaná (ikdyž // `undefined` je hodnota sama o sobě) // false, null, undefined, NaN, 0 and "" vrací nepravdu (false). Všechno ostatní @@ -156,6 +160,9 @@ jinaPromenna = 10; // Proměnné vytvořené bez přiřazení obsahují hodnotu undefined. var dalsiPromenna; // = undefined +// Pokud chcete vytvořit několik proměnných najednou, můžete je oddělit čárkou +var someFourthVar = 2, someFifthVar = 4; + // Existuje kratší forma pro matematické operace na proměnné promenna += 5; // se provede stejně jako promenna = promenna + 5; // promenna je ted 10 @@ -313,6 +320,12 @@ setTimeout(funkce, 5000); // Poznámka: setTimeout není část JS jazyka, ale funkce poskytována // prohlížeči a NodeJS +// Další funkce poskytovaná prohlížeči je je setInterval +function myFunction(){ + // tento kód bude volán každých 5 vteřin +} +setInterval(myFunction, 5000); + // Objekty funkcí nemusíme ani deklarovat pomocí jména, můžeme je napsat jako // ananymní funkci přímo vloženou jako argument setTimeout(function(){ @@ -503,6 +516,11 @@ if (0){ // Tento kód se nespustí, protože 0 je nepravdivá (false) } +if (new Number(0)){ + // Tento kód se spustí, protože obalená čísla jsou objekty, + // a objekty jsou vždy pravdivé +} + // Avšak, obalovací objekty a normální vestavěnné typy sdílejí prototyp, takže // můžete přidat funkcionalitu k řetězci String.prototype.prvniZnak = function(){ -- cgit v1.2.3 From f4371a8367ab4dbb5ac3e112fe6a5fc6654a28c8 Mon Sep 17 00:00:00 2001 From: Jiang haiyun Date: Thu, 25 Aug 2016 14:32:09 +0800 Subject: Sync with the English version & minor tweaks --- zh-cn/yaml-cn.html.markdown | 82 ++++++++++++++++++++++++++++++++------------- 1 file changed, 58 insertions(+), 24 deletions(-) diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown index fc510eb5..bbda20e9 100644 --- a/zh-cn/yaml-cn.html.markdown +++ b/zh-cn/yaml-cn.html.markdown @@ -4,33 +4,36 @@ contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - ["Zach Zhang", "https://github.com/checkcheckzz"] + - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] filename: learnyaml-cn.yaml lang: zh-cn --- -YAML是一个数据序列化语言,被设计成人类直接可写可读的。 +YAML 是一个数据序列化语言,被设计成人类直接可写可读的。 -它是JSON的严格超集,增加了语法显著换行符和缩进,就像Python。但和Python不一样, -YAML根本不容许文字制表符。 +它是 JSON 的严格超集,增加了语法显著换行符和缩进,就像 Python。但和 Python 不一样, +YAML 根本不容许文字制表符。 ```yaml -# YAML中的注解看起来像这样。 +# YAML 中的注解看起来像这样。 ################ -# 标量类型 # +# 标量类型 # ################ -# 我们的根对象 (它们在整个文件里延续) 将会是一个地图, +# 我们的根对象 (它们在整个文件里延续) 将会是一个映射, # 它等价于在别的语言里的一个字典,哈西表或对象。 key: value another_key: Another value goes here. a_number_value: 100 +# 如果你想将数字 1 作为值,你必须要将它括在引号中。 +# 不然 YAML 解析器会假定它是一个布尔值 true。 scientific_notation: 1e+12 boolean: true null_value: null key with spaces: value -# 注意到字符串不需要被引用。但是,它们可以被引用。 +# 注意到字符串不需要被括在引号中。但是,它们可以被括起来。 "Keys can be quoted too.": "Useful if you want to put a ':' in your key." # 多行字符串既可以写成像一个'文字块'(使用 |), @@ -54,7 +57,7 @@ folded_style: > this text will appear over two lines. #################### -# 集合类型 # +# 集合类型 # #################### # 嵌套是通过缩进完成的。 @@ -64,18 +67,24 @@ a_nested_map: another_nested_map: hello: hello -# 地图不用有字符串键值。 +# 映射的键值不必是字符串。 0.25: a float key -# 键值也可以是多行对象,用?表明键值的开始。 +# 键值也可以是复合型的,比如多行对象 +# 我们用 ? 后跟一个空格来表示一个复合键的开始。 ? | This is a key that has multiple lines : and this is its value -# YAML也容许键值是集合类型,但是很多语言将会抱怨。 +# YAML 也允许使用复杂键语法表示序列间的映射关系。 +# 但有些语言的解析器可能会不支持。 +# 一个例子: +? - Manchester United + - Real Madrid +: [ 2001-01-01, 2002-02-02 ] -# 序列 (等价于表或数组) 看起来像这样: +# 序列 (等价于列表或数组) 看起来像这样: a_sequence: - Item 1 - Item 2 @@ -87,50 +96,75 @@ a_sequence: - This is a sequence - inside another sequence -# 因为YAML是JSON的超集,你也可以写JSON风格的地图和序列: +# 因为 YAML 是 JSON 的超集,你也可以写 JSON 风格的映射和序列: json_map: {"key": "value"} json_seq: [3, 2, 1, "takeoff"] ####################### -# 其余的YAML特点 # +# 其余的 YAML 特性 # ####################### -# YAML还有一个方便的特点叫'锚',它让你简单地在整个文件里重复内容。 -# 两个键值将会有相同的值: +# YAML 还有一个方便的特性叫 '锚',它能让你很容易在文档中进行文本复用。 +# 如下两个键会有相同的值: anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name -# YAML还有标签,你可以用它显示地声明类型。 +# 锚也可被用来复制/继承属性 +base: &base + name: Everyone has same name + +foo: &foo + <<: *base + age: 10 + +bar: &bar + <<: *base + age: 20 + +# foo 和 bar 将都含有 name: Everyone has same name + +# YAML 还有标签,你可以用它显示地声明类型。 explicit_string: !!str 0.5 -# 一些解析器实现特定语言的标签,就像这个为了Python的复数类型。 +# 一些解析器实现特定语言的标签,就像这个针对 Python 的复数类型。 python_complex_number: !!python/complex 1+2j +# 我们也可以在 YAML 的复合键中使用特定语言的标签 +? !!python/tuple [5, 7] +: Fifty Seven +# 将会是 Python 中的 {(5, 7): 'Fifty Seven'} + #################### -# 其余的YAML类型 # +# 其余的 YAML 类型 # #################### -# 字符串和数字不是仅有的YAML可以理解的标量。 -# ISO 格式的日期和日期时间文字也是可以被解析的。 +# 除了字符串和数字,YAML 还能理解其它标量。 +# ISO 格式的日期和日期时间文本也可以被解析。 datetime: 2001-12-15T02:59:43.1Z datetime_with_spaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 -# 这个!!binary标签表明一个字符串实际上是一个二进制blob的base64编码表示。 +# 这个 !!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= -# YAML还有一个集合类型,它看起来像这样: +# YAML 还有一个集合类型,它看起来像这样: set: ? item1 ? item2 ? item3 -# 像Python一样,集合仅是有null数值的地图;上面的集合等价于: +# 像 Python 一样,集合仅是值为 null 的映射;上面的集合等价于: set2: item1: null item2: null item3: null ``` + +### 更多资源 + ++ [YAML official website](http://yaml.org/) ++ [Online YAML Validator](http://codebeautify.org/yaml-validator) -- cgit v1.2.3 From df01c7fcff9098f092245afc42d597616988b169 Mon Sep 17 00:00:00 2001 From: Jiang haiyun Date: Fri, 26 Aug 2016 08:44:16 +0800 Subject: It is a a text --> It is a text --- vim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vim.html.markdown b/vim.html.markdown index 80c5835a..cd61ca74 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -8,7 +8,7 @@ filename: LearnVim.txt [Vim](www.vim.org) -(Vi IMproved) is a clone of the popular vi editor for Unix. It is a a text +(Vi IMproved) is a clone of the popular vi editor for Unix. It is a text editor designed for speed and increased productivity, and is ubiquitous in most unix-based systems. It has numerous keybindings for speedy navigation to specific points in the file, and for fast editing. -- cgit v1.2.3 From 5a463a37256db3f1e42dd029d7d20e4cb03690dd Mon Sep 17 00:00:00 2001 From: Jiang Haiyun Date: Fri, 26 Aug 2016 16:05:48 +0800 Subject: Fix typo, 'Verbs ==> 'Verbs' (#2344) --- vim.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/vim.html.markdown b/vim.html.markdown index cd61ca74..edbc3da7 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -19,7 +19,7 @@ specific points in the file, and for fast editing. vim # Open in vim :q # Quit vim :w # Save current file - :wq # Save file and quit vim + :wq # Save file and quit vim :q! # Quit vim without saving file # ! *forces* :q to execute, hence quiting vim without saving :x # Save file and quit vim, shorter version of :wq @@ -77,9 +77,9 @@ specific points in the file, and for fast editing. Vim is based on the concept on **modes**. -Command Mode - vim starts up in this mode, used to navigate and write commands -Insert Mode - used to make changes in your file -Visual Mode - used to highlight text and do operations to them +Command Mode - vim starts up in this mode, used to navigate and write commands +Insert Mode - used to make changes in your file +Visual Mode - used to highlight text and do operations to them Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands ``` @@ -105,15 +105,15 @@ Ex Mode - used to drop down to the bottom with the ':' prompt to enter comm Vim can be thought of as a set of commands in a 'Verb-Modifier-Noun' format, where: -Verb - your action -Modifier - how you're doing your action +Verb - your action +Modifier - how you're doing your action Noun - the object on which your action acts on -A few important examples of 'Verbs, 'Modifiers', and 'Nouns': +A few important examples of 'Verbs', 'Modifiers', and 'Nouns': ``` # 'Verbs' - + d # Delete c # Change y # Yank (copy) -- cgit v1.2.3 From 12c9b8daba15cf4950ae73f9813219d45bf373e8 Mon Sep 17 00:00:00 2001 From: prestonpeterson Date: Sat, 27 Aug 2016 01:03:37 -0700 Subject: Update java.html.markdown (#2346) --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 56bffd88..57c10390 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -566,7 +566,7 @@ class PennyFarthing extends Bicycle { // out: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { - gear = 0; + this.gear = 0; } } -- cgit v1.2.3 From 1732caa9f45d512601bd6457a7672072a9879c84 Mon Sep 17 00:00:00 2001 From: Jiang haiyun Date: Fri, 26 Aug 2016 08:43:08 +0800 Subject: [vim/zh-cn] translation --- zh-cn/vim-cn.html.markdown | 236 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 zh-cn/vim-cn.html.markdown diff --git a/zh-cn/vim-cn.html.markdown b/zh-cn/vim-cn.html.markdown new file mode 100644 index 00000000..0c3f6043 --- /dev/null +++ b/zh-cn/vim-cn.html.markdown @@ -0,0 +1,236 @@ +--- +category: tool +tool: vim +filename: LearnVim-cn.txt +contributors: + - ["RadhikaG", "https://github.com/RadhikaG"] +translators: + - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] +lang: zh-cn +--- + + +[Vim](www.vim.org) +(Vi IMproved) 是 Unix 上的流行编辑器 vi 的克隆版本。这个文本编辑器 +是为性能和提升效率而设计的,并且在大多数基于 unix 的系统上普遍存在。 +它有大量的快捷键可用来快速导航到文件的特定位置,以便进行快速编辑。 + +## Vim 导航基础 + +``` + vim # 在 Vim 中打开 + :q # 退出 Vim + :w # 保存当前文件 + :wq # 保存文件并退出 Vim + :q! # 退出 Vim 并且不保存文件 + # ! *强制* 执行 :q, 因此没有保存就退出 Vim + :x # 保存文件并且退出 Vim, 是 :wq 的简写版本 + + u # 撤销 + CTRL+R # 重做 + + h # 左移一个字符 + j # 下移一行 + k # 上移一行 + l # 右移一个字符 + + # 在行内移动 + + 0 # 移到行首 + $ # 移到行尾 + ^ # 移到行内的第一个非空白字符处 + + # 在文本中查找 + + /word # 光标之后的所有该词都高亮显示 + ?word # 光标之前的所有该词都高亮显示 + n # 查找后将光标移到该词的下一个出现位置 + N # 光标移到该词的上一个出现位置 + + :%s/foo/bar/g # 将文件每一行上的所有 'foo' 都改成 'bar' + :s/foo/bar/g # 将当前行上的所有 'foo' 都改成 'bar' + + # 跳到字符处 + + f<字符> # 向前跳移到 <字符> 上 + t<字符> # 向前跳移到 <字符> 的左侧 + + # 例如, + f< # 向前跣到 < 上 + t< # 向前跳移到 < 的左侧 + + # 按词移动 + + w # 前移一个词 + b # 后移一个词 + e # 移到当前词的末尾 + + # 移动的其它命令 + + gg # 移到文件顶部 + G # 移到文件末尾 + :NUM # 移到第 NUM 行 (NUM 是任意数字) + H # 移到屏幕顶部 + M # 移到屏幕中间位置 + L # 移到屏幕末尾 +``` + +## 模式: + +Vim 基于 **模式** 这个概念。 + +命令模式 - Vim 启动后就处于这个模式,用于导航和操作命令 +插入模式 - 用于在你的文件中进行修改 +可视模式 - 用于高亮文本并对它们进行操作 +Ex 模式 - 用于跳到底部的 ':' 提示行上输入命令 + +``` + i # 在光标位置前,将 Vim 切换到插入模式 + a # 在光标位置后,将 Vim 切换到插入模式 + v # 将 Vim 切换到可视模式 + : # 将 Vim 切换到 ex 模式 + # 无论你当前处于什么模式,都返回到命令模式 + + # 复制和粘贴文本 + + y # 复制所选的内容 + yy # 复制当前行 + d # 删除所选的内容 + dd # 删除当前行 + p # 在当前光标位置后粘贴复制的文本 + P # 在当前光标位置前粘贴复制的文本 + x # 删除当前光标位置处的字符 +``` + +## Vim 的 '语法' + +Vim 可以被认为是按 '动词-修饰词-名词' 格式编排的一组命令: + +动词 - 你的动作 +修饰词 - 你如何执行你的动作 +名词 - 你的动作所作用于的对象 + +关于 '动词','修饰词',和 '名词' 的几个重要例子: + +``` + # '动词' + + d # 删除 + c # 修改 + y # 复制 + v # 可视化选择 + + # '修饰词' + + i # 内部的 + a # 周围的 + NUM # 数字 (NUM 是任意数字) + f # 查找文本并位于其上 + t # 查找文本并停于其前面 + / # 从光标处开始查找字符串 + ? # 在光标前查找字符串 + + # '名词' + + w # 词 + s # 句子 + p # 段落 + b # 块 + + # 示例 '语句' 或命令 + + d2w # 删除 2 个词 + cis # 修改段落内的内容 + yip # 复制段落内的内容 (复制你所在的段落) + ct< # 修改直到括号开启处 + # 对你的当前位置直到下个括号开启处的内容进行修改 + d$ # 删除直到行尾 +``` + +## 一些快捷键和技巧 + + +``` + > # 将所选内容缩进一级 + < # 将所选内容取消缩进一级 + :earlier 15m # 将文档还原到 15 分钟前的状态 + :later 15m # 逆转上述命令 + ddp # 相邻行交换位置,先 dd 再 p + . # 重复之前动作 +``` + +## 宏 + +宏基本上来说就是可录制的动作。 +当你开始录制宏时,它会记录你使用的 **每个** 动作和命令, +直到你停止录制。当调用宏时,它会将这个完全相同的动作和命令序列 +再次应用于所选文本之上。 + +``` + qa # 开始录制一个叫 'a' 的宏 + q # 停止录制 + @a # 重播宏 +``` + +### 配置 ~/.vimrc + +.vimrc 可用于在启动时对 Vim 进行配置。 + +这里是一个示例 ~/.vimrc 文件: + +``` +" 示例 ~/.vimrc +" 2015.10 + +" 需要 Vim iMproved 版本 +set nocompatible + +" 根据文件名检测文件类型,以便能进行智能自动缩进等操作。 +filetype indent plugin on + +" 开启语法高亮 +syntax on + +" 更好的命令行补全 +set wildmenu + +" 除了当使用大写字母时使用大小写无关查找 +set ignorecase +set smartcase + +" 当新开一行时,如果没有开启文件特定的缩进规则, +" 则缩进保持与你当前行一致 +set autoindent + +" 在左侧显示行号 +set number + +" 缩进选项,根据个人偏好进行修改 + +" 每个 TAB 的可视空格数 +set tabstop=4 + +" 编辑时 TAB 对应的空格数 +set softtabstop=4 + +" 当使用缩进操作 (>> 和 <<) 时缩进的空格数 +set shiftwidth=4 + +" 将 TAB 转换成空格 +set expandtab + +" 为缩进和对齐开启智能化的 TAB 和空格切换功能 +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 00302473841679ef7d3115fa03aac481f31d390f Mon Sep 17 00:00:00 2001 From: haiiiiiyun Date: Sat, 27 Aug 2016 13:38:04 +0800 Subject: zh-cn ruby page sync with English version & minor tweaks --- zh-cn/ruby-cn.html.markdown | 401 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 339 insertions(+), 62 deletions(-) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 14d38137..2d181de0 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -10,6 +10,7 @@ contributors: - ["ftwbzhao", "https://github.com/ftwbzhao"] translators: - ["Lin Xiangyu", "https://github.com/oa414"] + - ["Jiang Haiyun", "https://github.com/haiiiiiyun"] --- ```ruby @@ -35,6 +36,13 @@ translators: 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 + +# 位运算符 +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 # 算术符号只是语法糖而已 # 实际上是调用对象的方法 @@ -42,7 +50,7 @@ translators: 10.* 5 #=> 50 # 特殊的值也是对象 -nil # 空 +nil # 相当于其它语言中的 null true # 真 false # 假 @@ -54,13 +62,11 @@ false.class #=> FalseClass 1 == 1 #=> true 2 == 1 #=> false -# 不等运算符 +# 不相等运算符 1 != 1 #=> false 2 != 1 #=> true -!true #=> false -!false #=> true -# 除了false自己,nil是唯一的值为false的对象 +# 除了false自己,nil是唯一的另一个值为false的对象 !nil #=> true !false #=> true @@ -72,6 +78,26 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true + +# 组合比较运算符 +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# 逻辑运算符 +true && false #=> false +true || false #=> true +!true #=> false + +# 也有优先级更低的逻辑运算符 +# 它们用于控制流结构中,用来串接语句,直到返回true或false。 + +# `do_something_else` 只当 `do_something` 返回true时才会被调用 +do_something() and do_something_else() +# `log_error` 只当 `do_something` 返回false时才会被调用 +do_something() or log_error() + + # 字符串是对象 'I am a string'.class #=> String @@ -81,9 +107,28 @@ placeholder = "use string interpolation" "I can #{placeholder} when using double quoted strings" #=> "I can use string interpolation when using double quoted strings" +# 尽可能优先使用单引号的字符串 +# 双引号的字符串会进行一些额外的内部处理 + +# 合并字符串,但不能和数字合并 +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# 合并字符串及其运算符 +'hello ' * 3 #=> "hello hello hello " + +# 字符串追加 +'hello' << ' world' #=> "hello world" -# 输出值 +# 打印输出,并在末尾加换行符 puts "I'm printing!" +#=> I'm printing! +#=> nil + +# 打印输出,不加换行符 +print "I'm printing!" +#=> I'm printing! => nil # 变量 x = 25 #=> 25 @@ -96,17 +141,16 @@ x = y = 10 #=> 10 x #=> 10 y #=> 10 -# 按照惯例,用 snake_case 作为变量名 +# 按照惯例,使用类似snake_case风格的变量名 snake_case = true -# 使用具有描述性的运算符 +# 使用有意义的变量名 path_to_project_root = '/good/name/' path = '/bad/name/' # 符号(Symbols,也是对象) -# 符号是不可变的,内部用整数类型表示的可重用的值。 -# 通常用它代替字符串来有效地表示有意义的值。 - +# 符号是不可变的,内部用整数值表示的可重用的常数 +# 通常用它代替字符串来有效地表示有意义的值 :pending.class #=> Symbol @@ -132,26 +176,36 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] array[0] #=> 1 array[12] #=> nil -# 像运算符一样,[var]形式的访问 -# 也就是一个语法糖 -# 实际上是调用对象的[] 方法 +# 像运算符一样,[var] 形式的访问 +# 也只是语法糖 +# 实际上是调用对象的 [] 方法 array.[] 0 #=> 1 array.[] 12 #=> nil # 从尾部开始 array[-1] #=> 5 +array.last #=> 5 # 同时指定开始的位置和长度 array[2, 3] #=> [3, 4, 5] -# 或者指定一个范围 +# 将数组逆序 +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# 或者指定一个区间 array[1..3] #=> [2, 3, 4] # 像这样往数组增加一个元素 array << 6 #=> [1, 2, 3, 4, 5, 6] +# 或者像这样 +array.push(6) #=> [1, 2, 3, 4, 5, 6] -# 哈希表是Ruby的键值对的基本数据结构 -# 哈希表由大括号定义 +# 检查元素是否包含在数组中 +array.include?(1) #=> true + +# 哈希表是 Ruby 的主要键/值对表示法 +# 哈希表由大括号表示 hash = {'color' => 'green', 'number' => 5} hash.keys #=> ['color', 'number'] @@ -163,19 +217,14 @@ hash['number'] #=> 5 # 查询一个不存在地键将会返回nil hash['nothing here'] #=> nil -# 用 #each 方法来枚举哈希表: -hash.each do |k, v| - puts "#{k} is #{v}" -end - -# 从Ruby 1.9开始, 用符号作为键的时候有特别的记号表示: +# 从Ruby 1.9开始,用符号作为键的时候有特别的记号表示: -new_hash = { defcon: 3, action: true} +new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] # 小贴士:数组和哈希表都是可枚举的 -# 它们可以共享一些有用的方法,比如each, map, count 等等 +# 它们共享一些有用的方法,比如each,map,count等等 # 控制流 @@ -196,9 +245,15 @@ end #=> iteration 4 #=> iteration 5 -# 然而 -# 没人用for循环 -# 用`each`来代替,就像这样 + +# 但是,没有人用for循环。 +# 你应该使用"each"方法,然后再传给它一个块。 +# 所谓块就是可以传给像"each"这样的方法的代码段。 +# 它类似于其它语言中的lambdas, 匿名函数或闭包。 +# +# 区间上的"each"方法会对区间中的每个元素运行一次块代码。 +# 我们将counter作为一个参数传给了块。 +# 调用带有块的"each"方法看起来如下: (1..5).each do |counter| puts "iteration #{counter}" @@ -209,6 +264,23 @@ end #=> iteration 4 #=> iteration 5 +# 你也可以将块包含在一个大括号中: +(1..5).each { |counter| puts "iteration #{counter}" } + +# 数据结构中的内容也可以使用each来遍历。 +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +# 如果你还需要索引值,可以使用"each_with_index",并且定义 +# 一个索引变量 +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" @@ -220,6 +292,20 @@ end #=> iteration 4 #=> iteration 5 +# Ruby 中还有很多有用的循环遍历函数, +# 如"map","reduce","inject"等等。 +# 以map为例,它会遍历数组,并根据你在 +# 块中定义的逻辑对它进行处理,然后返回 +# 一个全新的数组。 +array = [1,2,3,4,5] +doubled = array.map do |element| + element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + grade = 'B' case grade @@ -236,6 +322,33 @@ when 'F' else puts "Alternative grading system, eh?" end +#=> "Better luck next time" + +# case也可以用区间 +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# 异常处理: +begin + # 这里的代码可能会抛出异常 + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end # 函数 @@ -243,7 +356,7 @@ def double(x) x * 2 end -# 函数 (以及所有的方法块) 隐式地返回了最后语句的值 +# 函数 (以及所有的块) 隐式地返回最后语句的值 double(2) #=> 4 # 当不存在歧义的时候括号是可有可无的 @@ -261,8 +374,8 @@ sum 3, 4 #=> 7 sum sum(3,4), 5 #=> 12 # yield -# 所有的方法都有一个隐式的块参数 -# 可以用yield参数调用 +# 所有的方法都有一个隐式的,可选的块参数 +# 可以用 'yield' 关键字调用 def surround puts "{" @@ -276,45 +389,84 @@ surround { puts 'hello world' } # hello world # } +# 可以向函数传递一个块 +# "&"标记传递的块是一个引用 +def guests(&block) + block.call 'some_argument' +end -# 用class关键字定义一个类 -class Human - - # 一个类变量,它被这个类地所有实例变量共享 - @@species = "H. sapiens" +# 可以传递多个参数,这些参数会转成一个数组, +# 这也是使用星号符 ("*") 的原因: +def guests(*array) + array.each { |guest| puts guest } +end - # 构造函数 - def initialize(name, age=0) - # 将参数name的值赋给实例变量@name - @name = name - # 如果没有给出age, 那么会采用参数列表中地默认地值 - @age = age - end +# 如果函数返回一个数组,在赋值时可以进行拆分: +def foods + ['pancake', 'sandwich', 'quesadilla'] +end +breakfast, lunch, dinner = foods +breakfast #=> 'pancake' +dinner #=> 'quesadilla' - # 基本的 setter 方法 - def name=(name) - @name = name - end +# 按照惯例,所有返回布尔值的方法都以?结尾 +5.even? # false +5.odd? # true - # 基本地 getter 方法 - def name - @name - end +# 如果方法名末尾有!,表示会做一些破坏性的操作,比如修改调用者自身。 +# 很多方法都会有一个!的版本来进行修改,和一个非!的版本 +# 只用来返回更新了的结果 +company_name = "Dunder Mifflin" +company_name.upcase #=> "DUNDER MIFFLIN" +company_name #=> "Dunder Mifflin" +company_name.upcase! # we're mutating company_name this time! +company_name #=> "DUNDER MIFFLIN" - # 一个类方法以self.开头 - # 它可以被类调用,但不能被类的实例调用 - def self.say(msg) - puts "#{msg}" - end - def species - @@species - end +# 用class关键字定义一个类 +class Human + # 一个类变量,它被这个类的所有实例变量共享 + @@species = "H. sapiens" + + # 基本构造函数 + def initialize(name, age = 0) + # 将参数值赋给实例变量"name" + @name = name + # 如果没有给出age,那么会采用参数列表中的默认值 + @age = age + end + + # 基本的setter方法 + def name=(name) + @name = name + end + + # 基本地getter方法 + def name + @name + end + + # 以上的功能也可以用下面的attr_accessor来封装 + attr_accessor :name + + # Getter/setter方法也可以像这样单独创建 + attr_reader :name + attr_writer :name + + # 类方法通过使用self与实例方法区别开来。 + # 它只能通过类来调用,不能通过实例调用。 + def self.say(msg) + puts "#{msg}" + end + + def species + @@species + end end -# 类的例子 +# 初始化一个类 jim = Human.new("Jim Halpert") dwight = Human.new("Dwight K. Schrute") @@ -327,7 +479,132 @@ jim.name #=> "Jim Halpert II" dwight.species #=> "H. sapiens" dwight.name #=> "Dwight K. Schrute" -# 调用对象的方法 -Human.say("Hi") #=> "Hi" +# 调用类方法 +Human.say('Hi') #=> "Hi" + +# 变量的作用域由它们的名字格式定义 +# 以$开头的变量具有全局域 +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# 以@开头的变量具有实例作用域 +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# 以@@开头的变量具有类作用域 +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# 以大写字母开头的变量是常数 +Var = "I'm a constant" +defined? Var #=> "constant" + +# 类也是对象。因此类也可以有实例变量。 +# 类变量在类以及其继承者之间共享。 + +# 基类 +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# 派生类 +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# 类实例变量不能在继承类间共享。 + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +module ModuleExample + def foo + 'foo' + end +end + +# '包含'模块后,模块的方法会绑定为类的实例方法 +# '扩展'模块后,模块的方法会绑定为类方法 + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# 当包含或扩展一个模块时,相应的回调代码会被执行。 +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' ``` + + +## 其它资源 + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [An Interactive Tutorial for Ruby](https://rubymonk.com/) - Learn Ruby through a series of interactive tutorials. +- [Official Documentation](http://ruby-doc.org/core) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. +- [Try Ruby](http://tryruby.org) - Learn the basic of Ruby programming language, interactive in the browser. -- cgit v1.2.3 From e810b6fd41d9df92bb2b83ad394f12468e5b2a3a Mon Sep 17 00:00:00 2001 From: Philipp Klose Date: Tue, 30 Aug 2016 10:11:09 +0200 Subject: minor typo (#2349) --- cmake.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake.html.markdown b/cmake.html.markdown index a2c8cc8a..45cf0585 100644 --- a/cmake.html.markdown +++ b/cmake.html.markdown @@ -45,7 +45,7 @@ cmake_minimum_required (VERSION 2.8) cmake_minimum_required (VERSION 2.8 FATAL_ERROR) # We setup the name for our project. After we do that, this will change some -# directories naming convention genearted by CMake. We can send the LANG of +# directories naming convention generated by CMake. We can send the LANG of # code as second param project (learncmake C) -- cgit v1.2.3 From 98abad6935b77e66a4b8f2ddff340d57dbfeb173 Mon Sep 17 00:00:00 2001 From: Adam Date: Wed, 31 Aug 2016 15:18:38 -0700 Subject: Remove redundant nl markdown and fix fortran file --- fortran95.html.markdown | 2 +- nl-nl/markdown-nl-html.markdown | 256 ---------------------------------------- tr-tr/c-tr.html.markdown | 2 +- 3 files changed, 2 insertions(+), 258 deletions(-) delete mode 100644 nl-nl/markdown-nl-html.markdown diff --git a/fortran95.html.markdown b/fortran95.html.markdown index 8479fef8..5d1424bf 100644 --- a/fortran95.html.markdown +++ b/fortran95.html.markdown @@ -17,7 +17,7 @@ This overview will discuss the features of Fortran 95 since it is the most widely implemented of the more recent specifications and the later versions are largely similar (by comparison FORTRAN 77 is a very different language). -```fortran +``` ! This is a comment. diff --git a/nl-nl/markdown-nl-html.markdown b/nl-nl/markdown-nl-html.markdown deleted file mode 100644 index 0f954715..00000000 --- a/nl-nl/markdown-nl-html.markdown +++ /dev/null @@ -1,256 +0,0 @@ ---- -language: markdown -contributors: - - ["Dan Turkel", "http://danturkel.com/"] -filename: learnmarkdown-nl.md -translators: - - ["Niels van Velzen", "https://nielsvanvelzen.me"] -lang: nl-nl ---- - -Markdown is gemaakt door John Gruber in 2004. De bedoeling was om een simpel te -lezen en schrijven syntax te creëren wat makkelijk om te zetten is naar -HTML (en tegenwoordig ook vele andere formaten). - -```markdown - - - - - - -# Dit is een

-## Dit is een

-### Dit is een

-#### Dit is een

-##### Dit is een

-###### Dit is een
- - -Dit is een h1 -============= - -Dit is een h2 -------------- - - - - -*Deze tekst staat schuin.* -_Net als deze tekst._ - -**Deze tekst is dikgedrukt.** -__Net als deze tekst.__ - -***En deze tekst is dik en schuin.*** -**_Net als dit!_** -*__En dit!__* - - - -~~Deze tekst is doorgehaald.~~ - - - - -Dit is een paragraaf. Ik typ in een paragraaf, is dat niet leuk? - -Nu ben ik in paragraaf 2. -Nog steeds in paragraaf 2! - -Dit is paragraaf drie! - - - -Ik eindig met twee spaties (selecteer mij om het te zien). - -Er is een nieuwe regel boven mij! - - - -> Dit is een citaat. Je kan -> handmatig je lijnen laten vormen of je kan je lijnen lang laten worden en vanzelf op nieuwe regels verder laten gaan. -> Het maakt niet uit zolang je maar begint met een `>`. - -> Je kunt ook meer dan 1 level ->> uitlijning gebruiken. -> Hoe handig is dat? - - - - -* Item -* Item -* Nog een item - -of - -+ Item -+ Item -+ Nog een item - -of - -- Item -- Item -- Nog een item - - - -1. Item een -2. Item twee -3. Item drie - - - -1. Item een -1. Item twee -1. Item drie - - - - - -1. Item een -2. Item twee -3. Item drie - * Sub-item een - * Sub-item twee -4. Item vier - - - -Checkboxes hieronder zonder de 'x' zijn leeg. -- [ ] Eerste taak. -- [ ] Tweede taak -Checkboxes met een 'x' zijn klaar. -- [x] Deze taak is klaar. - - - - - Dit is code - net als dit - - - - mijn_array.each do |item| - puts item - end - - - -John wist niet eens wat de `go_to()` functie deed! - - - -\`\`\`ruby -def foobar - puts "Hallo wereld!" -end -\`\`\` - - - - - - -*** ---- -- - - -**************** - - - - -[Klik op mij!](http://test.com/) - - - -[Klik op mij!](http://test.com/ "Link naar Test.com") - - - -[Ga naar de muziek](/music/). - - - -[Klik op deze link][link1] vor meer informatie erover! -[Bekijk deze ook eens][foobar] als je wilt. - -[link1]: http://test.com/ "Cool!" -[foobar]: http://foobar.biz/ "In orde!" - - - - - -[Dit][] is een link. - -[dit]: http://ditiseenlink.nl/ - - - - - - -![Dit is de alt attribuut van het plaatje](http://imgur.com/myimage.jpg "Een optionele titel") - - - -![Dit is de alt attribuut.][mijnplaatje] - -[mijnplaatje]: relative/urls/cool/image.jpg "Hier is de titel" - - - - - is hetzelfde als -[http://testwebsite.com/](http://testwebsite.com/) - - - - - - - -Ik wil *deze tekst met sterretjes typen* maar ik wil het niet schuin, dus ik doe dit: \*deze tekst met sterretjes typen\*. - - - - -Computer gecrashed? Gebruik eens -Ctrl+Alt+Del - - - - -| kolom1 | kolom2 |kolom3 | -| :--------------- | :---------: | ----------------: | -| Links-uitgelijnd | Gecentreerd | Rechts-uitgelijnd | -| blah | blah | blah | - - - -Kolom 1 | Kolom 2 | Kolom 3 -:-- | :-: | --: -Dit is zo lelijk | stop | er mee - - - -``` - -Voor meer informatie, bekijk Josn Gruber's officiele post over de syntax [hier](http://daringfireball.net/projects/markdown/syntax). Of bekijk Adam Pritchard's grote cheatsheet [hier](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) (beide Engels). diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 2d4240ed..33544765 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -202,7 +202,7 @@ int main() { 0x02 >> 1; // => 0x01 (bitwise right shift (by 1)) // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir: - // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32) + // - isaretli sayinin isaret bitinde yap?ilan kaydirma (int a = 1 << 32) // - negatif sayilarda sol kaydirma (int a = -1 << 2) // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma: // int a = 1 << 32; // UB if int is 32 bits wide -- cgit v1.2.3 From 678fa3b97468a903fc256d95c58f54db5a531a64 Mon Sep 17 00:00:00 2001 From: Patrick Callahan Date: Thu, 1 Sep 2016 02:28:23 -0400 Subject: Remove Python 2 resources from Python 3 page (#2350) There were several resources here that teach Python 2, but not Python 3. I removed them so that a reader will only see resources that apply to Python 3. --- python3.html.markdown | 5 ----- 1 file changed, 5 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 6b3486a6..09b041b8 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -887,12 +887,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Free Online * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) * [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) @@ -903,5 +900,3 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 3d270111bd45c8eac51a642951e81e3313436648 Mon Sep 17 00:00:00 2001 From: Alois Date: Thu, 1 Sep 2016 19:27:41 +0200 Subject: [WIP] [toml/en] Add TOML support (#2282) * Init support for TOML * Add scalar types section * Move comment to key value * Improve introduction * Move int comment to int key value * Add array support * Add version warning * Add support for table * Add inline table part * Add support array of table part * Fix bugs/typos to follow the review * Improve sub tables example * Fix wrong quotes on multiLineLiteralString * Fix letter case for coherence * Remove old comment * Move from variety to color Thanks @robochat --- toml.html.markdown | 274 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 274 insertions(+) create mode 100755 toml.html.markdown diff --git a/toml.html.markdown b/toml.html.markdown new file mode 100755 index 00000000..980563f9 --- /dev/null +++ b/toml.html.markdown @@ -0,0 +1,274 @@ +--- +language: toml +filename: learntoml.toml +contributors: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +--- + +TOML stands for Tom's Obvious, Minimal Language. It is a data serialisation language designed to be a minimal configuration file format that's easy to read due to obvious semantics. + +It is an alternative to YAML and JSON. It aims to be more human friendly than JSON and simpler that YAML. TOML is designed to map unambiguously to a hash table. TOML should be easy to parse into data structures in a wide variety of languages. + +Be warned, TOML's spec is still changing a lot. Until it's marked as 1.0, you +should assume that it is unstable and act accordingly. This document follows TOML v0.4.0. + +```toml +# Comments in TOML look like this. + +################ +# SCALAR TYPES # +################ + +# Our root object (which continues for the entire document) will be a map, +# which is equivalent to a dictionary, hash or object in other languages. + +# The key, equals sign, and value must be on the same line +# (though some values can be broken over multiple lines). +key = "value" +string = "hello" +number = 42 +float = 3.14 +boolean = true +dateTime = 1979-05-27T07:32:00-08:00 +scientificNotation = 1e+12 +"key can be quoted" = true # Both " and ' are fine +"key may contains" = "letters, numbers, underscores, and dashes" + +# A bare key must be non-empty, but an empty quoted key is allowed +"" = "blank" # VALID but discouraged +'' = 'blank' # VALID but discouraged + +########## +# String # +########## + +# All strings must contain only valid UTF-8 characters. +# We can escape characters and some of them have a compact escape sequence. +# For example, \t add a tabulation. Refers to the spec to get all of them. +basicString = "are surrounded by quotation marks. \"I'm quotable\". Name\tJos" + +multiLineString = """ +are surrounded by three quotation marks +on each side and allow newlines.""" + +literalString = 'are surrounded by single quotes. Escaping are not allowed.' + +multiLineLiteralString = ''' +are surrounded by three single quotes on each side +and allow newlines. Still no escaping. +The first newline is trimmed in raw strings. + All other whitespace + is preserved. #! are preserved? +''' + +# For binary data it is recommended that you use Base64, another ASCII or UTF8 +# encoding. The handling of that encoding will be application specific. + +########### +# Integer # +########### + +## Integers can start with a +, a - or nothing. +## Leading zeros are not allowed. Hex, octal, and binary forms are not allowed. +## Values that cannot be expressed as a series of digits are not allowed. +int1 = +42 +int2 = 0 +int3 = -21 +integerRange = 64 + +## You can use underscores to enhance readability. Each +## underscore must be surrounded by at least one digit. +int4 = 5_349_221 +int5 = 1_2_3_4_5 # VALID but discouraged + +######### +# Float # +######### + +# Floats are an integer followed by a fractional and/or an exponent part. +flt1 = 3.1415 +flt2 = -5e6 +flt3 = 6.626E-34 + +########### +# Boolean # +########### + +bool1 = true +bool2 = false +boolMustBeLowercase = true + +############ +# Datetime # +############ + +date1 = 1979-05-27T07:32:00Z # follows the RFC 3339 spec +date2 = 1979-05-27T07:32:00 # without offset +date3 = 1979-05-27 # without offset nor time + +#################### +# COLLECTION TYPES # +#################### + +######### +# Array # +######### + +array1 = [ 1, 2, 3 ] +array2 = [ "Commas", "are", "delimiters" ] +array3 = [ "Don't mixed", "different", "types" ] +array4 = [ [ 1.2, 2.4 ], ["all", 'strings', """are the same""", '''type'''] ] +array5 = [ + "Whitespace", "is", "ignored" +] + +######### +# Table # +######### + +# Tables (or hash tables or dictionaries) are collections of key/value +# pairs. They appear in square brackets on a line by themselves. +# Empty tables are allowed and simply have no key/value pairs within them. +[table] + +# Under that, and until the next table or EOF are the key/values of that table. +# Key/value pairs within tables are not guaranteed to be in any specific order. +[table-1] +key1 = "some string" +key2 = 123 + +[table-2] +key1 = "another string" +key2 = 456 + +# Dots are prohibited in bare keys because dots are used to signify nested tables. +# Naming rules for each dot separated part are the same as for keys. +[dog."tater.man"] +type = "pug" + +# In JSON land, that would give you the following structure: +# { "dog": { "tater.man": { "type": "pug" } } } + +# Whitespace around dot-separated parts is ignored, however, best practice is to +# not use any extraneous whitespace. +[a.b.c] # this is best practice +[ d.e.f ] # same as [d.e.f] +[ j . "ʞ" . 'l' ] # same as [j."ʞ".'l'] + +# You don't need to specify all the super-tables if you don't want to. TOML knows +# how to do it for you. +# [x] you +# [x.y] don't +# [x.y.z] need these +[x.y.z.w] # for this to work + +# As long as a super-table hasn't been directly defined and hasn't defined a +# specific key, you may still write to it. +[a.b] +c = 1 + +[a] +d = 2 + +# You cannot define any key or table more than once. Doing so is invalid. + +# DO NOT DO THIS +[a] +b = 1 + +[a] +c = 2 + +# DO NOT DO THIS EITHER +[a] +b = 1 + +[a.b] +c = 2 + +# All table names must be non-empty. +[] # INVALID +[a.] # INVALID +[a..b] # INVALID +[.b] # INVALID +[.] # INVALID + +################ +# Inline table # +################ + +inlineTables = { areEnclosedWith = "{ and }", mustBeInline = true } +point = { x = 1, y = 2 } + +################### +# Array of Tables # +################### + +# An array of tables can be expressed by using a table name in double brackets. +# Each table with the same double bracketed name will be an item in the array. +# The tables are inserted in the order encountered. + +[[products]] +name = "array of table" +sku = 738594937 +emptyTableAreAllowed = true + +[[products]] + +[[products]] +name = "Nail" +sku = 284758393 +color = "gray" + +# You can create nested arrays of tables as well. Each double-bracketed +# sub-table will belong to the nearest table element above it. + +[[fruit]] + name = "apple" + + [fruit.Geometry] + shape = "round" + note = "I am an fruit's property" + + [[fruit.color]] + name = "red" + note = "I am an array's item in apple" + + [[fruit.color]] + name = "green" + note = "I am in the same array than red" + +[[fruit]] + name = "banana" + + [[fruit.color]] + name = "yellow" + note = "I am an array's item too but banana's one" +``` + +In JSON land, this code will be: + +```json +{ + "fruit": [ + { + "name": "apple", + "geometry": { "shape": "round", "note": "..."}, + "color": [ + { "name": "red", "note": "..." }, + { "name": "green", "note": "..." } + ] + }, + { + "name": "banana", + "color": [ + { "name": "yellow", "note": "..." } + ] + } + ] +} +``` + +### More Resources + ++ [TOML official repository](https://github.com/toml-lang/toml) -- cgit v1.2.3 From 425d1dee6704599029ef7e27445328ad4c91d341 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 1 Sep 2016 21:03:09 +0200 Subject: Delete HTML-fr.html.markdown --- HTML-fr.html.markdown | 115 -------------------------------------------------- 1 file changed, 115 deletions(-) delete mode 100644 HTML-fr.html.markdown diff --git a/HTML-fr.html.markdown b/HTML-fr.html.markdown deleted file mode 100644 index fdde9107..00000000 --- a/HTML-fr.html.markdown +++ /dev/null @@ -1,115 +0,0 @@ ---- -language: html -filename: learnhtml-fr.html -contributors: - - ["Christophe THOMAS", "https://github.com/WinChris"] -lang: fr-fr ---- -HTML signifie HyperText Markup Language. -C'est un langage (format de fichiers) qui permet d'écrire des pages internet. -C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). -Les fichiers HTML sont en réalité de simple fichier texte. -Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. -Ce balisage sert à donner une signification au texte ainsi entouré. -Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. - -**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. -Cet article porte principalement sur la syntaxe et quelques astuces. - - -```HTML - - - - - - - - - - - Mon Site - - -

Hello, world!

- Venez voir ce que ça donne -

Ceci est un paragraphe

-

Ceci est un autre paragraphe

-
    -
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • -
  • Ceci est un autre item
  • -
  • Et ceci est le dernier item de la liste
  • -
- - - - - - - - - - - - - - - - - - - - Mon Site - - - - - - - -

Hello, world!

- - Venez voir ce que ça donne -

Ceci est un paragraphe

-

Ceci est un autre paragraphe

-
    - -
  • Ceci est un item d'une liste non ordonnée (liste à puces)
  • -
  • Ceci est un autre item
  • -
  • Et ceci est le dernier item de la liste
  • -
- - - - - - - - - - - - - - - - - - - - - - - - - -
First Header Second Header
Première ligne, première cellule Première ligne, deuxième cellule
Deuxième ligne, première celluleDeuxième ligne, deuxième cellule
- -## Utilisation - -Le HTML s'écrit dans des fichiers `.html`. - -## En savoir plus - -* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) -* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From 7beaa529b912ccda6e26eee85acae50e79c6d6d5 Mon Sep 17 00:00:00 2001 From: Patrick Callahan Date: Thu, 1 Sep 2016 17:27:33 -0400 Subject: [python3/en] Adding "Dive Into Python 3" (#2353) The previous version of this file had the original Dive Into Python, which was written with Python 2 in mind. It has come to my attention that the author of the original has published an updated version designed for Python 3, so I added this version back in. --- python3.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python3.html.markdown b/python3.html.markdown index 09b041b8..dc534f74 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -896,7 +896,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python 3](https://www.amazon.com/gp/product/1430224150?ie=UTF8&tag=diveintomark-20&creativeASIN=1430224150) -- cgit v1.2.3 From 66c8b036dcdbcd538f914e14d073194d704159fa Mon Sep 17 00:00:00 2001 From: robochat Date: Sat, 3 Sep 2016 19:30:53 +0200 Subject: [html/en] adding translation of html/fr (#2354) * [html/en] adding a translation of html/fr. * [html/en] small changes and 1 bug fix. * [html/fr] small bug fix. * [html/en] small bug fix. --- fr-fr/HTML-fr.html.markdown | 2 + html.html.markdown | 120 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 html.html.markdown diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown index 4d2da921..b52fd34a 100644 --- a/fr-fr/HTML-fr.html.markdown +++ b/fr-fr/HTML-fr.html.markdown @@ -106,6 +106,8 @@ Cet article porte principalement sur la syntaxe et quelques astuces. +``` + ## Utilisation Le HTML s'écrit dans des fichiers `.html`. diff --git a/html.html.markdown b/html.html.markdown new file mode 100644 index 00000000..3e5e43c3 --- /dev/null +++ b/html.html.markdown @@ -0,0 +1,120 @@ +--- +language: html +filename: learnhtml.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Robert Steed", "https://github.com/robochat"] +--- + +HTML stands for HyperText Markup Language. +It is a language which us to write pages for the world wide web. +It is a markup language, it enables us to write to write webpages using code to indicate how text and data should be displayed. +In fact, html files are simple text files. +What is this markup? It is a method of organising the page's data by surrounding it with opening tags and closing tags. +This markup serves to give significance to the text that it encloses. +Like other computer languages, HTML has many versions. Here we will talk about HTML5. + +**NOTE :** You can test the different tags and elements as you progress through the tutorial on a site like [codepen](http://codepen.io/pen/) in order to see their effects, understand how they work and familiarise yourself with the language. +This article is concerned principally with HTML syntax and some useful tips. + + +```html + + + + + + + + + + My Site + + +

Hello, world!

+ Come look at what this shows/a> +

This is a paragraph.

+

This is another paragraph.

+
    +
  • This is an item in a non-enumerated list (bullet list)
  • +
  • This is another item
  • +
  • And this is the last item on the list
  • +
+ + + + + + + + + + + + + + + + + + + + + My Site + + + + + + + +

Hello, world!

+ +
Come look at what this shows +

This is a paragraph.

+

This is another paragraph.

+
    + +
  • This is an item in a non-enumerated list (bullet list)
  • +
  • This is another item
  • +
  • And this is the last item on the list
  • +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
First Header Second Header
first row, first column first row, second column
second row, first columnsecond row, second column
+ +``` + +## Usage + +HTML is written in files ending with `.html`. + +## To Learn More + +* [wikipedia](https://en.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) +* [W3School](http://www.w3schools.com/html/html_intro.asp) -- cgit v1.2.3 From a00c47f70141ee694eef7dabc54778d3c178607d Mon Sep 17 00:00:00 2001 From: Baurzhan Muftakhidinov Date: Mon, 5 Sep 2016 12:42:02 +0500 Subject: Add missing space. (#2356) --- binary-search.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/binary-search.html.markdown b/binary-search.html.markdown index 92df4875..ce436b44 100644 --- a/binary-search.html.markdown +++ b/binary-search.html.markdown @@ -9,7 +9,7 @@ contributors: ## Why Binary Search? -Searching is one of the prime problems in the domain of Computer Science.Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. +Searching is one of the prime problems in the domain of Computer Science. Today there are more than 1 trillion searches per year, and we need algorithms that can do that very fastly. Binary search is one of the fundamental algorithms in computer science. In order to explore it, we’ll first build up a theoretical backbone, then use that to implement the algorithm properly. ## Introduction -- cgit v1.2.3 From d75468c6fe58c3152facf0dffd8743a6c2edbec0 Mon Sep 17 00:00:00 2001 From: robochat Date: Mon, 5 Sep 2016 10:34:25 +0200 Subject: adding missing lang entries to headers for 3 tutorials (#2352) --- id-id/markdown.html.markdown | 1 + it-it/rust-it.html.markdown | 1 + pt-br/elixir.html.markdown | 1 + 3 files changed, 3 insertions(+) diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown index 9a7c18cc..06ad1092 100644 --- a/id-id/markdown.html.markdown +++ b/id-id/markdown.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Dan Turkel", "http://danturkel.com/"] translators: - ["Tasya Aditya Rukmana", "http://github.com/tadityar"] +lang: id-id filename: markdown-id.md --- diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown index dd5005f2..8ef09712 100644 --- a/it-it/rust-it.html.markdown +++ b/it-it/rust-it.html.markdown @@ -2,6 +2,7 @@ language: rust contributors: - ["Carlo Milanesi", "http://github.com/carlomilanesi"] +lang: it-it filename: rust-it.html.markdown --- diff --git a/pt-br/elixir.html.markdown b/pt-br/elixir.html.markdown index b4ca8a52..f8c56101 100644 --- a/pt-br/elixir.html.markdown +++ b/pt-br/elixir.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Dzianis Dashkevich", "https://github.com/dskecse"] translators: - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br filename: learnelixir-pt.ex --- -- cgit v1.2.3 From 30e5ceed3174347d675b5eb9a474c960e1542d44 Mon Sep 17 00:00:00 2001 From: Ondrej Linek Date: Mon, 5 Sep 2016 22:19:17 +0200 Subject: add Czech [cs-cz] translation of the Go intro. (#2357) --- cs-cz/go.html.markdown | 431 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 431 insertions(+) create mode 100644 cs-cz/go.html.markdown diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown new file mode 100644 index 00000000..f814d2da --- /dev/null +++ b/cs-cz/go.html.markdown @@ -0,0 +1,431 @@ +--- +name: Go +category: language +language: Go +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Ondra Linek", "https://github.com/defectus/"] + +--- + +Jazyk Go byl vytvořen, jelikož bylo potřeba dokončit práci. Není to poslední +trend ve světě počítačové vědy, ale je to nejrychlejší a nejnovější způsob, +jak řešit realné problémy. + +Go používá známé koncepty imperativních jazyků se statickým typováním. +Rychle se kompiluje a také rychle běží. Přidává snadno pochopitelnou +podporu konkurenčnosti, což umožňuje využít výhody multi-core procesorů a +jazyk také obsahuje utility, které pomáhají se škálovatelným programováním. + +Go má již v základu vynikající knihovnu a je s ním spojená nadšená komunita. + +```go +// Jednořádkový komentář +/* Několika + řádkový komentář */ + +// Každý zdroják začíná deklarací balíčku (package) +// Main je vyhrazené jméno, které označuje spustitelný soubor, +// narozdíl od knihovny +package main + +// Importní deklarace říkají, které knihovny budou použity v tomto souboru. +import ( + "fmt" // Obsahuje formátovací funkce a tisk na konzolu + "io/ioutil" // Vstupně/výstupní funkce + m "math" // Odkaz na knihovnu math (matematické funkce) pod zkratkou m + "net/http" // Podpora http protokolu, klient i server. + "strconv" // Konverze řetězců, např. na čísla a zpět. +) + +// Definice funkce. Funkce main je zvláštní, je to vstupní bod do programu. +// Ať se vám to líbí, nebo ne, Go používá složené závorky +func main() { + // Println vypisuje na stdout. + // Musí být kvalifikováno jménem svého balíčko, ftm. + fmt.Println("Hello world!") + + // Zavoláme další funkci + svetPoHello() +} + +// Funkce mají své parametry v závorkách +// Pokud funkce nemá parametry, tak musíme stejně závorky uvést. +func svetPoHello() { + var x int // Deklarace proměnné. Proměnné musí být před použitím deklarované + x = 3 // Přiřazení hodnoty do proměnné + // Existuje "krátká" deklarace := kde se typ proměnné odvodí, + // proměnná vytvoří a přiřadí se jí hodnota + y := 4 + sum, prod := naucSeNasobit(x, y) // Funkce mohou vracet více hodnot + fmt.Println("sum:", sum, "prod:", prod) // Jednoduchý výstup + naucSeTypy() // < y minut je za námi, je čas učit se víc! +} + +/* <- začátek mnohořádkového komentáře +Funkce mohou mít parametry a (několik) návratových hodnot. +V tomto případě jsou `x`, `y` parametry a `sum`, `prod` jsou návratové hodnoty. +Všiměte si, že `x` a `sum` jsou typu `int`. +*/ +func naucSeNasobit(x, y int) (sum, prod int) { + return x + y, x * y // Vracíme dvě hodnoty +} + +// zabudované typy a literáty. +func naucSeTypy() { + // Krátká deklarace většinou funguje + str := "Learn Go!" // typ řetězec. + + s2 := `"surový" literát řetězce +může obsahovat nové řádky` // Opět typ řetězec. + + // Můžeme použít ne ASCII znaky, Go používá UTF-8. + g := 'Σ' // type runa, což je alias na int32 a ukládá se do něj znak UTF-8 + + f := 3.14195 // float64, je IEEE-754 64-bit číslem s plovoucí čárkou. + c := 3 + 4i // complex128, interně uložené jako dva float64. + + // takhle vypadá var s inicializací + var u uint = 7 // Číslo bez znaménka, jehož velikost záleží na implementaci, + // stejně jako int + var pi float32 = 22. / 7 + + // takto se převádí typy za pomoci krátké syntaxe + n := byte('\n') // byte je jiné jméno pro uint8. + + // Pole mají fixní délku, které se určuje v době kompilace. + var a4 [4]int // Pole 4 intů, všechny nastaveny na 0. + a3 := [...]int{3, 1, 5} // Pole nastaveno na tři hodnoty + // elementy mají hodntu 3, 1 a 5 + + // Slicy mají dynamickou velikost. Pole i slacy mají své výhody, + // ale většinou se používají slicy. + s3 := []int{4, 5, 9} // Podobně jako a3, ale není tu výpustka. + s4 := make([]int, 4) // Alokuj slice 4 intů, všechny nastaveny na 0. + var d2 [][]float64 // Deklarace slicu, nic se nealokuje. + bs := []byte("a slice") // Přetypování na slice + + // Protože jsou dynamické, můžeme ke slicům přidávat za běhu + // Přidat ke slicu můžeme pomocí zabudované funkce append(). + // Prvním parametrem je slice, návratová hodnota je aktualizovaný slice. + s := []int{1, 2, 3} // Výsledkem je slice se 3 elementy. + s = append(s, 4, 5, 6) // Přidány další 3 elementy. Slice má teď velikost 6. + fmt.Println(s) // Slice má hodnoty [1 2 3 4 5 6] + + // Pokud chceme k poli přičíst jiné pole, můžeme předat referenci na slice, + // nebo jeho literát a přidat výpustku, čímž se slicu "rozbalí" a přidá se k + // původnímu slicu. + s = append(s, []int{7, 8, 9}...) // druhým parametrem je literát slicu. + fmt.Println(s) // slice má teď hodnoty [1 2 3 4 5 6 7 8 9] + + p, q := naucSePraciSPameti() // Deklarujeme p a q jako typ pointer na int. + fmt.Println(*p, *q) // * dereferencuje pointer. Tím se vypíší dva inty. + + // Mapy jsou dynamické rostoucí asociativní pole, jako hashmapa, nebo slovník + // (dictionary) v jiných jazycích + m := map[string]int{"tri": 3, "ctyri": 4} + m["jedna"] = 1 + + // Napoužité proměnné jsou v Go chybou. + // Použijte podtržítko, abychom proměnno "použili". + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Výpis promenné se počítá jako použití. + fmt.Println(s, c, a4, s3, d2, m) + + naucSeVetveníProgramu() // Zpátky do běhu. +} + +// narozdíl od jiných jazyků, v Go je možné mít pojmenované návratové hodnoty. +// Tak můžeme vracet hodnoty z mnoha míst funkce, aniž bychom uváděli hodnoty v +// return. +func naucSePojmenovaneNavraty(x, y int) (z int) { + z = x * y + return // z je zde implicitní, jelikož bylo pojmenováno. +} + +// Go má garbage collector. Používá pointery, ale neumožňuje jejich aritmetiku. +// Můžete tedy udělat chybu použitím nil odkazu, ale ne jeho posunutím. +func naucSePraciSPameti() (p, q *int) { + // Pojmenované parametry p a q mají typ odkaz na int. + p = new(int) // Zabudované funkce new alokuje paměť. + // Alokované místo pro int má hodnotu 0 a p už není nil. + s := make([]int, 20) // Alokujeme paměť pro 20 intů. + s[3] = 7 // Jednu z nich nastavíme. + r := -2 // Deklarujeme další lokální proměnnou. + return &s[3], &r // a vezmeme si jejich odkaz pomocí &. +} + +func narocnyVypocet() float64 { + return m.Exp(10) +} + +func naucSeVetveníProgramu() { + // Výraz if vyžaduje složené závorky, ale podmínka nemusí být v závorkách. + if true { + fmt.Println("říkal jsme ti to") + } + // Formátování je standardizované pomocí utility "go fmt". + if false { + // posměšek. + } else { + // úšklebek. + } + // Použij switch, když chceš zřetězit if. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // jednotlivé case nepropadávají. není potřeba "break" + case 43: + // nedosažitelné, jelikož už bylo ošetřeno. + default: + // implicitní větev je nepovinná. + } + // Stejně jako if, for (smyčka) nepoužívá závorky. + // Proměnné definované ve for jsou lokální vůči smyčce. + for x := 0; x < 3; x++ { // ++ je výrazem. + fmt.Println("iterace", x) + } + // zde je x == 42. + + // For je jediná smyčka v Go, ale má několik tvarů. + for { // Nekonečná smyčka + break // Dělám si legraci + continue // Sem se nedostaneme + } + + // Můžete použít klíčové slovo range pro iteraci nad mapami, poli, slicy, + // řetězci a kanály. + // range vrací jednu (kanál) nebo dvě hodnoty (pole, slice, řetězec a mapa). + for key, value := range map[string]int{"jedna": 1, "dva": 2, "tri": 3} { + // pro každý pár (klíč a hodnota) je vypiš + fmt.Printf("klíč=%s, hodnota=%d\n", key, value) + } + + // stejně jako for, := v podmínce if přiřazuje hodnotu + // nejříve nastavíme y a pak otestujeme, jestli je y větší než x. + if y := narocnyVypocet(); y > x { + x = y + } + // Funkční literáty jsou tzv. uzávěry (closure) + xBig := func() bool { + return x > 10000 // odkazuje na x deklarované ve příkladu použití switch + } + x = 99999 + fmt.Println("xBig:", xBig()) // true + x = 1.3e3 // To udělá z x == 1300 + fmt.Println("xBig:", xBig()) // teď už false. + + // Dále je možné funkční literáty definovat a volat na místě jako parametr + // funkce, dokavaď: + // a) funkční literát je okamžitě volán pomocí (), + // b) výsledek se shoduje s očekávaným typem. + fmt.Println("Sečte + vynásobí dvě čísla: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Voláno s parametry 10 a 2 + // => Sečti a vynásob dvě čísla. 24 + + // Když to potřebujete, tak to milujete + goto miluji +miluji: + + naučteSeFunkčníFactory() // funkce vracející funkce je zábava(3)(3) + naučteSeDefer() // malá zajížďka k důležitému klíčovému slovu. + naučteSeInterfacy() // Přichází dobré věci! +} + +func naučteSeFunkčníFactory() { + // Následující dvě varianty jsou stejné, ale ta druhá je praktičtější + fmt.Println(větaFactory("létní")("Hezký", "den!")) + + d := větaFactory("letní") + fmt.Println(d("Hezký", "den!")) + fmt.Println(d("Líný", "odpoledne!")) +} + +// Dekorátory jsou běžné v jiných jazycích. To samé můžete udělat v Go +// pomocí parameterizovatelných funkčních literátů. +func větaFactory(můjŘetězec string) func(před, po string) string { + return func(před, po string) string { + return fmt.Sprintf("%s %s %s", před, můjŘetězec, po) // nový řetězec + } +} + +func naučteSeDefer() (ok bool) { + // Odloží (defer) příkazy na okamžik těsně před opuštěním funkce. + // tedy poslední se provede první + defer fmt.Println("odložené příkazy jsou zpravovaná v LIFO pořadí.") + defer fmt.Println("\nProto je tato řádka vytištěna první") + // Defer se běžně používá k zavírání souborů a tím se zajistí, že soubor + // bude po ukončení funkce zavřen. + return true +} + +// definuje typ interfacu s jednou metodou String() +type Stringer interface { + String() string +} + +// Definuje pár jako strukturu se dvěma poli typu int x a y. +type pár struct { + x, y int +} + +// Definuje method pár. Pár tedy implementuje interface Stringer. +func (p pár) String() string { // p je tu nazýváno "Receiver" - přijímač + // Sprintf je další veřejná funkce z balíčku fmt. + // Pomocí tečky přistupujeme k polím proměnné p + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func naučteSeInterfacy() { + // Složené závorky jsou "strukturální literáty. Vyhodnotí a inicializuje + // strukturu. Syntaxe := deklaruje a inicializuje strukturu. + p := pár{3, 4} + fmt.Println(p.String()) // Volá metodu String na p typu pár. + var i Stringer // Deklaruje i jako proměnné typu Stringer. + i = p // Toto je možné, jelikož oba implementují Stringer + // zavolá metodu String(( typu Stringer a vytiskne to samé jako předchozí. + fmt.Println(i.String()) + + // Funkce ve balíčku fmt volají metodu String, když zjišťují, jak se má typ + // vytisknout. + fmt.Println(p) // Vytiskne to samé, jelikož Println volá String(). + fmt.Println(i) // Ten samý výstup. + + naučSeVariabilníParametry("super", "učit se", "tady!") +} + +// Funcke mohou mít proměnlivé množství parametrů. +func naučSeVariabilníParametry(mojeŘetězce ...interface{}) { + // Iterujeme přes všechny parametry + // Potržítku tu slouží k ignorování indexu v poli. + for _, param := range mojeŘetězce { + fmt.Println("parameter:", param) + } + + // Použít variadický parametr jako variadický parametr, nikoliv pole. + fmt.Println("parametery:", fmt.Sprintln(mojeŘetězce...)) + + naučSeOšetřovatChyby() +} + +func naučSeOšetřovatChyby() { + // ", ok" je metodou na zjištění, jestli něco fungovalo, nebo ne. + m := map[int]string{3: "tri", 4: "ctyri"} + if x, ok := m[1]; !ok { // ok bude false, jelikož 1 není v mapě. + fmt.Println("není tu jedna") + } else { + fmt.Print(x) // x by bylo tou hodnotou, pokud by bylo v mapě. + } + // hodnota error není jen znamením OK, ale může říct více o chybě. + if _, err := strconv.Atoi("ne-int"); err != nil { // _ hodnotu zahodíme + // vytiskne 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // Znovu si povíme o interfacech, zatím se podíváme na + naučSeKonkurenčnost() +} + +// c je kanál, způsob, jak bezpečně komunikovat v konkurenčním prostředí. +func zvyš(i int, c chan int) { + c <- i + 1 // <- znamená "pošli" a posílá data do kanálu na levé straně. +} + +// Použijeme funkci zvyš a konkurečně budeme zvyšovat čísla. +func naučSeKonkurenčnost() { + // funkci make jsme již použili na slicy. make alokuje a inicializuje slidy, + // mapy a kanály. + c := make(chan int) + // nastartuj tři konkurenční go-rutiny. Čísla se budou zvyšovat + // pravděpodobně paralelně pokud je počítač takto nakonfigurován. + // Všechny tři zapisují do toho samého kanálu. + go zvyš(0, c) // go je výraz pro start nové go-rutiny. + go zvyš(10, c) + go zvyš(-805, c) + // Přečteme si tři výsledky a vytiskeneme je.. + // Nemůžeme říct, v jakém pořadí výsledky přijdou! + fmt.Println(<-c, <-c, <-c) // pokud je kanál na pravo, jedná se o "přijmi". + + cs := make(chan string) // Další kanál, tentokrát pro řetězce. + ccs := make(chan chan string) // Kanál kanálu řetězců. + go func() { c <- 84 }() // Start nové go-rutiny na posílání hodnot. + go func() { cs <- "wordy" }() // To samé s cs. + // Select má syntaxi jako switch, ale vztahuje se k operacím nad kanály. + // Náhodně vybere jeden case, který je připraven na komunikaci. + select { + case i := <-c: // Přijatá hodnota může být přiřazena proměnné. + fmt.Printf("je to typ %T", i) + case <-cs: // nebo může být zahozena + fmt.Println("je to řetězec") + case <-ccs: // prázdný kanál, nepřipraven ke komunikaci. + fmt.Println("to se nestane.") + } + // V tomto okamžiku máme hodnotu buď z kanálu c nabo cs. Jedna nebo druhá + // nastartovaná go-rutina skončila a další zůstane blokovaná. + + naučSeProgramovatWeb() // Go to umí. A vy to chcete taky. +} + +// jen jedna funkce z balíčku http spustí web server. +func naučSeProgramovatWeb() { + + // První parametr ListenAndServe je TCP adresa, kde poslouchat. + // Druhý parametr je handler, implementující interace http.Handler. + go func() { + err := http.ListenAndServe(":8080", pár{}) + fmt.Println(err) // neignoruj chyby + }() + + requestServer() +} + +// Umožní typ pár stát se http tím, že implementuje její jedinou metodu +// ServeHTTP. +func (p pár) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Servíruj data metodou http.ResponseWriter + w.Write([]byte("Naučil ses Go za y minut!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWebserver řekl: `%s`", string(body)) +} +``` + +## Kam dále + +Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/). +Tam najdete tutoriály, interaktivní konzolu a mnoho materiálu ke čtení. +Kromě úvodu, [dokumenty](https://golang.org/doc/) tam obsahují jak psát čistý kód v Go +popis balíčků (package), dokumentaci příkazové řádky a historii releasů. + +Také doporučujeme přečíst si definici jazyka. Je čtivá a překvapivě krátká. Tedy alespoň proti +jiným současným jazyků. + +Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://play.golang.org/p/r46YvCu-XX). +Můžete tam spouštět programy s prohlížeče. Také můžete [https://play.golang.org](https://play.golang.org) použít jako +[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop), kde si v rychlosti vyzkoušíte věci, bez instalace Go. + +Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](http://golang.org/src/pkg/). +Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](http://golang.org/pkg/) +tak se podíváte na dokumentaci. + +Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/). + +Go mobile přidává podporu pro Android a iOS. Můžete s ním psát nativní mobilní aplikace nebo knihovny, které půjdou +spustit přes Javu (pro Android), nebo Objective-C (pro iOS). Navštivte [web Go Mobile](https://github.com/golang/go/wiki/Mobile) +pro více informací. -- cgit v1.2.3 From ffba631fdd0413bbcde75d2d3791f679c7029d8e Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 5 Sep 2016 22:19:48 +0200 Subject: Update go.html.markdown --- cs-cz/go.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown index f814d2da..36217414 100644 --- a/cs-cz/go.html.markdown +++ b/cs-cz/go.html.markdown @@ -2,7 +2,8 @@ name: Go category: language language: Go -filename: learngo.go +filename: learngo-cs.go +lang: cs-cz contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] @@ -13,7 +14,6 @@ contributors: - ["Clayton Walker", "https://github.com/cwalk"] translators: - ["Ondra Linek", "https://github.com/defectus/"] - --- Jazyk Go byl vytvořen, jelikož bylo potřeba dokončit práci. Není to poslední -- cgit v1.2.3 From b59e6fa07d1cd13951f9bbd54f9aaf31e0367943 Mon Sep 17 00:00:00 2001 From: Martin Pacheco Date: Tue, 6 Sep 2016 05:13:39 -0300 Subject: add new resource link (#2307) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The link is a PDF elaborated by teachers of the course "Programación 3" (Algorithms and Data Structures) with examples about calculating the order of an algorithm and other topics in the context of asymptotic notation. This material is publicly listed here: https://eva.fing.edu.uy/pluginfile.php/95278/mod_resource/content/0/Apuntes%20sobre%20An%C3%A1lisis%20de%20Algoritmos.pdf but I uploaded it to Scribd because I know that the link could eventually change since it's hosted in a moodle platform and now and then the teachers change the location of the files. --- es-es/asymptotic-notation-es.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/es-es/asymptotic-notation-es.html.markdown b/es-es/asymptotic-notation-es.html.markdown index f3fe1614..3507429c 100644 --- a/es-es/asymptotic-notation-es.html.markdown +++ b/es-es/asymptotic-notation-es.html.markdown @@ -168,3 +168,4 @@ definiciones y ejemplos. * [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) * [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) +* [Apuntes Facultad de Ingeniería](https://www.scribd.com/document/317979564/Apuntes-Sobre-Analisis-de-Algoritmos) -- cgit v1.2.3 From a35179982940297bd857ceddfdc792c3ff2a73d0 Mon Sep 17 00:00:00 2001 From: Matthias Kern Date: Tue, 6 Sep 2016 10:25:45 +0200 Subject: [tmux] Updating for version 2.1 (#1733) * Update mouse option and remove old window-status-content options for tmux 2.1 compability * Add contribution and update timestamp --- tmux.html.markdown | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index ae73d912..e39d78fc 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -3,6 +3,7 @@ category: tool tool: tmux contributors: - ["mdln", "https://github.com/mdln"] + - ["matthiaskern", "https://github.com/matthiaskern"] filename: LearnTmux.txt --- @@ -116,7 +117,7 @@ like how .vimrc or init.el are used. ``` # Example tmux.conf -# 2014.10 +# 2015.12 ### General @@ -129,7 +130,7 @@ set -g history-limit 2048 set -g base-index 1 # Mouse -set-option -g mouse-select-pane on +set-option -g -q mouse on # Force reload of config file unbind r @@ -204,8 +205,6 @@ setw -g window-status-bg black setw -g window-status-current-fg green setw -g window-status-bell-attr default setw -g window-status-bell-fg red -setw -g window-status-content-attr default -setw -g window-status-content-fg yellow setw -g window-status-activity-attr default setw -g window-status-activity-fg yellow @@ -246,6 +245,4 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | [Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) -[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) - - +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) -- cgit v1.2.3 From 91c1f6b83212f6a0403ace29dde0c24021d7ebd2 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 6 Sep 2016 10:26:04 +0200 Subject: #1733 --- tmux.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/tmux.html.markdown b/tmux.html.markdown index e39d78fc..1214a5ba 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -3,7 +3,6 @@ category: tool tool: tmux contributors: - ["mdln", "https://github.com/mdln"] - - ["matthiaskern", "https://github.com/matthiaskern"] filename: LearnTmux.txt --- -- cgit v1.2.3 From 191019111b9c9c377ea0f4db6db845ced07fb546 Mon Sep 17 00:00:00 2001 From: IamRafy Date: Tue, 6 Sep 2016 13:56:22 +0530 Subject: Meteor Js (#1711) * Livescript is Updated * Revert "Livescript is Updated" This reverts commit 9f609e23e647abc3088fbae51551b9486531df0e. * Meteor js --- Meteor.html.markdown | 567 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 567 insertions(+) create mode 100644 Meteor.html.markdown diff --git a/Meteor.html.markdown b/Meteor.html.markdown new file mode 100644 index 00000000..d47d302b --- /dev/null +++ b/Meteor.html.markdown @@ -0,0 +1,567 @@ +--- +language: Meteor.js +Filename: Meteor.html.markdown +contributors: + - ["Mohammed Rafy", "https://github.com/IamRafy/"] + +--- + + + +Meteor is an ultra-simple environment for building modern websites. What once took weeks, even with the best tools, now takes hours with Meteor. + +The web was originally designed to work in the same way that mainframes worked in the 70s. The application server rendered a screen and sent it over the network to a dumb terminal. Whenever the user did anything, that server rerendered a whole new screen. This model served the Web well for over a decade. It gave rise to LAMP, Rails, Django, PHP. + +But the best teams, with the biggest budgets and the longest schedules, now build applications in JavaScript that run on the client. These apps have stellar interfaces. They don't reload pages. They are reactive: changes from any client immediately appear on everyone's screen. + +They've built them the hard way. Meteor makes it an order of magnitude simpler, and a lot more fun. You can build a complete application in a weekend, or a sufficiently caffeinated hackathon. No longer do you need to provision server resources, or deploy API endpoints in the cloud, or manage a database, or wrangle an ORM layer, or swap back and forth between JavaScript and Ruby, or broadcast data invalidations to clients. +Meteor Supports OS X, Windows, and Linux. // https://github.com/meteor/meteor/wiki/Supported-Platforms +On Windows? https://install.meteor.com/windows +On OS X or Linux? Install the latest official Meteor release from your terminal: +$ curl https://install.meteor.com/ | sh +The Windows installer supports Windows 7, Windows 8.1, Windows Server 2008, and Windows Server 2012. The command line installer supports Mac OS X 10.7 (Lion) and above, and Linux on x86 and x86_64 architectures. + +Once you've installed Meteor, create a project: +meteor create myapp +Run it locally: + +cd myapp +meteor +# Meteor server running on: http://localhost:3000/ + +Then, open a new terminal tab and unleash it on the world (on a free server we provide): + +meteor deploy myapp.meteor.com + +Principles of Meteor + +* Data on the Wire. Meteor doesn't send HTML over the network. The server sends data and lets the client render it. + +* One Language. Meteor lets you write both the client and the server parts of your application in JavaScript. + +* Database Everywhere. You can use the same methods to access your database from the client or the server. + +* Latency Compensation. On the client, Meteor prefetches data and simulates models to make it look like server method calls return instantly. + +* Full Stack Reactivity. In Meteor, realtime is the default. All layers, from database to template, update themselves automatically when necessary. + +* Embrace the Ecosystem. Meteor is open source and integrates with existing open source tools and frameworks. + +* Simplicity Equals Productivity. The best way to make something seem simple is to have it actually be simple. Meteor's main functionality has clean, classically beautiful APIs. + +Developer Resources +------------------- + +If anything in Meteor catches your interest, we hope you'll get involved with the project! + +TUTORIAL +Get started fast with the official Meteor tutorial! https://www.meteor.com/install + +STACK OVERFLOW +The best place to ask (and answer!) technical questions is on Stack Overflow. Be sure to add the meteor tag to your question. +http://stackoverflow.com/questions/tagged/meteor + +FORUMS +Visit the Meteor discussion forumsto announce projects, get help, talk about the community, or discuss changes to core. +https://forums.meteor.com/ + +GITHUB +The core code is on GitHub. If you're able to write code or file issues, we'd love to have your help. Please read Contributing to Meteor for how to get started. https://github.com/meteor/meteor + +THE METEOR MANUAL +In-depth articles about the core components of Meteor can be found on the Meteor Manual. The first article is about Tracker, our transparent reactivity framework. More articles (covering topics like Blaze, Unibuild, and DDP) are coming soon! http://manual.meteor.com/ + +What is Meteor? +--------------- + +Meteor is two things: + +A library of packages: pre-written, self-contained modules that you might need in your app. + +There are about a dozen core Meteor packages that most any app will use. Two examples: webapp, which handles incoming HTTP connections, and templating, which lets you make HTML templates that automatically update live as data changes. Then there are optional packages like email, which lets your app send emails, or the Meteor Accounts series (accounts-password, accounts-facebook, accounts-ui, and others) which provide a full-featured user account system that you can drop right into your app. In addition to these "core" packages, there are thousands of community-written packages in Atmosphere, one of which might do just what you need. + +A command-line tool called meteor. + +meteor is a build tool analogous to make, rake, or the non-visual parts of Visual Studio. It gathers up all of the source files and assets in your application, carries out any necessary build steps (such as compiling CoffeeScript, minifying CSS, building npm modules, or generating source maps), fetches the packages used by your app, and outputs a standalone, ready-to-run application bundle. In development mode it can do all of this interactively, so that whenever you change a file you immediately see the changes in your browser. It's super easy to use out of the box, but it's also extensible: you can add support for new languages and compilers by adding build plugin packages to your app. + +The key idea in the Meteor package system is that everything should work identically in the browser and on the server (wherever it makes sense, of course: browsers can't send email and servers can't capture mouse events). Our whole ecosystem has been built from the ground up to support this. + +Structuring your application +---------------------------- + +A Meteor application is a mix of client-side JavaScript that runs inside a web browser or PhoneGap mobile app, server-side JavaScript that runs on the Meteor server inside a Node.js container, and all the supporting HTML templates, CSS rules, and static assets. Meteor automates the packaging and transmission of these different components, and it is quite flexible about how you choose to structure those components in your file tree. + +Special Directories +------------------- + +By default, any JavaScript files in your Meteor folder are bundled and sent to the client and the server. However, the names of the files and directories inside your project can affect their load order, where they are loaded, and some other characteristics. Here is a list of file and directory names that are treated specially by Meteor: + +client + +Any directory named client is not loaded on the server. Similar to wrapping your code in if (Meteor.isClient) { ... }. All files loaded on the client are automatically concatenated and minified when in production mode. In development mode, JavaScript and CSS files are not minified, to make debugging easier. (CSS files are still combined into a single file for consistency between production and development, because changing the CSS file's URL affects how URLs in it are processed.) + +HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: , , and