From 1482bfc52b65c028c364670ab9f2561e7660a932 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 18:04:56 +0300 Subject: Add not translated verson of javasript --- ru-ru/javascript-ru.html.markdown | 529 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 529 insertions(+) create mode 100644 ru-ru/javascript-ru.html.markdown diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown new file mode 100644 index 00000000..7e2c0cca --- /dev/null +++ b/ru-ru/javascript-ru.html.markdown @@ -0,0 +1,529 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + - ["--mynamehere--", "http://github.com/--mynamehere--"] +filename: javascript-ru.js +lang: ru-ru +--- + +JavaScript was created by Netscape's Brendan Eich in 1995. It was originally +intended as a simpler scripting language for websites, complementing the use of +Java for more complex web applications, but its tight integration with Web pages +and built-in support in browsers has caused it to become far more common than +Java in web frontends. + +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. + +Feedback would be highly appreciated! You can reach me at +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// Comments are like C. Single-line comments start with two slashes, +/* and multiline comments start with slash-star + and end with star-slash */ + +// Statements can be terminated by ; +doStuff(); + +// ... but they don't have to be, as semicolons are automatically inserted +// wherever there's a newline, except in certain cases. +doStuff() + +// Because those cases can cause unexpected results, we'll keep on using +// semicolons in this guide. + +/////////////////////////////////// +// 1. Numbers, Strings and Operators + +// 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. +3; // = 3 +1.5; // = 1.5 + +// Some basic arithmetic works as you'd expect. +1 + 1; // = 2 +.1 + .2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Including uneven division. +5 / 2; // = 2.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 + +// Precedence is enforced with parentheses. +(1 + 3) * 2; // = 8 + +// There are three special not-a-real-number values: +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0 + +// There's also a boolean type. +true; +false; + +// Strings are created with ' or ". +'abc'; +"Hello, world"; + +// Negation uses the ! symbol +!true; // = false +!false; // = true + +// Equality is === +1 === 1; // = true +2 === 1; // = false + +// Inequality is !== +1 !== 1; // = false +2 !== 1; // = true + +// More comparisons +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Strings are concatenated with + +"Hello " + "world!"; // = "Hello world!" + +// and are compared with < and > +"a" < "b"; // = true + +// Type coercion is performed for comparisons with double equals... +"5" == 5; // = true +null == undefined; // = true + +// ...unless you use === +"5" === 5; // = false +null === undefined; // = false + +// You can access characters in a string with charAt +"This is a string".charAt(0); // = 'T' + +// ...or use substring to get larger pieces +"Hello world".substring(0, 5); // = "Hello" + +// length is a property, so don't use () +"Hello".length; // = 5 + +// There's also null and undefined +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 and "" are falsy; everything else is truthy. +// Note that 0 is falsy and "0" is truthy, even though 0 == "0". + +/////////////////////////////////// +// 2. Variables, Arrays and Objects + +// Variables are declared with the var keyword. JavaScript is dynamically typed, +// so you don't need to specify type. Assignment uses a single = character. +var someVar = 5; + +// 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 +// you defined it in. + +// Variables declared without being assigned to are set to undefined. +var someThirdVar; // = undefined + +// There's shorthand for performing math operations on variables: +someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now +someVar *= 10; // now someVar is 100 + +// and an even-shorter-hand for adding or subtracting 1 +someVar++; // now someVar is 101 +someVar--; // back to 100 + +// Arrays are ordered lists of values, of any type. +var myArray = ["Hello", 45, true]; + +// Their members can be accessed using the square-brackets subscript syntax. +// Array indices start at zero. +myArray[1]; // = 45 + +// Arrays are mutable and of variable length. +myArray.push("World"); +myArray.length; // = 4 + +// Add/Modify at specific index +myArray[3] = "Hello"; + +// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other +// languages: an unordered collection of key-value pairs. +var myObj = {key1: "Hello", key2: "World"}; + +// Keys are strings, but quotes aren't required if they're a valid +// JavaScript identifier. Values can be any type. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Object attributes can also be accessed using the subscript syntax, +myObj["my other key"]; // = 4 + +// ... or using the dot syntax, provided the key is a valid identifier. +myObj.myKey; // = "myValue" + +// Objects are mutable; values can be changed and new keys added. +myObj.myThirdKey = true; + +// If you try to access a value that's not yet set, you'll get undefined. +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){ + // evaluated if count is 3 +} else if (count == 4){ + // evaluated if count is 4 +} else { + // evaluated if it's not either 3 or 4 +} + +// As does while. +while (true){ + // An infinite loop! +} + +// Do-while loops are like while loops, except they always run at least once. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// the for loop is the same as C and Java: +// initialisation; continue condition; iteration. +for (var i = 0; i < 5; i++){ + // will run 5 times +} + +// && 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"; + + +// switch statement checks for equality with === +// use 'break' after each case +// or the cases after the correct one will be executed too. +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 are declared with the function keyword. +function myFunction(thing){ + return thing.toUpperCase(); +} +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() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// JavaScript functions are first class objects, so they can be reassigned to +// different variable names and passed to other functions as arguments - for +// example, when supplying an event handler: +function myFunction(){ + // this code will be called in 5 seconds' time +} +setTimeout(myFunction, 5000); +// Note: setTimeout isn't part of the JS language, but is provided by browsers +// and Node.js. + +// 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(){ + // this code will be called in 5 seconds' time +}, 5000); + +// JavaScript has function scope; functions get their own scope but other blocks +// do not. +if (true){ + var i = 5; +} +i; // = 5 - not undefined as you'd expect in a block-scoped language + +// This has led to a common pattern of "immediately-executing anonymous +// functions", which prevent temporary variables from leaking into the global +// scope. +(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 + +// One of JavaScript's most powerful features is closures. If a function is +// defined inside another function, the inner function has access to all the +// outer function's variables, even after the outer function exits. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Inner functions are put in the local scope by default, as if they were + // declared with 'var'. + 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. More about Objects; Constructors and Prototypes + +// Objects can contain functions. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// When functions attached to an object are called, they can access the object +// they're attached to using the this keyword. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// What this is set to has to do with how the function is called, not where +// it's defined. So, our function doesn't work if it isn't called in the +// context of the object. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Inversely, a function can be assigned to the object and gain access to it +// through this, even if it wasn't attached when it was defined. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// We can also specify a context for a function to execute in when we invoke it +// using 'call' or 'apply'. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// The 'apply' function is nearly identical, but takes an array for an argument list. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// This is useful when working with a function that accepts a sequence of arguments +// and you want to pass an array. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use +// bind. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// Bind can also be used to partially apply (curry) a function. + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// When you call a function with the new keyword, a new object is created, and +// made available to the function via the this keyword. Functions designed to be +// called like that are called constructors. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Every JavaScript object has a 'prototype'. When you go to access a property +// on an object that doesn't exist on the actual object, the interpreter will +// look at its prototype. + +// Some JS implementations let you access an object's prototype on the magic +// property __proto__. While this is useful for explaining prototypes it's not +// part of the standard; we'll get to standard ways of using prototypes later. +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!" + +// Of course, if your property isn't on your prototype, the prototype's +// prototype is searched, and so on. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// There's no copying involved here; each object stores a reference to its +// prototype. This means we can alter the prototype and our changes will be +// reflected everywhere. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// We mentioned that __proto__ was non-standard, and there's no standard way to +// change the prototype of an existing object. However, there are two ways to +// create a new object with a given prototype. + +// The first is Object.create, which is a recent addition to JS, and therefore +// not available in all implementations yet. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// The second way, which works anywhere, has to do with constructors. +// Constructors have a property called prototype. This is *not* the prototype of +// the constructor function itself; instead, it's the prototype that new objects +// are given when they're created with that constructor and the new keyword. +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. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Except, they aren't exactly equivalent. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // This code won't execute, because 0 is falsy. +} +if (Number(0)){ + // This code *will* execute, because Number(0) is truthy. +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +// For instance, we mentioned that Object.create isn't yet available in all +// implementations, but we can still use it with this 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(); + } +} +``` + +## Further Reading + +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 3c0733f45ce2de89888ea3dd2a16401df1a4a6b7 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:41:16 +0300 Subject: Translate preamble --- ru-ru/javascript-ru.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 7e2c0cca..963805f9 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,16 +9,28 @@ filename: javascript-ru.js lang: ru-ru --- +Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально +предполагалось, что он станет простым вариантом скриптового языка для сайтов, +дополняющий к Java, который в свою очередь использовался бы для более сложных +web-приложений. Но тонкая интегрированность javascript с web-страницей и +встроенная поддержка в браузерах привели к тому, чтобы он стал более +распространен в web-разработке, чем Java. JavaScript was created by Netscape's Brendan Eich in 1995. It was originally intended as a simpler scripting language for websites, complementing the use of Java for more complex web applications, but its tight integration with Web pages and built-in support in browsers has caused it to become far more common than Java in web frontends. +Использование Javascript не ограничивается браузерами. Проект Node.js, +предоставляющий независимую среду выполнения на движке Google Chrome V8 +JavaScript, становится все более популярным. 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. +Обратная связь важна и нужна! Вы можете написаться мне +на [@_remedy]() или +[mymail](). Feedback would be highly appreciated! You can reach me at [@adambrenecki](https://twitter.com/adambrenecki), or [adam@brenecki.id.au](mailto:adam@brenecki.id.au). -- cgit v1.2.3 From 89ac5d6b77e84517e8844d694676f9e25d171538 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:44:21 +0300 Subject: Translate 1st part --- ru-ru/javascript-ru.html.markdown | 56 ++++++++++++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 963805f9..aa1d1f3c 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -36,29 +36,43 @@ Feedback would be highly appreciated! You can reach me at [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js +// Комментарии оформляются как в C. +// Обнострочнные комментарии начинаются с двух слешей, // Comments are like C. Single-line comments start with two slashes, +/* а многострочные с слеша и звездочки + и заканчиваются звездочеий и слешом */ /* and multiline comments start with slash-star and end with star-slash */ +// Выражения разделяются с помощью ; // Statements can be terminated by ; doStuff(); +// ... но этого можно и делать, разделители подставляются автоматически +// после перехода на новую строку за исключением особых случаев // ... but they don't have to be, as semicolons are automatically inserted // wherever there's a newline, except in certain cases. doStuff() +// Это может приводить к непредсказуемому результату и поэтому мы будем +// использовать разделители в этом туре. // Because those cases can cause unexpected results, we'll keep on using // semicolons in this guide. /////////////////////////////////// +// 1. Числа, Строки и Операторы // 1. Numbers, Strings and Operators +// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой стандарта +// IEEE 754) +// todo: сформулировать // 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. 3; // = 3 1.5; // = 1.5 +// В основном базовая арифметика работает предсказуемо // Some basic arithmetic works as you'd expect. 1 + 1; // = 2 .1 + .2; // = 0.30000000000000004 @@ -66,76 +80,92 @@ doStuff() 10 * 2; // = 20 35 / 5; // = 7 +// Включая нецелочисленное деление (todo:уточнить!) // Including uneven division. 5 / 2; // = 2.5 +// Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, +// оно будет приведено к 32-битному целому со знаком. // 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 +// (todo:перевести) // Precedence is enforced with parentheses. (1 + 3) * 2; // = 8 +// Есть три особых не реальных числовых значения: // There are three special not-a-real-number values: -Infinity; // result of e.g. 1/0 --Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0 +Infinity; // допустим, результат операции 1/0 +-Infinity; // допустим, результат операции -1/0 +NaN; // допустим, результат операции 0/0 +// Так же есть тип булевых данных. // There's also a boolean type. true; false; +// Строки создаются с помощью ' или ". // Strings are created with ' or ". 'abc'; "Hello, world"; -// Negation uses the ! symbol +// Оператор ! означает отрицание !true; // = false !false; // = true -// Equality is === +// Равество это === 1 === 1; // = true 2 === 1; // = false -// Inequality is !== +// Неравенство это !== 1 !== 1; // = false 2 !== 1; // = true -// More comparisons +// Еще сравнения 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true 2 >= 2; // = true -// Strings are concatenated with + +// Строки складываются с помощью + "Hello " + "world!"; // = "Hello world!" -// and are compared with < and > +// и сравниваются с помощью < и > "a" < "b"; // = true +// Приведение типов выполняется при сравнении с ==... // Type coercion is performed for comparisons with double equals... "5" == 5; // = true null == undefined; // = true -// ...unless you use === +// ...в отличие от === "5" === 5; // = false null === undefined; // = false +// Для доступа к конкретному символу строки используйте charAt // You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' +// ... или используйте substring для получения подстроки // ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" +// length(длина) - свойство, не используйте () // length is a property, so don't use () "Hello".length; // = 5 +// Есть null и undefined // There's also null and undefined -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) +null; // используется что бы указать явно, что значения нет +undefined; // испрользуется чтобы показать, что значения не было установлено + // собственно, undefined так и переводится +// false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении +// в булеву типу становятся false) // false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. +// Обратите внимание что 0 приводится к false, а "0" к true, не смотря на то, +// что "0"==0 // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// -- cgit v1.2.3 From 27825265f397087a60e597d5a0a1ae44d180ddc5 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 30 Oct 2014 21:58:59 +0300 Subject: Translate part 3 --- ru-ru/javascript-ru.html.markdown | 41 +++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index aa1d1f3c..1369d0d7 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,6 +9,8 @@ filename: javascript-ru.js lang: ru-ru --- +todo: привести все названия языка к коректному написанию + Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, дополняющий к Java, который в свою очередь использовался бы для более сложных @@ -169,60 +171,83 @@ undefined; // испрользуется чтобы показать, что з // Note that 0 is falsy and "0" is truthy, even though 0 == "0". /////////////////////////////////// -// 2. Variables, Arrays and Objects +// 2. Переменные, массивы и объекты +// Переменные объявляются ключевым словом var. Javascript динамически +// типизируемый, так что указывать тип не нужно. +// Присвоение значения описывается с помощью оператора = // Variables are declared with the var keyword. JavaScript is dynamically typed, // so you don't need to specify type. Assignment uses a single = character. var someVar = 5; +// если не указать ключевого слова var, ошибки не будет... // 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 // you defined it in. +// Переменные объявленные без присвоения значения, содержать undefined // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined +// Для математических операций над числами есть короткая запись: // There's shorthand for performing math operations on variables: -someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now -someVar *= 10; // now someVar is 100 +someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь +someVar *= 10; // а теперь -- 100 -// and an even-shorter-hand for adding or subtracting 1 -someVar++; // now someVar is 101 -someVar--; // back to 100 +// еще более короткая запись для добавления и вычитания 1 +someVar++; // теперь someVar равно 101 +someVar--; // обратно к 100 +// Массивы -- упорядоченные списки значений любых типов. // Arrays are ordered lists of values, of any type. var myArray = ["Hello", 45, true]; +// Для доступу к элементам массивов используйте квадратные скобки. +// Индексы массивов начинаются с 0 // Their members can be accessed using the square-brackets subscript syntax. // Array indices start at zero. myArray[1]; // = 45 +// Массивы мутабельны(изменяемы) и имеют переменную длину. // Arrays are mutable and of variable length. -myArray.push("World"); +myArray.push("World"); // добавить элемент myArray.length; // = 4 -// Add/Modify at specific index +// Добавить или изменить значение по конкретному индексу myArray[3] = "Hello"; +// Объёкты javascript похожи на dictionary или map из других языков +// программирования. Это неупорядочнные коллекции пар ключ-значение. // JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; +// Ключи -- это строки, но кавычки не требуются если названия явлюятся +// корректными javascript идентификаторами. Значения могут быть любого типа. // Keys are strings, but quotes aren't required if they're a valid // JavaScript identifier. Values can be any type. var myObj = {myKey: "myValue", "my other key": 4}; +// Доступ к атрибту объекта можно получить с помощью квадратных скобок // Object attributes can also be accessed using the subscript syntax, myObj["my other key"]; // = 4 +// ... или используя точечную нотацию, при условии что ключ является +// корректным идентификатором // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" +// Объекты мутабельны. В существуюещем объекте можно изменить значние +// или добавить новый атрибут // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; +// При попытке доступа к атрибуту, который до этого не был создан, будет +// возвращен undefined // If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey; // = undefined -- cgit v1.2.3 From 4fefe7ac06d2cfc87c0de263ea87475daa96248e Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 22:54:49 +0300 Subject: Translate Logic and Control Structures --- ru-ru/javascript-ru.html.markdown | 44 ++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 1369d0d7..c0e4c0fa 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -252,65 +252,79 @@ myObj.myThirdKey = true; myObj.myFourthKey; // = undefined /////////////////////////////////// +// 3. Логика и управляющие структуры // 3. Logic and Control Structures +// +// Синтаксис управляющих структур очень похож на его реализацию в Java. // The syntax for this section is almost identical to Java's. +// if работает так как вы ожидаете. // The if structure works as you'd expect. var count = 1; if (count == 3){ - // evaluated if count is 3 + // выполнится, если значение count равно 3 } else if (count == 4){ - // evaluated if count is 4 + // выполнится, если значение count равно 4 } else { - // evaluated if it's not either 3 or 4 + // выполнится, если значение countне будет равно ни 3 ни 4 } -// As does while. +// Поведение while тоже вполне предсказуемо while (true){ - // An infinite loop! + // Бесконечный цикл } +// Циклы do-while похожи на while, но они всегда выполняются хотябы 1 раз. // Do-while loops are like while loops, except they always run at least once. var input do { input = getInput(); } while (!isValid(input)) +// Цикл for такой же как в C b Java: +// инициализация; условие продолжения; итерация // the for loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ + // выполнится 5 раз // will run 5 times } +// && - логическое и, || - логическое или // && is logical and, || is logical or -if (house.size == "big" && house.colour == "blue"){ +if (house.size == "big" && house.color == "blue"){ house.contains = "bear"; } -if (colour == "red" || colour == "blue"){ +if (color == "red" || color == "blue"){ + // если цвет или красный или синий // colour is either red or blue } +// && и || удобны для установки значений по умолчанию. // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; +// выражение switch проверяет равество с помощью === +// используйте 'break' после каждого case +// иначе помимо правильного case выполнятся и все последующие. // switch statement checks for equality with === // use 'break' after each case // or the cases after the correct one will be executed too. -grade = 'B'; +grade = '4'; // оценка switch (grade) { - case 'A': - console.log("Great job"); + case '5': + console.log("Великолепно"); break; - case 'B': - console.log("OK job"); + case '4': + console.log("Неплохо"); break; - case 'C': - console.log("You can do better"); + case '3': + console.log("Можно и лучше"); break; default: - console.log("Oy vey"); + console.log("Да уж."); break; } -- cgit v1.2.3 From b1ec17dae0827b4c17d18399d4bd666a9e617bc4 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 22:55:18 +0300 Subject: Fix grammar --- ru-ru/javascript-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index c0e4c0fa..a22055ef 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -237,12 +237,12 @@ var myObj = {myKey: "myValue", "my other key": 4}; myObj["my other key"]; // = 4 // ... или используя точечную нотацию, при условии что ключ является -// корректным идентификатором +// корректным идентификатором. // ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" // Объекты мутабельны. В существуюещем объекте можно изменить значние -// или добавить новый атрибут +// или добавить новый атрибут. // Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; -- cgit v1.2.3 From 44615813763e218e4f1140ff6c9dbcdd6948d858 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sat, 1 Nov 2014 23:21:54 +0300 Subject: Translate 4. Functions, Scope and Closures --- ru-ru/javascript-ru.html.markdown | 50 ++++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index a22055ef..b5556f49 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -330,79 +330,117 @@ switch (grade) { /////////////////////////////////// +// 4. Функции, Область видимости и Замыкания // 4. Functions, Scope and Closures +// Функции в JavaScript объявляются с помощью ключевого слова function. // JavaScript functions are declared with the function keyword. function myFunction(thing){ - return thing.toUpperCase(); + return thing.toUpperCase(); // приведение к верхнему регистру } myFunction("foo"); // = "FOO" +// Помните, что значение, которое должно быть возкращено должно начинаться +// на той же строке, где расположено ключевое слово 'return'. В противном случае +// будет возвращено undefined. Такое поведения объясняется автоматической +// вставкой разделителей ';'. Оглядывйтесь на этот факт, если используете +// BSD стиль оформления кода. // 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() { - return // <- semicolon automatically inserted here + return // <- разделитель автоматически будет вставлен здесь { thisIsAn: 'object literal' } } myFunction(); // = undefined +// Функции в JavaScript являются объектами, поэтому их можно назначить в +// переменные с разными названиями и передавать в другие функции, как аргументы, +// на пример, при указании обработчика события. // JavaScript functions are first class objects, so they can be reassigned to // different variable names and passed to other functions as arguments - for // example, when supplying an event handler: function myFunction(){ + // этот фрагмент кода будет вызван через 5 секунд // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); +// Обратите внимание, что setTimeout не является частью языка, однако он +// доступен в API браузеров и Node.js. // Note: setTimeout isn't part of the JS language, but is provided by browsers // and Node.js. +// Объект функции на самом деле не обязательно объявлять с именем - можно +// создать анонимную функцию прямо в аргументах другой функции. // 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(){ + // этот фрагмент кода будет вызван через 5 секунд // this code will be called in 5 seconds' time }, 5000); +// В JavaScript есть области видимости. У функций есть собственные области +// видимости, у других блоков их нет. // JavaScript has function scope; functions get their own scope but other blocks // do not. if (true){ var i = 5; } -i; // = 5 - not undefined as you'd expect in a block-scoped language +i; // = 5, а не undefined, как это было бы ожидаемо(todo: поправить) + // в языке, создающем области видисти для блоков " +// Это привело к появлению паттерна общего назначения "immediately-executing +// anonymous functions" (сразу выполняющиеся анонимные функции), который +// позволяет предотвратить запись временных переменных в общую облать видимости. // This has led to a common pattern of "immediately-executing anonymous // functions", which prevent temporary variables from leaking into the global // scope. (function(){ var temporary = 5; + // Для доступа к глобальной области видимости можно использовать запись в + // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный + // объект может называться по-разному в небраузерных средах, таких Node.js. // 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 +temporary; // вызывает исключение ReferenceError permanent; // = 10 +// Одной из сильных сторон JavaScript являются замыкания. Если функция +// объявлена в вниутри другой функции, внутренняя функция имеет доступ ко всем +// переменным внешней функции, даже после того, как внешняя функции завершила +// свое выполнение // One of JavaScript's most powerful features is closures. If a function is // defined inside another function, the inner function has access to all the // outer function's variables, even after the outer function exits. function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!"; + var prompt = "Привет, " + name + "!"; + // Внутренние фунции помещаются в локальную область видимости, как-будто они + // объявлены с ключевым словом 'var'. // Inner functions are put in the local scope by default, as if they were // declared with 'var'. function inner(){ alert(prompt); } setTimeout(inner, 5000); + // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds + // завершит свое выполнение сразу и setTimeout вызовет inner позже. + // Однако, так как inner "замкнута"(todo: уточнить "закрыта внутри") + // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной + // prompt, когда будет вызвана. // 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 +sayHelloInFiveSeconds("Вася"); // откроет модальное окно с сообщением + // "Привет, Вася" по истечении 5 секунд. + /////////////////////////////////// // 5. More about Objects; Constructors and Prototypes -- cgit v1.2.3 From 6e694a82b2503a2cce524df96c1c59af6d4ecdea Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Sun, 2 Nov 2014 01:12:22 +0300 Subject: Translate last chapter --- ru-ru/javascript-ru.html.markdown | 59 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index b5556f49..f0c91278 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -443,8 +443,10 @@ sayHelloInFiveSeconds("Вася"); // откроет модальное окно /////////////////////////////////// +// 5. Немного об Объектах. Конструкторы и Прототипы // 5. More about Objects; Constructors and Prototypes +// Объекты погут содержать функции // Objects can contain functions. var myObj = { myFunc: function(){ @@ -453,6 +455,8 @@ var myObj = { }; myObj.myFunc(); // = "Hello world!" +// Когда функции прикрепленные к объекту вызываются, они могут получить доступ +// к данным объекта, ипользую ключевое слово this. // When functions attached to an object are called, they can access the object // they're attached to using the this keyword. myObj = { @@ -463,12 +467,17 @@ myObj = { }; myObj.myFunc(); // = "Hello world!" +// Содержание this определяется исходя из того, как была вызвана функция, а +// не места её определения. По этой причине наша функция не будет работать вне +// контекста объекта. // What this is set to has to do with how the function is called, not where // it's defined. So, our function doesn't work if it isn't called in the // context of the object. var myFunc = myObj.myFunc; myFunc(); // = undefined +// И напротив, функция может быть присвоена объекту и получить доступ к нему +// через this, даже если она не была прикреплена к объекту в момент её создания. // Inversely, a function can be assigned to the object and gain access to it // through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ @@ -477,6 +486,7 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" +// Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. // We can also specify a context for a function to execute in when we invoke it // using 'call' or 'apply'. @@ -485,10 +495,13 @@ var anotherFunc = function(s){ } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" +// Функция 'apply' очень похожа, но принимает массив со списком аргументов. // The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" +// Это может быть удобно, когда работаешь с фунцией принимающей на вход +// последовательность аргументов и нужно передать их в виде массива. // This is useful when working with a function that accepts a sequence of arguments // and you want to pass an array. @@ -496,18 +509,25 @@ 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. // But, 'call' and 'apply' are only temporary. When we want it to stick, we can use // bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" +// bind можно использовать чтобы частично передать аргументы в +// функцию (каррировать). // Bind can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 +// Когда функция вызывается с ключевым словом new, создается новый объект. +// Данный объект становится доступным функции через ключевое слово this. +// Функции спроектированные вызываться таким способом называются конструкторами. // When you call a function with the new keyword, a new object is created, and // made available to the function via the this keyword. Functions designed to be // called like that are called constructors. @@ -518,10 +538,17 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 +// Любой объект в JavaScript имеет 'прототип'. Когда выпытаетесь получить доступ +// к свойству не объявленному в данном объекте, интерпретатор будет искать его +// в прототипе. // Every JavaScript object has a 'prototype'. When you go to access a property // on an object that doesn't exist on the actual object, the interpreter will // look at its prototype. +// Некоторые реализации JS позволяют получить доступ к прототипу с помощью +// волшебного свойства __proto__. До момента пока оно не являются стандартным, +// __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся +// со стандартными способами работы с прототипом несколько позже. // Some JS implementations let you access an object's prototype on the magic // property __proto__. While this is useful for explaining prototypes it's not // part of the standard; we'll get to standard ways of using prototypes later. @@ -537,10 +564,10 @@ var myPrototype = { myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 - -// This works for functions, too. myObj.myFunc(); // = "hello world!" +// Естествно, если в свойства нет в прототипе, поиск будет продолжен в прототипе +// прототипа и так далее. // Of course, if your property isn't on your prototype, the prototype's // prototype is searched, and so on. myPrototype.__proto__ = { @@ -548,21 +575,32 @@ myPrototype.__proto__ = { }; myObj.myBoolean; // = true +// Ничего не копируется, каждый объект хранит ссылку на свой прототип. Если +// изменить прототип, все изменения отразятся во всех его потомках. // There's no copying involved here; each object stores a reference to its // prototype. This means we can alter the prototype and our changes will be // reflected everywhere. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 +// Как было сказано выше, __proto__ не является стандартом, и нет стандартного +// способа изменить прототип у созданного объекта. Однако, есть два способа +// создать объект с заданным прототипом. // We mentioned that __proto__ was non-standard, and there's no standard way to // change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. +// Первый способ - Object.create, был добавлен в JS относительно недавно, и +// потому не доступен в более ранних реализациях языка. // The first is Object.create, which is a recent addition to JS, and therefore // not available in all implementations yet. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 +// Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют +// свойство prototype. Это воовсе не прототип функции конструктора, напротив, +// это прототип, который присваевается новым объектам, созданным с этим +// конструктором с помощью ключевого слова new. // The second way, which works anywhere, has to do with constructors. // Constructors have a property called prototype. This is *not* the prototype of // the constructor function itself; instead, it's the prototype that new objects @@ -578,23 +616,30 @@ myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 +// У встроенных типов таких, как строки и числа, тоже есть конструкторы, +// создающие эквивалентные объекты-обертки. // Built-in types like strings and numbers also have constructors that create // equivalent wrapper objects. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true +// Правда, они не совсем эквивалентны. // Except, they aren't exactly equivalent. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ + // Этот фрагмент кода не будет выпонен, так как 0 приводится к false // This code won't execute, because 0 is falsy. } if (Number(0)){ + // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. // This code *will* execute, because Number(0) is truthy. } +// Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, +// следовательно вы можете расширить функциональность строки, например. // However, the wrapper objects and the regular builtins share a prototype, so // you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ @@ -602,17 +647,23 @@ String.prototype.firstCharacter = function(){ } "abc".firstCharacter(); // = "a" +// Этот факт часто используется для создания полифилов(polyfill) - реализации +// новых возможностей JS в его болле старых версиях для того чтобы их можно было +// использовать в устаревших браузерах. // 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. +// Например, мы упомянули, что Object.create не доступен во всех версиях +// JavaScript, но мы може создать полифилл. // For instance, we mentioned that Object.create isn't yet available in all // implementations, but we can still use it with this polyfill: -if (Object.create === undefined){ // don't overwrite it if it exists +if (Object.create === undefined){ // не переопределяем если есть 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(); } -- cgit v1.2.3 From 821880e95f4b61cdb89eebc7d0077a069b43a2a6 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 11:32:51 +0300 Subject: =?UTF-8?q?=C2=A0Add=20Further=20Reading?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ru-ru/javascript-ru.html.markdown | 39 ++++++++++++++++----------------------- 1 file changed, 16 insertions(+), 23 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index f0c91278..1f0cfb3f 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -655,7 +655,7 @@ String.prototype.firstCharacter = function(){ // used in older environments such as outdated browsers. // Например, мы упомянули, что Object.create не доступен во всех версиях -// JavaScript, но мы може создать полифилл. +// JavaScript, но мы можем создать полифилл. // For instance, we mentioned that Object.create isn't yet available in all // implementations, but we can still use it with this polyfill: if (Object.create === undefined){ // не переопределяем если есть @@ -670,30 +670,23 @@ if (Object.create === undefined){ // не переопределяем если } ``` -## Further Reading +## Что еще почитать -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. +[Современный учебник JavaScript](http://learn.javascript.ru/) от Ильи Кантора +является довольно качественным и глубоким учебным материалом, освещающим все +особенности современного языка. Помимо учебника на том же домене можно найти +[перевод спецификации ECMAScript 5.1](http://es5.javascript.ru/) и справочник по +возможностям языка. -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) +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) позволяет +довольно быстро изучить основные тонкие места в работе с JS, но фокусируется +только на таких моментах -[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. +[Справочник](https://developer.mozilla.org/ru/docs/JavaScript) от MDN +(Mozilla Development Network) содержит информацию о возможностях языка на +английском. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. +Название проекта ["Принципы написания консистентного, идиоматического кода на +JavaScript"](https://github.com/rwaldron/idiomatic.js/tree/master/translations/ru_RU) +говорит само за себя. -[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 958ba0d69e9c4ac21a39d37b61f7dea1b5a155de Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 12:28:49 +0300 Subject: Remove comments with english + fix some typo --- ru-ru/javascript-ru.html.markdown | 235 +++++++------------------------------- 1 file changed, 44 insertions(+), 191 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 1f0cfb3f..abbafc8d 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - - ["--mynamehere--", "http://github.com/--mynamehere--"] + - ["Maxim Koretskiy", "http://github.com/maximkoretskiy"] filename: javascript-ru.js lang: ru-ru --- @@ -13,47 +13,30 @@ todo: привести все названия языка к коректном Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, -дополняющий к Java, который в свою очередь использовался бы для более сложных +дополняющий к Java, который бы в свою очередь использовался для более сложных web-приложений. Но тонкая интегрированность javascript с web-страницей и встроенная поддержка в браузерах привели к тому, чтобы он стал более -распространен в web-разработке, чем Java. -JavaScript was created by Netscape's Brendan Eich in 1995. It was originally -intended as a simpler scripting language for websites, complementing the use of -Java for more complex web applications, but its tight integration with Web pages -and built-in support in browsers has caused it to become far more common than -Java in web frontends. - -Использование Javascript не ограничивается браузерами. Проект Node.js, +распространен в frontend-разработке, чем Java. + +Использование JavaScript не ограничивается браузерами. Проект Node.js, предоставляющий независимую среду выполнения на движке Google Chrome V8 JavaScript, становится все более популярным. -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. Обратная связь важна и нужна! Вы можете написаться мне -на [@_remedy]() или -[mymail](). -Feedback would be highly appreciated! You can reach me at -[@adambrenecki](https://twitter.com/adambrenecki), or +на [@adambrenecki](https://twitter.com/adambrenecki) или [adam@brenecki.id.au](mailto:adam@brenecki.id.au). ```js // Комментарии оформляются как в C. -// Обнострочнные комментарии начинаются с двух слешей, -// Comments are like C. Single-line comments start with two slashes, +// Однострочнные коментарии начинаются с двух слешей, /* а многострочные с слеша и звездочки и заканчиваются звездочеий и слешом */ -/* and multiline comments start with slash-star - and end with star-slash */ // Выражения разделяются с помощью ; -// Statements can be terminated by ; doStuff(); -// ... но этого можно и делать, разделители подставляются автоматически +// ... но этого можно и не делать, разделители подставляются автоматически // после перехода на новую строку за исключением особых случаев -// ... but they don't have to be, as semicolons are automatically inserted -// wherever there's a newline, except in certain cases. doStuff() // Это может приводить к непредсказуемому результату и поэтому мы будем @@ -65,50 +48,41 @@ doStuff() // 1. Числа, Строки и Операторы // 1. Numbers, Strings and Operators -// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой стандарта -// IEEE 754) -// todo: сформулировать -// 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. +// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой +// стандарта IEEE 754) +// Числа имеют 52-битную мантиссу, чего достаточно для хранения хранения целых +// чисел до 9✕10¹⁵ приблизительно. 3; // = 3 1.5; // = 1.5 // В основном базовая арифметика работает предсказуемо -// Some basic arithmetic works as you'd expect. 1 + 1; // = 2 .1 + .2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -// Включая нецелочисленное деление (todo:уточнить!) -// Including uneven division. +// Включая нецелочисленное деление 5 / 2; // = 2.5 // Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, // оно будет приведено к 32-битному целому со знаком. -// 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 // (todo:перевести) -// Precedence is enforced with parentheses. +// Приоритет выполнения операций можно менять с помощью скобок. (1 + 3) * 2; // = 8 // Есть три особых не реальных числовых значения: -// There are three special not-a-real-number values: Infinity; // допустим, результат операции 1/0 -Infinity; // допустим, результат операции -1/0 NaN; // допустим, результат операции 0/0 // Так же есть тип булевых данных. -// There's also a boolean type. true; false; // Строки создаются с помощью ' или ". -// Strings are created with ' or ". 'abc'; "Hello, world"; @@ -137,7 +111,6 @@ false; "a" < "b"; // = true // Приведение типов выполняется при сравнении с ==... -// Type coercion is performed for comparisons with double equals... "5" == 5; // = true null == undefined; // = true @@ -146,29 +119,23 @@ null == undefined; // = true null === undefined; // = false // Для доступа к конкретному символу строки используйте charAt -// You can access characters in a string with charAt "This is a string".charAt(0); // = 'T' // ... или используйте substring для получения подстроки -// ...or use substring to get larger pieces "Hello world".substring(0, 5); // = "Hello" // length(длина) - свойство, не используйте () -// length is a property, so don't use () "Hello".length; // = 5 // Есть null и undefined -// There's also null and undefined null; // используется что бы указать явно, что значения нет undefined; // испрользуется чтобы показать, что значения не было установлено // собственно, undefined так и переводится // false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении // в булеву типу становятся false) -// false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. -// Обратите внимание что 0 приводится к false, а "0" к true, не смотря на то, -// что "0"==0 -// Note that 0 is falsy and "0" is truthy, even though 0 == "0". +// Обратите внимание что 0 приводится к false, а "0" к true, +// не смотря на то, что "0"==0 /////////////////////////////////// // 2. Переменные, массивы и объекты @@ -176,25 +143,18 @@ undefined; // испрользуется чтобы показать, что з // Переменные объявляются ключевым словом var. Javascript динамически // типизируемый, так что указывать тип не нужно. // Присвоение значения описывается с помощью оператора = -// Variables are declared with the var keyword. JavaScript is dynamically typed, -// so you don't need to specify type. Assignment uses a single = character. var someVar = 5; // если не указать ключевого слова var, ошибки не будет... -// 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 -// you defined it in. // Переменные объявленные без присвоения значения, содержать undefined -// Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined -// Для математических операций над числами есть короткая запись: -// There's shorthand for performing math operations on variables: +// Для математических операций над переменными есть короткая запись: someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь someVar *= 10; // а теперь -- 100 @@ -203,71 +163,55 @@ someVar++; // теперь someVar равно 101 someVar--; // обратно к 100 // Массивы -- упорядоченные списки значений любых типов. -// Arrays are ordered lists of values, of any type. var myArray = ["Hello", 45, true]; // Для доступу к элементам массивов используйте квадратные скобки. // Индексы массивов начинаются с 0 -// Their members can be accessed using the square-brackets subscript syntax. -// Array indices start at zero. myArray[1]; // = 45 // Массивы мутабельны(изменяемы) и имеют переменную длину. -// Arrays are mutable and of variable length. myArray.push("World"); // добавить элемент myArray.length; // = 4 // Добавить или изменить значение по конкретному индексу myArray[3] = "Hello"; -// Объёкты javascript похожи на dictionary или map из других языков +// Объекты javascript похожи на dictionary или map из других языков // программирования. Это неупорядочнные коллекции пар ключ-значение. -// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other -// languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; // Ключи -- это строки, но кавычки не требуются если названия явлюятся // корректными javascript идентификаторами. Значения могут быть любого типа. -// Keys are strings, but quotes aren't required if they're a valid -// JavaScript identifier. Values can be any type. var myObj = {myKey: "myValue", "my other key": 4}; // Доступ к атрибту объекта можно получить с помощью квадратных скобок -// Object attributes can also be accessed using the subscript syntax, myObj["my other key"]; // = 4 // ... или используя точечную нотацию, при условии что ключ является // корректным идентификатором. -// ... or using the dot syntax, provided the key is a valid identifier. myObj.myKey; // = "myValue" // Объекты мутабельны. В существуюещем объекте можно изменить значние // или добавить новый атрибут. -// Objects are mutable; values can be changed and new keys added. myObj.myThirdKey = true; // При попытке доступа к атрибуту, который до этого не был создан, будет // возвращен undefined -// If you try to access a value that's not yet set, you'll get undefined. myObj.myFourthKey; // = undefined /////////////////////////////////// -// 3. Логика и управляющие структуры -// 3. Logic and Control Structures +// 3. Логика и Управляющие структуры -// // Синтаксис управляющих структур очень похож на его реализацию в Java. -// The syntax for this section is almost identical to Java's. // if работает так как вы ожидаете. -// The if structure works as you'd expect. var count = 1; if (count == 3){ // выполнится, если значение count равно 3 } else if (count == 4){ // выполнится, если значение count равно 4 } else { - // выполнится, если значение countне будет равно ни 3 ни 4 + // выполнится, если значение count не будет равно ни 3 ни 4 } // Поведение while тоже вполне предсказуемо @@ -282,36 +226,27 @@ do { input = getInput(); } while (!isValid(input)) -// Цикл for такой же как в C b Java: +// Цикл for такой же как в C и Java: // инициализация; условие продолжения; итерация -// the for loop is the same as C and Java: -// initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // выполнится 5 раз - // will run 5 times } // && - логическое и, || - логическое или -// && is logical and, || is logical or if (house.size == "big" && house.color == "blue"){ house.contains = "bear"; } if (color == "red" || color == "blue"){ // если цвет или красный или синий - // colour is either red or blue } // && и || удобны для установки значений по умолчанию. // && and || "short circuit", which is useful for setting default values. var name = otherName || "default"; - -// выражение switch проверяет равество с помощью === -// используйте 'break' после каждого case +// выражение switch проверяет равество с помощью === +// используйте 'break' после каждого case, // иначе помимо правильного case выполнятся и все последующие. -// switch statement checks for equality with === -// use 'break' after each case -// or the cases after the correct one will be executed too. grade = '4'; // оценка switch (grade) { case '5': @@ -331,10 +266,8 @@ switch (grade) { /////////////////////////////////// // 4. Функции, Область видимости и Замыкания -// 4. Functions, Scope and Closures // Функции в JavaScript объявляются с помощью ключевого слова function. -// JavaScript functions are declared with the function keyword. function myFunction(thing){ return thing.toUpperCase(); // приведение к верхнему регистру } @@ -343,7 +276,7 @@ myFunction("foo"); // = "FOO" // Помните, что значение, которое должно быть возкращено должно начинаться // на той же строке, где расположено ключевое слово 'return'. В противном случае // будет возвращено undefined. Такое поведения объясняется автоматической -// вставкой разделителей ';'. Оглядывйтесь на этот факт, если используете +// вставкой разделителей ';'. Помните этот факт, если используете // BSD стиль оформления кода. // 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 @@ -360,94 +293,66 @@ myFunction(); // = undefined // Функции в JavaScript являются объектами, поэтому их можно назначить в // переменные с разными названиями и передавать в другие функции, как аргументы, // на пример, при указании обработчика события. -// JavaScript functions are first class objects, so they can be reassigned to -// different variable names and passed to other functions as arguments - for -// example, when supplying an event handler: function myFunction(){ // этот фрагмент кода будет вызван через 5 секунд - // this code will be called in 5 seconds' time } setTimeout(myFunction, 5000); // Обратите внимание, что setTimeout не является частью языка, однако он // доступен в API браузеров и Node.js. -// Note: setTimeout isn't part of the JS language, but is provided by browsers -// and Node.js. // Объект функции на самом деле не обязательно объявлять с именем - можно // создать анонимную функцию прямо в аргументах другой функции. -// 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(){ // этот фрагмент кода будет вызван через 5 секунд - // this code will be called in 5 seconds' time }, 5000); // В JavaScript есть области видимости. У функций есть собственные области // видимости, у других блоков их нет. -// JavaScript has function scope; functions get their own scope but other blocks -// do not. if (true){ var i = 5; } -i; // = 5, а не undefined, как это было бы ожидаемо(todo: поправить) - // в языке, создающем области видисти для блоков " +i; // = 5, а не undefined, как это было бы в языке, создающем + // области видисти для блоков кода // Это привело к появлению паттерна общего назначения "immediately-executing // anonymous functions" (сразу выполняющиеся анонимные функции), который // позволяет предотвратить запись временных переменных в общую облать видимости. -// This has led to a common pattern of "immediately-executing anonymous -// functions", which prevent temporary variables from leaking into the global -// scope. (function(){ var temporary = 5; // Для доступа к глобальной области видимости можно использовать запись в // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный // объект может называться по-разному в небраузерных средах, таких Node.js. - // 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; // вызывает исключение ReferenceError permanent; // = 10 // Одной из сильных сторон JavaScript являются замыкания. Если функция -// объявлена в вниутри другой функции, внутренняя функция имеет доступ ко всем +// объявлена в внутри другой функции, внутренняя функция имеет доступ ко всем // переменным внешней функции, даже после того, как внешняя функции завершила -// свое выполнение -// One of JavaScript's most powerful features is closures. If a function is -// defined inside another function, the inner function has access to all the -// outer function's variables, even after the outer function exits. +// свое выполнение. function sayHelloInFiveSeconds(name){ var prompt = "Привет, " + name + "!"; - // Внутренние фунции помещаются в локальную область видимости, как-будто они - // объявлены с ключевым словом 'var'. - // Inner functions are put in the local scope by default, as if they were - // declared with 'var'. + // Внутренние функции помещаются в локальную область видимости, как-будто + // они объявлены с ключевым словом 'var'. function inner(){ alert(prompt); } setTimeout(inner, 5000); // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds // завершит свое выполнение сразу и setTimeout вызовет inner позже. - // Однако, так как inner "замкнута"(todo: уточнить "закрыта внутри") + // Однако, так как inner "закрыта внутри" или "замкнута в" // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной // prompt, когда будет вызвана. - // 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("Вася"); // откроет модальное окно с сообщением // "Привет, Вася" по истечении 5 секунд. /////////////////////////////////// -// 5. Немного об Объектах. Конструкторы и Прототипы -// 5. More about Objects; Constructors and Prototypes +// 5. Немного еще об Объектах. Конструкторы и Прототипы -// Объекты погут содержать функции -// Objects can contain functions. +// Объекты могут содержать функции var myObj = { myFunc: function(){ return "Hello world!"; @@ -456,9 +361,7 @@ var myObj = { myObj.myFunc(); // = "Hello world!" // Когда функции прикрепленные к объекту вызываются, они могут получить доступ -// к данным объекта, ипользую ключевое слово this. -// When functions attached to an object are called, they can access the object -// they're attached to using the this keyword. +// к данным объекта, ипользуя ключевое слово this. myObj = { myString: "Hello world!", myFunc: function(){ @@ -470,16 +373,11 @@ myObj.myFunc(); // = "Hello world!" // Содержание this определяется исходя из того, как была вызвана функция, а // не места её определения. По этой причине наша функция не будет работать вне // контекста объекта. -// What this is set to has to do with how the function is called, not where -// it's defined. So, our function doesn't work if it isn't called in the -// context of the object. var myFunc = myObj.myFunc; myFunc(); // = undefined // И напротив, функция может быть присвоена объекту и получить доступ к нему // через this, даже если она не была прикреплена к объекту в момент её создания. -// Inversely, a function can be assigned to the object and gain access to it -// through this, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); } @@ -487,23 +385,17 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. -// We can also specify a context for a function to execute in when we invoke it -// using 'call' or 'apply'. - var anotherFunc = function(s){ return this.myString + s; } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" // Функция 'apply' очень похожа, но принимает массив со списком аргументов. -// The 'apply' function is nearly identical, but takes an array for an argument list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" // Это может быть удобно, когда работаешь с фунцией принимающей на вход // последовательность аргументов и нужно передать их в виде массива. -// This is useful when working with a function that accepts a sequence of arguments -// and you want to pass an array. Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) @@ -511,15 +403,12 @@ Math.min.apply(Math, [42, 6, 27]); // = 6 // Однако, 'call' и 'apply' не имеют постоянного эффекта. Если вы хотите // зафиксировать контекст для функции, используйте bind. -// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use -// bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -// bind можно использовать чтобы частично передать аргументы в +// bind также можно использовать чтобы частично передать аргументы в // функцию (каррировать). -// Bind can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); @@ -528,9 +417,6 @@ doubler(8); // = 16 // Когда функция вызывается с ключевым словом new, создается новый объект. // Данный объект становится доступным функции через ключевое слово this. // Функции спроектированные вызываться таким способом называются конструкторами. -// When you call a function with the new keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be -// called like that are called constructors. var MyConstructor = function(){ this.myNumber = 5; @@ -538,20 +424,14 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Любой объект в JavaScript имеет 'прототип'. Когда выпытаетесь получить доступ -// к свойству не объявленному в данном объекте, интерпретатор будет искать его -// в прототипе. -// Every JavaScript object has a 'prototype'. When you go to access a property -// on an object that doesn't exist on the actual object, the interpreter will -// look at its prototype. +// Любой объект в JavaScript имеет 'прототип'. Когда вы пытаетесь получить +// доступ к свойству не объявленному в данном объекте, интерпретатор будет +// искать его в прототипе. // Некоторые реализации JS позволяют получить доступ к прототипу с помощью -// волшебного свойства __proto__. До момента пока оно не являются стандартным, +// "волшебного" свойства __proto__. До момента пока оно не являются стандартным, // __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся // со стандартными способами работы с прототипом несколько позже. -// Some JS implementations let you access an object's prototype on the magic -// property __proto__. While this is useful for explaining prototypes it's not -// part of the standard; we'll get to standard ways of using prototypes later. var myObj = { myString: "Hello world!" }; @@ -566,10 +446,8 @@ myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 myObj.myFunc(); // = "hello world!" -// Естествно, если в свойства нет в прототипе, поиск будет продолжен в прототипе -// прототипа и так далее. -// Of course, if your property isn't on your prototype, the prototype's -// prototype is searched, and so on. +// Естественно, если в свойства нет в прототипе, поиск будет продолжен в +// прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true }; @@ -577,34 +455,22 @@ myObj.myBoolean; // = true // Ничего не копируется, каждый объект хранит ссылку на свой прототип. Если // изменить прототип, все изменения отразятся во всех его потомках. -// There's no copying involved here; each object stores a reference to its -// prototype. This means we can alter the prototype and our changes will be -// reflected everywhere. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 // Как было сказано выше, __proto__ не является стандартом, и нет стандартного // способа изменить прототип у созданного объекта. Однако, есть два способа // создать объект с заданным прототипом. -// We mentioned that __proto__ was non-standard, and there's no standard way to -// change the prototype of an existing object. However, there are two ways to -// create a new object with a given prototype. // Первый способ - Object.create, был добавлен в JS относительно недавно, и // потому не доступен в более ранних реализациях языка. -// The first is Object.create, which is a recent addition to JS, and therefore -// not available in all implementations yet. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 // Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют -// свойство prototype. Это воовсе не прототип функции конструктора, напротив, +// свойство prototype. Это вовсе не прототип функции конструктора, напротив, // это прототип, который присваевается новым объектам, созданным с этим // конструктором с помощью ключевого слова new. -// The second way, which works anywhere, has to do with constructors. -// Constructors have a property called prototype. This is *not* the prototype of -// the constructor function itself; instead, it's the prototype that new objects -// are given when they're created with that constructor and the new keyword. MyConstructor.prototype = { myNumber: 5, getMyNumber: function(){ @@ -618,53 +484,40 @@ myNewObj2.getMyNumber(); // = 6 // У встроенных типов таких, как строки и числа, тоже есть конструкторы, // создающие эквивалентные объекты-обертки. -// Built-in types like strings and numbers also have constructors that create -// equivalent wrapper objects. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true // Правда, они не совсем эквивалентны. -// Except, they aren't exactly equivalent. typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // Этот фрагмент кода не будет выпонен, так как 0 приводится к false - // This code won't execute, because 0 is falsy. } if (Number(0)){ // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. - // This code *will* execute, because Number(0) is truthy. } // Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, // следовательно вы можете расширить функциональность строки, например. -// However, the wrapper objects and the regular builtins share a prototype, so -// you can actually add functionality to a string, for instance. String.prototype.firstCharacter = function(){ return this.charAt(0); } "abc".firstCharacter(); // = "a" // Этот факт часто используется для создания полифилов(polyfill) - реализации -// новых возможностей JS в его болле старых версиях для того чтобы их можно было +// новых возможностей JS в его более старых версиях для того чтобы их можно было // использовать в устаревших браузерах. -// 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. // Например, мы упомянули, что Object.create не доступен во всех версиях // JavaScript, но мы можем создать полифилл. -// For instance, we mentioned that Object.create isn't yet available in all -// implementations, but we can still use it with this polyfill: -if (Object.create === undefined){ // не переопределяем если есть +if (Object.create === undefined){ // не переопределяем, если есть Object.create = function(proto){ // создаем временный конструктор с заданным прототипом var Constructor = function(){}; Constructor.prototype = proto; // создаём новый объект с правильным прототипом - // then use it to create a new, appropriately-prototyped object return new Constructor(); } } -- cgit v1.2.3 From c689f9f8218dfa95fe655364301326f8dbd369b7 Mon Sep 17 00:00:00 2001 From: Maksim Koretskiy Date: Thu, 13 Nov 2014 12:34:19 +0300 Subject: Remove todos --- ru-ru/javascript-ru.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index abbafc8d..ad66b501 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,8 +9,6 @@ filename: javascript-ru.js lang: ru-ru --- -todo: привести все названия языка к коректному написанию - Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально предполагалось, что он станет простым вариантом скриптового языка для сайтов, дополняющий к Java, который бы в свою очередь использовался для более сложных -- cgit v1.2.3 From 12e01249b37d65d8e7cf95b311782531978552d5 Mon Sep 17 00:00:00 2001 From: Swapnil Joshi Date: Tue, 16 Dec 2014 22:33:08 +0530 Subject: Changed function name to match function call --- hy.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hy.html.markdown b/hy.html.markdown index 04bd05c9..9beaff0c 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -83,7 +83,7 @@ True ; => True (greet "bilbo") ;=> "hello bilbo" ; functions can take optional arguments as well as keyword arguments -(defn foolist [arg1 &optional [arg2 2]] +(defn foolists [arg1 &optional [arg2 2]] [arg1 arg2]) (foolists 3) ;=> [3 2] -- cgit v1.2.3 From c43b73a369526a922282f429ba7b1472b64c4f8e Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Sat, 20 Dec 2014 09:52:43 +0900 Subject: start translating julia into japanese --- ja-jp/julia-jp.html.markdown | 747 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 747 insertions(+) create mode 100644 ja-jp/julia-jp.html.markdown diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown new file mode 100644 index 00000000..3a52018c --- /dev/null +++ b/ja-jp/julia-jp.html.markdown @@ -0,0 +1,747 @@ +--- +language: Julia +contributors: + - ["Leah Hanson", "http://leahhanson.us"] +filename: learnjulia.jl +--- + +Julia is a new homoiconic functional language focused on technical computing. +While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. + +This is based on the current development version of Julia, as of October 18th, 2013. + +```ruby + +# Single line comments start with a hash (pound) symbol. +#= Multiline comments can be written + by putting '#=' before the text and '=#' + after the text. They can also be nested. +=# + +#################################################### +## 1. Primitive Datatypes and Operators +#################################################### + +# Everything in Julia is a expression. + +# There are several basic types of numbers. +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) + +# All of the normal infix operators are available. +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float +div(5, 2) # => 2 # for a truncated result, use div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # power, not bitwise xor +12 % 10 # => 2 + +# Enforce precedence with parentheses +(1 + 3) * 2 # => 8 + +# Bitwise Operators +~2 # => -3 # bitwise not +3 & 5 # => 1 # bitwise and +2 | 4 # => 6 # bitwise or +2 $ 4 # => 6 # bitwise xor +2 >>> 1 # => 1 # logical shift right +2 >> 1 # => 1 # arithmetic shift right +2 << 1 # => 4 # logical/arithmetic shift left + +# You can use the bits function to see the binary representation of a number. +bits(12345) +# => "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +# => "0100000011001000000111001000000000000000000000000000000000000000" + +# Boolean values are primitives +true +false + +# Boolean operators +!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 +# Comparisons can be chained +1 < 2 < 3 # => true +2 < 3 < 2 # => false + +# Strings are created with " +"This is a string." + +# Character literals are written with ' +'a' + +# A string can be indexed like an array of characters +"This is a string"[1] # => 'T' # Julia indexes from 1 +# However, this is will not work well for UTF8 strings, +# so iterating over strings is recommended (map, for loops, etc). + +# $ can be used for string interpolation: +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" +# You can put any Julia expression inside the parenthesis. + +# Another way to format strings is the printf macro. +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +# Printing is easy +println("I'm Julia. Nice to meet you!") + +#################################################### +## 2. Variables and Collections +#################################################### + +# You don't declare variables before assigning to them. +some_var = 5 # => 5 +some_var # => 5 + +# Accessing a previously unassigned variable is an error +try + some_other_var # => ERROR: some_other_var not defined +catch e + println(e) +end + +# Variable names start with a letter. +# After that, you can use letters, digits, underscores, and exclamation points. +SomeOtherVar123! = 6 # => 6 + +# You can also use unicode characters +☃ = 8 # => 8 +# These are especially handy for mathematical notation +2 * π # => 6.283185307179586 + +# A note on naming conventions in Julia: +# +# * Word separation can be indicated by underscores ('_'), but use of +# underscores is discouraged unless the name would be hard to read +# otherwise. +# +# * Names of Types begin with a capital letter and word separation is shown +# with CamelCase instead of underscores. +# +# * Names of functions and macros are in lower case, without underscores. +# +# * Functions that modify their inputs have names that end in !. These +# functions are sometimes called mutating functions or in-place functions. + +# Arrays store a sequence of values indexed by integers 1 through n: +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[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] + +# Add stuff to the end of a list with push! and append! +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] + +# Remove from the end with pop +pop!(b) # => 6 and b is now [4,5] + +# Let's put it back +push!(b,6) # b is now [4,5,6] again. + +a[1] # => 1 # remember that Julia indexes from 1, not 0! + +# end is a shorthand for the last index. It can be used in any +# indexing expression +a[end] # => 6 + +# we also have shift and unshift +shift!(a) # => 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] + +# Function names that end in exclamations points indicate that they modify +# their argument. +arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] +sort(arr) # => [4,5,6]; arr is still [5,4,6] +sort!(arr) # => [4,5,6]; arr is now [4,5,6] + +# Looking out of bounds is a BoundsError +try + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# Errors list the line and file they came from, even if it's in the standard +# library. If you built Julia from source, you can look in the folder base +# inside the julia folder to find these files. + +# You can initialize arrays from ranges +a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] + +# You can look at ranges with slice syntax. +a[1:3] # => [1, 2, 3] +a[2:end] # => [2, 3, 4, 5] + +# Remove elements from an array by index with splice! +arr = [3,4,5] +splice!(arr,2) # => 4 ; arr is now [3,5] + +# Concatenate lists with append! +b = [1,2,3] +append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] + +# Check for existence in a list with in +in(1, a) # => true + +# Examine the length with length +length(a) # => 8 + +# Tuples are immutable. +tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] # => 1 +try: + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# Many list functions also work on tuples +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true + +# You can unpack tuples into variables +a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 + +# Tuples are created even if you leave out the parentheses +d, e, f = 4, 5, 6 # => (4,5,6) + +# A 1-element tuple is distinct from the value it contains +(1,) == 1 # => false +(1) == 1 # => true + +# Look how easy it is to swap two values +e, d = d, e # => (5,4) # d is now 5 and e is now 4 + + +# Dictionaries store mappings +empty_dict = Dict() # => Dict{Any,Any}() + +# You can create a dictionary using a literal +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# Look up values with [] +filled_dict["one"] # => 1 + +# Get all keys +keys(filled_dict) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - dictionary keys are not sorted or in the order you inserted them. + +# Get all values +values(filled_dict) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# Note - Same as above regarding key ordering. + +# Check for existence of keys in a dictionary with in, haskey +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false + +# Trying to look up a non-existant key will raise an error +try + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# Use the get method to avoid that error by providing a default value +# get(dictionary,key,default_value) +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 + +# Use Sets to represent collections of unordered, unique values +empty_set = Set() # => Set{Any}() +# Initialize a set with values +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) + +# Add more values to a set +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) + +# Check if the values are in the set +in(2, filled_set) # => true +in(10, filled_set) # => false + +# There are functions for set intersection, union, and difference. +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) + + +#################################################### +## 3. Control Flow +#################################################### + +# Let's make a variable +some_var = 5 + +# Here is an if statement. Indentation is not meaningful in Julia. +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # This elseif clause is optional. + println("some_var is smaller than 10.") +else # The else clause is optional too. + println("some_var is indeed 10.") +end +# => prints "some var is smaller than 10" + + +# For loops iterate over iterables. +# Iterable types include Range, Array, Set, Dict, and String. +for animal=["dog", "cat", "mouse"] + println("$animal is a mammal") + # You can use $ to interpolate variables or expression into strings +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# You can use 'in' instead of '='. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is a $(a[2])") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is a $v") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# While loops loop while a condition is true +x = 0 +while x < 4 + println(x) + x += 1 # Shorthand for x = x + 1 +end +# prints: +# 0 +# 1 +# 2 +# 3 + +# Handle exceptions with a try/catch block +try + error("help") +catch e + println("caught it $e") +end +# => caught it ErrorException("help") + + +#################################################### +## 4. Functions +#################################################### + +# The keyword 'function' creates new functions +#function name(arglist) +# body... +#end +function add(x, y) + println("x is $x and y is $y") + + # Functions return the value of their last statement + x + y +end + +add(5, 6) # => 11 after printing out "x is 5 and y is 6" + +# You can define functions that take a variable number of +# positional arguments +function varargs(args...) + return args + # use the keyword return to return anywhere in the function +end +# => varargs (generic function with 1 method) + +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, +# 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) + +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x...) # => Set{Int64}(2,3,1) + + +# You can define functions with optional positional arguments +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" +try + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() +catch e + println(e) +end + +# You can define functions that take keyword arguments +function keyword_args(;k1=4,name2="hello") # note the ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k1"=>4] + +# You can combine all kinds of arguments in the same function +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Julia has first class functions +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# This is "stabby lambda syntax" for creating anonymous functions +(x -> x > 2)(3) # => true + +# This function is identical to create_adder implementation above. +function create_adder(x) + y -> x + y +end + +# You can also name the internal function, if you want +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) # => 13 + + +# There are built-in higher order functions +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# We can use list comprehensions for nicer maps +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] + +#################################################### +## 5. Types +#################################################### + +# Julia has a type system. +# Every value has a type; variables do not have types themselves. +# You can use the `typeof` function to get the type of a value. +typeof(5) # => Int64 + +# Types are first-class values +typeof(Int64) # => DataType +typeof(DataType) # => DataType +# DataType is the type that represents types, including itself. + +# Types are used for documentation, optimizations, and dispatch. +# They are not statically checked. + +# Users can define types +# They are like records or structs in other languages. +# New types are defined using the `type` keyword. + +# type Name +# field::OptionalType +# ... +# end +type Tiger + taillength::Float64 + coatcolor # not including a type annotation is the same as `::Any` +end + +# The default constructor's arguments are the properties +# of the type, in the order they are listed in the definition +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") + +# The type doubles as the constructor function for values of that type +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") + +# These struct-style types are called concrete types +# They can be instantiated, but cannot have subtypes. +# The other kind of types is abstract types. + +# abstract Name +abstract Cat # just a name and point in the type hierarchy + +# Abstract types cannot be instantiated, but can have subtypes. +# For example, Number is an abstract type +subtypes(Number) # => 6-element Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) # => 0-element Array{Any,1} + +# Every type has a super type; use the `super` function to get it. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any +# All of these type, except for Int64, are abstract. + +# <: is the subtyping operator +type Lion <: Cat # Lion is a subtype of Cat + mane_color + roar::String +end + +# You can define more constructors for your type +# Just define a function of the same name as the type +# and call an existing constructor to get a value of the correct type +Lion(roar::String) = Lion("green",roar) +# This is an outer constructor because it's outside the type definition + +type Panther <: Cat # Panther is also a subtype of Cat + eye_color + Panther() = new("green") + # Panthers will only have this constructor, and no default constructor. +end +# Using inner constructors, like Panther does, gives you control +# over how values of the type can be created. +# When possible, you should use outer constructors rather than inner ones. + +#################################################### +## 6. Multiple-Dispatch +#################################################### + +# In Julia, all named functions are generic functions +# This means that they are built up from many small methods +# Each constructor for Lion is a method of the generic function Lion. + +# For a non-constructor example, let's make a function meow: + +# Definitions for Lion, Panther, Tiger +function meow(animal::Lion) + animal.roar # access type properties using dot notation +end + +function meow(animal::Panther) + "grrr" +end + +function meow(animal::Tiger) + "rawwwr" +end + +# Testing the meow function +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" + +# Review the local type hierarchy +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true + +# Defining a function that takes Cats +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(Lion("42")) # => prints "The cat says 42" +try + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +# In OO languages, single dispatch is common; +# this means that the method is picked based on the type of the first argument. +# In Julia, all of the argument types contribute to selecting the best method. + +# Let's define a function with more arguments, so we can see the difference +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +# => fight (generic function with 1 method) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! + +# Let's change the behavior when the Cat is specifically a Lion +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +# => fight (generic function with 2 methods) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! + +# We don't need a Tiger in order to fight +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# => fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) +catch +end + +# Also let the cat go first +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +# => Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# This warning is because it's unclear which fight will be called in: +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# The result may be different in other versions of Julia + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie + + +# Under the hood +# You can take a look at the llvm and the assembly code generated. + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +# What happens when we feed square_area an integer? +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Prologue + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # Fetch l from memory? + # imul RAX, RAX # Square l and store the result in RAX + # pop RBP # Restore old base pointer + # ret # Result will still be in RAX + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) + # pop RBP + # ret + # +# Note that julia will use floating point instructions if any of the +# arguements are floats. +# Let's calculate the area of a circle +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # +``` + +## Further Reading + +You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) + +The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From 09ab1c3aee929fd9336cecdff6ff2c5d3cd4f06a Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Sat, 20 Dec 2014 12:33:17 +0900 Subject: finish translating (original english remains for review) --- ja-jp/julia-jp.html.markdown | 232 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 212 insertions(+), 20 deletions(-) diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown index 3a52018c..0c596c99 100644 --- a/ja-jp/julia-jp.html.markdown +++ b/ja-jp/julia-jp.html.markdown @@ -2,9 +2,17 @@ language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] -filename: learnjulia.jl +translators: + - ["Yuichi Motoyama", "https://github.com/yomichi"] +filename: learnjulia-jp.jl --- +Julia は科学技術計算向けに作られた、同図像性を持った(homoiconic) プログラミング言語です。 +マクロによる同図像性や第一級関数をもち、なおかつ低階層も扱えるにもかかわらず、 +Julia はPython 並に学習しやすく、使いやすい言語となっています。 + +この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。 + Julia is a new homoiconic functional language focused on technical computing. While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. @@ -12,6 +20,12 @@ This is based on the current development version of Julia, as of October 18th, 2 ```ruby +# ハッシュ(シャープ)記号から改行までは単一行コメントとなります。 +#= 複数行コメントは、 + '#=' と '=#' とで囲むことで行えます。 + 入れ子構造にすることもできます。 +=# + # Single line comments start with a hash (pound) symbol. #= Multiline comments can be written by putting '#=' before the text and '=#' @@ -20,49 +34,61 @@ This is based on the current development version of Julia, as of October 18th, 2 #################################################### ## 1. Primitive Datatypes and Operators +## 1. 基本的な型と演算子 #################################################### +# Julia ではすべて式となります。 # Everything in Julia is a expression. +# 基本となる数値型がいくつかあります。 # There are several basic types of numbers. 3 # => 3 (Int64) 3.2 # => 3.2 (Float64) 2 + 1im # => 2 + 1im (Complex{Int64}) 2//3 # => 2//3 (Rational{Int64}) +# 一般的な中置演算子が使用可能です。 # All of the normal infix operators are available. 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7.0 +5 / 2 # => 2.5 # 整数型同士の割り算の結果は、浮動小数点数型になります 5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float +div(5, 2) # => 2 # 整数のまま割り算するには、 div を使います div(5, 2) # => 2 # for a truncated result, use div 5 \ 35 # => 7.0 +2 ^ 2 # => 4 # べき乗です。排他的論理和ではありません 2 ^ 2 # => 4 # power, not bitwise xor 12 % 10 # => 2 +# 丸括弧で演算の優先順位をコントロールできます # Enforce precedence with parentheses (1 + 3) * 2 # => 8 +# ビット演算 # Bitwise Operators -~2 # => -3 # bitwise not -3 & 5 # => 1 # bitwise and -2 | 4 # => 6 # bitwise or -2 $ 4 # => 6 # bitwise xor -2 >>> 1 # => 1 # logical shift right -2 >> 1 # => 1 # arithmetic shift right -2 << 1 # => 4 # logical/arithmetic shift left - +~2 # => -3 # ビット反転 +3 & 5 # => 1 # ビット積 +2 | 4 # => 6 # ビット和 +2 $ 4 # => 6 # 排他的論理和 +2 >>> 1 # => 1 # 右論理シフト +2 >> 1 # => 1 # 右算術シフト +2 << 1 # => 4 # 左シフト + +# bits 関数を使うことで、数の二進表現を得られます。 # You can use the bits function to see the binary representation of a number. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" +# ブール値が用意されています # Boolean values are primitives true false +# ブール代数 # Boolean operators !true # => false !false # => true @@ -74,39 +100,51 @@ false 1 > 10 # => false 2 <= 2 # => true 2 >= 2 # => true +# 比較演算子をつなげることもできます # Comparisons can be chained 1 < 2 < 3 # => true 2 < 3 < 2 # => false +# 文字列は " で作れます # Strings are created with " "This is a string." +# 文字リテラルは ' で作れます # Character literals are written with ' 'a' +# 文字列は文字の配列のように添字アクセスできます # A string can be indexed like an array of characters -"This is a string"[1] # => 'T' # Julia indexes from 1 +"This is a string"[1] # => 'T' # Julia では添字は 1 から始まります +# ただし、UTF8 文字列の場合は添字アクセスではうまくいかないので、 +# その場合はイテレーションを行ってください(map 関数や for ループなど) # However, this is will not work well for UTF8 strings, # so iterating over strings is recommended (map, for loops, etc). +# $ を使うことで、文字列に変数や、任意の式を埋め込めます。 # $ can be used for string interpolation: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" # You can put any Julia expression inside the parenthesis. +# 他にも、printf マクロを使うことでも変数を埋め込めます。 # Another way to format strings is the printf macro. @printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 +# 出力も簡単です # Printing is easy println("I'm Julia. Nice to meet you!") #################################################### ## 2. Variables and Collections +## 2. 変数と配列 #################################################### +# 変数の宣言は不要で、いきなり変数に値を代入・束縛できます。 # You don't declare variables before assigning to them. some_var = 5 # => 5 some_var # => 5 +# 値の束縛されていない変数を使おうとするとエラーになります。 # Accessing a previously unassigned variable is an error try some_other_var # => ERROR: some_other_var not defined @@ -114,40 +152,62 @@ catch e println(e) end +# 変数名は文字から始めます。 +# その後は、文字だけでなく数字やアンダースコア(_), 感嘆符(!)が使えます。 # Variable names start with a letter. # After that, you can use letters, digits, underscores, and exclamation points. SomeOtherVar123! = 6 # => 6 +# Unicode 文字も使えます。 # You can also use unicode characters ☃ = 8 # => 8 +# ギリシャ文字などを使うことで数学的な記法が簡単にかけます。 # These are especially handy for mathematical notation 2 * π # => 6.283185307179586 +# Julia における命名習慣について: # A note on naming conventions in Julia: # +# * 変数名における単語の区切りにはアンダースコアを使っても良いですが、 +# 使わないと読みにくくなる、というわけではない限り、 +# 推奨はされません。 +# # * Word separation can be indicated by underscores ('_'), but use of # underscores is discouraged unless the name would be hard to read # otherwise. # +# * 型名は大文字で始め、単語の区切りはキャメルケースを使います。 +# # * Names of Types begin with a capital letter and word separation is shown # with CamelCase instead of underscores. # +# * 関数やマクロの名前は小文字で書きます。 +# 分かち書きにアンダースコアをつかわず、直接つなげます。 +# # * Names of functions and macros are in lower case, without underscores. # +# * 内部で引数を変更する関数は、名前の最後に ! をつけます。 +# この手の関数は、しばしば「破壊的な関数」とか「in-place な関数」とか呼ばれます。 +# # * Functions that modify their inputs have names that end in !. These # functions are sometimes called mutating functions or in-place functions. +# 配列は、1 から始まる整数によって添字付けられる、値の列です。 # Arrays store a sequence of values indexed by integers 1 through n: 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[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] +# 配列の終端に値を追加するには push! を、 +# 他の配列を追加するには append! を使います。 # Add stuff to the end of a list with push! and append! push!(a,1) # => [1] push!(a,2) # => [1,2] @@ -155,28 +215,36 @@ push!(a,4) # => [1,2,4] push!(a,3) # => [1,2,4,3] append!(a,b) # => [1,2,4,3,4,5,6] +# 配列の終端から値を削除するには pop! を使います。 # Remove from the end with pop pop!(b) # => 6 and b is now [4,5] +# もう一度戻しましょう。 # Let's put it back push!(b,6) # b is now [4,5,6] again. +a[1] # => 1 # Julia では添字は0 ではなく1 から始まること、お忘れなく! a[1] # => 1 # remember that Julia indexes from 1, not 0! +# end は最後の添字を表す速記法です。 +# 添字を書く場所ならどこにでも使えます。 # end is a shorthand for the last index. It can be used in any # indexing expression a[end] # => 6 +# 先頭に対する追加・削除は shift!, unshift! です。 # we also have shift and unshift shift!(a) # => 1 and a is now [2,4,3,4,5,6] unshift!(a,7) # => [7,2,4,3,4,5,6] +# ! で終わる関数名は、その引数を変更するということを示します。 # Function names that end in exclamations points indicate that they modify # their argument. arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] sort(arr) # => [4,5,6]; arr is still [5,4,6] sort!(arr) # => [4,5,6]; arr is now [4,5,6] +# 配列の範囲外アクセスをすると BoundsError が発生します。 # Looking out of bounds is a BoundsError try a[0] # => ERROR: BoundsError() in getindex at array.jl:270 @@ -185,31 +253,40 @@ catch e println(e) end +# エラーが発生すると、どのファイルのどの行で発生したかが表示されます。 # Errors list the line and file they came from, even if it's in the standard # library. If you built Julia from source, you can look in the folder base # inside the julia folder to find these files. +# 配列は範囲オブジェクトから作ることもできます。 # You can initialize arrays from ranges a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +# 添字として範囲オブジェクトを渡すことで、 +# 配列の部分列を得ることもできます。 # You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] a[2:end] # => [2, 3, 4, 5] +# 添字を用いて配列から値の削除をしたい場合は、splice! を使います。 # Remove elements from an array by index with splice! arr = [3,4,5] splice!(arr,2) # => 4 ; arr is now [3,5] +# 配列の結合は append! です。 # Concatenate lists with append! b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] +# 配列内に指定した値があるかどうかを調べるのには in を使います。 # Check for existence in a list with in in(1, a) # => true +# length で配列の長さを取得できます。 # Examine the length with length length(a) # => 8 +# 変更不可能 (immutable) な値の組として、タプルが使えます。 # Tuples are immutable. tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] # => 1 @@ -219,51 +296,65 @@ catch e println(e) end +# 配列に関する関数の多くが、タプルでも使えます。 # Many list functions also work on tuples length(tup) # => 3 tup[1:2] # => (1,2) in(2, tup) # => true +# タプルから値をばらして(unpack して) 複数の変数に代入できます。 # You can unpack tuples into variables a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +# 丸括弧なしでもタプルになります。 # Tuples are created even if you leave out the parentheses d, e, f = 4, 5, 6 # => (4,5,6) +# ひとつの値だけからなるタプルは、その値自体とは区別されます。 # A 1-element tuple is distinct from the value it contains (1,) == 1 # => false (1) == 1 # => true +# 値の交換もタプルを使えば簡単です。 # Look how easy it is to swap two values e, d = d, e # => (5,4) # d is now 5 and e is now 4 +# 辞書 (Dict) は、値から値への変換の集合です。 # Dictionaries store mappings empty_dict = Dict() # => Dict{Any,Any}() +# 辞書型リテラルは次のとおりです。 # You can create a dictionary using a literal filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} +# [] を使ったアクセスができます。 # Look up values with [] filled_dict["one"] # => 1 +# すべての鍵(添字)は keys で得られます。 # Get all keys keys(filled_dict) # => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 必ずしも辞書に追加した順番には並んでいないことに注意してください。 # Note - dictionary keys are not sorted or in the order you inserted them. +# 同様に、values はすべての値を返します。 # Get all values values(filled_dict) # => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 鍵と同様に、必ずしも辞書に追加した順番には並んでいないことに注意してください。 # Note - Same as above regarding key ordering. +# in や haskey を使うことで、要素や鍵が辞書の中にあるかを調べられます。 # Check for existence of keys in a dictionary with in, haskey in(("one", 1), filled_dict) # => true in(("two", 3), filled_dict) # => false haskey(filled_dict, "one") # => true haskey(filled_dict, 1) # => false +# 存在しない鍵を問い合わせると、エラーが発生します。 # Trying to look up a non-existant key will raise an error try filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 @@ -271,23 +362,30 @@ catch e println(e) end +# get 関数を使い、鍵がなかった場合のデフォルト値を与えておくことで、 +# このエラーを回避できます。 # Use the get method to avoid that error by providing a default value # get(dictionary,key,default_value) get(filled_dict,"one",4) # => 1 get(filled_dict,"four",4) # => 4 +# 集合 (Set) は一意な値の、順序付けられていない集まりです。 # Use Sets to represent collections of unordered, unique values empty_set = Set() # => Set{Any}() +# 集合の初期化 # Initialize a set with values filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) +# 集合への追加 # Add more values to a set push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) +# in で、値が既に存在するかを調べられます。 # Check if the values are in the set in(2, filled_set) # => true in(10, filled_set) # => false +# 積集合や和集合、差集合を得る関数も用意されています。 # There are functions for set intersection, union, and difference. other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) intersect(filled_set, other_set) # => Set{Int64}(3,4,5) @@ -297,26 +395,32 @@ setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) #################################################### ## 3. Control Flow +## 3. 制御構文 #################################################### +# まずは変数を作ります。 # Let's make a variable some_var = 5 +# if 構文です。Julia ではインデントに意味はありません。 # Here is an if statement. Indentation is not meaningful in Julia. if some_var > 10 println("some_var is totally bigger than 10.") -elseif some_var < 10 # This elseif clause is optional. +elseif some_var < 10 # elseif 節は省略可能です。 println("some_var is smaller than 10.") -else # The else clause is optional too. +else # else 節も省略可能です。 println("some_var is indeed 10.") end -# => prints "some var is smaller than 10" - +# => "some var is smaller than 10" と出力されます。 +# for ループによって、反復可能なオブジェクトを走査できます。 +# 反復可能なオブジェクトの型として、 +# Range, Array, Set, Dict, String などがあります。 # For loops iterate over iterables. # Iterable types include Range, Array, Set, Dict, and String. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") + # $ を使うことで文字列に変数の値を埋め込めます。 # You can use $ to interpolate variables or expression into strings end # prints: @@ -324,6 +428,7 @@ end # cat is a mammal # mouse is a mammal +# for = の代わりに for in を使うこともできます # You can use 'in' instead of '='. for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") @@ -349,6 +454,7 @@ end # cat is a mammal # mouse is a mammal +# while ループは、条件式がtrue となる限り実行され続けます。 # While loops loop while a condition is true x = 0 while x < 4 @@ -361,6 +467,7 @@ end # 2 # 3 +# 例外は try/catch で捕捉できます。 # Handle exceptions with a try/catch block try error("help") @@ -372,8 +479,10 @@ end #################################################### ## 4. Functions +## 4. 関数 #################################################### +# function キーワードを次のように使うことで、新しい関数を定義できます。 # The keyword 'function' creates new functions #function name(arglist) # body... @@ -381,34 +490,42 @@ end function add(x, y) println("x is $x and y is $y") + # 最後に評価された式の値が、関数全体の返り値となります。 # Functions return the value of their last statement x + y end add(5, 6) # => 11 after printing out "x is 5 and y is 6" +# 可変長引数関数も定義できます。 # You can define functions that take a variable number of # positional arguments function varargs(args...) return args + # return キーワードを使うことで、好きな位置で関数から抜けられます。 # use the keyword return to return anywhere in the function end # => varargs (generic function with 1 method) varargs(1,2,3) # => (1,2,3) +# ... はsplat と呼ばれます +# (訳注:「ピシャッという音(名詞)」「衝撃で平らにする(動詞)」) +# 今回は関数定義で使いましたが、関数呼び出しに使うこともできます。 +# その場合、配列やタプルの要素を開いて、複数の引数へと割り当てることとなります。 # The ... is called a splat. # We just used it in a function definition. # It can also be used in a fuction 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) +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # 「整数の配列」の集合 +Set([1,2,3]...) # => Set{Int64}(1,2,3) # 整数の集合 x = (1,2,3) # => (1,2,3) -Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # a Set of Tuples +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # タプルの集合 Set(x...) # => Set{Int64}(2,3,1) +# 引数に初期値を与えることで、オプション引数をもった関数を定義できます。 # You can define functions with optional positional arguments function defaults(a,b,x=5,y=6) return "$a $b and $x $y" @@ -424,8 +541,9 @@ catch e println(e) end +# キーワード引数を持った関数も作れます。 # You can define functions that take keyword arguments -function keyword_args(;k1=4,name2="hello") # note the ; +function keyword_args(;k1=4,name2="hello") # ; が必要なことに注意 return ["k1"=>k1,"name2"=>name2] end @@ -433,6 +551,7 @@ keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] keyword_args() # => ["name2"=>"hello","k1"=>4] +# もちろん、これらを組み合わせることもできます。 # You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") println("normal arg: $normal_arg") @@ -446,6 +565,7 @@ all_the_args(1, 3, keyword_arg=4) # optional arg: 3 # keyword arg: 4 +# Julia では関数は第一級関数として、値として扱われます。 # Julia has first class functions function create_adder(x) adder = function (y) @@ -454,14 +574,17 @@ function create_adder(x) return adder end +# ラムダ式によって無名関数をつくれます。 # This is "stabby lambda syntax" for creating anonymous functions (x -> x > 2)(3) # => true +# 先ほどの create_adder と同じもの # This function is identical to create_adder implementation above. function create_adder(x) y -> x + y end +# 中の関数に名前をつけても構いません。 # You can also name the internal function, if you want function create_adder(x) function adder(y) @@ -474,31 +597,44 @@ add_10 = create_adder(10) add_10(3) # => 13 +# いくつかの高階関数が定義されています。 # There are built-in higher order functions map(add_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +# map の代わりとしてリスト内包表記も使えます。 # We can use list comprehensions for nicer maps [add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### ## 5. Types +## 5. 型 #################################################### +# Julia ではすべての値にひとつの型がついています。 +# 変数に、ではなくて値に、です。 +# typeof 関数を使うことで、値が持つ型を取得できます。 # Julia has a type system. # Every value has a type; variables do not have types themselves. # You can use the `typeof` function to get the type of a value. typeof(5) # => Int64 +# 型自身もまた、第一級の値であり、型を持っています。 # Types are first-class values typeof(Int64) # => DataType typeof(DataType) # => DataType +# DataType は型を表現する型であり、DataType 自身もDataType 型の値です。 # DataType is the type that represents types, including itself. +# 型はドキュメント化や最適化、関数ディスパッチのために使われます。 +# 静的な型チェックは行われません。 # Types are used for documentation, optimizations, and dispatch. # They are not statically checked. +# 自分で新しい型を定義することもできます。 +# 他の言語で言う、構造体やレコードに近いものになっています。 +# 型定義には type キーワードを使います。 # Users can define types # They are like records or structs in other languages. # New types are defined using the `type` keyword. @@ -509,23 +645,33 @@ typeof(DataType) # => DataType # end type Tiger taillength::Float64 + coatcolor # 型注釈を省略した場合、自動的に :: Any として扱われます。 coatcolor # not including a type annotation is the same as `::Any` end +# 型を定義すると、その型のプロパティすべてを、定義した順番に +# 引数として持つデフォルトコンストラクタが自動的に作られます。 # The default constructor's arguments are the properties # of the type, in the order they are listed in the definition tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") +# 型名がそのままコンストラクタ名(関数名)となります。 # The type doubles as the constructor function for values of that type sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") +# このような、構造体スタイルの型は、具体型(concrete type)と呼ばれます。 +# 具体型はインスタンス化可能ですが、派生型(subtype)を持つことができません。 +# 具体型の他には抽象型(abstract type)があります。 # These struct-style types are called concrete types # They can be instantiated, but cannot have subtypes. # The other kind of types is abstract types. # abstract Name +abstract Cat # 型の階層図の途中の一点を指し示す名前となります。 abstract Cat # just a name and point in the type hierarchy +# 抽象型はインスタンス化できませんが、派生型を持つことができます。 +# 例えば、 Number は以下の派生型を持つ抽象型です。 # Abstract types cannot be instantiated, but can have subtypes. # For example, Number is an abstract type subtypes(Number) # => 6-element Array{Any,1}: @@ -537,6 +683,8 @@ subtypes(Number) # => 6-element Array{Any,1}: # Real subtypes(Cat) # => 0-element Array{Any,1} +# すべての型は、直接的にはただひとつの基本型(supertype) を持ちます。 +# super 関数でこれを取得可能です。 # Every type has a super type; use the `super` function to get it. typeof(5) # => Int64 super(Int64) # => Signed @@ -545,41 +693,60 @@ super(Real) # => Number super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any +# Int64 を除き、これらはすべて抽象型です。 # All of these type, except for Int64, are abstract. +# <: は派生形を表す演算子です。 +# これを使うことで派生型を定義できます。 # <: is the subtyping operator -type Lion <: Cat # Lion is a subtype of Cat +type Lion <: Cat # Lion は 抽象型 Cat の派生型 mane_color roar::String end +# 型名と同じ名前の関数を定義し、既に存在するコンストラクタを呼び出して、 +# 必要とする型の値を返すことによって、 +# デフォルトコンストラクタ以外のコンストラクタを作ることができます。 + # You can define more constructors for your type # Just define a function of the same name as the type # and call an existing constructor to get a value of the correct type Lion(roar::String) = Lion("green",roar) +# 型定義の外側で定義されたコンストラクタなので、外部コンストラクタと呼ばれます。 # This is an outer constructor because it's outside the type definition -type Panther <: Cat # Panther is also a subtype of Cat +type Panther <: Cat # Panther も Cat の派生型 eye_color Panther() = new("green") + # Panther は内部コンストラクタとしてこれのみを持ち、 + # デフォルトコンストラクタを持たない # Panthers will only have this constructor, and no default constructor. end +# 内部コンストラクタを使うことで、どのような値が作られるのかをコントロールすることができます。 +# 出来る限り、外部コンストラクタを使うべきです。 # Using inner constructors, like Panther does, gives you control # over how values of the type can be created. # When possible, you should use outer constructors rather than inner ones. #################################################### ## 6. Multiple-Dispatch +## 6. 多重ディスパッチ #################################################### +# Julia では、すべての名前付きの関数は総称的関数(generic function) です。 +# これは、関数はいくつかの細かいメソッドの集合である、という意味です。 +# 例えば先の Lion 型のコンストラクタ Lion は、Lion という関数の1つのメソッドです。 # In Julia, all named functions are generic functions # This means that they are built up from many small methods # Each constructor for Lion is a method of the generic function Lion. +# コンストラクタ以外の例をみるために、新たに meow 関数を作りましょう。 # For a non-constructor example, let's make a function meow: +# Lion, Panther, Tiger 型それぞれに対する meow 関数のメソッド定義 # Definitions for Lion, Panther, Tiger function meow(animal::Lion) + animal.roar # 型のプロパティには . でアクセスできます。 animal.roar # access type properties using dot notation end @@ -591,16 +758,19 @@ function meow(animal::Tiger) "rawwwr" end +# meow 関数の実行 # Testing the meow function meow(tigger) # => "rawwr" meow(Lion("brown","ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" +# 型の階層関係を見てみましょう # Review the local type hierarchy issubtype(Tiger,Cat) # => false issubtype(Lion,Cat) # => true issubtype(Panther,Cat) # => true +# 抽象型 Cat の派生型を引数にとる関数 # Defining a function that takes Cats function pet_cat(cat::Cat) println("The cat says $(meow(cat))") @@ -613,10 +783,15 @@ catch e println(e) end +# オブジェクト指向言語では、一般的にシングルディスパッチが用いられます。 +# つまり、関数に複数あるメソッドのうちにどれが呼ばれるかは、 +# その第一引数によってのみ決定されます。 +# 一方でJulia では、すべての引数の型が、このメソッド決定に寄与します。 # In OO languages, single dispatch is common; # this means that the method is picked based on the type of the first argument. # In Julia, all of the argument types contribute to selecting the best method. +# 多変数関数を定義して、この辺りを見て行きましょう。 # Let's define a function with more arguments, so we can see the difference function fight(t::Tiger,c::Cat) println("The $(t.coatcolor) tiger wins!") @@ -626,6 +801,7 @@ end fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! +# 第二引数の Cat が実際は Lion だった時に、挙動が変わるようにします。 # Let's change the behavior when the Cat is specifically a Lion fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") # => fight (generic function with 2 methods) @@ -633,6 +809,7 @@ fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! +# 別に Tiger だけが戦う必要もないですね。 # We don't need a Tiger in order to fight fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") # => fight (generic function with 3 methods) @@ -643,6 +820,7 @@ try catch end +# 第一引数にも Cat を許しましょう。 # Also let the cat go first fight(c::Cat,l::Lion) = println("The cat beats the Lion") # => Warning: New definition @@ -654,14 +832,17 @@ fight(c::Cat,l::Lion) = println("The cat beats the Lion") # is defined first. #fight (generic function with 4 methods) +# 警告が出ましたが、これは次の対戦で何が起きるのかが不明瞭だからです。 # This warning is because it's unclear which fight will be called in: fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# Julia のバージョンによっては、結果が違うかもしれません。 # The result may be different in other versions of Julia fight(l::Lion,l2::Lion) = println("The lions come to a tie") fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie +# Julia が生成する LLVM 内部表現や、アセンブリを調べることもできます。 # Under the hood # You can take a look at the llvm and the assembly code generated. @@ -669,6 +850,7 @@ square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 +# square_area に整数を渡すと何が起きる? # What happens when we feed square_area an integer? code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions @@ -704,6 +886,10 @@ code_native(square_area, (Float64,)) # pop RBP # ret # + +# Julia では、浮動小数点数と整数との演算では +# 自動的に浮動小数点数用の命令が生成されることに注意してください。 +# 円の面積を計算してみましょう。 # Note that julia will use floating point instructions if any of the # arguements are floats. # Let's calculate the area of a circle @@ -740,8 +926,14 @@ code_native(circle_area, (Float64,)) # ``` +## より勉強するために ## Further Reading +[公式ドキュメント](http://docs.julialang.org/en/latest/manual/) (英語)にはより詳細な解説が記されています。 + You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) +Julia に関して助けが必要ならば、[メーリングリスト](https://groups.google.com/forum/#!forum/julia-users) が役に立ちます。 +みんな非常に親密に教えてくれます。 + The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From 6027c90c90a55702d003f17a72fd82ed7f870be0 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sat, 20 Dec 2014 23:03:25 +0100 Subject: Scala compiler fails to infer the return type when there's an explicit return statement --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5a478f2a..35645922 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -199,7 +199,7 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most // def that surrounds it. It has no effect on anonymous functions. For example: -def foo(x: Int) = { +def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) return z // This line makes z the return value of foo! -- cgit v1.2.3 From 6dca0e7ae41140765cb3b0c1513cfa897294efe5 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sun, 21 Dec 2014 13:08:21 +0100 Subject: Fixed Person class' constructor signature --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5a478f2a..544abd5b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -476,7 +476,7 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name:String, phoneNumber:String) +case class Person(name:String, age:Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) -- cgit v1.2.3 From c4e1109e3aeef641798a59daf56f82aa60dc81ff Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 22 Dec 2014 13:35:46 +1100 Subject: Remove spurious "[" --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index f08c4679..32febcfd 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -49,7 +49,7 @@ public class LearnJava { // Types & Variables /////////////////////////////////////// - // Declare a variable using [ + // Declare a variable using // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) byte fooByte = 100; -- cgit v1.2.3 From c9ae9ea396cae5c357511cecb3a308740409302a Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 22 Dec 2014 13:37:03 +1100 Subject: Spelling corrrection --- java.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index f08c4679..d77d1c23 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -268,9 +268,9 @@ public class LearnJava { System.out.println(bar); // Prints A, because the statement is true - /////////////////////////////////////// - // Converting Data Types And Typcasting - /////////////////////////////////////// + //////////////////////////////////////// + // Converting Data Types And Typecasting + //////////////////////////////////////// // Converting data -- cgit v1.2.3 From 7915169dde85bfd7afdfc2398440b6db7ec28682 Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Mon, 22 Dec 2014 14:45:11 +0900 Subject: finish translating X=Julia into Japanese --- ja-jp/julia-jp.html.markdown | 240 ++++++------------------------------------- 1 file changed, 31 insertions(+), 209 deletions(-) diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown index 0c596c99..0c1d7e49 100644 --- a/ja-jp/julia-jp.html.markdown +++ b/ja-jp/julia-jp.html.markdown @@ -8,88 +8,67 @@ filename: learnjulia-jp.jl --- Julia は科学技術計算向けに作られた、同図像性を持った(homoiconic) プログラミング言語です。 -マクロによる同図像性や第一級関数をもち、なおかつ低階層も扱えるにもかかわらず、 -Julia はPython 並に学習しやすく、使いやすい言語となっています。 +マクロによる同図像性や第一級関数などの抽象化機能の恩恵を受けつつ、低階層をも扱えますが、 +それでいてPython 並に学習しやすく、使いやすい言語となっています。 この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。 -Julia is a new homoiconic functional language focused on technical computing. -While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. - -This is based on the current development version of Julia, as of October 18th, 2013. - ```ruby # ハッシュ(シャープ)記号から改行までは単一行コメントとなります。 #= 複数行コメントは、 '#=' と '=#' とで囲むことで行えます。 + #= 入れ子構造にすることもできます。 -=# - -# Single line comments start with a hash (pound) symbol. -#= Multiline comments can be written - by putting '#=' before the text and '=#' - after the text. They can also be nested. + =# =# #################################################### -## 1. Primitive Datatypes and Operators ## 1. 基本的な型と演算子 #################################################### # Julia ではすべて式となります。 -# Everything in Julia is a expression. # 基本となる数値型がいくつかあります。 -# There are several basic types of numbers. 3 # => 3 (Int64) 3.2 # => 3.2 (Float64) 2 + 1im # => 2 + 1im (Complex{Int64}) 2//3 # => 2//3 (Rational{Int64}) # 一般的な中置演算子が使用可能です。 -# All of the normal infix operators are available. 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7.0 5 / 2 # => 2.5 # 整数型同士の割り算の結果は、浮動小数点数型になります -5 / 2 # => 2.5 # dividing an Int by an Int always results in a Float div(5, 2) # => 2 # 整数のまま割り算するには、 div を使います -div(5, 2) # => 2 # for a truncated result, use div 5 \ 35 # => 7.0 2 ^ 2 # => 4 # べき乗です。排他的論理和ではありません -2 ^ 2 # => 4 # power, not bitwise xor 12 % 10 # => 2 # 丸括弧で演算の優先順位をコントロールできます -# Enforce precedence with parentheses (1 + 3) * 2 # => 8 # ビット演算 -# Bitwise Operators ~2 # => -3 # ビット反転 3 & 5 # => 1 # ビット積 2 | 4 # => 6 # ビット和 -2 $ 4 # => 6 # 排他的論理和 +2 $ 4 # => 6 # ビット排他的論理和 2 >>> 1 # => 1 # 右論理シフト 2 >> 1 # => 1 # 右算術シフト 2 << 1 # => 4 # 左シフト # bits 関数を使うことで、数の二進表現を得られます。 -# You can use the bits function to see the binary representation of a number. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" # ブール値が用意されています -# Boolean values are primitives true false # ブール代数 -# Boolean operators !true # => false !false # => true 1 == 1 # => true @@ -101,151 +80,109 @@ false 2 <= 2 # => true 2 >= 2 # => true # 比較演算子をつなげることもできます -# Comparisons can be chained 1 < 2 < 3 # => true 2 < 3 < 2 # => false # 文字列は " で作れます -# Strings are created with " "This is a string." # 文字リテラルは ' で作れます -# Character literals are written with ' 'a' # 文字列は文字の配列のように添字アクセスできます -# A string can be indexed like an array of characters "This is a string"[1] # => 'T' # Julia では添字は 1 から始まります # ただし、UTF8 文字列の場合は添字アクセスではうまくいかないので、 -# その場合はイテレーションを行ってください(map 関数や for ループなど) -# However, this is will not work well for UTF8 strings, -# so iterating over strings is recommended (map, for loops, etc). +# イテレーションを行ってください(map 関数や for ループなど) # $ を使うことで、文字列に変数や、任意の式を埋め込めます。 -# $ can be used for string interpolation: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# You can put any Julia expression inside the parenthesis. # 他にも、printf マクロを使うことでも変数を埋め込めます。 -# Another way to format strings is the printf macro. @printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 # 出力も簡単です -# Printing is easy println("I'm Julia. Nice to meet you!") #################################################### -## 2. Variables and Collections -## 2. 変数と配列 +## 2. 変数と配列、タプル、集合、辞書 #################################################### # 変数の宣言は不要で、いきなり変数に値を代入・束縛できます。 -# You don't declare variables before assigning to them. some_var = 5 # => 5 some_var # => 5 -# 値の束縛されていない変数を使おうとするとエラーになります。 -# Accessing a previously unassigned variable is an error +# 値に束縛されていない変数を使おうとするとエラーになります。 try some_other_var # => ERROR: some_other_var not defined catch e println(e) end -# 変数名は文字から始めます。 -# その後は、文字だけでなく数字やアンダースコア(_), 感嘆符(!)が使えます。 -# Variable names start with a letter. -# After that, you can use letters, digits, underscores, and exclamation points. +# 変数名は数字や記号以外の文字から始めます。 +# その後は、数字やアンダースコア(_), 感嘆符(!)も使えます。 SomeOtherVar123! = 6 # => 6 # Unicode 文字も使えます。 -# You can also use unicode characters ☃ = 8 # => 8 # ギリシャ文字などを使うことで数学的な記法が簡単にかけます。 -# These are especially handy for mathematical notation 2 * π # => 6.283185307179586 # Julia における命名習慣について: -# A note on naming conventions in Julia: # # * 変数名における単語の区切りにはアンダースコアを使っても良いですが、 # 使わないと読みにくくなる、というわけではない限り、 # 推奨はされません。 # -# * Word separation can be indicated by underscores ('_'), but use of -# underscores is discouraged unless the name would be hard to read -# otherwise. -# -# * 型名は大文字で始め、単語の区切りはキャメルケースを使います。 -# -# * Names of Types begin with a capital letter and word separation is shown -# with CamelCase instead of underscores. +# * 型名は大文字で始め、単語の区切りにはキャメルケースを使います。 # # * 関数やマクロの名前は小文字で書きます。 -# 分かち書きにアンダースコアをつかわず、直接つなげます。 -# -# * Names of functions and macros are in lower case, without underscores. +# 単語の分かち書きにはアンダースコアをつかわず、直接つなげます。 # # * 内部で引数を変更する関数は、名前の最後に ! をつけます。 # この手の関数は、しばしば「破壊的な関数」とか「in-place な関数」とか呼ばれます。 -# -# * Functions that modify their inputs have names that end in !. These -# functions are sometimes called mutating functions or in-place functions. + # 配列は、1 から始まる整数によって添字付けられる、値の列です。 -# Arrays store a sequence of values indexed by integers 1 through n: 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[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] -# 配列の終端に値を追加するには push! を、 -# 他の配列を追加するには append! を使います。 -# Add stuff to the end of a list with push! and append! +# 配列の末尾に値を追加するには push! を、 +# 他の配列を結合するには append! を使います。 push!(a,1) # => [1] push!(a,2) # => [1,2] push!(a,4) # => [1,2,4] push!(a,3) # => [1,2,4,3] append!(a,b) # => [1,2,4,3,4,5,6] -# 配列の終端から値を削除するには pop! を使います。 -# Remove from the end with pop +# 配列の末尾から値を削除するには pop! を使います。 pop!(b) # => 6 and b is now [4,5] -# もう一度戻しましょう。 -# Let's put it back +# 一旦元に戻しておきましょう。 push!(b,6) # b is now [4,5,6] again. a[1] # => 1 # Julia では添字は0 ではなく1 から始まること、お忘れなく! -a[1] # => 1 # remember that Julia indexes from 1, not 0! # end は最後の添字を表す速記法です。 # 添字を書く場所ならどこにでも使えます。 -# end is a shorthand for the last index. It can be used in any -# indexing expression a[end] # => 6 -# 先頭に対する追加・削除は shift!, unshift! です。 -# we also have shift and unshift +# 先頭に対する削除・追加は shift!, unshift! です。 shift!(a) # => 1 and a is now [2,4,3,4,5,6] unshift!(a,7) # => [7,2,4,3,4,5,6] # ! で終わる関数名は、その引数を変更するということを示します。 -# Function names that end in exclamations points indicate that they modify -# their argument. arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] sort(arr) # => [4,5,6]; arr is still [5,4,6] sort!(arr) # => [4,5,6]; arr is now [4,5,6] # 配列の範囲外アクセスをすると BoundsError が発生します。 -# Looking out of bounds is a BoundsError try a[0] # => ERROR: BoundsError() in getindex at array.jl:270 a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 @@ -254,40 +191,33 @@ catch e end # エラーが発生すると、どのファイルのどの行で発生したかが表示されます。 -# Errors list the line and file they came from, even if it's in the standard -# library. If you built Julia from source, you can look in the folder base -# inside the julia folder to find these files. +# 標準ライブラリで発生したものでもファイル名と行数が出ます。 +# ソースからビルドした場合など、標準ライブラリのソースが手元にある場合は +# base/ ディレクトリから探し出して見てください。 # 配列は範囲オブジェクトから作ることもできます。 -# You can initialize arrays from ranges a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] # 添字として範囲オブジェクトを渡すことで、 # 配列の部分列を得ることもできます。 -# You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] a[2:end] # => [2, 3, 4, 5] # 添字を用いて配列から値の削除をしたい場合は、splice! を使います。 -# Remove elements from an array by index with splice! arr = [3,4,5] splice!(arr,2) # => 4 ; arr is now [3,5] # 配列の結合は append! です。 -# Concatenate lists with append! b = [1,2,3] append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] # 配列内に指定した値があるかどうかを調べるのには in を使います。 -# Check for existence in a list with in in(1, a) # => true # length で配列の長さを取得できます。 -# Examine the length with length length(a) # => 8 # 変更不可能 (immutable) な値の組として、タプルが使えます。 -# Tuples are immutable. tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. tup[1] # => 1 try: @@ -297,65 +227,51 @@ catch e end # 配列に関する関数の多くが、タプルでも使えます。 -# Many list functions also work on tuples length(tup) # => 3 tup[1:2] # => (1,2) in(2, tup) # => true # タプルから値をばらして(unpack して) 複数の変数に代入できます。 -# You can unpack tuples into variables a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 # 丸括弧なしでもタプルになります。 -# Tuples are created even if you leave out the parentheses d, e, f = 4, 5, 6 # => (4,5,6) # ひとつの値だけからなるタプルは、その値自体とは区別されます。 -# A 1-element tuple is distinct from the value it contains (1,) == 1 # => false (1) == 1 # => true # 値の交換もタプルを使えば簡単です。 -# Look how easy it is to swap two values e, d = d, e # => (5,4) # d is now 5 and e is now 4 # 辞書 (Dict) は、値から値への変換の集合です。 -# Dictionaries store mappings empty_dict = Dict() # => Dict{Any,Any}() # 辞書型リテラルは次のとおりです。 -# You can create a dictionary using a literal filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] # => Dict{ASCIIString,Int64} # [] を使ったアクセスができます。 -# Look up values with [] filled_dict["one"] # => 1 # すべての鍵(添字)は keys で得られます。 -# Get all keys keys(filled_dict) # => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # 必ずしも辞書に追加した順番には並んでいないことに注意してください。 -# Note - dictionary keys are not sorted or in the order you inserted them. # 同様に、values はすべての値を返します。 -# Get all values values(filled_dict) # => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) # 鍵と同様に、必ずしも辞書に追加した順番には並んでいないことに注意してください。 -# Note - Same as above regarding key ordering. # in や haskey を使うことで、要素や鍵が辞書の中にあるかを調べられます。 -# Check for existence of keys in a dictionary with in, haskey in(("one", 1), filled_dict) # => true in(("two", 3), filled_dict) # => false haskey(filled_dict, "one") # => true haskey(filled_dict, 1) # => false # 存在しない鍵を問い合わせると、エラーが発生します。 -# Trying to look up a non-existant key will raise an error try filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 catch e @@ -364,29 +280,22 @@ end # get 関数を使い、鍵がなかった場合のデフォルト値を与えておくことで、 # このエラーを回避できます。 -# Use the get method to avoid that error by providing a default value -# get(dictionary,key,default_value) get(filled_dict,"one",4) # => 1 get(filled_dict,"four",4) # => 4 # 集合 (Set) は一意な値の、順序付けられていない集まりです。 -# Use Sets to represent collections of unordered, unique values empty_set = Set() # => Set{Any}() # 集合の初期化 -# Initialize a set with values filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) # 集合への追加 -# Add more values to a set push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) # in で、値が既に存在するかを調べられます。 -# Check if the values are in the set in(2, filled_set) # => true in(10, filled_set) # => false # 積集合や和集合、差集合を得る関数も用意されています。 -# There are functions for set intersection, union, and difference. 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) @@ -394,16 +303,13 @@ setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) #################################################### -## 3. Control Flow ## 3. 制御構文 #################################################### # まずは変数を作ります。 -# Let's make a variable some_var = 5 # if 構文です。Julia ではインデントに意味はありません。 -# Here is an if statement. Indentation is not meaningful in Julia. if some_var > 10 println("some_var is totally bigger than 10.") elseif some_var < 10 # elseif 節は省略可能です。 @@ -416,8 +322,6 @@ end # for ループによって、反復可能なオブジェクトを走査できます。 # 反復可能なオブジェクトの型として、 # Range, Array, Set, Dict, String などがあります。 -# For loops iterate over iterables. -# Iterable types include Range, Array, Set, Dict, and String. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") # $ を使うことで文字列に変数の値を埋め込めます。 @@ -429,7 +333,6 @@ end # mouse is a mammal # for = の代わりに for in を使うこともできます -# You can use 'in' instead of '='. for animal in ["dog", "cat", "mouse"] println("$animal is a mammal") end @@ -438,6 +341,7 @@ end # cat is a mammal # mouse is a mammal +# 辞書ではタプルが返ってきます。 for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] println("$(a[1]) is a $(a[2])") end @@ -446,6 +350,7 @@ end # cat is a mammal # mouse is a mammal +# タプルのアンパック代入もできます。 for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] println("$k is a $v") end @@ -455,7 +360,6 @@ end # mouse is a mammal # while ループは、条件式がtrue となる限り実行され続けます。 -# While loops loop while a condition is true x = 0 while x < 4 println(x) @@ -468,7 +372,6 @@ end # 3 # 例外は try/catch で捕捉できます。 -# Handle exceptions with a try/catch block try error("help") catch e @@ -478,12 +381,10 @@ end #################################################### -## 4. Functions ## 4. 関数 #################################################### # function キーワードを次のように使うことで、新しい関数を定義できます。 -# The keyword 'function' creates new functions #function name(arglist) # body... #end @@ -491,19 +392,15 @@ function add(x, y) println("x is $x and y is $y") # 最後に評価された式の値が、関数全体の返り値となります。 - # Functions return the value of their last statement x + y end add(5, 6) # => 11 after printing out "x is 5 and y is 6" # 可変長引数関数も定義できます。 -# You can define functions that take a variable number of -# positional arguments function varargs(args...) return args # return キーワードを使うことで、好きな位置で関数から抜けられます。 - # use the keyword return to return anywhere in the function end # => varargs (generic function with 1 method) @@ -513,10 +410,6 @@ 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, -# 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]) # 「整数の配列」の集合 Set([1,2,3]...) # => Set{Int64}(1,2,3) # 整数の集合 @@ -526,7 +419,6 @@ Set(x...) # => Set{Int64}(2,3,1) # 引数に初期値を与えることで、オプション引数をもった関数を定義できます。 -# You can define functions with optional positional arguments function defaults(a,b,x=5,y=6) return "$a $b and $x $y" end @@ -542,7 +434,6 @@ catch e end # キーワード引数を持った関数も作れます。 -# You can define functions that take keyword arguments function keyword_args(;k1=4,name2="hello") # ; が必要なことに注意 return ["k1"=>k1,"name2"=>name2] end @@ -552,7 +443,6 @@ keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] keyword_args() # => ["name2"=>"hello","k1"=>4] # もちろん、これらを組み合わせることもできます。 -# You can combine all kinds of arguments in the same function function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") println("normal arg: $normal_arg") println("optional arg: $optional_positional_arg") @@ -566,7 +456,6 @@ all_the_args(1, 3, keyword_arg=4) # keyword arg: 4 # Julia では関数は第一級関数として、値として扱われます。 -# Julia has first class functions function create_adder(x) adder = function (y) return x + y @@ -575,17 +464,14 @@ function create_adder(x) end # ラムダ式によって無名関数をつくれます。 -# This is "stabby lambda syntax" for creating anonymous functions (x -> x > 2)(3) # => true # 先ほどの create_adder と同じもの -# This function is identical to create_adder implementation above. function create_adder(x) y -> x + y end # 中の関数に名前をつけても構いません。 -# You can also name the internal function, if you want function create_adder(x) function adder(y) x + y @@ -598,47 +484,33 @@ add_10(3) # => 13 # いくつかの高階関数が定義されています。 -# There are built-in higher order functions map(add_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # map の代わりとしてリスト内包表記も使えます。 -# We can use list comprehensions for nicer maps [add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] #################################################### -## 5. Types ## 5. 型 #################################################### # Julia ではすべての値にひとつの型がついています。 # 変数に、ではなくて値に、です。 # typeof 関数を使うことで、値が持つ型を取得できます。 -# Julia has a type system. -# Every value has a type; variables do not have types themselves. -# You can use the `typeof` function to get the type of a value. typeof(5) # => Int64 # 型自身もまた、第一級の値であり、型を持っています。 -# Types are first-class values typeof(Int64) # => DataType typeof(DataType) # => DataType # DataType は型を表現する型であり、DataType 自身もDataType 型の値です。 -# DataType is the type that represents types, including itself. # 型はドキュメント化や最適化、関数ディスパッチのために使われます。 # 静的な型チェックは行われません。 -# Types are used for documentation, optimizations, and dispatch. -# They are not statically checked. # 自分で新しい型を定義することもできます。 # 他の言語で言う、構造体やレコードに近いものになっています。 # 型定義には type キーワードを使います。 -# Users can define types -# They are like records or structs in other languages. -# New types are defined using the `type` keyword. - # type Name # field::OptionalType # ... @@ -646,34 +518,24 @@ typeof(DataType) # => DataType type Tiger taillength::Float64 coatcolor # 型注釈を省略した場合、自動的に :: Any として扱われます。 - coatcolor # not including a type annotation is the same as `::Any` end # 型を定義すると、その型のプロパティすべてを、定義した順番に # 引数として持つデフォルトコンストラクタが自動的に作られます。 -# The default constructor's arguments are the properties -# of the type, in the order they are listed in the definition tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") # 型名がそのままコンストラクタ名(関数名)となります。 -# The type doubles as the constructor function for values of that type sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") # このような、構造体スタイルの型は、具体型(concrete type)と呼ばれます。 # 具体型はインスタンス化可能ですが、派生型(subtype)を持つことができません。 # 具体型の他には抽象型(abstract type)があります。 -# These struct-style types are called concrete types -# They can be instantiated, but cannot have subtypes. -# The other kind of types is abstract types. # abstract Name abstract Cat # 型の階層図の途中の一点を指し示す名前となります。 -abstract Cat # just a name and point in the type hierarchy # 抽象型はインスタンス化できませんが、派生型を持つことができます。 # 例えば、 Number は以下の派生型を持つ抽象型です。 -# Abstract types cannot be instantiated, but can have subtypes. -# For example, Number is an abstract type subtypes(Number) # => 6-element Array{Any,1}: # Complex{Float16} # Complex{Float32} @@ -685,7 +547,6 @@ subtypes(Cat) # => 0-element Array{Any,1} # すべての型は、直接的にはただひとつの基本型(supertype) を持ちます。 # super 関数でこれを取得可能です。 -# Every type has a super type; use the `super` function to get it. typeof(5) # => Int64 super(Int64) # => Signed super(Signed) # => Real @@ -694,11 +555,9 @@ super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any # Int64 を除き、これらはすべて抽象型です。 -# All of these type, except for Int64, are abstract. # <: は派生形を表す演算子です。 # これを使うことで派生型を定義できます。 -# <: is the subtyping operator type Lion <: Cat # Lion は 抽象型 Cat の派生型 mane_color roar::String @@ -708,46 +567,31 @@ end # 必要とする型の値を返すことによって、 # デフォルトコンストラクタ以外のコンストラクタを作ることができます。 -# You can define more constructors for your type -# Just define a function of the same name as the type -# and call an existing constructor to get a value of the correct type Lion(roar::String) = Lion("green",roar) # 型定義の外側で定義されたコンストラクタなので、外部コンストラクタと呼ばれます。 -# This is an outer constructor because it's outside the type definition type Panther <: Cat # Panther も Cat の派生型 eye_color Panther() = new("green") # Panther は内部コンストラクタとしてこれのみを持ち、 # デフォルトコンストラクタを持たない - # Panthers will only have this constructor, and no default constructor. end # 内部コンストラクタを使うことで、どのような値が作られるのかをコントロールすることができます。 # 出来る限り、外部コンストラクタを使うべきです。 -# Using inner constructors, like Panther does, gives you control -# over how values of the type can be created. -# When possible, you should use outer constructors rather than inner ones. #################################################### -## 6. Multiple-Dispatch ## 6. 多重ディスパッチ #################################################### # Julia では、すべての名前付きの関数は総称的関数(generic function) です。 # これは、関数はいくつかの細かいメソッドの集合である、という意味です。 # 例えば先の Lion 型のコンストラクタ Lion は、Lion という関数の1つのメソッドです。 -# In Julia, all named functions are generic functions -# This means that they are built up from many small methods -# Each constructor for Lion is a method of the generic function Lion. # コンストラクタ以外の例をみるために、新たに meow 関数を作りましょう。 -# For a non-constructor example, let's make a function meow: # Lion, Panther, Tiger 型それぞれに対する meow 関数のメソッド定義 -# Definitions for Lion, Panther, Tiger function meow(animal::Lion) animal.roar # 型のプロパティには . でアクセスできます。 - animal.roar # access type properties using dot notation end function meow(animal::Panther) @@ -759,19 +603,16 @@ function meow(animal::Tiger) end # meow 関数の実行 -# Testing the meow function meow(tigger) # => "rawwr" meow(Lion("brown","ROAAR")) # => "ROAAR" meow(Panther()) # => "grrr" # 型の階層関係を見てみましょう -# Review the local type hierarchy issubtype(Tiger,Cat) # => false issubtype(Lion,Cat) # => true issubtype(Panther,Cat) # => true # 抽象型 Cat の派生型を引数にとる関数 -# Defining a function that takes Cats function pet_cat(cat::Cat) println("The cat says $(meow(cat))") end @@ -785,14 +626,10 @@ end # オブジェクト指向言語では、一般的にシングルディスパッチが用いられます。 # つまり、関数に複数あるメソッドのうちにどれが呼ばれるかは、 -# その第一引数によってのみ決定されます。 +# その第一引数(もしくは、 . や -> の前にある値の型)によってのみ決定されます。 # 一方でJulia では、すべての引数の型が、このメソッド決定に寄与します。 -# In OO languages, single dispatch is common; -# this means that the method is picked based on the type of the first argument. -# In Julia, all of the argument types contribute to selecting the best method. # 多変数関数を定義して、この辺りを見て行きましょう。 -# Let's define a function with more arguments, so we can see the difference function fight(t::Tiger,c::Cat) println("The $(t.coatcolor) tiger wins!") end @@ -802,7 +639,6 @@ fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! # 第二引数の Cat が実際は Lion だった時に、挙動が変わるようにします。 -# Let's change the behavior when the Cat is specifically a Lion fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") # => fight (generic function with 2 methods) @@ -810,7 +646,6 @@ fight(tigger,Panther()) # => prints The orange tiger wins! fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! # 別に Tiger だけが戦う必要もないですね。 -# We don't need a Tiger in order to fight fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") # => fight (generic function with 3 methods) @@ -821,7 +656,6 @@ catch end # 第一引数にも Cat を許しましょう。 -# Also let the cat go first fight(c::Cat,l::Lion) = println("The cat beats the Lion") # => Warning: New definition # fight(Cat,Lion) at none:1 @@ -833,25 +667,20 @@ fight(c::Cat,l::Lion) = println("The cat beats the Lion") #fight (generic function with 4 methods) # 警告が出ましたが、これは次の対戦で何が起きるのかが不明瞭だからです。 -# This warning is because it's unclear which fight will be called in: fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr # Julia のバージョンによっては、結果が違うかもしれません。 -# The result may be different in other versions of Julia fight(l::Lion,l2::Lion) = println("The lions come to a tie") fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie # Julia が生成する LLVM 内部表現や、アセンブリを調べることもできます。 -# Under the hood -# You can take a look at the llvm and the assembly code generated. square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 # square_area に整数を渡すと何が起きる? -# What happens when we feed square_area an integer? code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none @@ -859,10 +688,10 @@ code_native(square_area, (Int32,)) # push RBP # mov RBP, RSP # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX + # movsxd RAX, EDI # l を取得 + # imul RAX, RAX # l*l を計算して RAX に入れる + # pop RBP # Base Pointer を元に戻す + # ret # 終了。RAX の中身が結果 code_native(square_area, (Float32,)) # .section __TEXT,__text,regular,pure_instructions @@ -871,7 +700,7 @@ code_native(square_area, (Float32,)) # push RBP # mov RBP, RSP # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) + # vmulss XMM0, XMM0, XMM0 # 単精度浮動小数点数演算 (AVX) # pop RBP # ret @@ -882,7 +711,7 @@ code_native(square_area, (Float64,)) # push RBP # mov RBP, RSP # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) + # vmulsd XMM0, XMM0, XMM0 # 倍精度浮動小数点数演算 (AVX) # pop RBP # ret # @@ -890,9 +719,6 @@ code_native(square_area, (Float64,)) # Julia では、浮動小数点数と整数との演算では # 自動的に浮動小数点数用の命令が生成されることに注意してください。 # 円の面積を計算してみましょう。 -# Note that julia will use floating point instructions if any of the -# arguements are floats. -# Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 @@ -927,13 +753,9 @@ code_native(circle_area, (Float64,)) ``` ## より勉強するために -## Further Reading [公式ドキュメント](http://docs.julialang.org/en/latest/manual/) (英語)にはより詳細な解説が記されています。 -You can get a lot more detail from [The Julia Manual](http://docs.julialang.org/en/latest/manual/) - Julia に関して助けが必要ならば、[メーリングリスト](https://groups.google.com/forum/#!forum/julia-users) が役に立ちます。 みんな非常に親密に教えてくれます。 -The best place to get help with Julia is the (very friendly) [mailing list](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From a3ce8e9d6c0810e83852f6e197cf3a55006f5c7e Mon Sep 17 00:00:00 2001 From: Nikolay Kirsh Date: Mon, 22 Dec 2014 13:01:43 +0500 Subject: Russuan spelling corrrection --- ru-ru/go-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 44a22b45..e06ae9bd 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -65,7 +65,7 @@ func beyondHello() { learnTypes() // < y minutes, learn more! } -// Функция имеющая входные параметры и возврат нескольких значений. +// Функция, имеющая входные параметры и возвращающая несколько значений. func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Возврат двух значений. } -- cgit v1.2.3 From 54b8be676862ec85920c952db4f4e791f4d721b0 Mon Sep 17 00:00:00 2001 From: euporie Date: Mon, 22 Dec 2014 13:26:30 +0100 Subject: Fixed typo at the end --- pogo.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pogo.html.markdown b/pogo.html.markdown index 60a83edd..aa5d49f3 100644 --- a/pogo.html.markdown +++ b/pogo.html.markdown @@ -199,4 +199,4 @@ 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/), inlcuding 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! +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 674284cfcb0fa3194ad854d711288ec9aa5b98e9 Mon Sep 17 00:00:00 2001 From: maniexx Date: Mon, 22 Dec 2014 15:24:09 +0100 Subject: Delete PYMOTW3 due to lack of content --- python3.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index f6babaff..8bcc85d1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -609,7 +609,6 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Dead Tree -- cgit v1.2.3 From ed819ed91774d37ada2e77af941289aeefbf6a86 Mon Sep 17 00:00:00 2001 From: switchhax Date: Tue, 23 Dec 2014 16:27:30 +0100 Subject: [YAML/en] translated to [YAML/de] --- de-de/bash-de.html.markdown | 2 +- de-de/yaml-de.html.markdown | 138 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 de-de/yaml-de.html.markdown diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index ad782e06..fb9cd9d4 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -17,7 +17,7 @@ Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder ```bash #!/bin/bash -# Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie +# Die erste Zeile des Scripts nennt sich Shebang, dies gibt dem System an, # wie das Script ausgeführt werden soll: http://de.wikipedia.org/wiki/Shebang # Du hast es bestimmt schon mitgekriegt, Kommentare fangen mit # an. Das Shebang ist auch ein Kommentar diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown new file mode 100644 index 00000000..88318014 --- /dev/null +++ b/de-de/yaml-de.html.markdown @@ -0,0 +1,138 @@ +--- +language: yaml +filename: learnyaml.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Ruben M.", https://github.com/switchhax] +--- + +YAML ist eine Sprache zur Datenserialisierung, die sofort von Menschenhand geschrieben und gelesen werden kann. + +YAML ist eine Erweiterung von JSON, mit der Erweiterung von syntaktisch wichtigen Zeilenumbrüche und Einrückung sowie in Python. Anders als in Python erlaubt YAML keine Tabulator-Zeichen. + +```yaml +# Kommentare in YAML schauen so aus. + +################# +# SKALARE TYPEN # +################# + +# Unser Kernobjekt (für das ganze Dokument) wird das Assoziative Datenfeld (Map) sein, +# welches equivalent zu einem Hash oder einem Objekt einer anderen Sprache ist. +Schlüssel: Wert +nochn_Schlüssel: Hier kommt noch ein Wert hin. +eine_Zahl: 100 +wissenschaftliche_Notation: 1e+12 +boolean: true +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." + +# Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text) +# oder ein 'folded block' (> gefolgt vom text). +literal_block: | + Dieser ganze Block an Text ist der Wert vom Schlüssel literal_block, + mit Erhaltung der Zeilenumbrüche. + + Das Literal fährt solange fort bis dieses unverbeult ist und die vorherschende Einrückung wird + gekürzt. + + Zeilen, die weiter eingerückt sind, behalten den Rest ihrer Einrückung - + diese Zeilen sind mit 4 Leerzeichen eingerückt. +folded_style: > + Dieser ganze Block an Text ist der Wert vom Schlüssel folded_style, aber diesmal + werden alle Zeilenumbrüche durch ein Leerzeichen ersetzt. + + Freie Zeilen, wie obendrüber, werden in einen Zeilenumbruch verwandelt. + + Weiter eingerückte Zeilen behalten ihre Zeilenumbrüche - + diese Textpassage wird auf zwei Zeilen sichtbar sein. + +#################### +# COLLECTION TYPEN # +#################### + +# Verschachtelung wird duch Einrückung erzielt. +eine_verschachtelte_map: + schlüssel: wert + nochn_Schlüssel: Noch ein Wert. + noch_eine_verschachtelte_map: + hallo: hallo + +# Schlüssel müssen nicht immer String sein. +0.25: ein Float-Wert als Schluessel + +# Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels +? | + Dies ist ein Schlüssel, + der mehrzeilig ist. +: und dies ist sein Wert + +# YAML erlaubt auch Collections als Schlüssel, doch viele Programmiersprachen +# werden sich beklagen. + +# Folgen (equivalent zu Listen oder Arrays) schauen so aus: +eine_Folge: + - Artikel 1 + - Artikel 2 + - 0.5 # Folgen können verschiedene Typen enthalten. + - Artikel 4 + - schlüssel: wert + nochn_schlüssel: nochn_wert + - + - Dies ist eine Folge + - innerhalb einer Folge + +# Weil YAML eine Erweiterung von JSON ist, können JSON-ähnliche Maps und Folgen +# geschrieben werden: +json_map: {"schlüssel": "wert"} +json_seq: [3, 2, 1, "Start"] + +############################ +# EXTRA YAML EIGENSCHAFTEN # +############################ + +# YAML stellt zusätzlich Verankerung zu Verfügung, welche es einfach machen +# Inhalte im Dokument zu vervielfältigen. Beide Schlüssel werden den selben Wert haben. +verankerter_inhalt: &anker_name Dieser String wird als Wert beider Schlüssel erscheinen. +anderer_anker: *anker_name + +# YAML hat auch Tags, mit denen man explizit Typangaben angibt. +explicit_string: !!str 0.5 +# Manche Parser implementieren sprachspezifische Tags wie dieser hier für Pythons +# komplexe Zahlen. +python_komplexe_Zahlen: !!python/komplex 1+2j + +#################### +# EXTRA YAML TYPEN # +#################### + +# Strings and Zahlen sind nicht die einzigen Skalare, welche YAML versteht. +# ISO-formatierte Datumsangaben and Zeiangaben können ebenso geparsed werden. +DatumZeit: 2001-12-15T02:59:43.1Z +DatumZeit_mit_Leerzeichen: 2001-12-14 21:59:43.10 -5 +Datum: 2002-12-14 + +# Der !!binary Tag zeigt das ein String base64 verschlüsselt ist. +# Representation des Binären Haufens +gif_datei: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML bietet auch Mengen (Sets), welche so ausschauen +menge: + ? artikel1 + ? artikel2 + ? artikel3 + +# Wie in Python sind Mengen nicht anderes als Maps nur mit null als Wert; das Beispiel oben drüber ist equivalent zu: +menge: + artikel1: null + artikel2: null + artikel3: null +``` -- cgit v1.2.3 From 28fcbc8e1c7d22bbc192418b4f3513f2ca4ead3e Mon Sep 17 00:00:00 2001 From: Louie Dinh Date: Tue, 23 Dec 2014 11:23:22 -0800 Subject: Fix typo --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 53381f32..da04d381 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -264,7 +264,7 @@ 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 => 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 -- cgit v1.2.3 From 4ab8d7427d60f48a5b076c0e589477a147659d31 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 24 Dec 2014 10:38:16 +0100 Subject: Update livescript.html.markdown Fix syntax errors on numbery var names --- livescript.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/livescript.html.markdown b/livescript.html.markdown index 429b91cb..e64f7719 100644 --- a/livescript.html.markdown +++ b/livescript.html.markdown @@ -219,8 +219,8 @@ identity 1 # => 1 # Operators are not functions in LiveScript, but you can easily turn # them into one! Enter the operator sectioning: -divide-by-2 = (/ 2) -[2, 4, 8, 16].map(divide-by-2) .reduce (+) +divide-by-two = (/ 2) +[2, 4, 8, 16].map(divide-by-two) .reduce (+) # Not only of function application lives LiveScript, as in any good @@ -248,8 +248,8 @@ reduce = (f, xs, initial) --> xs.reduce f, initial # The underscore is also used in regular partial application, which you # can use for any function: div = (left, right) -> left / right -div-by-2 = div _, 2 -div-by-2 4 # => 2 +div-by-two = div _, 2 +div-by-two 4 # => 2 # Last, but not least, LiveScript has back-calls, which might help -- cgit v1.2.3 From f323083ba49a2e1fa0b5a11b4ce2bf74a21cac86 Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 24 Dec 2014 18:22:48 +0100 Subject: rework of the tutorial --- perl6.html.markdown | 356 ++++++++++++++++++++++++++-------------------------- 1 file changed, 180 insertions(+), 176 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b178de1e..1536b152 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -35,7 +35,8 @@ my $variable; ## * Scalars. They represent a single value. They start with a `$` my $str = 'String'; -my $str2 = "String"; # double quotes allow for interpolation +# double quotes allow for interpolation (which we'll see later): +my $str2 = "String"; # variable names can contain but not end with simple quotes and dashes, # and can contain (and end with) underscores : @@ -66,23 +67,13 @@ my @keys = 0, 2; @array[@keys] = @letters; # Assign using an array say @array; #=> a 6 b -# There are two more kinds of lists: Parcel and Arrays. -# Parcels are immutable lists (you can't modify a list that's not assigned). -# This is a parcel: -(1, 2, 3); # Not assigned to anything. Changing an element would provoke an error -# This is a list: -my @a = (1, 2, 3); # Assigned to `@a`. Changing elements is okay! - -# Lists flatten (in list context). You'll see below how to apply item context -# or use arrays to have real nested lists. - - -## * Hashes. Key-Value Pairs. -# Hashes are actually arrays of Pairs (`Key => Value`), -# except they get "flattened", removing duplicated keys. +## * Hashes, or key-value Pairs. +# Hashes are actually arrays of Pairs +# (you can construct a Pair object using the syntax `Key => Value`), +# except they get "flattened" (hash context), removing duplicated keys. my %hash = 1 => 2, 3 => 4; -my %hash = autoquoted => "key", # keys *can* get auto-quoted +my %hash = autoquoted => "key", # keys get auto-quoted "some other" => "value", # trailing commas are okay ; my %hash = ; # you can also create a hash @@ -112,30 +103,6 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument say "Hello, $name !"; } -# Since you can omit parenthesis to call a function with no arguments, -# you need "&" in the name to capture `say-hello`. -my &s = &say-hello; -my &other-s = sub { say "Anonymous function !" } - -# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" -sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". - # Note: you can have parameters *before* (like here) - # a slurpy one, but not *after*. - say @rest.join(' / ') ~ " !"; -} -say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! - # Note that the splat did not consume - # the parameter before. - -## You can call a function with an array using the -# "argument list flattening" operator `|` -# (it's not actually the only role of this operator, but it's one of them) -sub concat3($a, $b, $c) { - say "$a, $b, $c"; -} -concat3(|@array); #=> a, b, c - # `@array` got "flattened" as a part of the argument list - ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional say "I might return `(Any)` if I don't have an argument passed, @@ -154,23 +121,20 @@ hello-to; #=> Hello, World ! hello-to(); #=> Hello, World ! hello-to('You'); #=> Hello, You ! -## You can also, by using a syntax akin to the one of hashes (yay unification !), +## You can also, by using a syntax akin to the one of hashes (yay unified syntax !), ## pass *named* arguments to a `sub`. +# They're optional, and will default to "Any" (Perl's "null"-like value). sub with-named($normal-arg, :$named) { say $normal-arg + $named; } with-named(1, named => 6); #=> 7 # There's one gotcha to be aware of, here: # If you quote your key, Perl 6 won't be able to see it at compile time, -# and you'll have a single Pair object as a positional paramater. +# and you'll have a single Pair object as a positional paramater, +# which means this fails: +with-named(1, 'named' => 6); with-named(2, :named(5)); #=> 7 -with-named(3, :4named); #=> 7 - # (special colon pair syntax for numbers, - # to be used with s// and such, see later) - -with-named(3); # warns, because we tried to use the undefined $named in a `+`: - # by default, named arguments are *optional* # To make a named argument mandatory, you can use `?`'s inverse, `!` sub with-mandatory-named(:$str!) { @@ -187,11 +151,6 @@ sub takes-a-bool($name, :$bool) { # ... you can use the same "short boolean" hash syntax: takes-a-bool('config', :bool); # config takes True takes-a-bool('config', :!bool); # config takes False -# or you can use the "adverb" form: -takes-a-bool('config'):bool; #=> config takes True -takes-a-bool('config'):!bool; #=> config takes False -# You'll learn to love (or maybe hate, eh) that syntax later. - ## You can also provide your named arguments with defaults: sub named-def(:$def = 5) { @@ -201,8 +160,29 @@ named-def; #=> 5 named-def(:10def); #=> 10 named-def(def => 15); #=> 15 -# -- Note: we're going to learn *more* on subs really soon, -# but we need to grasp a few more things to understand their real power. Ready? +# Since you can omit parenthesis to call a function with no arguments, +# you need "&" in the name to capture `say-hello`. +my &s = &say-hello; +my &other-s = sub { say "Anonymous function !" } + +# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" +sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". + # Note: you can have parameters *before* (like here) + # a slurpy one, but not *after*. + say @rest.join(' / ') ~ " !"; +} +say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! + # Note that the splat did not consume + # the parameter before. + +## You can call a function with an array using the +# "argument list flattening" operator `|` +# (it's not actually the only role of this operator, but it's one of them) +sub concat3($a, $b, $c) { + say "$a, $b, $c"; +} +concat3(|@array); #=> a, b, c + # `@array` got "flattened" as a part of the argument list ### Containers # In Perl 6, values are actually stored in "containers". @@ -220,17 +200,13 @@ sub mutate($n is rw) { # A sub itself returns a container, which means it can be marked as rw: my $x = 42; -sub mod() is rw { $x } -mod() = 52; # in this case, the parentheses are mandatory - # (else Perl 6 thinks `mod` is a "term") +sub x-store() is rw { $x } +x-store() = 52; # in this case, the parentheses are mandatory + # (else Perl 6 thinks `mod` is an identifier) say $x; #=> 52 ### Control Flow Structures - -# You don't need to put parenthesis around the condition, -# but that also means you always have to use brackets (`{ }`) for their body: - ## Conditionals # - `if` @@ -247,30 +223,38 @@ unless False { say "It's not false !"; } +# As you can see, you don't need parentheses around conditions. +# However, you do need the brackets around the "body" block: +# if (true) say; # This doesn't work ! + # You can also use their postfix versions, with the keyword after: say "Quite truthy" if True; -# if (true) say; # This doesn't work ! - # - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages) my $a = $condition ?? $value-if-true !! $value-if-false; # - `given`-`when` looks like other languages `switch`, but much more # powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_. +# # This variable contains the default argument of a block, # a loop's current iteration (unless explicitly named), etc. +# # `given` simply puts its argument into `$_` (like a block would do), # and `when` compares it using the "smart matching" (`~~`) operator. +# # Since other Perl 6 constructs use this variable (as said before, like `for`, # blocks, etc), this means the powerful `when` is not only applicable along with # a `given`, but instead anywhere a `$_` exists. given "foo bar" { - when /foo/ { # Don't worry about smart matching -- just know `when` uses it. + say $_; #=> foo bar + when /foo/ { # Don't worry about smart matching yet – just know `when` uses it. # This is equivalent to `if $_ ~~ /foo/`. say "Yay !"; } when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, # so you can also put "normal" conditionals. + # This when is equivalent to this `if`: + # if ($_.chars > 50) ~~ True {...} say "Quite a long string !"; } default { # same as `when *` (using the Whatever Star) @@ -281,7 +265,7 @@ given "foo bar" { ## Looping constructs # - `loop` is an infinite loop if you don't pass it arguments, -# but can also be a c-style `for`: +# but can also be a C-style `for` loop: loop { say "This is an infinite loop !"; last; # last breaks out of the loop, like the `break` keyword in other languages @@ -296,7 +280,7 @@ loop (my $i = 0; $i < 5; $i++) { # - `for` - Passes through an array for @array -> $variable { - say "I've found $variable !"; + say "I've got $variable !"; } # As we saw with given, for's default "current iteration" variable is `$_`. @@ -316,22 +300,15 @@ for @array { last if $_ == 5; # Or break out of a loop (like `break` in C-like languages). } -# Note - the "lambda" `->` syntax isn't reserved to `for`: +# The "pointy block" syntax isn't specific to for. +# It's just a way to express a block in Perl6. if long-computation() -> $result { say "The result is $result"; } -## Loops can also have a label, and be jumped to through these. -OUTER: while 1 { - say "hey"; - while 1 { - OUTER.last; # All the control keywords must be called on the label itself - } -} - # Now that you've seen how to traverse a list, you need to be aware of something: # List context (@) flattens. If you traverse nested lists, you'll actually be traversing a -# shallow list (except if some sub-list were put in item context ($)). +# shallow list. for 1, 2, (3, (4, ((5)))) { say "Got $_."; } #=> Got 1. Got 2. Got 3. Got 4. Got 5. @@ -348,9 +325,14 @@ for [1, 2, 3, 4] { say "Got $_."; } #=> Got 1 2 3 4. -# The other difference between `$()` and `[]` is that `[]` always returns a mutable Array -# whereas `$()` will return a Parcel when given a Parcel. +# You need to be aware of when flattening happens exactly. +# The general guideline is that argument lists flatten, but not method calls. +# Also note that `.list` and array assignment flatten (`@ary = ...`) flatten. +((1,2), 3, (4,5)).map({...}); # iterates over three elements (method call) +map {...}, ((1,2),3,(4,5)); # iterates over five elements (argument list is flattened) +(@a, @b, @c).pick(1); # picks one of three arrays (method call) +pick 1, @a, @b, @c; # flattens argument list and pick one element ### Operators @@ -394,9 +376,6 @@ $arg ~~ &bool-returning-function; # `True` if the function, passed `$arg` 1 ~~ True; # smart-matching against a boolean always returns that boolean # (and will warn). -# - `===` is value identity and uses `.WHICH` on the objects to compare them -# - `=:=` is container identity and uses `VAR()` on the objects to compare them - # You also, of course, have `<`, `<=`, `>`, `>=`. # Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`. 3 > 4; @@ -559,6 +538,21 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # Note : those are sorted lexicographically. # `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` +## About types... +# Perl6 is gradually typed. This means you can specify the type +# of your variables/arguments/return types, or you can omit them +# and they'll default to "Any". +# You obviously get access to a few base types, like Int and Str. +# The constructs for declaring types are "class", "role", +# which you'll see later. + +# For now, let us examinate "subset": +# a "subset" is a "sub-type" with additional checks. +# For example: "a very big integer is an Int that's greater than 500" +# You can specify the type you're subtyping (by default, Any), +# and add additional checks with the "where" keyword: +subset VeryBigInteger of Int where * > 500; + ## Multiple Dispatch # Perl 6 can decide which variant of a `sub` to call based on the type of the # arguments, or on arbitrary preconditions, like with a type or a `where`: @@ -567,20 +561,19 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) multi sub sayit(Int $n) { # note the `multi` keyword here say "Number: $n"; } -multi sayit(Str $s) } # the `sub` is the default +multi sayit(Str $s) } # a multi is a `sub` by default say "String: $s"; } sayit("foo"); # prints "String: foo" sayit(True); # fails at *compile time* with # "calling 'sayit' will never work with arguments of types ..." -# with arbitrary precondition: +# with arbitrary precondition (remember subsets?): multi is-big(Int $n where * > 50) { "Yes !" } # using a closure multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching # (could use a regexp, etc) multi is-big(Int $) { "No" } -# You can also name these checks, by creating "subsets": subset Even of Int where * %% 2; multi odd-or-even(Even) { "Even" } # The main case using the type. @@ -724,7 +717,7 @@ role PrintableVal { } } -# you "use" a mixin with "does" : +# you "import" a mixin (a "role") with "does": class Item does PrintableVal { has $.val; @@ -1083,9 +1076,7 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # It's a prefix meta-operator that takes a binary functions and # one or many lists. If it doesn't get passed any argument, # it either return a "default value" for this operator -# (a value that wouldn't change the result if passed as one -# of the element of the list to be passed to the operator), -# or `Any` if there's none (examples below). +# (a meaningless value) or `Any` if there's none (examples below). # # Otherwise, it pops an element from the list(s) one at a time, and applies # the binary function to the last result (or the list's first element) @@ -1107,9 +1098,7 @@ say [//] Nil, Any, False, 1, 5; #=> False # Default value examples: say [*] (); #=> 1 say [+] (); #=> 0 - # In both cases, they're results that, were they in the lists, - # wouldn't have any impact on the final value - # (since N*1=N and N+0=N). + # meaningless values, since N*1=N and N+0=N. say [//]; #=> (Any) # There's no "default value" for `//`. @@ -1163,90 +1152,6 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # That's why `@primes[^100]` will take a long time the first time you print # it, then be instant. - -## * Sort comparison -# They return one value of the `Order` enum : `Less`, `Same` and `More` -# (which numerify to -1, 0 or +1). -1 <=> 4; # sort comparison for numerics -'a' leg 'b'; # sort comparison for string -$obj eqv $obj2; # sort comparison using eqv semantics - -## * Generic ordering -3 before 4; # True -'b' after 'a'; # True - -## * Short-circuit default operator -# Like `or` and `||`, but instead returns the first *defined* value : -say Any // Nil // 0 // 5; #=> 0 - -## * Short-circuit exclusive or (XOR) -# Returns `True` if one (and only one) of its arguments is true -say True ^^ False; #=> True - -## * Flip Flop -# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). -# are operators that take two predicates to test: -# They are `False` until their left side returns `True`, then are `True` until -# their right side returns `True`. -# Like for ranges, you can exclude the iteration when it became `True`/`False` -# by using `^` on either side. -# Let's start with an example : -for { - # by default, `ff`/`fff` smart-match (`~~`) against `$_`: - if 'met' ^ff 'meet' { # Won't enter the if for "met" - # (explained in details below). - .say - } - - if rand == 0 ff rand == 1 { # compare variables other than `$_` - say "This ... probably will never run ..."; - } -} -# This will print "young hero we shall meet" (excluding "met"): -# the flip-flop will start returning `True` when it first encounters "met" -# (but will still return `False` for "met" itself, due to the leading `^` -# on `ff`), until it sees "meet", which is when it'll start returning `False`. - -# The difference between `ff` (awk-style) and `fff` (sed-style) is that -# `ff` will test its right side right when its left side changes to `True`, -# and can get back to `False` right away -# (*except* it'll be `True` for the iteration that matched) - -# While `fff` will wait for the next iteration to -# try its right side, once its left side changed: -.say if 'B' ff 'B' for ; #=> B B - # because the right-hand-side was tested - # directly (and returned `True`). - # "B"s are printed since it matched that time - # (it just went back to `False` right away). -.say if 'B' fff 'B' for ; #=> B C B - # The right-hand-side wasn't tested until - # `$_` became "C" - # (and thus did not match instantly). - -# A flip-flop can change state as many times as needed: -for { - .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", - #=> "print this printing again" -} - -# you might also use a Whatever Star, -# which is equivalent to `True` for the left side or `False` for the right: -for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here - # (sometimes called "superstitious parentheses") - .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, - # it'll never go back to `False` - #=> 60 3 40 60 -} - -# You can also use this property to create an `If` -# that'll not go through the first time : -for { - .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, - # but the `^` makes it *not run* on the first iteration - #=> b c -} - - ### Regular Expressions # I'm sure a lot of you have been waiting for this one. # Well, now that you know a good deal of Perl 6 already, we can get started. @@ -1470,6 +1375,105 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # As you can see, this is *very* powerful. # It even went as far as to show inline the constants. # (the type is only displayed if the argument is `$`/is named) + +### +### APPENDIX A: +### +### List of things +### + +# It's considered by now you know the Perl6 basics. +# This section is just here to list some common operations, +# but which are not in the "main part" of the tutorial to bloat it up + +## Operators + + +## * Sort comparison +# They return one value of the `Order` enum : `Less`, `Same` and `More` +# (which numerify to -1, 0 or +1). +1 <=> 4; # sort comparison for numerics +'a' leg 'b'; # sort comparison for string +$obj eqv $obj2; # sort comparison using eqv semantics + +## * Generic ordering +3 before 4; # True +'b' after 'a'; # True + +## * Short-circuit default operator +# Like `or` and `||`, but instead returns the first *defined* value : +say Any // Nil // 0 // 5; #=> 0 + +## * Short-circuit exclusive or (XOR) +# Returns `True` if one (and only one) of its arguments is true +say True ^^ False; #=> True +## * Flip Flop +# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). +# are operators that take two predicates to test: +# They are `False` until their left side returns `True`, then are `True` until +# their right side returns `True`. +# Like for ranges, you can exclude the iteration when it became `True`/`False` +# by using `^` on either side. +# Let's start with an example : +for { + # by default, `ff`/`fff` smart-match (`~~`) against `$_`: + if 'met' ^ff 'meet' { # Won't enter the if for "met" + # (explained in details below). + .say + } + + if rand == 0 ff rand == 1 { # compare variables other than `$_` + say "This ... probably will never run ..."; + } +} +# This will print "young hero we shall meet" (excluding "met"): +# the flip-flop will start returning `True` when it first encounters "met" +# (but will still return `False` for "met" itself, due to the leading `^` +# on `ff`), until it sees "meet", which is when it'll start returning `False`. + +# The difference between `ff` (awk-style) and `fff` (sed-style) is that +# `ff` will test its right side right when its left side changes to `True`, +# and can get back to `False` right away +# (*except* it'll be `True` for the iteration that matched) - +# While `fff` will wait for the next iteration to +# try its right side, once its left side changed: +.say if 'B' ff 'B' for ; #=> B B + # because the right-hand-side was tested + # directly (and returned `True`). + # "B"s are printed since it matched that time + # (it just went back to `False` right away). +.say if 'B' fff 'B' for ; #=> B C B + # The right-hand-side wasn't tested until + # `$_` became "C" + # (and thus did not match instantly). + +# A flip-flop can change state as many times as needed: +for { + .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", + #=> "print this printing again" +} + +# you might also use a Whatever Star, +# which is equivalent to `True` for the left side or `False` for the right: +for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here + # (sometimes called "superstitious parentheses") + .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, + # it'll never go back to `False` + #=> 60 3 40 60 +} + +# You can also use this property to create an `If` +# that'll not go through the first time : +for { + .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, + # but the `^` makes it *not run* on the first iteration + #=> b c +} + + +# - `===` is value identity and uses `.WHICH` on the objects to compare them +# - `=:=` is container identity and uses `VAR()` on the objects to compare them + ``` If you want to go further, you can: -- cgit v1.2.3 From e2606bb26259f702e6359afa4075c8a081fb7600 Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 08:56:36 -0200 Subject: general translation to pt-br for common-lisp completed --- pt-br/common-lisp-pt.html.markdown | 636 +++++++++++++++++++++++++++++++++++++ 1 file changed, 636 insertions(+) create mode 100644 pt-br/common-lisp-pt.html.markdown diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown new file mode 100644 index 00000000..a2506aec --- /dev/null +++ b/pt-br/common-lisp-pt.html.markdown @@ -0,0 +1,636 @@ +--- + +language: "Common Lisp" +filename: commonlisp.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] +--- + + + + + +ANSI Common Lisp é uma linguagem de uso geral, multi-paradigma, designada +para uma variedade de aplicações na indústria. É frequentemente citada +como uma linguagem de programação programável. + + + + +O ponto inicial clássico é [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) + + + + +Outro livro recente e popular é o +[Land of Lisp](http://landoflisp.com/). + + +```common_lisp + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. Sintaxe +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; "Form" Geral + + + + +;; Lisp tem dois pedaços fundamentais de sintaxe: o ATOM e S-expression. +;; Tipicamente, S-expressions agrupadas são chamadas de `forms`. + + +10 ; um atom; é avaliado para ele mesmo + + + +:THING ;Outro atom; avaliado para o símbolo :thing. + + + +t ; outro atom, denotado true. + + + +(+ 1 2 3 4) ; uma s-expression + +'(4 :foo t) ;outra s-expression + + +;;; Comentários + +;; Comentários de uma única linha começam com ponto e vírgula; usar dois para +;; comentários normais, três para comentários de seção, e quadro para comentários +;; em nível de arquivo. + +#| Bloco de comentário + pode abranger várias linhas e... + #| + eles podem ser aninhados + |# +|# + +;;; Ambiente + +;; Existe uma variedade de implementações; a maioria segue o padrão. +;; CLISP é um bom ponto de partida. + +;; Bibliotecas são gerenciadas através do Quicklisp.org's Quicklisp systemm. + +;; Common Lisp é normalmente desenvolvido com um editor de texto e um REPL +;; (Read Evaluate Print Loop) rodando ao mesmo tempo. O REPL permite exploração +;; interativa do programa como ele é "ao vivo" no sistema. + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. Tipos Primitivos e Operadores +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Símbolos + +'foo ; => FOO Perceba que um símbolo é automáticamente convertido para maíusculo. + +;; Intern manualmente cria um símbolo a partir de uma string. + +(intern "AAAA") ; => AAAA + +(intern "aaa") ; => |aaa| + +;;; Números +9999999999999999999999 ; inteiro +#b111 ; binário => 7 +#o111 ; octal => 73 +#x111 ; hexadecimal => 273 +3.14159s0 ; single +3.14159d0 ; double +1/2 ; ratios +#C(1 2) ; números complexos + + +;; Funções são escritas como (f x y z ...) +;; onde f é uma função e x, y, z, ... são operadores +;; Se você quiser criar uma lista literal de dados, use ' para evitar +;; que a lista seja avaliada - literalmente, "quote" os dados. +'(+ 1 2) ; => (+ 1 2) +;; Você também pode chamar uma função manualmente: +(funcall #'+ 1 2 3) ; => 6 +;; O mesmo para operações aritiméticas +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + + ;;; Booleans +t ; para true (qualquer valor não nil é true) +nil ; para false - e para lista vazia +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 + + ;;; Caracteres +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; String são arrays de caracteres com tamanho fixo. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; barra é um escape de caracter + +;; String podem ser concatenadas também! +(concatenate 'string "Hello " "world!") ; => "Hello world!" + +;; Uma String pode ser tratada como uma sequência de caracteres +(elt "Apple" 0) ; => #\A + +;; format pode ser usado para formatar strings +(format nil "~a can be ~a" "strings" "formatted") + +;; Impimir é bastante fácil; ~% indica nova linha +(format t "Common Lisp is groovy. Dude.~%") + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variáveis +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Você pode criar uma global (escopo dinâmico) usando defparameter +;; um nome de variável pode conter qualquer caracter, exceto: ()",'`;#|\ + +;; Variáveis de escopo dinâmico devem ter asteriscos em seus nomes! + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;; Você pode usar caracteres unicode também. +(defparameter *AΛB* nil) + + +;; Acessando uma variável anteriormente não ligada é um +;; comportamento não definido (mas possível). Não faça isso. + +;; Ligação local: `me` é vinculado com "dance with you" somente dentro +;; de (let ... ). Let permite retornar o valor do último `form` no form let. + +(let ((me "dance with you")) + me) +;; => "dance with you" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Estruturas e Coleções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Estruturas +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) + +(dog-p *rover*) ; => t ;; ewww) +(dog-name *rover*) ; => "rover" + +;; Dog-p, make-dog, and dog-name foram todas criadas por defstruct! + +;;; Pares +;; `cons' constroi pares, `car' and `cdr' extrai o primeiro +;; e o segundo elemento +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; Listas + +;; Listas são estruturas de dados do tipo listas encadeadas, criadas com `cons' +;; pares e terminam `nil' (ou '()) para marcar o final da lista +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) +;; `list' é um construtor conveniente para listas +(list 1 2 3) ; => '(1 2 3) +;; e a quote (') também pode ser usado para um valor de lista literal +'(1 2 3) ; => '(1 2 3) + +;; Ainda pode-se usar `cons' para adicionar um item no começo da lista. +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Use `append' para - surpreendentemente - juntar duas listas +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Ou use concatenate - + +(concatenate 'list '(1 2) '(3 4)) + +;; Listas são um tipo muito central, então existe uma grande variedade de +;; funcionalidades para eles, alguns exemplos: +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Vetores + +;; Vector's literais são arrays de tamanho fixo. +#(1 2 3) ; => #(1 2 3) + +;; Use concatenate para juntar dois vectors +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Arrays + +;; Ambos vetores e strings são um caso especial de arrays. + +;; 2D arrays + +(make-array (list 2 2)) + +;; (make-array '(2 2)) também funciona. + +; => #2A((0 0) (0 0)) + +(make-array (list 2 2 2)) + +; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;; Cuidado - os valores de inicialição padrões são +;; definidos pela implementção. Aqui vai como defini-lós. + +(make-array '(2) :initial-element 'unset) + +; => #(UNSET UNSET) + +;; E, para acessar o element em 1,1,1 - +(aref (make-array (list 2 2 2)) 1 1 1) + +; => 0 + +;;; Vetores Ajustáveis + +;; Vetores ajustáveis tem a mesma representação impressa que os vectores +;; de tamanho fixo +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) + +*adjvec* ; => #(1 2 3) + +;; Adicionando novo elemento +(vector-push-extend 4 *adjvec*) ; => 3 + +*adjvec* ; => #(1 2 3 4) + + + +;;; Ingenuamente, conjuntos são apenas listas: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;; Mas você irá querer usar uma estrutura de dados melhor que uma lista encadeada. +;; para performance. + +;;; Dicionários são implementados como hash tables + +;; Cria um hash table +(defparameter *m* (make-hash-table)) + +;; seta um valor +(setf (gethash 'a *m*) 1) + +;; Recupera um valor +(gethash 'a *m*) ; => 1, t + +;; Detalhe - Common Lisp tem multiplos valores de retorno possíveis. gethash +;; retorna t no segundo valor se alguma coisa foi encontrada, e nil se não. + +;; Recuperando um valor não presente retorna nil + (gethash 'd *m*) ;=> nil, nil + +;; Você pode fornecer um valor padrão para uma valores não encontrados +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;; Vamos tratas múltiplos valores de rotorno aqui. + +(multiple-value-bind + (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind + (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `lambda' para criar funções anônimas +;; Uma função sempre retorna um valor da última expressão avaliada. +;; A representação exata impressão de uma função varia de acordo ... + +(lambda () "Hello World") ; => # + +;; Use funcall para chamar uma função lambda. +(funcall (lambda () "Hello World")) ; => "Hello World" + +;; Ou Apply +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;; "De-anonymize" a função +(defun hello-world () + "Hello World") +(hello-world) ; => "Hello World" + +;; O () acima é a lista de argumentos da função. +(defun hello (name) + (format nil "Hello, ~a " name)) + +(hello "Steve") ; => "Hello, Steve" + +;; Funções podem ter argumentos opcionais; eles são nil por padrão + +(defun hello (name &optional from) + (if from + (format t "Hello, ~a, from ~a" name from) + (format t "Hello, ~a" name))) + + (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + +;; E os padrões podem ser configurados... +(defun hello (name &optional (from "The world")) + (format t "Hello, ~a, from ~a" name from)) + +(hello "Steve") +; => Hello, Steve, from The world + +(hello "Steve" "the alpacas") +; => Hello, Steve, from the alpacas + + +;; E é claro, palavras-chaves são permitidas também... frequentemente mais +;; flexivel que &optional. + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~a ~a, from ~a" honorific name from)) + +(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Igualdade +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Common Lisp tem um sistema sofisticado de igualdade. Alguns são cobertos aqui. + +;; Para número use `=' +(= 3 3.0) ; => t +(= 2 1) ; => nil + +;; para identidade de objeto (aproximadamente) use `eql` +(eql 3 3) ; => t +(eql 3 3.0) ; => nil +(eql (list 3) (list 3)) ; => nil + +;; para listas, strings, e para pedaços de vetores use `equal' +(equal (list 'a 'b) (list 'a 'b)) ; => t +(equal (list 'a 'b) (list 'b 'a)) ; => nil + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Fluxo de Controle +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Condicionais + +(if t ; testa a expressão + "this is true" ; então expressão + "this is false") ; senão expressão +; => "this is true" + +;; Em condicionais, todos valores não nulos são tratados como true +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;; `cond' encadeia uma série de testes para selecionar um resultado +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;; Typecase é um condicional que escolhe uma de seus cláusulas com base do tipo do valor + +(typecase 1 + (string :string) + (integer :int)) + +; => :int + +;;; Interação + +;; Claro que recursão é suportada: + +(defun walker (n) + (if (zerop n) + :walked + (walker (1- n)))) + +(walker 5) ; => :walked + +;; Na maioria das vezes, nós usamos DOTLISO ou LOOP + +(dolist (i '(1 2 3 4)) + (format t "~a" i)) + +; => 1234 + +(loop for i from 0 below 10 + collect i) + +; => (0 1 2 3 4 5 6 7 8 9) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutação +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `setf' para atribuir um novo valor para uma variável existente. Isso foi +;; demonstrado anteriormente no exemplo da hash table. + +(let ((variable 10)) + (setf variable 2)) + ; => 2 + + +;; Um bom estilo Lisp é para minimizar funções destrutivas e para evitar +;; mutação quando razoável. + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Classes e Objetos +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Sem clases Animal, vamos usar os veículos de transporte de tração +;; humana mecânicos. + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;; defcalss, seguido do nome, seguido por uma list de superclass, +;; seguido por um uma 'slot list', seguido por qualidades opcionais como +;; :documentation + +;; Quando nenhuma lista de superclasse é setada, uma lista padrão para +;; para o objeto padrão é usada. Isso *pode* ser mudado, mas não até você +;; saber o que está fazendo. Olhe em Art of the Metaobject Protocol +;; para maiores informações. + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + + +;; Chamando DESCRIBE na classe human-powered-conveyance no REPL dá: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;; Note o comportamento reflexivo disponível para você! Common Lisp é +;; projetada para ser um sistema interativo. + +;; Para definir um métpdo, vamos encontrar o que nossa cirunferência da +;; roda da bicicleta usando a equação: C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;; pi já é definido para a gente em Lisp! + +;; Vamos supor que nós descobrimos que o valor da eficiência do número +;; de remadores em uma canoa é aproximadamente logarítmica. Isso provavelmente deve ser definido +;; no construtor / inicializador. + +;; Veja como initializar sua instância após Common Lisp ter construído isso: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;; Em seguida, para a construção de uma ocorrência e verificar a eficiência média ... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros permitem que você estenda a sintaxe da lingaugem + +;; Common Lisp nãov vem com um loop WHILE- vamos adicionar um. +;; Se obedecermos nossos instintos 'assembler', acabamos com: + +(defmacro while (condition &body body) + "Enquanto `condition` é verdadeiro, `body` é executado. + +`condition` é testado antes de cada execução do `body`" + (let ((block-name (gensym))) + `(tagbody + (unless ,condition + (go ,block-name)) + (progn + ,@body) + ,block-name))) + +;; Vamos dar uma olhada em uma versão alto nível disto: + + +(defmacro while (condition &body body) + "Enquanto `condition` for verdadeira, `body` é executado. + +`condition` é testado antes de cada execução do `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;; Entretanto, com um compilador moderno, isso não é preciso; o LOOP +;; 'form' compila igual e é bem mais fácil de ler. + +;; Noteq ue ``` é usado , bem como `,` e `@`. ``` é um operador 'quote-type' +;; conhecido como 'quasiquote'; isso permite o uso de `,` . `,` permite "unquoting" +;; e variáveis. @ interpolará listas. + +;; Gensym cria um símbolo único garantido que não existe em outras posições +;; o sistema. Isto é porque macros são expandidas em tempo de compilação e +;; variáveis declaradas na macro podem colidir com as variáveis usadas na +;; código regular. + +;; Veja Practical Common Lisp para maiores informações sobre macros. +``` + + +## Leitura Adicional + +[Continua em frente com Practical Common Lisp book.](http://www.gigamonkeys.com/book/) + + +## Créditos + +Muitos agradecimentos ao pessoal de Schema fornecer um grande ponto de partida +o que facilitou muito a migração para Common Lisp. + +- [Paul Khuong](https://github.com/pkhuong) pelas grandes revisiões. -- cgit v1.2.3 From 0b65be8f0c876a10fb2ac823d5c551f90d7ef51e Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:06:38 -0200 Subject: Removing comments... --- pt-br/common-lisp-pt.html.markdown | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index a2506aec..ba45c4ed 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -1,27 +1,19 @@ --- - language: "Common Lisp" -filename: commonlisp.lisp +filename: commonlisp-pt.lisp contributors: - ["Paul Nathan", "https://github.com/pnathan"] +translators: + - ["Édipo Luis Féderle", "https://github.com/edipofederle"] --- - - - - ANSI Common Lisp é uma linguagem de uso geral, multi-paradigma, designada para uma variedade de aplicações na indústria. É frequentemente citada como uma linguagem de programação programável. - - O ponto inicial clássico é [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) - - - Outro livro recente e popular é o [Land of Lisp](http://landoflisp.com/). @@ -34,25 +26,17 @@ Outro livro recente e popular é o ;;; "Form" Geral - - ;; Lisp tem dois pedaços fundamentais de sintaxe: o ATOM e S-expression. ;; Tipicamente, S-expressions agrupadas são chamadas de `forms`. - -10 ; um atom; é avaliado para ele mesmo - +10 ; um atom; é avaliado para ele mesmo :THING ;Outro atom; avaliado para o símbolo :thing. - - t ; outro atom, denotado true. - - (+ 1 2 3 4) ; uma s-expression '(4 :foo t) ;outra s-expression -- cgit v1.2.3 From a56473fc318aefbe279077c9fa6efc275894ab39 Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:15:03 -0200 Subject: clean up and improvements --- pt-br/common-lisp-pt.html.markdown | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index ba45c4ed..b154c544 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -12,7 +12,7 @@ para uma variedade de aplicações na indústria. É frequentemente citada como uma linguagem de programação programável. -O ponto inicial clássico é [Practical Common Lisp and freely available.](http://www.gigamonkeys.com/book/) +O ponto inicial clássico é [Practical Common Lisp e livremente disponível](http://www.gigamonkeys.com/book/) Outro livro recente e popular é o [Land of Lisp](http://landoflisp.com/). @@ -60,7 +60,7 @@ t ; outro atom, denotado true. ;; Existe uma variedade de implementações; a maioria segue o padrão. ;; CLISP é um bom ponto de partida. -;; Bibliotecas são gerenciadas através do Quicklisp.org's Quicklisp systemm. +;; Bibliotecas são gerenciadas através do Quicklisp.org's Quicklisp sistema. ;; Common Lisp é normalmente desenvolvido com um editor de texto e um REPL ;; (Read Evaluate Print Loop) rodando ao mesmo tempo. O REPL permite exploração @@ -73,7 +73,7 @@ t ; outro atom, denotado true. ;;; Símbolos -'foo ; => FOO Perceba que um símbolo é automáticamente convertido para maíusculo. +'foo ; => FOO Perceba que um símbolo é automáticamente convertido para maiúscula. ;; Intern manualmente cria um símbolo a partir de uma string. @@ -413,7 +413,8 @@ nil ; para false - e para lista vazia ((< 2 2) (error "wrong again!")) (t 'ok)) ; => 'OK -;; Typecase é um condicional que escolhe uma de seus cláusulas com base do tipo do valor +;; Typecase é um condicional que escolhe uma de seus cláusulas com base do tipo +;; do seu valor (typecase 1 (string :string) @@ -542,8 +543,8 @@ nil ; para false - e para lista vazia ;; pi já é definido para a gente em Lisp! ;; Vamos supor que nós descobrimos que o valor da eficiência do número -;; de remadores em uma canoa é aproximadamente logarítmica. Isso provavelmente deve ser definido -;; no construtor / inicializador. +;; de remadores em uma canoa é aproximadamente logarítmica. Isso provavelmente +;; deve ser definido no construtor / inicializador. ;; Veja como initializar sua instância após Common Lisp ter construído isso: @@ -564,7 +565,7 @@ nil ; para false - e para lista vazia ;; Macros permitem que você estenda a sintaxe da lingaugem -;; Common Lisp nãov vem com um loop WHILE- vamos adicionar um. +;; Common Lisp não vem com um loop WHILE - vamos adicionar um. ;; Se obedecermos nossos instintos 'assembler', acabamos com: (defmacro while (condition &body body) -- cgit v1.2.3 From f4c735c05021418bf8e207d49619397bfe37eff7 Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:19:21 -0200 Subject: fix. --- pt-br/common-lisp-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index b154c544..5561c23d 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -178,7 +178,7 @@ nil ; para false - e para lista vazia (dog-p *rover*) ; => t ;; ewww) (dog-name *rover*) ; => "rover" -;; Dog-p, make-dog, and dog-name foram todas criadas por defstruct! +;; Dog-p, make-dog, e dog-name foram todas criadas por defstruct! ;;; Pares ;; `cons' constroi pares, `car' and `cdr' extrai o primeiro @@ -615,7 +615,7 @@ nil ; para false - e para lista vazia ## Créditos -Muitos agradecimentos ao pessoal de Schema fornecer um grande ponto de partida +Muitos agradecimentos ao pessoal de Schema por fornecer um grande ponto de partida o que facilitou muito a migração para Common Lisp. - [Paul Khuong](https://github.com/pkhuong) pelas grandes revisiões. -- cgit v1.2.3 From b59262601656a0f803729d37b6c83d414af0457a Mon Sep 17 00:00:00 2001 From: elf Date: Fri, 26 Dec 2014 09:20:30 -0200 Subject: fix word --- pt-br/common-lisp-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index 5561c23d..ce654846 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -618,4 +618,4 @@ nil ; para false - e para lista vazia Muitos agradecimentos ao pessoal de Schema por fornecer um grande ponto de partida o que facilitou muito a migração para Common Lisp. -- [Paul Khuong](https://github.com/pkhuong) pelas grandes revisiões. +- [Paul Khuong](https://github.com/pkhuong) pelas grandes revisões. -- cgit v1.2.3 From 1c52c5ea125285eb8a3af5cf4cb510e9c3e7a49b Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 29 Dec 2014 22:48:01 +0100 Subject: @wryk++ --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 1536b152..b10e04bf 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -212,7 +212,7 @@ say $x; #=> 52 # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), 0, "0", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: (), 0, "0", "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { -- cgit v1.2.3 From 228cc6ec5ae0d20a94292c66cf43e44755d3758b Mon Sep 17 00:00:00 2001 From: Cameron Steele Date: Mon, 29 Dec 2014 15:00:12 -0800 Subject: typo in Haxe documentation --- haxe.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haxe.html.markdown b/haxe.html.markdown index 6a868f09..8599de8d 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -484,7 +484,7 @@ class LearnHaxe3{ // we can read this variable trace(foo_instance.public_read + " is the value for foo_instance.public_read"); // but not write it - // foo_instance.public_write = 4; // this will throw an error if uncommented: + // foo_instance.public_read = 4; // this will throw an error if uncommented: // trace(foo_instance.public_write); // as will this. trace(foo_instance + " is the value for foo_instance"); // calls the toString method -- cgit v1.2.3 From 427875663c221ae11ff3b8a8a6e6d66e89b36ac2 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 11:56:23 +0200 Subject: basic --- tr-tr/csharp-tr.html.markdown | 824 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 824 insertions(+) create mode 100644 tr-tr/csharp-tr.html.markdown diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown new file mode 100644 index 00000000..ecbc2b18 --- /dev/null +++ b/tr-tr/csharp-tr.html.markdown @@ -0,0 +1,824 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Melih Mucuk", "http://melihmucuk.com"] +filename: LearnCSharp.cs +--- + +C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. + +[Daha fazlasını okuyun.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) + +```c# +// Tek satırlık yorumlar // ile başlar +/* +Birden fazla satırlı yorumlar buna benzer +*/ +/// +/// Bu bir XML dokümantasyon yorumu +/// + +// Uygulamanın kullanacağı ad alanlarını belirtin +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// Kodu düzenlemek için paketler içinde alan tanımlayın +namespace Learning +{ + // Her .cs dosyası, dosya ile aynı isimde en az bir sınıf içermeli + // bu kurala uymak zorunda değilsiniz ancak mantıklı olan yol budur. + public class LearnCSharp + { + // TEMEL SÖZ DİZİMİ - daha önce Java ya da C++ kullandıysanız İLGİNÇ ÖZELLİKLER'e geçin + public static void Syntax() + { + // Satırları yazdırmak için Console.WriteLine kullanın + Console.WriteLine("Merhaba Dünya"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Yeni satıra geçmeden yazdırmak için Console.Write kullanın + Console.Write("Merhaba "); + Console.Write("Dünya"); + + /////////////////////////////////////////////////// + // Tipler & Değişkenler + // + // Bir değişken tanımlamak için kullanın + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Numbers default to being int or uint depending on size. + // L is used to denote that this variable value is of type long or ulong + + // Double - Double-precision 64-bit IEEE 754 Floating Point + double fooDouble = 123.4; // Precision: 15-16 digits + + // Float - Single-precision 32-bit IEEE 754 Floating Point + float fooFloat = 234.5f; // Precision: 7 digits + // f is used to denote that this variable value is of type float + + // Decimal - a 128-bits data type, with more precision than other floating-point types, + // suited for financial and monetary calculations + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // or false + + // Char - A single 16-bit Unicode character + char fooChar = 'A'; + + // Strings -- unlike the previous base types which are all value types, + // a string is a reference type. That is, you can set it to null + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // You can access each character of the string with an indexer: + char charFromString = fooString[1]; // => 'e' + // Strings are immutable: you can't do fooString[1] = 'X'; + + // Compare strings with current culture, ignoring case + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatting, based on sprintf + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Dates & Formatting + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // You can split a string over two lines with the @ symbol. To escape " use "" + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // Use const or read-only to make a variable immutable + // const values are calculated at compile time + const int HOURS_I_WORK_PER_WEEK = 9001; + + /////////////////////////////////////////////////// + // Data Structures + /////////////////////////////////////////////////// + + // Arrays - zero indexed + // The array size must be decided upon declaration + // The format for declaring an array is follows: + // [] = new []; + int[] intArray = new int[10]; + + // Another way to declare & initialize an array + int[] y = { 9000, 1000, 1337 }; + + // Indexing an array - Accessing an element + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Arrays are mutable. + intArray[1] = 1; + + // Lists + // Lists are used more frequently than arrays as they are more flexible + // The format for declaring a list is follows: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; // intialize + // The <> are for generics - Check out the cool stuff section + + // Lists don't default to a value; + // A value must be added before accessing the index + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Others data structures to check out: + // Stack/Queue + // Dictionary (an implementation of a hash map) + // HashSet + // Read-only Collections + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operators + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Shorthand for multiple declarations + + // Arithmetic is straightforward + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Comparison operators + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitwise operators! + /* + ~ Unary bitwise complement + << Signed left shift + >> Signed right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR + */ + + // Incrementations + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Control Structures + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If statements are c-like + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Ternary operators + // A simple if/else can be written as follows + // ? : + string isTrue = (true) ? "True" : "False"; + + // While loop + int fooWhile = 0; + while (fooWhile < 100) + { + //Iterated 100 times, fooWhile 0->99 + fooWhile++; + } + + // Do While Loop + int fooDoWhile = 0; + do + { + //Iterated 100 times, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + + //for loop structure => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //Iterated 10 times, fooFor 0->9 + } + + // For Each Loop + // foreach loop structure => foreach( in ) + // The foreach loop loops over any object implementing IEnumerable or IEnumerable + // All the collection types (Array, List, Dictionary...) in the .Net framework + // implement one or both of these interfaces. + // (The ToCharArray() could be removed, because a string also implements IEnumerable) + foreach (char character in "Hello World".ToCharArray()) + { + //Iterated over all the characters in the string + } + + // 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; + // You can assign more than one case to an action + // But you can't add an action without a break before another case + // (if you want to do this, you would have to explicitly add a goto case x + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; + default: + monthString = "Some other month"; + break; + } + + /////////////////////////////////////// + // Converting Data Types And Typecasting + /////////////////////////////////////// + + // Converting data + + // Convert String To Integer + // this will throw an Exception on failure + int.Parse("123");//returns an integer version of "123" + + // try parse will default to type default on failure + // in this case: 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Function is boolean + Console.WriteLine(tryInt); // 123 + + // Convert Integer To String + // Convert class has a number of methods to facilitate conversions + Convert.ToString(123); + // or + tryInt.ToString(); + } + + /////////////////////////////////////// + // CLASSES - see definitions at end of file + /////////////////////////////////////// + public static void Classes() + { + // See Declaration of objects at end of file + + // Use new to instantiate a class + Bicycle trek = new Bicycle(); + + // Call object methods + trek.SpeedUp(3); // You should always use setter and getter methods + trek.Cadence = 100; + + // ToString is a convention to display the value of this Object. + Console.WriteLine("trek info: " + trek.Info()); + + // Instantiate a new Penny Farthing + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // End main method + + // CONSOLE ENTRY A console application must have a main method as an entry point + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // INTERESTING FEATURES + // + + // DEFAULT METHOD SIGNATURES + + public // Visibility + static // Allows for direct call on class without object + int // Return Type, + MethodSignatures( + int maxCount, // First variable, expects an int + int count = 0, // will default the value to 0 if not passed in + int another = 3, + params string[] otherParams // captures all other parameters passed to method + ) + { + return -1; + } + + // Methods can have the same name, as long as the signature is unique + public static void MethodSignatures(string maxCount) + { + } + + // GENERICS + // The classes for TKey and TValue is specified by the user calling this function. + // This method emulates the SetDefault of Python + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // You can narrow down the objects that are passed in + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // We can iterate, since T is a IEnumerable + foreach (var item in toPrint) + // Item is an int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // OPTIONAL PARAMETERS + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + + // EXTENSION METHODS + int i = 3; + i.Print(); // Defined below + + // NULLABLE TYPES - great for database interaction / return values + // any value type (i.e. not a class) can be made nullable by suffixing a ? + // ? = + int? nullable = null; // short hand for Nullable + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // true if not null + + // ?? is syntactic sugar for specifying default value (coalesce) + // in case variable is null + int notNullable = nullable ?? 0; // 0 + + // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; will not work as magic is a string, not an int + + // GENERICS + // + var phonebook = new Dictionary() { + {"Sarah", "212 555 5555"} // Add some entries to the phone book + }; + + // Calling SETDEFAULT defined as a generic above + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // nb, you don't need to specify the TKey and TValue since they can be + // derived implicitly + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA EXPRESSIONS - allow you to write code in line + Func square = (x) => x * x; // Last T item is the return value + Console.WriteLine(square(3)); // 9 + + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. + // Most of objects that access unmanaged resources (file handle, device contexts, etc.) + // implement the IDisposable interface. The using statement takes care of + // cleaning those IDisposable objects for you. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // At the end of scope, resources will be released. + // Even if an exception is thrown. + } + + // PARALLEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Will spin up separate threads for each request, and join on them + // before going to the next step! + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + website => + { + // Do something that takes a long time on the file + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // This won't happen till after all requests have been completed + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DYNAMIC OBJECTS (great for working with other languages) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // No need to define class first! + + // You can even add methods (returns a string, and takes in a string) + student.Introduce = new Func( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE - almost all collections implement this, which gives you a lot of + // very useful Map / Filter / Reduce style methods + var bikes = new List(); + bikes.Sort(); // Sorts the array + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + var result = bikes + .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + + var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + + // Create a list of IMPLICIT objects based on some parameters of the bike + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Hard to show here, but you get type ahead completion since the compiler can implicitly work + // out the types above! + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // And this is where things get wicked - combines linq and parallel operations + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of + // cores + + // LINQ - maps a store to IQueryable objects, with delayed execution + // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + var db = new BikeRepository(); + + // execution is delayed, which is great when querying a database + var filter = db.Bikes.Where(b => b.HasTassles); // no query run + if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality + filter = filter.Where(b => b.IsBroken); // no query run + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // still no query run + + // Now the query runs, but opens a reader, so only populates are you iterate through + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // End LearnCSharp class + + // You can include other classes in a .cs file + + public static class Extensions + { + // EXTENSION FUNCTIONS + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Class Declaration Syntax: + // class { + // //data fields, constructors, functions all inside. + // //functions are called as methods in Java. + // } + + public class Bicycle + { + // Bicycle's Fields/Variables + public int Cadence // Public: Can be accessed from anywhere + { + get // get - define a method to retrieve the property + { + return _cadence; + } + set // set - define a method to set a proprety + { + _cadence = value; // Value is the value passed in to the setter + } + } + private int _cadence; + + protected virtual int Gear // Protected: Accessible from the class and subclasses + { + get; // creates an auto property so you don't need a member field + set; + } + + internal int Wheels // Internal: Accessible from within the assembly + { + get; + private set; // You can set modifiers on the get/set methods + } + + int _speed; // Everything is private by default: Only accessible from within this class. + // can also use keyword private + public string Name { get; set; } + + // Enum is a value type that consists of a set of named constants + // It is really just mapping a name to a value (an int, unless specified otherwise). + // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. + // An enum can't contain the same value twice. + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, //you can explicitly set a value to a name + Gitane // 43 + } + // We defined this type inside a Bicycle class, so it is a nested type + // Code outside of this class should reference this type as Bicycle.Brand + + public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + + // Static members belong to the type itself rather then specific object. + // You can access them without a reference to any object: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + static public int BicyclesCreated = 0; + + // readonly values are set at run time + // they can only be assigned upon declaration or in a constructor + readonly bool _hasCardsInSpokes = false; // read-only private + + // Constructors are a way of creating classes + // This is a default constructor + public Bicycle() + { + this.Gear = 1; // you can access members of the object with the keyword this + Cadence = 50; // but you don't always need it + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // This is a specified constructor (it contains arguments) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // calls base first + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Constructors can be chained + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Function Syntax: + // () + + // classes can implement getters and setters for their fields + // or they can implement properties (this is the preferred way in C#) + + // Method parameters can have default values. + // In this case, methods can be called with these parameters omitted + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // properties get/set values + // when only data needs to be accessed, consider using properties. + // properties may have either get or set, or both + private bool _hasTassles; // private variable + public bool HasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // You can also define an automatic property in one line + // this syntax will create a backing field automatically. + // You can set an access modifier on either the getter or the setter (or both) + // to restrict its access: + public bool IsBroken { get; private set; } + + // Properties can be auto-implemented + public int FrameSize + { + get; + // you are able to specify access modifiers for either get or set + // this means only Bicycle class can call set on Framesize + private set; + } + + // It's also possible to define custom Indexers on objects. + // All though this is not entirely useful in this example, you + // could do bicycle[0] which yields "chris" to get the first passenger or + // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" } + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + + //Method to display the attribute values of this Object. + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Methods can also be static. It can be useful for helper methods + public static bool DidWeCreateEnoughBycles() + { + // Within a static method, we only can reference static class members + return BicyclesCreated > 9000; + } // If your class only needs static members, consider marking the class itself as static. + + + } // end class Bicycle + + // PennyFarthing is a subclass of Bicycle + class PennyFarthing : Bicycle + { + // (Penny Farthings are those bicycles with the big front wheel. + // They have no gears.) + + // calling parent constructor + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new ArgumentException("You can't change gears on a PennyFarthing"); + } + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Calling the base version of the method + return result; + } + } + + // Interfaces only contain signatures of the members, without the implementation. + interface IJumpable + { + void Jump(int meters); // all interface members are implicitly public + } + + interface IBreakable + { + bool Broken { get; } // interfaces can contain properties as well as methods & events + } + + // Class can inherit only one other class, but can implement any amount of interfaces + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// + /// Used to connect to DB for LinqToSql example. + /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// + public class BikeRepository : DbSet + { + public BikeRepository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // End Namespace +``` + +## Topics Not Covered + + * Flags + * Attributes + * Static properties + * Exceptions, Abstraction + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + +## Further Reading + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + + + +[C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From 32174fe9ce787f9135bda27dd3d3fddc9b0225bd Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 12:01:40 +0200 Subject: types --- tr-tr/csharp-tr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index ecbc2b18..29c29145 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -81,8 +81,8 @@ namespace Learning // Long - 64-bit integer long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) - // Numbers default to being int or uint depending on size. - // L is used to denote that this variable value is of type long or ulong + // Sayılar boyutlarına göre ön tanımlı olarak int ya da uint olabilir. + // L, bir değerin long ya da ulong tipinde olduğunu belirtmek için kullanılır. // Double - Double-precision 64-bit IEEE 754 Floating Point double fooDouble = 123.4; // Precision: 15-16 digits -- cgit v1.2.3 From 20a921fd03a8274e817944f5732b7b69f4267abd Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 16:07:18 +0200 Subject: arrays --- tr-tr/csharp-tr.html.markdown | 52 +++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 29c29145..8c6a7d43 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -82,63 +82,63 @@ namespace Learning long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) // Sayılar boyutlarına göre ön tanımlı olarak int ya da uint olabilir. - // L, bir değerin long ya da ulong tipinde olduğunu belirtmek için kullanılır. + // L, değişken değerinin long ya da ulong tipinde olduğunu belirtmek için kullanılır. - // Double - Double-precision 64-bit IEEE 754 Floating Point - double fooDouble = 123.4; // Precision: 15-16 digits + // Double - Çift hassasiyetli 64-bit IEEE 754 kayan sayı + double fooDouble = 123.4; // Hassasiyet: 15-16 basamak - // Float - Single-precision 32-bit IEEE 754 Floating Point - float fooFloat = 234.5f; // Precision: 7 digits - // f is used to denote that this variable value is of type float + // Float - Tek hassasiyetli 32-bit IEEE 754 kayan sayı + float fooFloat = 234.5f; // Hassasiyet: 7 basamak + // f, değişken değerinin float tipinde olduğunu belirtmek için kullanılır. - // Decimal - a 128-bits data type, with more precision than other floating-point types, - // suited for financial and monetary calculations + // Decimal - 128-bit veri tiğinde ve diğer kayan sayı veri tiplerinden daha hassastır, + // finansal ve mali hesaplamalar için uygundur. decimal fooDecimal = 150.3m; // Boolean - true & false - bool fooBoolean = true; // or false + bool fooBoolean = true; // veya false - // Char - A single 16-bit Unicode character + // Char - 16-bitlik tek bir unicode karakter char fooChar = 'A'; - // Strings -- unlike the previous base types which are all value types, - // a string is a reference type. That is, you can set it to null + // Strings -- Önceki baz tiplerinin hepsi değer tipiyken, + // string bir referans tipidir. Null değer atayabilirsiniz string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; Console.WriteLine(fooString); - // You can access each character of the string with an indexer: + // İndeks numarası kullanarak bir string'in bütün karakterlerine erişilebilirsiniz: char charFromString = fooString[1]; // => 'e' - // Strings are immutable: you can't do fooString[1] = 'X'; + // String'ler değiştirilemez: fooString[1] = 'X' işlemini yapamazsınız; - // Compare strings with current culture, ignoring case + // String'leri geçerli kültür değeri ve büyük küçük harf duyarlılığı olmadan karşılaştırma string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); - // Formatting, based on sprintf + // sprintf baz alınarak formatlama string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); - // Dates & Formatting + // Tarihler & Formatlama DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - // You can split a string over two lines with the @ symbol. To escape " use "" + // Bir string'i iki satıra bölmek için @ sembolü kullanabilirsiniz. " işaretinden kaçmak için "" kullanın string bazString = @"Here's some stuff on a new line! ""Wow!"", the masses cried"; - // Use const or read-only to make a variable immutable - // const values are calculated at compile time + // Bir değişkeni değiştirilemez yapmak için const ya da read-only kullanın. + // const değerleri derleme sırasında hesaplanır const int HOURS_I_WORK_PER_WEEK = 9001; /////////////////////////////////////////////////// - // Data Structures + // Veri Yapıları /////////////////////////////////////////////////// - // Arrays - zero indexed - // The array size must be decided upon declaration - // The format for declaring an array is follows: - // [] = new []; + // Diziler - Sıfır indeksli + // Dizi boyutuna tanımlama sırasında karar verilmelidir. + // Dizi tanımlama formatı şöyledir: + // [] = new []; int[] intArray = new int[10]; - // Another way to declare & initialize an array + // Bir diğer dizi tanımlama formatı şöyledir: int[] y = { 9000, 1000, 1337 }; // Indexing an array - Accessing an element -- cgit v1.2.3 From 4ba98e1b9782ac8dc1a476296fb9cf1095943787 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 16:46:49 +0200 Subject: swithc case --- tr-tr/csharp-tr.html.markdown | 98 +++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 49 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 8c6a7d43..1ecf18e8 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -141,46 +141,46 @@ on a new line! ""Wow!"", the masses cried"; // Bir diğer dizi tanımlama formatı şöyledir: int[] y = { 9000, 1000, 1337 }; - // Indexing an array - Accessing an element + // Bir diziyi indeksleme - Bir elemente erişme Console.WriteLine("intArray @ 0: " + intArray[0]); - // Arrays are mutable. + // Diziler değiştirilebilir. intArray[1] = 1; - // Lists - // Lists are used more frequently than arrays as they are more flexible - // The format for declaring a list is follows: - // List = new List(); + // Listeler + // Listeler daha esnek oldukları için dizilerden daha sık kullanılırlar. + // Bir liste tanımlama formatı şöyledir: + // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // intialize - // The <> are for generics - Check out the cool stuff section + List z = new List { 9000, 1000, 1337 }; // tanımlama + // <> işareti genelleme içindir - Güzel özellikler sekmesini inceleyin - // Lists don't default to a value; - // A value must be added before accessing the index + // Listelerin varsayılan bir değeri yoktur; + // İndekse erişmeden önce değer eklenmiş olmalıdır intList.Add(1); Console.WriteLine("intList @ 0: " + intList[0]); - // Others data structures to check out: - // Stack/Queue - // Dictionary (an implementation of a hash map) - // HashSet - // Read-only Collections - // Tuple (.Net 4+) + // Diğer veri yapıları için şunlara bakın: + // Stack/Queue (Yığın/Kuyruk) + // Dictionary (hash map'in uygulanması) (Sözlük) + // HashSet (karma seti) + // Read-only Collections (Değiştirilemez koleksiyonlar) + // Tuple (.Net 4+) (tüp) /////////////////////////////////////// - // Operators + // Operatörler /////////////////////////////////////// Console.WriteLine("\n->Operators"); - int i1 = 1, i2 = 2; // Shorthand for multiple declarations + int i1 = 1, i2 = 2; // Birden çok tanımlamanın kısa yolu - // Arithmetic is straightforward + // Aritmetik basittir Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 - // Modulo + // Mod Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - // Comparison operators + // Karşılaştırma operatörleri Console.WriteLine("3 == 2? " + (3 == 2)); // => false Console.WriteLine("3 != 2? " + (3 != 2)); // => true Console.WriteLine("3 > 2? " + (3 > 2)); // => true @@ -188,17 +188,17 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true - // Bitwise operators! + // Bit düzeyi operatörleri! /* - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ~ Tekli bit tamamlayıcısı + << Sola kaydırma Signed left shift + >> Sağa kaydırma Signed right shift + & Bit düzeyi AND + ^ Bit düzeyi harici OR + | Bit düzeyi kapsayan OR */ - // Incrementations + // Arttırma int i = 0; Console.WriteLine("\n->Inc/Dec-rementation"); Console.WriteLine(i++); //i = 1. Post-Incrementation @@ -207,11 +207,11 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(--i); //i = 0. Pre-Decrementation /////////////////////////////////////// - // Control Structures + // Kontrol Yapıları /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // If statements are c-like + // If ifadesi c benzeridir int j = 10; if (j == 10) { @@ -226,47 +226,47 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("I also don't"); } - // Ternary operators - // A simple if/else can be written as follows - // ? : + // Üçlü operatörler + // Basit bir if/else ifadesi şöyle yazılabilir + // ? : string isTrue = (true) ? "True" : "False"; - // While loop + // While döngüsü int fooWhile = 0; while (fooWhile < 100) { - //Iterated 100 times, fooWhile 0->99 + //100 kere tekrarlanır, fooWhile 0->99 fooWhile++; } - // Do While Loop + // Do While Döngüsü int fooDoWhile = 0; do { - //Iterated 100 times, fooDoWhile 0->99 + //100 kere tekrarlanır, fooDoWhile 0->99 fooDoWhile++; } while (fooDoWhile < 100); - //for loop structure => for(; ; ) + //for döngüsü yapısı => for(; ; ) for (int fooFor = 0; fooFor < 10; fooFor++) { - //Iterated 10 times, fooFor 0->9 + //10 kere tekrarlanır, fooFor 0->9 } - // For Each Loop - // foreach loop structure => foreach( in ) - // The foreach loop loops over any object implementing IEnumerable or IEnumerable - // All the collection types (Array, List, Dictionary...) in the .Net framework - // implement one or both of these interfaces. - // (The ToCharArray() could be removed, because a string also implements IEnumerable) + // For Each Döngüsü + // foreach döngüsü yapısı => foreach( in ) + // foreach döngüsü, IEnumerable ya da IEnumerable e dönüştürülmüş herhangi bir obje üzerinde döngü yapabilir + // .Net framework üzerindeki bütün koleksiyon tiplerinden (Dizi, Liste, Sözlük...) + // biri ya da hepsi uygulanarak gerçekleştirilebilir. + // (ToCharArray() silindi, çünkü string'ler aynı zamanda IEnumerable'dır.) foreach (char character in "Hello World".ToCharArray()) { - //Iterated over all the characters in the string + //String içindeki bütün karakterler üzerinde döner } // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), + // Bir switch byte, short, char ve int veri tipleri ile çalışır. + // Aynı zamanda sıralı tipler ilede çalışabilir.(Enum Tipleri bölümünde tartışıldı), // the String class, and a few special classes that wrap // primitive types: Character, Byte, Short, and Integer. int month = 3; -- cgit v1.2.3 From 9b1b260c6c3510ccbcc213dd37175ae4383cf08f Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 17:13:30 +0200 Subject: classes --- tr-tr/csharp-tr.html.markdown | 50 +++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 1ecf18e8..37a1090a 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -266,9 +266,9 @@ on a new line! ""Wow!"", the masses cried"; // Switch Case // Bir switch byte, short, char ve int veri tipleri ile çalışır. - // Aynı zamanda sıralı tipler ilede çalışabilir.(Enum Tipleri bölümünde tartışıldı), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. + // Aynı zamanda sıralı tipler ile de çalışabilir.(Enum Tipleri bölümünde tartışıldı), + // String sınıfı, ve bir kaç özel sınıf kaydırılır + // basit tipler: Character, Byte, Short, and Integer. int month = 3; string monthString; switch (month) @@ -282,9 +282,9 @@ on a new line! ""Wow!"", the masses cried"; case 3: monthString = "March"; break; - // You can assign more than one case to an action - // But you can't add an action without a break before another case - // (if you want to do this, you would have to explicitly add a goto case x + // Bir aksiyon için birden fazla durum atayabilirsiniz + // Ancak, break olmadan yeni bir durum ekleyemezsiniz + // (Eğer bunu yapmak istiyorsanız, goto komutu eklemek zorundasınız) case 6: case 7: case 8: @@ -296,51 +296,51 @@ on a new line! ""Wow!"", the masses cried"; } /////////////////////////////////////// - // Converting Data Types And Typecasting + // Veri Tipleri Dönüştürme ve Typecasting /////////////////////////////////////// - // Converting data + // Veri Dönüştürme - // Convert String To Integer - // this will throw an Exception on failure - int.Parse("123");//returns an integer version of "123" + // String'i Integer'a Dönüştürme + // bu başarısız olursa hata fırlatacaktır + int.Parse("123");// "123" 'in Integer değerini döndürür - // try parse will default to type default on failure - // in this case: 0 + // try parse hata durumunda değişkene varsayılan bir değer atamak için kullanılır + // bu durumda: 0 int tryInt; - if (int.TryParse("123", out tryInt)) // Function is boolean + if (int.TryParse("123", out tryInt)) // Fonksiyon boolean'dır Console.WriteLine(tryInt); // 123 - // Convert Integer To String - // Convert class has a number of methods to facilitate conversions + // Integer'ı String'e Dönüştürme + // Convert sınıfı dönüştürme işlemini kolaylaştırmak için bir dizi metoda sahiptir Convert.ToString(123); - // or + // veya tryInt.ToString(); } /////////////////////////////////////// - // CLASSES - see definitions at end of file + // SINIFLAR - dosyanın sonunda tanımları görebilirsiniz /////////////////////////////////////// public static void Classes() { - // See Declaration of objects at end of file + // Obje tanımlamalarını dosyanın sonunda görebilirsiniz - // Use new to instantiate a class + // Bir sınıfı türetmek için new kullanın Bicycle trek = new Bicycle(); - // Call object methods - trek.SpeedUp(3); // You should always use setter and getter methods + // Obje metodlarını çağırma + trek.SpeedUp(3); // Her zaman setter ve getter metodları kullanmalısınız trek.Cadence = 100; - // ToString is a convention to display the value of this Object. + // ToString objenin değerini göstermek için kullanılır. Console.WriteLine("trek info: " + trek.Info()); - // Instantiate a new Penny Farthing + // Yeni bir Penny Farthing sınıfı türetmek PennyFarthing funbike = new PennyFarthing(1, 10); Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); - } // End main method + } // Ana metodun sonu // CONSOLE ENTRY A console application must have a main method as an entry point public static void Main(string[] args) -- cgit v1.2.3 From 765e4d3be987edd441b5f3cdee83543645fca642 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 19:30:07 +0200 Subject: lasssstttt --- tr-tr/csharp-tr.html.markdown | 232 +++++++++++++++++++++--------------------- 1 file changed, 114 insertions(+), 118 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 37a1090a..cfbee5e8 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -153,7 +153,7 @@ on a new line! ""Wow!"", the masses cried"; List intList = new List(); List stringList = new List(); List z = new List { 9000, 1000, 1337 }; // tanımlama - // <> işareti genelleme içindir - Güzel özellikler sekmesini inceleyin + // <> işareti generic ifadeler içindir - Güzel özellikler sekmesini inceleyin // Listelerin varsayılan bir değeri yoktur; // İndekse erişmeden önce değer eklenmiş olmalıdır @@ -342,39 +342,39 @@ on a new line! ""Wow!"", the masses cried"; Console.Read(); } // Ana metodun sonu - // CONSOLE ENTRY A console application must have a main method as an entry point + // KONSOLE BAŞLANGICI Bir konsol uygulaması başlangıç olarak mutlaka ana metod'a sahip olmalı public static void Main(string[] args) { OtherInterestingFeatures(); } // - // INTERESTING FEATURES + // İLGİNÇ ÖZELLİKLER // - // DEFAULT METHOD SIGNATURES + // VARSAYILAN METOD TANIMLAMALARI - public // Visibility - static // Allows for direct call on class without object - int // Return Type, + public // Görünebilir + static // Sınıf üzerinden obje türetmeden çağırılabilir + int // Dönüş Tipi, MethodSignatures( - int maxCount, // First variable, expects an int - int count = 0, // will default the value to 0 if not passed in + int maxCount, // İlk değişken, int değer bekler + int count = 0, // Eğer değer gönderilmezse varsayılan olarak 0 değerini alır int another = 3, - params string[] otherParams // captures all other parameters passed to method + params string[] otherParams // Metoda gönderilen diğer bütün parametreleri alır ) { return -1; } - // Methods can have the same name, as long as the signature is unique + // Metodlar tanımlamalar benzersiz ise aynı isimleri alabilirler public static void MethodSignatures(string maxCount) { } - // GENERICS - // The classes for TKey and TValue is specified by the user calling this function. - // This method emulates the SetDefault of Python + // GENERIC'LER + // TKey ve TValue değerleri kullanıcı tarafından bu fonksiyon çağırılırken belirtilir. + // Bu metod Python'daki SetDefault'a benzer public static TValue SetDefault( IDictionary dictionary, TKey key, @@ -386,68 +386,66 @@ on a new line! ""Wow!"", the masses cried"; return result; } - // You can narrow down the objects that are passed in + // Gönderilen objeleri daraltabilirsiniz public static void IterateAndPrint(T toPrint) where T: IEnumerable { - // We can iterate, since T is a IEnumerable + // Eğer T IEnumerable ise tekrarlayabiliriz foreach (var item in toPrint) - // Item is an int + // Item bir int Console.WriteLine(item.ToString()); } public static void OtherInterestingFeatures() { - // OPTIONAL PARAMETERS + // İSTEĞE BAĞLI PARAMETRELER MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); - MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + MethodSignatures(3, another: 3); // isteğe bağlı olanlar gönderilmedi - // EXTENSION METHODS + // UZANTI METODLARI int i = 3; - i.Print(); // Defined below + i.Print(); // Aşağıda tanımlandı - // NULLABLE TYPES - great for database interaction / return values - // any value type (i.e. not a class) can be made nullable by suffixing a ? - // ? = - int? nullable = null; // short hand for Nullable + // NULLABLE TYPES - veri tabanı işlemleri için uygun / return values + // Herhangi bir değer tipi sonuna ? eklenerek nullable yapılabilir (sınıflar hariç) + // ? = + int? nullable = null; // Nullable için kısa yol Console.WriteLine("Nullable variable: " + nullable); - bool hasValue = nullable.HasValue; // true if not null + bool hasValue = nullable.HasValue; // eğer null değilse true döner - // ?? is syntactic sugar for specifying default value (coalesce) - // in case variable is null + // ?? varsayılan değer belirlemek için söz dizimsel güzel bir özellik + // bu durumda değişken null'dır int notNullable = nullable ?? 0; // 0 - // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: + // TİPİ BELİRTİLMEMİŞ DEĞİŞKENLER - compiler değişkenin tipini bilmeden çalışabilir: var magic = "magic is a string, at compile time, so you still get type safety"; - // magic = 9; will not work as magic is a string, not an int + // magic = 9; string gibi çalışmayacaktır, bu bir int değil - // GENERICS + // GENERIC'LER // var phonebook = new Dictionary() { - {"Sarah", "212 555 5555"} // Add some entries to the phone book + {"Sarah", "212 555 5555"} // Telefon rehberine bir kaç numara ekleyelim. }; - // Calling SETDEFAULT defined as a generic above - Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone - // nb, you don't need to specify the TKey and TValue since they can be - // derived implicitly + // Yukarıda generic olarak tanımlanan SETDEFAULT'u çağırma + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // Telefonu yok + // TKey ve TValue tipini belirtmek zorunda değilsiniz Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 - // LAMBDA EXPRESSIONS - allow you to write code in line - Func square = (x) => x * x; // Last T item is the return value + // LAMBDA IFADELERİ - satır içinde kod yazmanıza olanak sağlar + Func square = (x) => x * x; // Son T nesnesi dönüş değeridir Console.WriteLine(square(3)); // 9 - // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. - // Most of objects that access unmanaged resources (file handle, device contexts, etc.) - // implement the IDisposable interface. The using statement takes care of - // cleaning those IDisposable objects for you. + // TEK KULLANIMLIK KAYNAK YÖNETİMİ - Yönetilemeyen kaynakların üstesinden kolayca gelebilirsiniz. + // Bir çok obje yönetilemeyen kaynaklara (dosya yakalama, cihaz içeriği, vb.) + // IDisposable arabirimi ile erişebilir. Using ifadesi sizin için IDisposable objeleri temizler. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); - // At the end of scope, resources will be released. - // Even if an exception is thrown. + // Bu bölümün sonunda kaynaklar temilenir. + // Hata fırlatılmış olsa bile. } - // PARALLEL FRAMEWORK + // PARALEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx var websites = new string[] { "http://www.google.com", "http://www.reddit.com", @@ -455,73 +453,71 @@ on a new line! ""Wow!"", the masses cried"; }; var responses = new Dictionary(); - // Will spin up separate threads for each request, and join on them - // before going to the next step! + // Her istek farklı bir thread de işlem görecek + // bir sonraki işleme geçmeden birleştirilecek. Parallel.ForEach(websites, - new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // en fazla 3 thread kullanmak için website => { - // Do something that takes a long time on the file + // Uzun sürecek bir işlem yapın using (var r = WebRequest.Create(new Uri(website)).GetResponse()) { responses[website] = r.ContentType; } }); - // This won't happen till after all requests have been completed + // Bütün istekler tamamlanmadan bu döndü çalışmayacaktır. foreach (var key in responses.Keys) Console.WriteLine("{0}:{1}", key, responses[key]); - // DYNAMIC OBJECTS (great for working with other languages) + // DİNAMİK OBJELER (diğer dillerle çalışırken kullanmak için uygun) dynamic student = new ExpandoObject(); - student.FirstName = "First Name"; // No need to define class first! + student.FirstName = "First Name"; // Önce yeni bir sınıf tanımlamanız gerekmez! - // You can even add methods (returns a string, and takes in a string) + // Hatta metod bile ekleyebilirsiniz (bir string döner, ve bir string alır) student.Introduce = new Func( (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); - // IQUERYABLE - almost all collections implement this, which gives you a lot of - // very useful Map / Filter / Reduce style methods + // IQUERYABLE - neredeyse bütün koleksiyonlar bundan türer, bu size bir çok + // kullanışlı Map / Filter / Reduce stili metod sağlar. var bikes = new List(); - bikes.Sort(); // Sorts the array - bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Sorts based on wheels + bikes.Sort(); // Dizi sıralama + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Wheels baz alınarak sıralama var result = bikes - .Where(b => b.Wheels > 3) // Filters - chainable (returns IQueryable of previous type) + .Where(b => b.Wheels > 3) // Filters- chainable (bir önceki tipin IQueryable'ını döner) .Where(b => b.IsBroken && b.HasTassles) - .Select(b => b.ToString()); // Map - we only this selects, so result is a IQueryable + .Select(b => b.ToString()); // Map - sadece bunu seçiyoruz, yani sonuç bir IQueryable olacak - var sum = bikes.Sum(b => b.Wheels); // Reduce - sums all the wheels in the collection + var sum = bikes.Sum(b => b.Wheels); // Reduce - koleksiyonda bulunan bütün wheel değerlerinin toplamı - // Create a list of IMPLICIT objects based on some parameters of the bike + // Bike içindeki bazı parametreleri baz alarak bir liste oluşturmak var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); - // Hard to show here, but you get type ahead completion since the compiler can implicitly work - // out the types above! + // Burada göstermek zor ama, compiler yukaridaki tipleri çözümleyebilirse derlenmeden önce tipi verebilir. foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) Console.WriteLine(bikeSummary.Name); // ASPARALLEL - // And this is where things get wicked - combines linq and parallel operations + // Linq ve paralel işlemlerini birleştirme var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); - // this will happen in parallel! Threads will automagically be spun up and the - // results divvied amongst them! Amazing for large datasets when you have lots of - // cores + // bu paralel bir şekilde gerçekleşecek! Threadler otomatik ve sihirli bir şekilde işleri paylaşacak! + // Birden fazla çekirdeğiniz varsa büyük veri setleri ile kullanmak için oldukça uygun bir yapı. - // LINQ - maps a store to IQueryable objects, with delayed execution - // e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document + // LINQ - IQueryable objelerini mapler ve saklar, gecikmeli bir işlemdir + // e.g. LinqToSql - veri tabanını mapler, LinqToXml xml dökümanlarını mapler. var db = new BikeRepository(); - // execution is delayed, which is great when querying a database - var filter = db.Bikes.Where(b => b.HasTassles); // no query run - if (42 > 6) // You can keep adding filters, even conditionally - great for "advanced search" functionality - filter = filter.Where(b => b.IsBroken); // no query run + // işlem gecikmelidir, bir veri tabanı üzerinde sorgulama yaparken harikadır. + var filter = db.Bikes.Where(b => b.HasTassles); // sorgu henüz çalışmadı + if (42 > 6) // Filtreler eklemeye devam edebilirsiniz - ileri düzey arama fonksiyonları için harikadır + filter = filter.Where(b => b.IsBroken); // sorgu henüz çalışmadı var query = filter .OrderBy(b => b.Wheels) .ThenBy(b => b.Name) - .Select(b => b.Name); // still no query run + .Select(b => b.Name); // hala sorgu çalışmadı - // Now the query runs, but opens a reader, so only populates are you iterate through + // Şimdi sorgu çalışıyor, reader'ı açar ama sadece sizin sorgunuza uyanlar foreach döngüsüne girer. foreach (string bike in query) Console.WriteLine(result); @@ -529,98 +525,98 @@ on a new line! ""Wow!"", the masses cried"; } - } // End LearnCSharp class + } // LearnCSharp sınıfının sonu - // You can include other classes in a .cs file + // Bir .cs dosyasına diğer sınıflarıda dahil edebilirsiniz public static class Extensions { - // EXTENSION FUNCTIONS + // UZANTI FONKSİYONLARI public static void Print(this object obj) { Console.WriteLine(obj.ToString()); } } - // Class Declaration Syntax: - // class { - // //data fields, constructors, functions all inside. - // //functions are called as methods in Java. + // Sınıf Tanımlama Sözdizimi: + // class { + // //veri alanları, kurucular , fonksiyonlar hepsi içindedir. + // //Fonksiyonlar Java'daki gibi metod olarak çağırılır. // } public class Bicycle { - // Bicycle's Fields/Variables - public int Cadence // Public: Can be accessed from anywhere + // Bicycle'ın Alanları/Değişkenleri + public int Cadence // Public: herhangi bir yerden erişilebilir { - get // get - define a method to retrieve the property + get // get - değeri almak için tanımlanan metod { return _cadence; } - set // set - define a method to set a proprety + set // set - değer atamak için tanımlanan metod { - _cadence = value; // Value is the value passed in to the setter + _cadence = value; // Değer setter'a gönderilen value değeridir } } private int _cadence; - protected virtual int Gear // Protected: Accessible from the class and subclasses + protected virtual int Gear // Protected: Sınıf ve alt sınıflar tarafından erişilebilir { - get; // creates an auto property so you don't need a member field + get; // bir üye alanına ihtiyacınız yok, bu otomatik olarak bir değer oluşturacaktır set; } - internal int Wheels // Internal: Accessible from within the assembly + internal int Wheels // Internal: Assembly tarafından erişilebilir { get; - private set; // You can set modifiers on the get/set methods + private set; // Nitelik belirleyicileri get/set metodlarında atayabilirsiniz } - int _speed; // Everything is private by default: Only accessible from within this class. - // can also use keyword private + int _speed; // Her şey varsayılan olarak private'dır : Sadece sınıf içinden erişilebilir. + // İsterseniz yinede private kelimesini kullanabilirsiniz. public string Name { get; set; } - // Enum is a value type that consists of a set of named constants - // It is really just mapping a name to a value (an int, unless specified otherwise). - // The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong. - // An enum can't contain the same value twice. + // Enum sabitler kümesinden oluşan bir değer tipidir. + // Gerçekten sadece bir isim ile bir değeri tutmak için kullanılır. (aksi belirtilmedikçe bir int'dir). + // İzin verilen enum tipleri şunlardır byte, sbyte, short, ushort, int, uint, long, veya ulong. + // Bir enum aynı değeri birden fazla sayıda barındıramaz. public enum BikeBrand { AIST, BMC, - Electra = 42, //you can explicitly set a value to a name + Electra = 42, // bir isme tam bir değer verebilirsiniz Gitane // 43 } - // We defined this type inside a Bicycle class, so it is a nested type - // Code outside of this class should reference this type as Bicycle.Brand + // Bu tipi Bicycle sınıfı içinde tanımladığımız için bu bir bağımlı tipdir. + // Bu sınıf dışında kullanmak için tipi Bicycle.Brand olarak kullanmamız gerekir - public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + public BikeBrand Brand; // Enum tipini tanımladıktan sonra alan tipini tanımlayabiliriz - // Static members belong to the type itself rather then specific object. - // You can access them without a reference to any object: + // Static üyeler belirli bir obje yerine kendi tipine aittir + // Onlara bir obje referans göstermeden erişebilirsiniz: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); static public int BicyclesCreated = 0; - // readonly values are set at run time - // they can only be assigned upon declaration or in a constructor + // readonly değerleri çalışma zamanında atanır + // onlara sadece tanımlama yapılarak ya da kurucular içinden atama yapılabilir readonly bool _hasCardsInSpokes = false; // read-only private - // Constructors are a way of creating classes - // This is a default constructor + // Kurucular sınıf oluşturmanın bir yoludur + // Bu bir varsayılan kurucudur. public Bicycle() { - this.Gear = 1; // you can access members of the object with the keyword this - Cadence = 50; // but you don't always need it + this.Gear = 1; // bu objenin üyelerine this anahtar kelimesi ile ulaşılır + Cadence = 50; // ama her zaman buna ihtiyaç duyulmaz _speed = 5; Name = "Bontrager"; Brand = BikeBrand.AIST; BicyclesCreated++; } - // This is a specified constructor (it contains arguments) + // Bu belirlenmiş bir kurucudur. (argümanlar içerir) public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes, BikeBrand brand) - : base() // calls base first + : base() // önce base'i çağırın { Gear = startGear; Cadence = startCadence; @@ -630,20 +626,20 @@ on a new line! ""Wow!"", the masses cried"; Brand = brand; } - // Constructors can be chained + // Kurucular zincirleme olabilir public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : this(startCadence, startSpeed, 0, "big wheels", true, brand) { } - // Function Syntax: - // () + // Fonksiyon Sözdizimi: + // () - // classes can implement getters and setters for their fields - // or they can implement properties (this is the preferred way in C#) + // sınıflar getter ve setter'ları alanları için kendisi uygular + // veya kendisi özellikleri uygulayabilir (C# da tercih edilen yol budur) - // Method parameters can have default values. - // In this case, methods can be called with these parameters omitted + // Metod parametreleri varsayılan değerlere sahip olabilir. + // Bu durumda, metodlar bu parametreler olmadan çağırılabilir. public void SpeedUp(int increment = 1) { _speed += increment; -- cgit v1.2.3 From 3f305ab2831b9e3a1ca9dce35ab42386989e9a61 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:07:15 +0200 Subject: completed --- tr-tr/csharp-tr.html.markdown | 71 +++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 36 deletions(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index cfbee5e8..e5cd3730 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -636,7 +636,7 @@ on a new line! ""Wow!"", the masses cried"; // () // sınıflar getter ve setter'ları alanları için kendisi uygular - // veya kendisi özellikleri uygulayabilir (C# da tercih edilen yol budur) + // veya property'ler eklenebilir (C# da tercih edilen yol budur) // Metod parametreleri varsayılan değerlere sahip olabilir. // Bu durumda, metodlar bu parametreler olmadan çağırılabilir. @@ -650,35 +650,34 @@ on a new line! ""Wow!"", the masses cried"; _speed -= decrement; } - // properties get/set values - // when only data needs to be accessed, consider using properties. - // properties may have either get or set, or both - private bool _hasTassles; // private variable + // property'lerin get/set değerleri + // sadece veri gerektiği zaman erişilebilir, kullanmak için bunu göz önünde bulundurun. + // property'ler sadece get ya da set'e sahip olabilir veya ikisine birden + private bool _hasTassles; // private değişken public bool HasTassles // public accessor { get { return _hasTassles; } set { _hasTassles = value; } } - // You can also define an automatic property in one line - // this syntax will create a backing field automatically. - // You can set an access modifier on either the getter or the setter (or both) - // to restrict its access: + // Ayrıca tek bir satırda otomatik property tanımlayabilirsiniz. + // bu söz dizimi otomatik olarak alan oluşturacaktır. + // Erişimi kısıtlamak için nitelik belirleyiciler getter veya setter'a ya da ikisine birden atanabilir: public bool IsBroken { get; private set; } - // Properties can be auto-implemented + // Property'ler otomatik eklenmiş olabilir public int FrameSize { get; - // you are able to specify access modifiers for either get or set - // this means only Bicycle class can call set on Framesize + // nitelik beliryecileri get veya set için tanımlayabilirsiniz + // bu sadece Bicycle sınıfı Framesize değerine atama yapabilir demektir private set; } - // It's also possible to define custom Indexers on objects. - // All though this is not entirely useful in this example, you - // could do bicycle[0] which yields "chris" to get the first passenger or - // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) + // Ayrıca obje üzerinde özel indeksleyici belirlemek mümkündür. + // Tüm bunlar bu örnek için çok kullanışlı değil, + // bicycle[0] ile ilk yolcu olan "chris" i almak mümkün veya + // bicycle[1] = "lisa" ile yolcuyu atayabilirsiniz. (bariz quattrocycle) private string[] passengers = { "chris", "phil", "darren", "regina" } public string this[int i] @@ -692,7 +691,7 @@ on a new line! ""Wow!"", the masses cried"; } } - //Method to display the attribute values of this Object. + //Bu objenin nitelik değerlerini göstermek için bir metod. public virtual string Info() { return "Gear: " + Gear + @@ -704,23 +703,23 @@ on a new line! ""Wow!"", the masses cried"; ; } - // Methods can also be static. It can be useful for helper methods + // Metodlar static olabilir. Yardımcı metodlar için kullanışlı olabilir. public static bool DidWeCreateEnoughBycles() { - // Within a static method, we only can reference static class members + // Bir static metod içinde sadece static sınıf üyeleri referans gösterilebilir return BicyclesCreated > 9000; - } // If your class only needs static members, consider marking the class itself as static. + } // Eğer sınıfınızın sadece static üyelere ihtiyacı varsa, sınıfın kendisini static yapmayı düşünebilirsiniz. - } // end class Bicycle + } // Bicycle sınıfı sonu - // PennyFarthing is a subclass of Bicycle + // PennyFarthing , Bicycle sınıfının alt sınıfıdır. class PennyFarthing : Bicycle { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) + // (Penny Farthing'ler ön jantı büyük bisikletlerdir. + // Vitesleri yoktur.) - // calling parent constructor + // Ana kurucuyu çağırmak public PennyFarthing(int startCadence, int startSpeed) : base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) { @@ -741,23 +740,23 @@ on a new line! ""Wow!"", the masses cried"; public override string Info() { string result = "PennyFarthing bicycle "; - result += base.ToString(); // Calling the base version of the method + result += base.ToString(); // Metodun temel versiyonunu çağırmak return result; } } - // Interfaces only contain signatures of the members, without the implementation. + // Arabirimler sadece üyelerin izlerini içerir, değerlerini değil. interface IJumpable { - void Jump(int meters); // all interface members are implicitly public + void Jump(int meters); // bütün arbirim üyeleri public'tir } interface IBreakable { - bool Broken { get; } // interfaces can contain properties as well as methods & events + bool Broken { get; } // arabirimler property'leri, metodları ve olayları içerebilir } - // Class can inherit only one other class, but can implement any amount of interfaces + // Sınıflar sadece tek bir sınıftan miras alabilir ama sınırsız sayıda arabirime sahip olabilir class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; @@ -777,8 +776,8 @@ on a new line! ""Wow!"", the masses cried"; } /// - /// Used to connect to DB for LinqToSql example. - /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) + /// LinqToSql örneği veri tabanına bağlanmak için kullanılır. + /// EntityFramework Code First harika! (Ruby'deki ActiveRecord'a benzer, ama iki yönlü) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// public class BikeRepository : DbSet @@ -790,10 +789,10 @@ on a new line! ""Wow!"", the masses cried"; public DbSet Bikes { get; set; } } -} // End Namespace +} // Namespace sonu ``` -## Topics Not Covered +## İşlenmeyen Konular * Flags * Attributes @@ -803,7 +802,7 @@ on a new line! ""Wow!"", the masses cried"; * Winforms * Windows Presentation Foundation (WPF) -## Further Reading +## Daha Fazlasını Okuyun * [DotNetPerls](http://www.dotnetperls.com) * [C# in Depth](http://manning.com/skeet2) @@ -817,4 +816,4 @@ on a new line! ""Wow!"", the masses cried"; -[C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) +[C# Kodlama Adetleri](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) -- cgit v1.2.3 From 634efbb8caaf02feba5f09edd450df1d684e6660 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:08:42 +0200 Subject: csharp/tr --- tr-tr/csharp-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index e5cd3730..c20f90ad 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -789,7 +789,7 @@ on a new line! ""Wow!"", the masses cried"; public DbSet Bikes { get; set; } } -} // Namespace sonu +} // namespace sonu ``` ## İşlenmeyen Konular -- cgit v1.2.3 From 71eda7df766a2be9777d977b8b3b946e37ee82d9 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:11:54 +0200 Subject: csharp/tr --- tr-tr/csharp-tr.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index c20f90ad..3573bbd4 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -11,6 +11,8 @@ filename: LearnCSharp.cs C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. +[Yazım yanlışları ve öneriler için bana ulaşabilirsiniz](mailto:melihmucuk@gmail.com) + [Daha fazlasını okuyun.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) ```c# -- cgit v1.2.3 From 3cb53d9e43143d330cd65c2f29fff93ffa0110f4 Mon Sep 17 00:00:00 2001 From: Melih Mucuk Date: Wed, 31 Dec 2014 20:18:46 +0200 Subject: csharp/tr --- tr-tr/csharp-tr.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 3573bbd4..7755ed44 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -5,8 +5,11 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] +translators: - ["Melih Mucuk", "http://melihmucuk.com"] +lang: tr-tr filename: LearnCSharp.cs + --- C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. -- cgit v1.2.3 From a7dc8b2f4c349d00754d346c78672844523b42ba Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Thu, 1 Jan 2015 21:41:21 -0700 Subject: add Tcl document --- tcl.html.markdown | 372 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 372 insertions(+) create mode 100755 tcl.html.markdown diff --git a/tcl.html.markdown b/tcl.html.markdown new file mode 100755 index 00000000..32619b7c --- /dev/null +++ b/tcl.html.markdown @@ -0,0 +1,372 @@ +--- +language: Tcl +contributors: + - ["Poor Yorick", "http://pooryorick.com/"] +filename: learntcl +--- + +Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a +reusable scripting language for chip design tools he was creating. In 1997 he +was awarded the [ACM Software System +Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl +can be used both as an embeddable scripting language and as a general +programming language. It can also be used as a portable C library, even in +cases where no scripting capability is needed, as it provides data structures +such as dynamic strings, lists, and hash tables. The C library also provides +portable functionality for loading dynamic libraries, string formatting and +code conversion, filesystem operations, network operations, and more. + +Tcl is a pleasure to program in. Its discipline of exposing all programmatic +functionality as commands, including things like loops and mathematical +operations that are usually baked into the syntax of other languages, allows it +to fade into the background of whatever domain-specific functionality a project +needs. Its design of exposing all values as strings, while internally caching +a structured representation, bridges the world of scripting and systems +programming in the best way. Even Lisp is more syntactically heavy than Tcl. + + + +```tcl +#! /bin/env tclsh + +################################################################################ +## 1. Guidelines +################################################################################ + +# Tcl is not Bash or C! This needs to be said because standard shell quoting +# habits almost work in Tcl and it is common for people to pick up Tcl and try +# to get by with syntax they know from another language. It works at first, +# but soon leads to frustration with more complex scripts. + +# Braces are just a quoting mechanism, not a code block constructor or a list +# constructor. Tcl doesn't have either of those things. Braces are used, +# though, to escape special characters in procedure bodies and in strings that +# are formatted as lists. + + +################################################################################ +## 2. Syntax +################################################################################ + +# Every line is a command. The first word is the name of the command, and +# subsequent words are arguments to the command. Words are delimited by +# whitespace. Since every word is a string, no escaping is necessary in the +# simple case. + +set greeting1 Sal +set greeting2 ut +set greeting3 ations + + +#semicolon also delimits commands + +set greeting1 Sal; set greeting2 ut; set greeting3 ations + + +# Dollar sign introduces variable substitution + +set greeting $greeting1$greeting2 + + +# Bracket introduces command substitution + +set greeting $greeting[set greeting3] + + +# backslash suppresses the special meaning of characters + +set amount \$16.42 + + +# backslash adds special meaning to certain characters + +puts lots\nof\n\n\n\n\n\nnewlines + + +# A word enclosed in braces is not subject to any special interpretation or +# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace +set somevar { + This is a literal $ sign, and this \} escaped + brace remains uninterpreted +} + +# In a word enclosed in double quotes, whitespace characters lose their special +# meaning + +set name Neo +set greeting "Hello, $name" + + +#variable names can be any string + +set {first name} New + + +# The brace form of variable substitution handles more complex variable names + +set greeting "Hello, ${first name}" + + +# The "set" command can always be used instead of variable substitution + +set greeting "Hello, [set {first name}]" + + +# To promote the words within a word to individual words of the current +# command, use the expansion operator, "{*}". + +set {*}{name Neo} + +# is equivalent to + +set name Neo + + +# An array is a special variable that is a container for other variables. + +set person(name) Neo +set person(gender) male + +set greeting "Hello, $person(name)" + +# A namespace holds commands and variables + +namespace eval people { + namespace eval person1 { + set name Neo + } +} + +#The full name of a variable includes its enclosing namespace(s), delimited by two colons: + +set greeting "Hello $people::person::name" + + + +################################################################################ +## 3. A Few Notes +################################################################################ + +# From this point on, there is no new syntax. Everything else there is to +# learn about Tcl is about the behaviour of individual commands, and what +# meaning they assign to their arguments. + + +# All other functionality is implemented via commands. To end up with an +# interpreter that can do nothing, delete the global namespace. It's not very +# useful to do such a thing, but it illustrates the nature of Tcl. + +namespace delete :: + + +# Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. + +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +# The full name of a variable can always be used, if desired. + +set people::person1::name Neo + + + +################################################################################ +## 4. Commands +################################################################################ + +# Math can be done with the "expr" command. + +set a 3 +set b 4 +set c [expr {$a + $b}] + +# Since "expr" performs variable substitution on its own, brace the expression +# to prevent Tcl from performing variable substitution first. See +# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. + + +# The "expr" command understands variable and command substitution + +set c [expr {$a + [set b]}] + + +# The "expr" command provides a set of mathematical functions + +set c [expr {pow($a,$b)}] + + +# Mathematical operators are available as commands in the ::tcl::mathop +# namespace + +::tcl::mathop::+ 5 3 + +# Commands can be imported from other namespaces + +namespace import ::tcl::mathop::+ +set result [+ 5 3] + + +# New commands can be created via the "proc" command. + +proc greet name { + return "Hello, $name!" +} + + +# As noted earlier, braces do not construct a code block. Every value, even +# the third argument of the "proc" command, is a string. The previous command +# could be defined without using braces at all: + +proc greet name return\ \"Hello,\ \$name! + + +# When the last parameter is the literal value, "args", it collects all extra +# arguments when the command is invoked + +proc fold {cmd args} { + set res 0 + foreach arg $args { + set res [cmd $res $arg] + } +} + +fold ::tcl::mathop::* 5 3 3 ;# -> 45 + + + +# Conditional execution is implemented as a command + +if {3 > 4} { + puts {This will never happen} +} elseif {4 > 4} { + puts {This will also never happen} +} else { + puts {This will always happen} +} + + +# Loops are implemented as commands. The first, second, and third +# arguments of the "for" command are treated as mathematical expressions + +for {set i 0} {$i < 10} {incr i} { + set res [expr {$res + $i}] +} + + +# The first argument of the "while" command is also treated as a mathematical +# expression + +set i 0 +while {$i < 10} { + incr i 2 +} + + +# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values + +set amounts 10\ 33\ 18 +set amount [lindex $amounts 1] + + +# Braces and backslash can be used to format more complex values in a list. +# There are three items in the following + +set values { + + one\ two + + {three four} + + five\{six + +} + + +# Since a list is a string, string operations could be performed on it, at the +# risk of corrupting the list. + +set values {one two three four} +set values [string map {two \{} $values] ;# $values is no-longer a \ + properly-formatted listwell-formed list + + +# The sure-fire way to get a properly-formmated list is to use "list" commands +set values [list one \{ three four] + +lappend values { } ;# add a single space as an item in the list + + +# Use "eval" to evaluate a value as a script + +eval { + set name Neo + set greeting "Hello, $name" +} + + +# A list can always be passed to "eval" as a script composed of a single +# command. + +eval {set name Neo} +eval [list set greeting "Hello, $name"] + + +# Therefore, when using "eval", use [list] to build up a desired command + +set command {set name} +lappend command {Archibald Sorbisol} +eval $command + + +# A common mistake is not to use list functions + +set command {set name} +append command { Archibald Sorbisol} +eval $command ;# There is an error here, because there are too many arguments \ + to "set" in {set name Archibald Sorbisol} + + +# This mistake can easily occur with the "subst" command. + +set replacement {Archibald Sorbisol} +set command {set name $replacement} +set command [subst $command] +eval $command ;# The same error as before: to many arguments to "set" in \ + {set name Archibald Sorbisol} + + +# The proper way is to format the substituted value using use the "list" +# command. + +set replacement [list {Archibald Sorbisol}] +set command {set name $replacement} +set command [subst $command] +eval $command + + +# It is extremely common to see the "list" command being used to properly +# format values that are substituted into Tcl script templates. There is an +# example of this in the following replacement "while" implementation. + + +#get rid of the built-in "while" command. + +rename ::while {} + + +# Define a new while command with the "proc" command. More sophisticated error +# handling is left as an exercise. + +proc while {condition script} { + if {[uplevel 1 [list expr $condition]]} { + uplevel 1 $script + tailcall [namespace which while] $condition $script + } +} +``` + + -- cgit v1.2.3 From 335d618b1a7ef1793ba30402101c58438bd44603 Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Thu, 1 Jan 2015 21:48:42 -0700 Subject: add reference --- tcl.html.markdown | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 32619b7c..ddf53fe9 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -2,7 +2,6 @@ language: Tcl contributors: - ["Poor Yorick", "http://pooryorick.com/"] -filename: learntcl --- Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a @@ -369,4 +368,10 @@ proc while {condition script} { } ``` +## Reference +[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) + +[Tcl Wiki](http://wiki.tcl.tk) + +[Tcl Subreddit](http://www.reddit.com/r/Tcl) -- cgit v1.2.3 From a80663a4ceeadaa813e17918123eff837e91fc51 Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Fri, 2 Jan 2015 07:56:48 -0700 Subject: better verbiage, add more commands. --- tcl.html.markdown | 159 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 100 insertions(+), 59 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index ddf53fe9..5402ce04 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -49,8 +49,10 @@ programming in the best way. Even Lisp is more syntactically heavy than Tcl. # Every line is a command. The first word is the name of the command, and # subsequent words are arguments to the command. Words are delimited by -# whitespace. Since every word is a string, no escaping is necessary in the -# simple case. +# whitespace. Since every word is a string, in the simple case no special +# markup such as quotes, braces, or backslash, is necessary. Even when quotes +# are used, they are not a string constructor, but just another escaping +# character. set greeting1 Sal set greeting2 ut @@ -58,27 +60,34 @@ set greeting3 ations #semicolon also delimits commands - set greeting1 Sal; set greeting2 ut; set greeting3 ations # Dollar sign introduces variable substitution +set greeting $greeting1$greeting2$greeting3 -set greeting $greeting1$greeting2 +# Bracket introduces command substitution. The result of the command is +# substituted in place of the bracketed script. When the "set" command is +# given only the name of a variable, it returns the value of that variable. +set greeting $greeting1$greeting2[set greeting3] -# Bracket introduces command substitution -set greeting $greeting[set greeting3] +# Command substitution should really be called script substitution, because an +# entire script, not just a command, can be placed between the brackets. The +# "incr" command increments the value of a variable and returns its value. +set greeting $greeting[ + incr i + incr i + incr i +] # backslash suppresses the special meaning of characters - set amount \$16.42 # backslash adds special meaning to certain characters - puts lots\nof\n\n\n\n\n\nnewlines @@ -89,55 +98,48 @@ set somevar { brace remains uninterpreted } + # In a word enclosed in double quotes, whitespace characters lose their special # meaning - set name Neo set greeting "Hello, $name" #variable names can be any string - set {first name} New # The brace form of variable substitution handles more complex variable names - set greeting "Hello, ${first name}" # The "set" command can always be used instead of variable substitution - set greeting "Hello, [set {first name}]" # To promote the words within a word to individual words of the current # command, use the expansion operator, "{*}". - set {*}{name Neo} # is equivalent to - set name Neo # An array is a special variable that is a container for other variables. - set person(name) Neo set person(gender) male - set greeting "Hello, $person(name)" -# A namespace holds commands and variables +# A namespace holds commands and variables namespace eval people { namespace eval person1 { set name Neo } } -#The full name of a variable includes its enclosing namespace(s), delimited by two colons: +#The full name of a variable includes its enclosing namespace(s), delimited by two colons: set greeting "Hello $people::person::name" @@ -146,20 +148,19 @@ set greeting "Hello $people::person::name" ## 3. A Few Notes ################################################################################ -# From this point on, there is no new syntax. Everything else there is to -# learn about Tcl is about the behaviour of individual commands, and what -# meaning they assign to their arguments. +# All other functionality is implemented via commands. From this point on, +# there is no new syntax. Everything else there is to learn about Tcl is about +# the behaviour of individual commands, and what meaning they assign to their +# arguments. -# All other functionality is implemented via commands. To end up with an -# interpreter that can do nothing, delete the global namespace. It's not very -# useful to do such a thing, but it illustrates the nature of Tcl. - +# To end up with an interpreter that can do nothing, delete the global +# namespace. It's not very useful to do such a thing, but it illustrates the +# nature of Tcl. namespace delete :: # Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. - namespace eval people { namespace eval person1 { variable name Neo @@ -168,7 +169,6 @@ namespace eval people { # The full name of a variable can always be used, if desired. - set people::person1::name Neo @@ -178,7 +178,6 @@ set people::person1::name Neo ################################################################################ # Math can be done with the "expr" command. - set a 3 set b 4 set c [expr {$a + $b}] @@ -189,56 +188,52 @@ set c [expr {$a + $b}] # The "expr" command understands variable and command substitution - set c [expr {$a + [set b]}] # The "expr" command provides a set of mathematical functions - set c [expr {pow($a,$b)}] # Mathematical operators are available as commands in the ::tcl::mathop # namespace - ::tcl::mathop::+ 5 3 # Commands can be imported from other namespaces - namespace import ::tcl::mathop::+ set result [+ 5 3] # New commands can be created via the "proc" command. - proc greet name { return "Hello, $name!" } +#multiple parameters can be specified +proc greet {greeting name} { + return "$greeting, $name!" +} + # As noted earlier, braces do not construct a code block. Every value, even # the third argument of the "proc" command, is a string. The previous command -# could be defined without using braces at all: +# rewritten to not use braces at all: +proc greet greeting\ name return\ \"Hello,\ \$name! -proc greet name return\ \"Hello,\ \$name! # When the last parameter is the literal value, "args", it collects all extra # arguments when the command is invoked - proc fold {cmd args} { set res 0 foreach arg $args { set res [cmd $res $arg] } } - fold ::tcl::mathop::* 5 3 3 ;# -> 45 - # Conditional execution is implemented as a command - if {3 > 4} { puts {This will never happen} } elseif {4 > 4} { @@ -250,7 +245,6 @@ if {3 > 4} { # Loops are implemented as commands. The first, second, and third # arguments of the "for" command are treated as mathematical expressions - for {set i 0} {$i < 10} {incr i} { set res [expr {$res + $i}] } @@ -258,7 +252,6 @@ for {set i 0} {$i < 10} {incr i} { # The first argument of the "while" command is also treated as a mathematical # expression - set i 0 while {$i < 10} { incr i 2 @@ -266,14 +259,14 @@ while {$i < 10} { # A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values - set amounts 10\ 33\ 18 set amount [lindex $amounts 1] -# Braces and backslash can be used to format more complex values in a list. -# There are three items in the following - +# Braces and backslash can be used to format more complex values in a list. A +# list looks exactly like a script, except that the newline character and the +# semicolon character lose their special meanings. This feature makes Tcl +# homoiconic. There are three items in the following list. set values { one\ two @@ -286,8 +279,7 @@ set values { # Since a list is a string, string operations could be performed on it, at the -# risk of corrupting the list. - +# risk of corrupting the formatting of the list. set values {one two three four} set values [string map {two \{} $values] ;# $values is no-longer a \ properly-formatted listwell-formed list @@ -295,12 +287,10 @@ set values [string map {two \{} $values] ;# $values is no-longer a \ # The sure-fire way to get a properly-formmated list is to use "list" commands set values [list one \{ three four] - lappend values { } ;# add a single space as an item in the list # Use "eval" to evaluate a value as a script - eval { set name Neo set greeting "Hello, $name" @@ -309,20 +299,17 @@ eval { # A list can always be passed to "eval" as a script composed of a single # command. - eval {set name Neo} eval [list set greeting "Hello, $name"] # Therefore, when using "eval", use [list] to build up a desired command - set command {set name} lappend command {Archibald Sorbisol} eval $command -# A common mistake is not to use list functions - +# A common mistake is not to use list functions when building up a command set command {set name} append command { Archibald Sorbisol} eval $command ;# There is an error here, because there are too many arguments \ @@ -330,7 +317,6 @@ eval $command ;# There is an error here, because there are too many arguments \ # This mistake can easily occur with the "subst" command. - set replacement {Archibald Sorbisol} set command {set name $replacement} set command [subst $command] @@ -340,7 +326,6 @@ eval $command ;# The same error as before: to many arguments to "set" in \ # The proper way is to format the substituted value using use the "list" # command. - set replacement [list {Archibald Sorbisol}] set command {set name $replacement} set command [subst $command] @@ -348,24 +333,80 @@ eval $command # It is extremely common to see the "list" command being used to properly -# format values that are substituted into Tcl script templates. There is an -# example of this in the following replacement "while" implementation. +# format values that are substituted into Tcl script templates. There are +# several examples of this, below. -#get rid of the built-in "while" command. +# The "apply" command evaluates a string as a command. +set cmd {{greeting name} { + return "$greeting, $name!" +}} +apply $cmd Whaddup Neo + + +# The "uplevel" command evaluates a script in some enclosing scope. +proc greet {} { + uplevel {puts "$greeting, $name"} +} + +proc set_double {varname value} { + if {[string is double $value]} { + uplevel [list variable $varname $value] + } else { + error [list {not a double} $value] + } +} + +# The "upvar" command links a variable in the current scope to a variable in +# some enclosing scope +proc set_double {varname value} { + if {[string is double $value]} { + upvar 1 $varname var + set var $value + } else { + error [list {not a double} $value] + } +} + + +#get rid of the built-in "while" command. rename ::while {} # Define a new while command with the "proc" command. More sophisticated error # handling is left as an exercise. - proc while {condition script} { if {[uplevel 1 [list expr $condition]]} { uplevel 1 $script tailcall [namespace which while] $condition $script } } + + +# The "coroutine" command creates a separate call stack, along with a command +# to enter that call stack. The "yield" command suspends execution in that +# stack. +proc countdown {} { + #send something back to the initial "coroutine" command + yield + + set count 3 + while {$count > 1} { + yield [incr count -1] + } + return 0 +} +coroutine countdown1 countdown +coroutine countdown2 countdown +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 +puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 2] ;# -> 1 + + ``` ## Reference -- cgit v1.2.3 From aac20efb70dbd10383c9bfa4dd9108d8a4fda9ce Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Fri, 2 Jan 2015 08:19:41 -0700 Subject: Reworked summary --- tcl.html.markdown | 46 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 9 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 5402ce04..44805b5c 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -13,15 +13,43 @@ programming language. It can also be used as a portable C library, even in cases where no scripting capability is needed, as it provides data structures such as dynamic strings, lists, and hash tables. The C library also provides portable functionality for loading dynamic libraries, string formatting and -code conversion, filesystem operations, network operations, and more. - -Tcl is a pleasure to program in. Its discipline of exposing all programmatic -functionality as commands, including things like loops and mathematical -operations that are usually baked into the syntax of other languages, allows it -to fade into the background of whatever domain-specific functionality a project -needs. Its design of exposing all values as strings, while internally caching -a structured representation, bridges the world of scripting and systems -programming in the best way. Even Lisp is more syntactically heavy than Tcl. +code conversion, filesystem operations, network operations, and more. +Various features of Tcl stand out: + +* Convenient cross-platform networking API + +* Fully virtualized filesystem + +* Stackable I/O channels + +* Asynchronous to the core + +* Full coroutines + +* A threading model recognized as robust and easy to use + + +If Lisp is a list processor, then Tcl is a string processor. All values are +strings. A list is a string format. A procedure definition is a string +format. To achieve performance, Tcl internally caches structured +representations of these values. The list commands, for example, operate on +the internal cached representation, and Tcl takes care of updating the string +representation if it is ever actually needed in the script. The copy-on-write +design of Tcl allows script authors can pass around large data values without +actually incurring additional memory overhead. Procedures are automatically +byte-compiled unless they use the more dynamic commands such as "uplevel", +"upvar", and "trace". + +Tcl is a pleasure to program in. It will appeal to hacker types who find Lisp, +Forth, or Smalltalk interesting, as well as to engineers and scientists who +just want to get down to business with a tool that bends to their will. Its +discipline of exposing all programmatic functionality as commands, including +things like loops and mathematical operations that are usually baked into the +syntax of other languages, allows it to fade into the background of whatever +domain-specific functionality a project needs. It's syntax, which is even +lighter that that of Lisp, just gets out of the way. + + -- cgit v1.2.3 From e059cd98f32fbd7793f2e8622cb6061c1a142146 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 2 Jan 2015 19:53:49 +0000 Subject: Let's see how factor highlighting looks in forth --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 570e12ed..4457e607 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -12,7 +12,7 @@ such as Open Firmware. It's also used by NASA. Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. -```forth +```factor \ This is a comment ( This is also a comment but it's only used when defining words ) -- cgit v1.2.3 From 732cdbed1ad345f2b826254bc7f0b6283124955e Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 2 Jan 2015 20:33:47 +0000 Subject: Update forth.html.markdown --- forth.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/forth.html.markdown b/forth.html.markdown index 4457e607..f7c0bf34 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -12,7 +12,7 @@ such as Open Firmware. It's also used by NASA. Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. -```factor +``` \ This is a comment ( This is also a comment but it's only used when defining words ) -- cgit v1.2.3 From 6263dda6de1f9163a80a3ceab2a05666149e6a79 Mon Sep 17 00:00:00 2001 From: sunxb10 Date: Sat, 3 Jan 2015 20:49:39 +0800 Subject: Chinese translation of MATLAB tutorial --- zh-cn/matlab-cn.html.markdown | 491 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 491 insertions(+) create mode 100644 zh-cn/matlab-cn.html.markdown diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown new file mode 100644 index 00000000..77ba765a --- /dev/null +++ b/zh-cn/matlab-cn.html.markdown @@ -0,0 +1,491 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] +translators: + - ["sunxb10", "https://github.com/sunxb10"] +lang: zh-cn +--- + +MATLAB 是 MATrix LABoratory (矩阵实验室)的缩写,它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。 + +如果您有任何需要反馈或交流的内容,请联系本教程作者[@the_ozzinator](https://twitter.com/the_ozzinator)、[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。 + +```matlab +% 以百分号作为注释符 + +%{ +多行注释 +可以 +这样 +表示 +%} + +% 指令可以随意跨行,但需要在跨行处用 '...' 标明: + a = 1 + 2 + ... + + 4 + +% 可以在MATLAB中直接向操作系统发出指令 +!ping google.com + +who % 显示内存中的所有变量 +whos % 显示内存中的所有变量以及它们的类型 +clear % 清除内存中的所有变量 +clear('A') % 清除指定的变量 +openvar('A') % 在变量编辑器中编辑指定变量 + +clc % 清除命令窗口中显示的所有指令 +diary % 将命令窗口中的内容写入本地文件 +ctrl-c % 终止当前计算 + +edit('myfunction.m') % 在编辑器中打开指定函数或脚本 +type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码 + +profile on % 打开 profile 代码分析工具 +profile of % 关闭 profile 代码分析工具 +profile viewer % 查看 profile 代码分析工具的分析结果 + +help command % 在命令窗口中显示指定命令的帮助文档 +doc command % 在帮助窗口中显示指定命令的帮助文档 +lookfor command % 在所有 MATLAB 内置函数的头部注释块的第一行中搜索指定命令 +lookfor command -all % 在所有 MATLAB 内置函数的整个头部注释块中搜索指定命令 + + +% 输出格式 +format short % 浮点数保留 4 位小数 +format long % 浮点数保留 15 位小数 +format bank % 金融格式,浮点数只保留 2 位小数 +fprintf('text') % 在命令窗口中显示 "text" +disp('text') % 在命令窗口中显示 "text" + + +% 变量与表达式 +myVariable = 4 % 命令窗口中将新创建的变量 +myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果 +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 + + +% 调用函数有两种方式: +% 标准函数语法: +load('myFile.mat', 'y') % 参数放在括号内,以英文逗号分隔 +% 指令语法: +load myFile.mat y % 不加括号,以空格分隔参数 +% 注意在指令语法中参数不需要加引号:在这种语法下,所有输入参数都只能是文本文字, +% 不能是变量的具体值,同样也不能是输出变量 +[V,D] = eig(A); % 这条函数调用无法转换成等价的指令语法 +[~,D] = eig(A); % 如果结果中只需要 D 而不需要 V 则可以这样写 + + + +% 逻辑运算 +1 > 5 % 假,ans = 0 +10 >= 10 % 真,ans = 1 +3 ~= 4 % 不等于 -> ans = 1 +3 == 3 % 等于 -> ans = 1 +3 > 1 && 4 > 1 % 与 -> ans = 1 +3 > 1 || 4 > 1 % 或 -> ans = 1 +~1 % 非 -> ans = 0 + +% 逻辑运算可直接应用于矩阵,运算结果也是矩阵 +A > 5 +% 对矩阵中每个元素做逻辑运算,若为真,则在运算结果的矩阵中对应位置的元素就是 1 +A( A > 5 ) +% 如此返回的向量,其元素就是 A 矩阵中所有逻辑运算为真的元素 + +% 字符串 +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString +b = '字符串' % MATLAB目前已经可以支持包括中文在内的多种文字 +length(b) % ans = 3 +b(2) % ans = 符 +[b,b] % ans = 字符串字符串 + + +% 元组(cell 数组) +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - 返回一个元组 +char(a(1)) % ans = one - 返回一个字符串 + + +% 结构体 +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; + + +% 向量 +x = [4 32 53 7 1] +x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % 列向量 + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + + +% 矩阵 +A = [1 2 3; 4 5 6; 7 8 9] +% 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素 +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6,A(row, column) +A(6) % ans = 8 +% (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素) + + +A(2,3) = 42 % 将第 2 行第 3 列的元素设为 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % 取原矩阵中的一块作为新矩阵 +%ans = + +% 5 42 +% 8 9 + +A(:,1) % 第 1 列的所有元素 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % 第 1 行的所有元素 +%ans = + +% 1 2 3 + +[A ; A] % 将两个矩阵上下相接构成新矩阵 +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% 等价于 +vertcat(A, A); + + +[A , A] % 将两个矩阵左右相接构成新矩阵 + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% 等价于 +horzcat(A, A); + + +A(:, [3 1 2]) % 重新排布原矩阵的各列 +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % 返回矩阵的行数和列数,ans = 3 3 + +A(1, :) =[] % 删除矩阵的第 1 行 +A(:, 1) =[] % 删除矩阵的第 1 列 + +transpose(A) % 矩阵转置,等价于 A' +ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数) + + +% 元素运算 vs. 矩阵运算 +% 单独运算符就是对矩阵整体进行矩阵运算 +% 在运算符加上英文句点就是对矩阵中的元素进行元素计算 +% 示例如下: +A * B % 矩阵乘法,要求 A 的列数等于 B 的行数 +A .* B % 元素乘法,要求 A 和 B 形状一致(A 的行数等于 B 的行数, A 的列数等于 B 的列数) +% 元素乘法的结果是与 A 和 B 形状一致的矩阵,其每个元素等于 A 对应位置的元素乘 B 对应位置的元素 + +% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算: +exp(A) % 对矩阵中每个元素做指数运算 +expm(A) % 对矩阵整体做指数运算 +sqrt(A) % 对矩阵中每个元素做开方运算 +sqrtm(A) % 对矩阵整体做开放运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵) + + +% 绘图 +x = 0:.10:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi(pi 就是圆周率) +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 轴范围是从 0 到 2*pi,y 轴范围是从 -1 到 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % 在同一张图中绘制多条曲线 +legend('Line 1 label', 'Line 2 label') % 为图片加注图例 +% 图例数量应当小于或等于实际绘制的曲线数目,从 plot 绘制的第一条曲线开始对应 + +% 在同一张图上绘制多条曲线的另一种方法: +% 使用 hold on,令系统保留前次绘图结果并在其上直接叠加新的曲线, +% 如果没有 hold on,则每个 plot 都会首先清除之前的绘图结果再进行绘制。 +% 在 hold on 和 hold off 中可以放置任意多的 plot 指令, +% 它们和 hold on 前最后一个 plot 指令的结果都将显示在同一张图中。 +plot(x, y1) +hold on +plot(x, y2) +plot(x, y3) +plot(x, y4) +hold off + +loglog(x, y) % 对数—对数绘图 +semilogx(x, y) % 半对数(x 轴对数)绘图 +semilogy(x, y) % 半对数(y 轴对数)绘图 + +fplot (@(x) x^2, [2,5]) % 绘制函数 x^2 在 [2, 5] 区间的曲线 + +grid on % 在绘制的图中显示网格,使用 grid off 可取消网格显示 +axis square % 将当前坐标系设定为正方形(保证在图形显示上各轴等长) +axis equal % 将当前坐标系设定为相等(保证在实际数值上各轴等长) + +scatter(x, y); % 散点图 +hist(x); % 直方图 + +z = sin(x); +plot3(x,y,z); % 绘制三维曲线 + +pcolor(A) % 伪彩色图(热图) +contour(A) % 等高线图 +mesh(A) % 网格曲面图 + +h = figure % 创建新的图片对象并返回其句柄 h +figure(h) % 将句柄 h 对应的图片作为当前图片 +close(h) % 关闭句柄 h 对应的图片 +close all % 关闭 MATLAB 中所用打开的图片 +close % 关闭当前图片 + +shg % 显示图形窗口 +clf clear % 清除图形窗口中的图像,并重置图像属性 + +% 图像属性可以通过图像句柄进行设定 +% 在创建图像时可以保存图像句柄以便于设置 +% 也可以用 gcf 函数返回当前图像的句柄 +h = plot(x, y); % 在创建图像时显式地保存图像句柄 +set(h, 'Color', 'r') +% 颜色代码:'y' 黄色,'m' 洋红色,'c' 青色,'r' 红色,'g' 绿色,'b' 蓝色,'w' 白色,'k' 黑色 +set(h, 'Color', [0.5, 0.5, 0.4]) +% 也可以使用 RGB 值指定颜色 +set(h, 'LineStyle', '--') +% 线型代码:'--' 实线,'---' 虚线,':' 点线,'-.' 点划线,'none' 不划线 +get(h, 'LineStyle') +% 获取当前句柄的线型 + + +% 用 gca 函数返回当前图像的坐标轴句柄 +set(gca, 'XDir', 'reverse'); % 令 x 轴反向 + +% 用 subplot 指令创建平铺排列的多张子图 +subplot(2,3,1); % 选择 2 x 3 排列的子图中的第 1 张图 +plot(x1); title('First Plot') % 在选中的图中绘图 +subplot(2,3,2); % 选择 2 x 3 排列的子图中的第 2 张图 +plot(x2); title('Second Plot') % 在选中的图中绘图 + + +% 要调用函数或脚本,必须保证它们在你的当前工作目录中 +path % 显示当前工作目录 +addpath /path/to/dir % 将指定路径加入到当前工作目录中 +rmpath /path/to/dir % 将指定路径从当前工作目录中删除 +cd /path/to/move/into % 以制定路径作为当前工作目录 + + +% 变量可保存到 .mat 格式的本地文件 +save('myFileName.mat') % 保存当前工作空间中的所有变量 +load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 + + +% .m 脚本文件 +% 脚本文件是一个包含多条 MATLAB 指令的外部文件,以 .m 为后缀名 +% 使用脚本文件可以避免在命令窗口中重复输入冗长的指令 + + +% .m 函数文件 +% 与脚本文件类似,同样以 .m 作为后缀名 +% 但函数文件可以接受用户输入的参数并返回运算结果 +% 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突 +% 函数文件的名称应当与其所定义的函数的名称一致(比如下面例子中函数文件就应命名为 double_input.m) +% 使用 'help double_input.m' 可返回函数定义中第一行注释信息 +function output = double_input(x) + % double_input(x) 返回 x 的 2 倍 + output = 2*x; +end +double_input(6) % ans = 12 + + +% 同样还可以定义子函数和内嵌函数 +% 子函数与主函数放在同一个函数文件中,且只能被这个主函数调用 +% 内嵌函数放在另一个函数体内,可以直接访问被嵌套函数的各个变量 + + +% 使用匿名函数可以不必创建 .m 函数文件 +% 匿名函数适用于快速定义某函数以便传递给另一指令或函数(如绘图、积分、求根、求极值等) +% 下面示例的匿名函数返回输入参数的平方根,可以使用句柄 sqr 进行调用: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % find out more + + +% 接受用户输入 +a = input('Enter the value: ') + + +% 从文件中读取数据 +fopen(filename) +% 类似函数还有 xlsread(excel 文件)、importdata(CSV 文件)、imread(图像文件) + + +% 输出 +disp(a) % 在命令窗口中打印变量 a 的值 +disp('Hello World') % 在命令窗口中打印字符串 +fprintf % 按照指定格式在命令窗口中打印内容 + +% 条件语句(if 和 elseif 语句中的括号并非必需,但推荐加括号避免混淆) +if (a > 15) + disp('Greater than 15') +elseif (a == 23) + disp('a is 23') +else + disp('neither condition met') +end + +% 循环语句 +% 注意:对向量或矩阵使用循环语句进行元素遍历的效率很低!! +% 注意:只要有可能,就尽量使用向量或矩阵的整体运算取代逐元素循环遍历!! +% MATLAB 在开发时对向量和矩阵运算做了专门优化,做向量和矩阵整体运算的效率高于循环语句 +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + + +% 程序运行计时:'tic' 是计时开始,'toc' 是计时结束并打印结果 +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + + +% 链接 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 代表具体版本号 +% 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载 +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % SQL 语句 +a = fetch(conn, sql) % a 即包含所需数据 + + +% 常用数学函数 +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 % 均匀分布的伪随机浮点数 +randi % 均匀分布的伪随机整数 +randn % 正态分布的伪随机浮点数 + +% 常用常数 +pi +NaN +inf + +% 求解矩阵方程(如果方程无解,则返回最小二乘近似解) +% \ 操作符等价于 mldivide 函数,/ 操作符等价于 mrdivide 函数 +x=A\b % 求解 Ax=b,比先求逆再左乘 inv(A)*b 更加高效、准确 +x=b/A % 求解 xA=b + +inv(A) % 逆矩阵 +pinv(A) % 伪逆矩阵 + + +% 常用矩阵函数 +zeros(m, n) % m x n 阶矩阵,元素全为 0 +ones(m, n) % m x n 阶矩阵,元素全为 1 +diag(A) % 返回矩阵 A 的对角线元素 +diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素 +eye(m, n) % m x n 阶单位矩阵 +linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点 +inv(A) % 矩阵 A 的逆矩阵 +det(A) % 矩阵 A 的行列式 +eig(A) % 矩阵 A 的特征值和特征向量 +trace(A) % 矩阵 A 的迹(即对角线元素之和),等价于 sum(diag(A)) +isempty(A) % 测试 A 是否为空 +all(A) % 测试 A 中所有元素是否都非 0 或都为真(逻辑值) +any(A) % 测试 A 中是否有元素非 0 或为真(逻辑值) +isequal(A, B) % 测试 A 和 B是否相等 +numel(A) % 矩阵 A 的元素个数 +triu(x) % 返回 x 的上三角这部分 +tril(x) % 返回 x 的下三角这部分 +cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积) +dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长 +transpose(A) % A 的转置,等价于 A' +fliplr(A) % 将一个矩阵左右翻转 +flipud(A) % 将一个矩阵上下翻转 + +% 矩阵分解 +[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵 +[P, D] = eig(A) % 特征值分解:AP = PD,D 是由特征值构成的对角阵,P 的各列就是对应的特征向量 +[U, S, V] = svd(X) % 奇异值分解:XV = US,U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵 + +% 常用向量函数 +max % 最大值 +min % 最小值 +length % 元素个数 +sort % 按升序排列 +sum % 各元素之和 +prod % 各元素之积 +mode % 众数 +median % 中位数 +mean % 平均值 +std % 标准差 +perms(x) % x 元素的全排列 + +``` + +## 相关资料 + +* 官方网页:[http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* 官方论坛:[http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) -- cgit v1.2.3 From d7672a2bc53dd8b81c4da8c620178cc2458c9238 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sat, 3 Jan 2015 19:48:53 +0100 Subject: Added warning on return usage --- scala.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 35645922..cfc5a1e9 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -198,7 +198,9 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most -// def that surrounds it. It has no effect on anonymous functions. For example: +// def that surrounds it. +// WARNING: Using return in Scala is error-prone and should be avoided. +// It has no effect on anonymous functions. For example: def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) -- cgit v1.2.3 From 79b730dcaa8994cb6b58af1e25a5aa9e06f48471 Mon Sep 17 00:00:00 2001 From: Poor Yorick Date: Sun, 4 Jan 2015 23:00:23 -0700 Subject: add filename: learntcl.tcl --- tcl.html.markdown | 893 +++++++++++++++++++++++++++--------------------------- 1 file changed, 447 insertions(+), 446 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 44805b5c..f2d92fcd 100755 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -1,446 +1,447 @@ ---- -language: Tcl -contributors: - - ["Poor Yorick", "http://pooryorick.com/"] ---- - -Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a -reusable scripting language for chip design tools he was creating. In 1997 he -was awarded the [ACM Software System -Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl -can be used both as an embeddable scripting language and as a general -programming language. It can also be used as a portable C library, even in -cases where no scripting capability is needed, as it provides data structures -such as dynamic strings, lists, and hash tables. The C library also provides -portable functionality for loading dynamic libraries, string formatting and -code conversion, filesystem operations, network operations, and more. -Various features of Tcl stand out: - -* Convenient cross-platform networking API - -* Fully virtualized filesystem - -* Stackable I/O channels - -* Asynchronous to the core - -* Full coroutines - -* A threading model recognized as robust and easy to use - - -If Lisp is a list processor, then Tcl is a string processor. All values are -strings. A list is a string format. A procedure definition is a string -format. To achieve performance, Tcl internally caches structured -representations of these values. The list commands, for example, operate on -the internal cached representation, and Tcl takes care of updating the string -representation if it is ever actually needed in the script. The copy-on-write -design of Tcl allows script authors can pass around large data values without -actually incurring additional memory overhead. Procedures are automatically -byte-compiled unless they use the more dynamic commands such as "uplevel", -"upvar", and "trace". - -Tcl is a pleasure to program in. It will appeal to hacker types who find Lisp, -Forth, or Smalltalk interesting, as well as to engineers and scientists who -just want to get down to business with a tool that bends to their will. Its -discipline of exposing all programmatic functionality as commands, including -things like loops and mathematical operations that are usually baked into the -syntax of other languages, allows it to fade into the background of whatever -domain-specific functionality a project needs. It's syntax, which is even -lighter that that of Lisp, just gets out of the way. - - - - - -```tcl -#! /bin/env tclsh - -################################################################################ -## 1. Guidelines -################################################################################ - -# Tcl is not Bash or C! This needs to be said because standard shell quoting -# habits almost work in Tcl and it is common for people to pick up Tcl and try -# to get by with syntax they know from another language. It works at first, -# but soon leads to frustration with more complex scripts. - -# Braces are just a quoting mechanism, not a code block constructor or a list -# constructor. Tcl doesn't have either of those things. Braces are used, -# though, to escape special characters in procedure bodies and in strings that -# are formatted as lists. - - -################################################################################ -## 2. Syntax -################################################################################ - -# Every line is a command. The first word is the name of the command, and -# subsequent words are arguments to the command. Words are delimited by -# whitespace. Since every word is a string, in the simple case no special -# markup such as quotes, braces, or backslash, is necessary. Even when quotes -# are used, they are not a string constructor, but just another escaping -# character. - -set greeting1 Sal -set greeting2 ut -set greeting3 ations - - -#semicolon also delimits commands -set greeting1 Sal; set greeting2 ut; set greeting3 ations - - -# Dollar sign introduces variable substitution -set greeting $greeting1$greeting2$greeting3 - - -# Bracket introduces command substitution. The result of the command is -# substituted in place of the bracketed script. When the "set" command is -# given only the name of a variable, it returns the value of that variable. -set greeting $greeting1$greeting2[set greeting3] - - -# Command substitution should really be called script substitution, because an -# entire script, not just a command, can be placed between the brackets. The -# "incr" command increments the value of a variable and returns its value. -set greeting $greeting[ - incr i - incr i - incr i -] - - -# backslash suppresses the special meaning of characters -set amount \$16.42 - - -# backslash adds special meaning to certain characters -puts lots\nof\n\n\n\n\n\nnewlines - - -# A word enclosed in braces is not subject to any special interpretation or -# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace -set somevar { - This is a literal $ sign, and this \} escaped - brace remains uninterpreted -} - - -# In a word enclosed in double quotes, whitespace characters lose their special -# meaning -set name Neo -set greeting "Hello, $name" - - -#variable names can be any string -set {first name} New - - -# The brace form of variable substitution handles more complex variable names -set greeting "Hello, ${first name}" - - -# The "set" command can always be used instead of variable substitution -set greeting "Hello, [set {first name}]" - - -# To promote the words within a word to individual words of the current -# command, use the expansion operator, "{*}". -set {*}{name Neo} - -# is equivalent to -set name Neo - - -# An array is a special variable that is a container for other variables. -set person(name) Neo -set person(gender) male -set greeting "Hello, $person(name)" - - -# A namespace holds commands and variables -namespace eval people { - namespace eval person1 { - set name Neo - } -} - - -#The full name of a variable includes its enclosing namespace(s), delimited by two colons: -set greeting "Hello $people::person::name" - - - -################################################################################ -## 3. A Few Notes -################################################################################ - -# All other functionality is implemented via commands. From this point on, -# there is no new syntax. Everything else there is to learn about Tcl is about -# the behaviour of individual commands, and what meaning they assign to their -# arguments. - - -# To end up with an interpreter that can do nothing, delete the global -# namespace. It's not very useful to do such a thing, but it illustrates the -# nature of Tcl. -namespace delete :: - - -# Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. -namespace eval people { - namespace eval person1 { - variable name Neo - } -} - - -# The full name of a variable can always be used, if desired. -set people::person1::name Neo - - - -################################################################################ -## 4. Commands -################################################################################ - -# Math can be done with the "expr" command. -set a 3 -set b 4 -set c [expr {$a + $b}] - -# Since "expr" performs variable substitution on its own, brace the expression -# to prevent Tcl from performing variable substitution first. See -# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. - - -# The "expr" command understands variable and command substitution -set c [expr {$a + [set b]}] - - -# The "expr" command provides a set of mathematical functions -set c [expr {pow($a,$b)}] - - -# Mathematical operators are available as commands in the ::tcl::mathop -# namespace -::tcl::mathop::+ 5 3 - -# Commands can be imported from other namespaces -namespace import ::tcl::mathop::+ -set result [+ 5 3] - - -# New commands can be created via the "proc" command. -proc greet name { - return "Hello, $name!" -} - -#multiple parameters can be specified -proc greet {greeting name} { - return "$greeting, $name!" -} - - -# As noted earlier, braces do not construct a code block. Every value, even -# the third argument of the "proc" command, is a string. The previous command -# rewritten to not use braces at all: -proc greet greeting\ name return\ \"Hello,\ \$name! - - - -# When the last parameter is the literal value, "args", it collects all extra -# arguments when the command is invoked -proc fold {cmd args} { - set res 0 - foreach arg $args { - set res [cmd $res $arg] - } -} -fold ::tcl::mathop::* 5 3 3 ;# -> 45 - - -# Conditional execution is implemented as a command -if {3 > 4} { - puts {This will never happen} -} elseif {4 > 4} { - puts {This will also never happen} -} else { - puts {This will always happen} -} - - -# Loops are implemented as commands. The first, second, and third -# arguments of the "for" command are treated as mathematical expressions -for {set i 0} {$i < 10} {incr i} { - set res [expr {$res + $i}] -} - - -# The first argument of the "while" command is also treated as a mathematical -# expression -set i 0 -while {$i < 10} { - incr i 2 -} - - -# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values -set amounts 10\ 33\ 18 -set amount [lindex $amounts 1] - - -# Braces and backslash can be used to format more complex values in a list. A -# list looks exactly like a script, except that the newline character and the -# semicolon character lose their special meanings. This feature makes Tcl -# homoiconic. There are three items in the following list. -set values { - - one\ two - - {three four} - - five\{six - -} - - -# Since a list is a string, string operations could be performed on it, at the -# risk of corrupting the formatting of the list. -set values {one two three four} -set values [string map {two \{} $values] ;# $values is no-longer a \ - properly-formatted listwell-formed list - - -# The sure-fire way to get a properly-formmated list is to use "list" commands -set values [list one \{ three four] -lappend values { } ;# add a single space as an item in the list - - -# Use "eval" to evaluate a value as a script -eval { - set name Neo - set greeting "Hello, $name" -} - - -# A list can always be passed to "eval" as a script composed of a single -# command. -eval {set name Neo} -eval [list set greeting "Hello, $name"] - - -# Therefore, when using "eval", use [list] to build up a desired command -set command {set name} -lappend command {Archibald Sorbisol} -eval $command - - -# A common mistake is not to use list functions when building up a command -set command {set name} -append command { Archibald Sorbisol} -eval $command ;# There is an error here, because there are too many arguments \ - to "set" in {set name Archibald Sorbisol} - - -# This mistake can easily occur with the "subst" command. -set replacement {Archibald Sorbisol} -set command {set name $replacement} -set command [subst $command] -eval $command ;# The same error as before: to many arguments to "set" in \ - {set name Archibald Sorbisol} - - -# The proper way is to format the substituted value using use the "list" -# command. -set replacement [list {Archibald Sorbisol}] -set command {set name $replacement} -set command [subst $command] -eval $command - - -# It is extremely common to see the "list" command being used to properly -# format values that are substituted into Tcl script templates. There are -# several examples of this, below. - - -# The "apply" command evaluates a string as a command. -set cmd {{greeting name} { - return "$greeting, $name!" -}} -apply $cmd Whaddup Neo - - -# The "uplevel" command evaluates a script in some enclosing scope. -proc greet {} { - uplevel {puts "$greeting, $name"} -} - -proc set_double {varname value} { - if {[string is double $value]} { - uplevel [list variable $varname $value] - } else { - error [list {not a double} $value] - } -} - - -# The "upvar" command links a variable in the current scope to a variable in -# some enclosing scope -proc set_double {varname value} { - if {[string is double $value]} { - upvar 1 $varname var - set var $value - } else { - error [list {not a double} $value] - } -} - - -#get rid of the built-in "while" command. -rename ::while {} - - -# Define a new while command with the "proc" command. More sophisticated error -# handling is left as an exercise. -proc while {condition script} { - if {[uplevel 1 [list expr $condition]]} { - uplevel 1 $script - tailcall [namespace which while] $condition $script - } -} - - -# The "coroutine" command creates a separate call stack, along with a command -# to enter that call stack. The "yield" command suspends execution in that -# stack. -proc countdown {} { - #send something back to the initial "coroutine" command - yield - - set count 3 - while {$count > 1} { - yield [incr count -1] - } - return 0 -} -coroutine countdown1 countdown -coroutine countdown2 countdown -puts [countdown 1] ;# -> 2 -puts [countdown 2] ;# -> 2 -puts [countdown 1] ;# -> 1 -puts [countdown 1] ;# -> 0 -puts [coundown 1] ;# -> invalid command name "countdown1" -puts [countdown 2] ;# -> 1 - - -``` - -## Reference - -[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) - -[Tcl Wiki](http://wiki.tcl.tk) - -[Tcl Subreddit](http://www.reddit.com/r/Tcl) +--- +language: Tcl +contributors: + - ["Poor Yorick", "http://pooryorick.com/"] +filename: learntcl.tcl +--- + +Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a +reusable scripting language for chip design tools he was creating. In 1997 he +was awarded the [ACM Software System +Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl +can be used both as an embeddable scripting language and as a general +programming language. It can also be used as a portable C library, even in +cases where no scripting capability is needed, as it provides data structures +such as dynamic strings, lists, and hash tables. The C library also provides +portable functionality for loading dynamic libraries, string formatting and +code conversion, filesystem operations, network operations, and more. +Various features of Tcl stand out: + +* Convenient cross-platform networking API + +* Fully virtualized filesystem + +* Stackable I/O channels + +* Asynchronous to the core + +* Full coroutines + +* A threading model recognized as robust and easy to use + + +If Lisp is a list processor, then Tcl is a string processor. All values are +strings. A list is a string format. A procedure definition is a string +format. To achieve performance, Tcl internally caches structured +representations of these values. The list commands, for example, operate on +the internal cached representation, and Tcl takes care of updating the string +representation if it is ever actually needed in the script. The copy-on-write +design of Tcl allows script authors can pass around large data values without +actually incurring additional memory overhead. Procedures are automatically +byte-compiled unless they use the more dynamic commands such as "uplevel", +"upvar", and "trace". + +Tcl is a pleasure to program in. It will appeal to hacker types who find Lisp, +Forth, or Smalltalk interesting, as well as to engineers and scientists who +just want to get down to business with a tool that bends to their will. Its +discipline of exposing all programmatic functionality as commands, including +things like loops and mathematical operations that are usually baked into the +syntax of other languages, allows it to fade into the background of whatever +domain-specific functionality a project needs. It's syntax, which is even +lighter that that of Lisp, just gets out of the way. + + + + + +```tcl +#! /bin/env tclsh + +################################################################################ +## 1. Guidelines +################################################################################ + +# Tcl is not Bash or C! This needs to be said because standard shell quoting +# habits almost work in Tcl and it is common for people to pick up Tcl and try +# to get by with syntax they know from another language. It works at first, +# but soon leads to frustration with more complex scripts. + +# Braces are just a quoting mechanism, not a code block constructor or a list +# constructor. Tcl doesn't have either of those things. Braces are used, +# though, to escape special characters in procedure bodies and in strings that +# are formatted as lists. + + +################################################################################ +## 2. Syntax +################################################################################ + +# Every line is a command. The first word is the name of the command, and +# subsequent words are arguments to the command. Words are delimited by +# whitespace. Since every word is a string, in the simple case no special +# markup such as quotes, braces, or backslash, is necessary. Even when quotes +# are used, they are not a string constructor, but just another escaping +# character. + +set greeting1 Sal +set greeting2 ut +set greeting3 ations + + +#semicolon also delimits commands +set greeting1 Sal; set greeting2 ut; set greeting3 ations + + +# Dollar sign introduces variable substitution +set greeting $greeting1$greeting2$greeting3 + + +# Bracket introduces command substitution. The result of the command is +# substituted in place of the bracketed script. When the "set" command is +# given only the name of a variable, it returns the value of that variable. +set greeting $greeting1$greeting2[set greeting3] + + +# Command substitution should really be called script substitution, because an +# entire script, not just a command, can be placed between the brackets. The +# "incr" command increments the value of a variable and returns its value. +set greeting $greeting[ + incr i + incr i + incr i +] + + +# backslash suppresses the special meaning of characters +set amount \$16.42 + + +# backslash adds special meaning to certain characters +puts lots\nof\n\n\n\n\n\nnewlines + + +# A word enclosed in braces is not subject to any special interpretation or +# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace +set somevar { + This is a literal $ sign, and this \} escaped + brace remains uninterpreted +} + + +# In a word enclosed in double quotes, whitespace characters lose their special +# meaning +set name Neo +set greeting "Hello, $name" + + +#variable names can be any string +set {first name} New + + +# The brace form of variable substitution handles more complex variable names +set greeting "Hello, ${first name}" + + +# The "set" command can always be used instead of variable substitution +set greeting "Hello, [set {first name}]" + + +# To promote the words within a word to individual words of the current +# command, use the expansion operator, "{*}". +set {*}{name Neo} + +# is equivalent to +set name Neo + + +# An array is a special variable that is a container for other variables. +set person(name) Neo +set person(gender) male +set greeting "Hello, $person(name)" + + +# A namespace holds commands and variables +namespace eval people { + namespace eval person1 { + set name Neo + } +} + + +#The full name of a variable includes its enclosing namespace(s), delimited by two colons: +set greeting "Hello $people::person::name" + + + +################################################################################ +## 3. A Few Notes +################################################################################ + +# All other functionality is implemented via commands. From this point on, +# there is no new syntax. Everything else there is to learn about Tcl is about +# the behaviour of individual commands, and what meaning they assign to their +# arguments. + + +# To end up with an interpreter that can do nothing, delete the global +# namespace. It's not very useful to do such a thing, but it illustrates the +# nature of Tcl. +namespace delete :: + + +# Because of name resolution behaviour, its safer to use the "variable" command to declare or to assign a value to a namespace. +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +# The full name of a variable can always be used, if desired. +set people::person1::name Neo + + + +################################################################################ +## 4. Commands +################################################################################ + +# Math can be done with the "expr" command. +set a 3 +set b 4 +set c [expr {$a + $b}] + +# Since "expr" performs variable substitution on its own, brace the expression +# to prevent Tcl from performing variable substitution first. See +# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. + + +# The "expr" command understands variable and command substitution +set c [expr {$a + [set b]}] + + +# The "expr" command provides a set of mathematical functions +set c [expr {pow($a,$b)}] + + +# Mathematical operators are available as commands in the ::tcl::mathop +# namespace +::tcl::mathop::+ 5 3 + +# Commands can be imported from other namespaces +namespace import ::tcl::mathop::+ +set result [+ 5 3] + + +# New commands can be created via the "proc" command. +proc greet name { + return "Hello, $name!" +} + +#multiple parameters can be specified +proc greet {greeting name} { + return "$greeting, $name!" +} + + +# As noted earlier, braces do not construct a code block. Every value, even +# the third argument of the "proc" command, is a string. The previous command +# rewritten to not use braces at all: +proc greet greeting\ name return\ \"Hello,\ \$name! + + + +# When the last parameter is the literal value, "args", it collects all extra +# arguments when the command is invoked +proc fold {cmd args} { + set res 0 + foreach arg $args { + set res [cmd $res $arg] + } +} +fold ::tcl::mathop::* 5 3 3 ;# -> 45 + + +# Conditional execution is implemented as a command +if {3 > 4} { + puts {This will never happen} +} elseif {4 > 4} { + puts {This will also never happen} +} else { + puts {This will always happen} +} + + +# Loops are implemented as commands. The first, second, and third +# arguments of the "for" command are treated as mathematical expressions +for {set i 0} {$i < 10} {incr i} { + set res [expr {$res + $i}] +} + + +# The first argument of the "while" command is also treated as a mathematical +# expression +set i 0 +while {$i < 10} { + incr i 2 +} + + +# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values +set amounts 10\ 33\ 18 +set amount [lindex $amounts 1] + + +# Braces and backslash can be used to format more complex values in a list. A +# list looks exactly like a script, except that the newline character and the +# semicolon character lose their special meanings. This feature makes Tcl +# homoiconic. There are three items in the following list. +set values { + + one\ two + + {three four} + + five\{six + +} + + +# Since a list is a string, string operations could be performed on it, at the +# risk of corrupting the formatting of the list. +set values {one two three four} +set values [string map {two \{} $values] ;# $values is no-longer a \ + properly-formatted listwell-formed list + + +# The sure-fire way to get a properly-formmated list is to use "list" commands +set values [list one \{ three four] +lappend values { } ;# add a single space as an item in the list + + +# Use "eval" to evaluate a value as a script +eval { + set name Neo + set greeting "Hello, $name" +} + + +# A list can always be passed to "eval" as a script composed of a single +# command. +eval {set name Neo} +eval [list set greeting "Hello, $name"] + + +# Therefore, when using "eval", use [list] to build up a desired command +set command {set name} +lappend command {Archibald Sorbisol} +eval $command + + +# A common mistake is not to use list functions when building up a command +set command {set name} +append command { Archibald Sorbisol} +eval $command ;# There is an error here, because there are too many arguments \ + to "set" in {set name Archibald Sorbisol} + + +# This mistake can easily occur with the "subst" command. +set replacement {Archibald Sorbisol} +set command {set name $replacement} +set command [subst $command] +eval $command ;# The same error as before: to many arguments to "set" in \ + {set name Archibald Sorbisol} + + +# The proper way is to format the substituted value using use the "list" +# command. +set replacement [list {Archibald Sorbisol}] +set command {set name $replacement} +set command [subst $command] +eval $command + + +# It is extremely common to see the "list" command being used to properly +# format values that are substituted into Tcl script templates. There are +# several examples of this, below. + + +# The "apply" command evaluates a string as a command. +set cmd {{greeting name} { + return "$greeting, $name!" +}} +apply $cmd Whaddup Neo + + +# The "uplevel" command evaluates a script in some enclosing scope. +proc greet {} { + uplevel {puts "$greeting, $name"} +} + +proc set_double {varname value} { + if {[string is double $value]} { + uplevel [list variable $varname $value] + } else { + error [list {not a double} $value] + } +} + + +# The "upvar" command links a variable in the current scope to a variable in +# some enclosing scope +proc set_double {varname value} { + if {[string is double $value]} { + upvar 1 $varname var + set var $value + } else { + error [list {not a double} $value] + } +} + + +#get rid of the built-in "while" command. +rename ::while {} + + +# Define a new while command with the "proc" command. More sophisticated error +# handling is left as an exercise. +proc while {condition script} { + if {[uplevel 1 [list expr $condition]]} { + uplevel 1 $script + tailcall [namespace which while] $condition $script + } +} + + +# The "coroutine" command creates a separate call stack, along with a command +# to enter that call stack. The "yield" command suspends execution in that +# stack. +proc countdown {} { + #send something back to the initial "coroutine" command + yield + + set count 3 + while {$count > 1} { + yield [incr count -1] + } + return 0 +} +coroutine countdown1 countdown +coroutine countdown2 countdown +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 +puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 2] ;# -> 1 + + +``` + +## Reference + +[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) + +[Tcl Wiki](http://wiki.tcl.tk) + +[Tcl Subreddit](http://www.reddit.com/r/Tcl) -- cgit v1.2.3 From 0512b3120acbe9d3a534cbc7685c30a65e067801 Mon Sep 17 00:00:00 2001 From: Jakukyo Friel Date: Wed, 7 Jan 2015 23:15:25 +0800 Subject: java: Add `@Override` for interfaces. --- java.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index 4661d4f9..3dd65679 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -4,6 +4,7 @@ language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] + - ["Jakukyo Friel", "http://weakish.github.io"] filename: LearnJava.java --- @@ -433,10 +434,12 @@ public interface Digestible { //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() { //... } @@ -445,10 +448,12 @@ public class Fruit implements Edible, Digestible { //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() { } -- cgit v1.2.3 From aa13db251bec274a1227235f0cea376c100f003b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Wed, 7 Jan 2015 14:35:03 -0300 Subject: [XML/en] translated to [XML/pt-br] --- pt-br/xml-pt.html.markdown | 133 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 pt-br/xml-pt.html.markdown diff --git a/pt-br/xml-pt.html.markdown b/pt-br/xml-pt.html.markdown new file mode 100644 index 00000000..40ddbc3a --- /dev/null +++ b/pt-br/xml-pt.html.markdown @@ -0,0 +1,133 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +XML é uma linguagem de marcação projetada para armazenar e transportar dados. + +Ao contrário de HTML, XML não especifica como exibir ou formatar os dados, +basta carregá-lo. + +* Sintaxe 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 + + +``` + +* Documento bem formatado x Validação + +Um documento XML é bem formatado se estiver sintaticamente correto.No entanto, +é possível injetar mais restrições no documento, utilizando definições de +documentos, tais como DTD e XML Schema. + +Um documento XML que segue uma definição de documento é chamado válido, sobre +esse documento. + +Com esta ferramenta, você pode verificar os dados XML fora da lógica da aplicação. + +```xml + + + + + + + + Everyday Italian + 30.00 + + + + + + + + + + +]> + + + + + + + + + + + + + +]> + + + + Everyday Italian + 30.00 + + +``` \ No newline at end of file -- cgit v1.2.3 From 7dad0b92cc81b34c98bdcb204ada59c4fd1f627b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Thu, 8 Jan 2015 11:28:11 -0300 Subject: [Hy/en] translated to [Hy/pt-bt] --- pt-br/hy-pt.html.markdown | 176 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 pt-br/hy-pt.html.markdown diff --git a/pt-br/hy-pt.html.markdown b/pt-br/hy-pt.html.markdown new file mode 100644 index 00000000..4230579d --- /dev/null +++ b/pt-br/hy-pt.html.markdown @@ -0,0 +1,176 @@ +--- +language: hy +filename: learnhy.hy +contributors: + - ["Abhishek L", "http://twitter.com/abhishekl"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +Hy é um dialeto de Lisp escrito sobre Python. Isto é possível convertendo +código Hy em árvore sintática abstrata python (ast). Portanto, isto permite +hy chamar código python nativo e vice-versa. + +Este tutorial funciona para hy ≥ 0.9.12 + +```clojure +;; Isso dá uma introdução básica em hy, como uma preliminar para o link abaixo +;; http://try-hy.appspot.com +;; +; Comentários em ponto-e-vírgula, como em outros LISPS + +;; s-noções básicas de expressão +; programas Lisp são feitos de expressões simbólicas ou sexps que se assemelham +(some-function args) +; agora o essencial "Olá mundo" +(print "hello world") + +;; Tipos de dados simples +; Todos os tipos de dados simples são exatamente semelhantes aos seus homólogos +; em python que +42 ; => 42 +3.14 ; => 3.14 +True ; => True +4+10j ; => (4+10j) um número complexo + +; Vamos começar com um pouco de aritmética muito simples +(+ 4 1) ;=> 5 +; o operador é aplicado a todos os argumentos, como outros lisps +(+ 4 1 2 3) ;=> 10 +(- 2 1) ;=> 1 +(* 4 2) ;=> 8 +(/ 4 1) ;=> 4 +(% 4 2) ;=> 0 o operador módulo +; exponenciação é representado pelo operador ** como python +(** 3 2) ;=> 9 +; formas aninhadas vão fazer a coisa esperada +(+ 2 (* 4 2)) ;=> 10 +; também operadores lógicos e ou não e igual etc. faz como esperado +(= 5 4) ;=> False +(not (= 5 4)) ;=> True + +;; variáveis +; variáveis são definidas usando SETV, nomes de variáveis podem usar utf-8, exceto +; for ()[]{}",'`;#| +(setv a 42) +(setv π 3.14159) +(def *foo* 42) +;; outros tipos de dados de armazenamento +; strings, lists, tuples & dicts +; estes são exatamente os mesmos tipos de armazenamento de python +"hello world" ;=> "hello world" +; operações de string funcionam semelhante em python +(+ "hello " "world") ;=> "hello world" +; Listas são criadas usando [], a indexação começa em 0 +(setv mylist [1 2 3 4]) +; tuplas são estruturas de dados imutáveis +(setv mytuple (, 1 2)) +; dicionários são pares de valores-chave +(setv dict1 {"key1" 42 "key2" 21}) +; :nome pode ser utilizado para definir palavras-chave em hy que podem ser utilizados para as chaves +(setv dict2 {:key1 41 :key2 20}) +; usar 'get' para obter o elemento em um índice/key +(get mylist 1) ;=> 2 +(get dict1 "key1") ;=> 42 +; Alternativamente, se foram utilizadas palavras-chave que podem ser chamadas diretamente +(:key1 dict2) ;=> 41 + +;; funções e outras estruturas de programa +; funções são definidas usando defn, o último sexp é devolvido por padrão +(defn greet [name] + "A simple greeting" ; uma docstring opcional + (print "hello " name)) + +(greet "bilbo") ;=> "hello bilbo" + +; funções podem ter argumentos opcionais, bem como argumentos-chave +(defn foolists [arg1 &optional [arg2 2]] + [arg1 arg2]) + +(foolists 3) ;=> [3 2] +(foolists 10 3) ;=> [10 3] + +; funções anônimas são criados usando construtores 'fn' ou 'lambda' +; que são semelhantes para 'defn' +(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] + +;; operações de sequência +; hy tem algumas utils embutidas para operações de sequência, etc. +; recuperar o primeiro elemento usando 'first' ou 'car' +(setv mylist [1 2 3 4]) +(setv mydict {"a" 1 "b" 2}) +(first mylist) ;=> 1 + +; corte listas usando 'slice' +(slice mylist 1 3) ;=> [2 3] + +; obter elementos de uma lista ou dict usando 'get' +(get mylist 1) ;=> 2 +(get mydict "b") ;=> 2 +; lista de indexação começa a partir de 0, igual em python +; assoc pode definir elementos em chaves/índices +(assoc mylist 2 10) ; faz mylist [1 2 10 4] +(assoc mydict "c" 3) ; faz mydict {"a" 1 "b" 2 "c" 3} +; há toda uma série de outras funções essenciais que torna o trabalho com +; sequências uma diversão + +;; Python interop +;; importação funciona exatamente como em python +(import datetime) +(import [functools [partial reduce]]) ; importa fun1 e fun2 do module1 +(import [matplotlib.pyplot :as plt]) ; fazendo uma importação em foo como em bar +; todos os métodos de python embutidas etc. são acessíveis a partir hy +; a.foo(arg) is called as (.foo a arg) +(.split (.strip "hello world ")) ;=> ["hello" "world"] + +;; Condicionais +; (if condition (body-if-true) (body-if-false) +(if (= passcode "moria") + (print "welcome") + (print "Speak friend, and Enter!")) + +; aninhe múltiplas cláusulas 'if else if' com cond +(cond + [(= someval 42) + (print "Life, universe and everything else!")] + [(> someval 42) + (print "val too large")] + [(< someval 42) + (print "val too small")]) + +; declarações de grupo com 'do', essas são executadas sequencialmente +; formas como defn tem um 'do' implícito +(do + (setv someval 10) + (print "someval is set to " someval)) ;=> 10 + +; criar ligações lexicais com 'let', todas as variáveis definidas desta forma +; tem escopo local +(let [[nemesis {"superman" "lex luther" + "sherlock" "moriarty" + "seinfeld" "newman"}]] + (for [(, h v) (.items nemesis)] + (print (.format "{0}'s nemesis was {1}" h v)))) + +;; classes +; classes são definidas da seguinte maneira +(defclass Wizard [object] + [[--init-- (fn [self spell] + (setv self.spell spell) ; init a mágica attr + None)] + [get-spell (fn [self] + self.spell)]]) + +;; acesse hylang.org +``` + +### Outras Leituras + +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) + +Acesso ao freenode irc com #hy, hashtag no twitter: #hylang -- cgit v1.2.3 From d1171443ddc0eda7cbabfc41d110a76a67e494ab Mon Sep 17 00:00:00 2001 From: mordner Date: Thu, 8 Jan 2015 23:21:39 +0100 Subject: Fixed one line being cut off and a comment about the export attribute was referring to the wrong function and variable. --- c.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index b5b804af..7670824a 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -386,7 +386,8 @@ int main() { // or when it's the argument of the `sizeof` or `alignof` operator: int arraythethird[10]; int *ptr = arraythethird; // equivalent with int *ptr = &arr[0]; - printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); // probably prints "40, 4" or "40, 8" + printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); + // probably prints "40, 4" or "40, 8" // Pointers are incremented and decremented based on their type @@ -477,7 +478,7 @@ void testFunc() { } //make external variables private to source file with static: -static int j = 0; //other files using testFunc() cannot access variable i +static int j = 0; //other files using testFunc2() cannot access variable j void testFunc2() { extern int j; } -- cgit v1.2.3 From 4ef0e78009896395804c609201c9b70254bddcb2 Mon Sep 17 00:00:00 2001 From: raiph Date: Fri, 9 Jan 2015 18:39:56 -0500 Subject: Fix link to synopses and call them 'design docs' --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b10e04bf..13f383fe 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1481,5 +1481,5 @@ If you want to go further, you can: - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such. - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful. - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize). - - Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting. + - Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting. -- cgit v1.2.3 From 8f29b15cda9cbc7ca8fc1f31ed0755245c9fc9c7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 11 Jan 2015 15:30:12 -0700 Subject: Rewrite the pattern matching section --- scala.html.markdown | 64 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 336251ba..3fa4d4b8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -198,8 +198,8 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most -// def that surrounds it. -// WARNING: Using return in Scala is error-prone and should be avoided. +// def that surrounds it. +// WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: def foo(x: Int): Int = { val anonFunc: Int => Int = { z => @@ -407,41 +407,55 @@ val otherGeorge = george.copy(phoneNumber = "9876") // 6. Pattern Matching ///////////////////////////////////////////////// -val me = Person("George", "1234") +// Pattern matching is a powerful and commonly used feature in Scala. Here's how +// you pattern match a case class. NB: Unlike other languages, Scala cases do +// not have breaks. -me match { case Person(name, number) => { - "We matched someone : " + name + ", phone : " + number }} - -me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } +def matchPerson(person: Person): String = person match { + // Then you specify the patterns: + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number +} -me match { case Person("George", number) => "Match"; case _ => "Hm..." } +val email = "(.*)@(.*)".r // Define a regex for the next example. -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } +// Pattern matching might look familiar to the switch statements in the C family +// of languages, but this is much more powerful. In Scala, you can match much +// more: +def matchEverything(obj: Any): String = obj match { + // You can match values: + case "Hello world" => "Got the string Hello world" -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match by type: + case x: Double => "Got a Double: " + x -val kate = Person("Kate", "1234") + // You can specify conditions: + case x: Int if x > 10000 => "Got a pretty big number!" -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match case classes as before: + case Person(name, number) => s"Got contact info for $name!" + // You can match regular expressions: + case email(name, domain) => s"Got email address $name@$domain" + // You can match tuples: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" -// Regular expressions -val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex -val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax + // You can match data structures: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" -val matcher = (value: String) => { - println(value match { - case email(name, domain) => s"It was an email: $name" - case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4" - case _ => s"No match on '$value'" // default if no match found - }) + // You can nest patterns: + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" } -matcher("mrbean@pyahoo.com") // => "It was an email: mrbean" -matcher("nope..") // => "No match on 'nope..'" -matcher("52917") // => "No match on '52917'" -matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" +// In fact, you can pattern match any object with an "unapply" method. This +// feature is so powerful that Scala lets you define whole functions as +// patterns: +val patternFunc: Person => String = { + case Person("George", number") => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} ///////////////////////////////////////////////// -- cgit v1.2.3 From c053f1559bb357d9e8ced2452096bf3a95cc7ddb Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 11 Jan 2015 18:11:06 -0700 Subject: Better wording about breaks in cases --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 3fa4d4b8..61c735e3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -409,7 +409,7 @@ val otherGeorge = george.copy(phoneNumber = "9876") // Pattern matching is a powerful and commonly used feature in Scala. Here's how // you pattern match a case class. NB: Unlike other languages, Scala cases do -// not have breaks. +// not need breaks, fall-through does not happen. def matchPerson(person: Person): String = person match { // Then you specify the patterns: -- cgit v1.2.3 From 22d0cb02a8e08532555edde1f5ccf9a34a2b6a77 Mon Sep 17 00:00:00 2001 From: Fla Date: Mon, 12 Jan 2015 14:10:41 +0100 Subject: Typo --- fr-fr/ruby-fr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index 75c8d0d3..1564d2b6 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -268,7 +268,7 @@ end # implicitement la valeur de la dernière instruction évaluée double(2) #=> 4 -# Les paranthèses sont facultative +# Les parenthèses sont facultatives # lorsqu'il n'y a pas d'ambiguïté sur le résultat double 3 #=> 6 -- cgit v1.2.3 From bb2ef18bcc24549560f56bcf1e3b1d8cdcf68f99 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, 5 Nov 2014 22:39:28 +0200 Subject: Adding the lang header --- ru-ru/java-ru.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 005495cc..913c0fe2 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -1,5 +1,6 @@ --- language: java +lang: ru-ru contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] -- cgit v1.2.3 From d2336d0ce4dc35e0d8627a4b0d089e06c8dffd88 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, 5 Nov 2014 22:52:46 +0200 Subject: Revert "Adding the lang header" This reverts commit 2b0aa461069d5356f5e6b4c166deac04d6597b4a. --- ru-ru/java-ru.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 913c0fe2..005495cc 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -1,6 +1,5 @@ --- language: java -lang: ru-ru contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Madison Dickson", "http://github.com/mix3d"] -- cgit v1.2.3 From 7b9eb42fb5f2c3b29bef2e08b570a6b6ef0ad8a7 Mon Sep 17 00:00:00 2001 From: "a.gonchar" Date: Wed, 24 Dec 2014 16:15:34 +0300 Subject: translation javascript into Russian --- ru-ru/javascript-ru.html.markdown | 503 ++++++++++++++++++-------------------- 1 file changed, 235 insertions(+), 268 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index ad66b501..dc35d18c 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -3,261 +3,250 @@ language: javascript contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] - ["Ariel Krakowski", "http://www.learneroo.com"] -translators: - - ["Maxim Koretskiy", "http://github.com/maximkoretskiy"] filename: javascript-ru.js +translators: + - ["Alexey Gonchar", "http://github.com/finico"] lang: ru-ru --- -Javascript был разработан Бренданом Айком из Netcape в 1995. Изначально -предполагалось, что он станет простым вариантом скриптового языка для сайтов, -дополняющий к Java, который бы в свою очередь использовался для более сложных -web-приложений. Но тонкая интегрированность javascript с web-страницей и -встроенная поддержка в браузерах привели к тому, чтобы он стал более -распространен в frontend-разработке, чем Java. - -Использование JavaScript не ограничивается браузерами. Проект Node.js, -предоставляющий независимую среду выполнения на движке Google Chrome V8 -JavaScript, становится все более популярным. +JavaScript был создан в 1995 году Бренданом Айком, работающим в компании Netscape. +Изначально он был задуман как простой язык сценариев для веб-сайтов, дополняющий +Java для более сложных веб-приложений, но его тесная интеграция с веб-страницами +и втроенная поддержка браузерами привели к тому, что он стал более распространынным, +чем Java в веб-интерфейсах. -Обратная связь важна и нужна! Вы можете написаться мне -на [@adambrenecki](https://twitter.com/adambrenecki) или -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +JavaScript не ограничивается только веб-браузером, например, Node.js, программная +платформа, позволяющая выполнять JavaScript, основанная на движке V8 от браузера +Google Chrome, становится все более популярной. ```js -// Комментарии оформляются как в C. -// Однострочнные коментарии начинаются с двух слешей, -/* а многострочные с слеша и звездочки - и заканчиваются звездочеий и слешом */ +// Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш, +/* а многострочные комментарии начинаются с звёздочка-слэш + и заканчиваются символами слэш-звёздочка */ -// Выражения разделяются с помощью ; +// Выражения заканчиваються точкой с запятой ; doStuff(); -// ... но этого можно и не делать, разделители подставляются автоматически -// после перехода на новую строку за исключением особых случаев +// ... но они необязательны, так как точки с запятой автоматически вставляются +// везде, где есть символ новой строки, за некоторыми исключениями. doStuff() -// Это может приводить к непредсказуемому результату и поэтому мы будем -// использовать разделители в этом туре. -// Because those cases can cause unexpected results, we'll keep on using -// semicolons in this guide. +// Так как эти исключения могут привести к неожиданным результатам, мы будем всегда +// использовать точку с запятой в этом руководстве. /////////////////////////////////// // 1. Числа, Строки и Операторы -// 1. Numbers, Strings and Operators -// В Javasript всего 1 числовой тип - 64-битное число с плавающей точкой -// стандарта IEEE 754) -// Числа имеют 52-битную мантиссу, чего достаточно для хранения хранения целых -// чисел до 9✕10¹⁵ приблизительно. +// В JavaScript только один тип числа (64-bit IEEE 754 double). +// Он имеет 52-битную мантиссу, которой достаточно для хранения целых чисел +// с точностью вплоть до 9✕10¹⁵. 3; // = 3 1.5; // = 1.5 -// В основном базовая арифметика работает предсказуемо +// Некоторые простые арифметические операции работают так, как вы ожидаете. 1 + 1; // = 2 -.1 + .2; // = 0.30000000000000004 +0.1 + 0.2; // = 0.30000000000000004 (а некоторые - нет) 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 -// Включая нецелочисленное деление +// Включая деление с остатком. 5 / 2; // = 2.5 -// Двоичные операции тоже есть. Если применить двоичную операцию к float-числу, -// оно будет приведено к 32-битному целому со знаком. +// Побитовые операции так же имеются; Они производят операции, используя +// двоичное представление числа, и возвращают новую последовательность из +// 32 бит (число) в качестве результата. 1 << 2; // = 4 -// (todo:перевести) -// Приоритет выполнения операций можно менять с помощью скобок. +// Приоритет в выражениях явно задаётся скобками. (1 + 3) * 2; // = 8 -// Есть три особых не реальных числовых значения: -Infinity; // допустим, результат операции 1/0 --Infinity; // допустим, результат операции -1/0 -NaN; // допустим, результат операции 0/0 +// Есть три специальных значения, которые не являются реальными числами: +Infinity; // "бесконечность", например, результат деления на 0 +-Infinity; // "минус бесконечность", результат деления отрицательного числа на 0 +NaN; // "не число", например, результат деления 0/0 -// Так же есть тип булевых данных. +// Существует также логический тип. true; false; -// Строки создаются с помощью ' или ". +// Строки создаются при помощи двойных или одинарных кавычек. 'abc'; "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 -// Для доступа к конкретному символу строки используйте charAt +// ...приведение типов может привести к странному поведению... +13 + !0; // 14 +"13" + !0; // '13true' + +// Вы можете получить доступ к любому символу строки, используя метод charAt "This is a string".charAt(0); // = 'T' -// ... или используйте substring для получения подстроки +// ...или используйте метод substring чтобы получить более крупные части "Hello world".substring(0, 5); // = "Hello" -// length(длина) - свойство, не используйте () +// length это свойство, для его получения не нужно использовать () "Hello".length; // = 5 -// Есть null и undefined -null; // используется что бы указать явно, что значения нет -undefined; // испрользуется чтобы показать, что значения не было установлено - // собственно, undefined так и переводится +// Так же есть null и undefined +null; // используется для обозначения намеренного значения "ничего" +undefined; // используется для обозначения переменных, не имеющих + // присвоенного значения (хотя переменная объявлена) -// false, null, undefined, NaN, 0 и "" являются falsy-значениями(при приведении -// в булеву типу становятся false) -// Обратите внимание что 0 приводится к false, а "0" к true, -// не смотря на то, что "0"==0 +// false, null, undefined, NaN, 0 и "" это ложь; все остальное - истина. +// Следует отметить, что 0 это ложь, а "0" - истина, несмотря на то, что 0 == "0". /////////////////////////////////// -// 2. Переменные, массивы и объекты +// 2. Переменные, Массивы и Объекты -// Переменные объявляются ключевым словом var. Javascript динамически -// типизируемый, так что указывать тип не нужно. -// Присвоение значения описывается с помощью оператора = +// Переменные объявляются при помощи ключевого слова var. JavaScript - язык с +// динамической типизацией, поэтому не нужно явно указывать тип. Для присваивания +// значения переменной используется символ = var someVar = 5; -// если не указать ключевого слова var, ошибки не будет... +// если вы пропустите слово var, вы не получите сообщение об ошибке... someOtherVar = 10; -// ...но переменная будет создана в глобальном контексте, в не области -// видимости, в которой она была объявлена. +// ...но ваша переменная будет создана в глобальном контексте, а не в текущем +// гед вы ее объявили. -// Переменные объявленные без присвоения значения, содержать undefined +// Переменным объявленным без присвоения устанавливается значение undefined. var someThirdVar; // = undefined -// Для математических операций над переменными есть короткая запись: -someVar += 5; // тоже что someVar = someVar + 5; someVar равно 10 теперь -someVar *= 10; // а теперь -- 100 +// У математических операций есть сокращённые формы: +someVar += 5; // как someVar = someVar + 5; someVar теперь имеет значение 10 +someVar *= 10; // теперь someVar имеет значение 100 -// еще более короткая запись для добавления и вычитания 1 -someVar++; // теперь someVar равно 101 -someVar--; // обратно к 100 +// а так же специальные операторы инкремент и декремент для увеличения и +// уменьшения переменной на единицу соответственно +someVar++; // теперь someVar имеет значение 101 +someVar--; // обратно 100 -// Массивы -- упорядоченные списки значений любых типов. +// Массивы это нумерованные списки из значений любого типа. var myArray = ["Hello", 45, true]; -// Для доступу к элементам массивов используйте квадратные скобки. -// Индексы массивов начинаются с 0 +// Их элементы могут быть доступны при помощи синтаксиса с квадратными скобками. +// Индексы массивов начинаются с нуля. myArray[1]; // = 45 -// Массивы мутабельны(изменяемы) и имеют переменную длину. -myArray.push("World"); // добавить элемент +// Массивы можно изменять, как и их длину. +myArray.push("World"); myArray.length; // = 4 -// Добавить или изменить значение по конкретному индексу +// Добавлять и редактировать определенный элемент myArray[3] = "Hello"; -// Объекты javascript похожи на dictionary или map из других языков -// программирования. Это неупорядочнные коллекции пар ключ-значение. +// Объекты в JavaScript похожи на "словари" или ассоциативные массиы в других +// языках: неупорядоченный набор пар ключ-значение. var myObj = {key1: "Hello", key2: "World"}; -// Ключи -- это строки, но кавычки не требуются если названия явлюятся -// корректными javascript идентификаторами. Значения могут быть любого типа. +// Ключи это строки, но кавычки необязательны, если строка удовлетворяет +// ограничениям для имён переменных. Значения могут быть любых типов. var myObj = {myKey: "myValue", "my other key": 4}; -// Доступ к атрибту объекта можно получить с помощью квадратных скобок +// Атрибуты объектов можно также получить, используя квадратные скобки, myObj["my other key"]; // = 4 -// ... или используя точечную нотацию, при условии что ключ является -// корректным идентификатором. +// или через точку, при условии, что ключ является допустимым идентификатором. myObj.myKey; // = "myValue" -// Объекты мутабельны. В существуюещем объекте можно изменить значние -// или добавить новый атрибут. +// Объекты изменяемы; можно изменять значения и добавлять новые ключи. myObj.myThirdKey = true; -// При попытке доступа к атрибуту, который до этого не был создан, будет -// возвращен undefined +// Если вы попытаетесь получить доступ к несуществующему свойству, +// вы получите undefined. myObj.myFourthKey; // = undefined /////////////////////////////////// -// 3. Логика и Управляющие структуры +// 3. Логика и управляющие конструкции. -// Синтаксис управляющих структур очень похож на его реализацию в Java. +// Синтаксис для этого раздела почти такой же как в Java. -// if работает так как вы ожидаете. +// Эта конструкция работает, как и следовало ожидать. var count = 1; -if (count == 3){ - // выполнится, если значение count равно 3 -} else if (count == 4){ - // выполнится, если значение count равно 4 +if (count == 3) { + // выполняется, если count равен 3 +} else if (count == 4) { + // выполняется, если count равен 4 } else { - // выполнится, если значение count не будет равно ни 3 ни 4 + // выполняется, если не 3 и не 4 } -// Поведение while тоже вполне предсказуемо +// Как это делает while. while (true){ - // Бесконечный цикл + // Бесконечный цикл! } -// Циклы do-while похожи на while, но они всегда выполняются хотябы 1 раз. -// Do-while loops are like while loops, except they always run at least once. +// Циклы do-while такие же как while, но они всегда выполняются хотя бы раз. var input do { input = getInput(); } while (!isValid(input)) -// Цикл for такой же как в C и Java: -// инициализация; условие продолжения; итерация -for (var i = 0; i < 5; i++){ - // выполнится 5 раз +// цикл for является таким же, как C и Java: +// инициализация; условие; шаг. +for (var i = 0; i < 5; i++) { + // будет запущен 5 раз } -// && - логическое и, || - логическое или -if (house.size == "big" && house.color == "blue"){ +// && это логическое И, || это логическое ИЛИ +if (house.size == "big" && house.colour == "blue") { house.contains = "bear"; } -if (color == "red" || color == "blue"){ - // если цвет или красный или синий +if (colour == "red" || colour == "blue") { + // цвет красный или синий } -// && и || удобны для установки значений по умолчанию. -// && and || "short circuit", which is useful for setting default values. +// || используется как "короткий цикл вычисления" для присваивания переменных. var name = otherName || "default"; -// выражение switch проверяет равество с помощью === -// используйте 'break' после каждого case, -// иначе помимо правильного case выполнятся и все последующие. -grade = '4'; // оценка +// Оператор switch выполняет проверку на равенство пр помощи === +// используйте break чтобы прервать выполнение после каждого case +// или выполнение пойдёт далее, игнорируя при этом остальные проверки. +grade = 'B'; switch (grade) { - case '5': - console.log("Великолепно"); + case 'A': + console.log("Great job"); break; - case '4': - console.log("Неплохо"); + case 'B': + console.log("OK job"); break; - case '3': - console.log("Можно и лучше"); + case 'C': + console.log("You can do better"); break; default: - console.log("Да уж."); + console.log("Oy vey"); break; } @@ -265,213 +254,197 @@ switch (grade) { /////////////////////////////////// // 4. Функции, Область видимости и Замыкания -// Функции в JavaScript объявляются с помощью ключевого слова function. -function myFunction(thing){ - return thing.toUpperCase(); // приведение к верхнему регистру +// Функции в JavaScript объявляются при помощи ключевого слова function. +function myFunction(thing) { + return thing.toUpperCase(); } myFunction("foo"); // = "FOO" -// Помните, что значение, которое должно быть возкращено должно начинаться -// на той же строке, где расположено ключевое слово 'return'. В противном случае -// будет возвращено undefined. Такое поведения объясняется автоматической -// вставкой разделителей ';'. Помните этот факт, если используете -// BSD стиль оформления кода. -// 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. +// Обратите внимание, что значение, которое будет возвращено, должно начинаться +// на той же строке, что и ключевое слово return, в противном случае вы будете +// всегда возвращать undefined по причине автоматической вставки точки с запятой. +// Следите за этим при использовании стиля форматирования Allman. function myFunction() { - return // <- разделитель автоматически будет вставлен здесь + return // <- здесь точка с запятой вставится автоматически { thisIsAn: 'object literal' } } myFunction(); // = undefined -// Функции в JavaScript являются объектами, поэтому их можно назначить в -// переменные с разными названиями и передавать в другие функции, как аргументы, -// на пример, при указании обработчика события. -function myFunction(){ - // этот фрагмент кода будет вызван через 5 секунд +// JavaScript функции - это объекты, поэтому они могут быть переприсвоены на +// различные имена переменных и передаваться другим функциям в качестве аргументов, +// например, когда назначается обработчик события: +function myFunction() { + // этот код будет вызван через 5 секунд } setTimeout(myFunction, 5000); -// Обратите внимание, что setTimeout не является частью языка, однако он -// доступен в API браузеров и Node.js. +// Примечание: setTimeout не является частью языка, но реализован в браузерах и Node.js -// Объект функции на самом деле не обязательно объявлять с именем - можно -// создать анонимную функцию прямо в аргументах другой функции. -setTimeout(function(){ - // этот фрагмент кода будет вызван через 5 секунд +// Функции не обязательно должны иметь имя при объявлении - вы можете написать +// анонимное определение функции непосредственно в агрументе другой функции. +setTimeout(function() { + // этот код будет вызван через 5 секунд }, 5000); -// В JavaScript есть области видимости. У функций есть собственные области -// видимости, у других блоков их нет. -if (true){ +// В JavaScript есть область видимости функции; функции имеют свою область +// видимости, а другие блоки - нет. +if (true) { var i = 5; } -i; // = 5, а не undefined, как это было бы в языке, создающем - // области видисти для блоков кода +i; // = 5 - не undefined как ожидалось бы в языках с блочной областью видимости -// Это привело к появлению паттерна общего назначения "immediately-executing -// anonymous functions" (сразу выполняющиеся анонимные функции), который -// позволяет предотвратить запись временных переменных в общую облать видимости. -(function(){ +// Это привело к общепринятому шаблону "самозапускающихся анонимных функций", +// которые препятствуют проникновению переменных в глобальную область видимости +(function() { var temporary = 5; - // Для доступа к глобальной области видимости можно использовать запись в - // некоторый 'глобальный объект', для браузеров это 'window'. Глобальный - // объект может называться по-разному в небраузерных средах, таких Node.js. + // Мы можем получить доступ к глобальной области для записи в "глобальный объект", + // который в веб-браузере всегда window. Глобальный объект может иметь другое + // имя в таких платформах, как Node.js window.permanent = 10; })(); -temporary; // вызывает исключение ReferenceError +temporary; // вызовет сообщение об ошибке с типом ReferenceError permanent; // = 10 -// Одной из сильных сторон JavaScript являются замыкания. Если функция -// объявлена в внутри другой функции, внутренняя функция имеет доступ ко всем -// переменным внешней функции, даже после того, как внешняя функции завершила -// свое выполнение. -function sayHelloInFiveSeconds(name){ - var prompt = "Привет, " + name + "!"; - // Внутренние функции помещаются в локальную область видимости, как-будто - // они объявлены с ключевым словом 'var'. - function inner(){ +// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция +// определена внутри другой функции, то внутренняя функция имеет доступ к +// переменным внешней функции, даже после того, как контекст выполнения выйдет из +// внешней функции. +function sayHelloInFiveSeconds(name) { + var prompt = "Hello, " + name + "!"; + // Внутренние функции по умолчанию помещаются в локальную область видимости, + // как если бы они были объявлены с var. + function inner() { alert(prompt); } setTimeout(inner, 5000); - // setTimeout является асинхроннной, и поэтому функция sayHelloInFiveSeconds - // завершит свое выполнение сразу и setTimeout вызовет inner позже. - // Однако, так как inner "закрыта внутри" или "замкнута в" - // sayHelloInFiveSeconds, inner все еще будет иметь доступ к переменной - // prompt, когда будет вызвана. + // setTimeout асинхронна, поэтому функция sayHelloInFiveSeconds сразу выйдет + // и тело setTimeout будет вызвано позже. Однако, поскольку внутренняя + // функция "замкнута", она по-прежнему имеет доступ к переменной prompt, + // когда sayHelloInFiveSeconds вызывется. } -sayHelloInFiveSeconds("Вася"); // откроет модальное окно с сообщением - // "Привет, Вася" по истечении 5 секунд. - +sayHelloInFiveSeconds("Adam"); // откроется окно с "Hello, Adam!" через 5 секунд /////////////////////////////////// -// 5. Немного еще об Объектах. Конструкторы и Прототипы +// 5. Подробнее про Объекты, Конструкторы и Прототипы -// Объекты могут содержать функции +// Объекты могут содержать в себе функции. var myObj = { - myFunc: function(){ + myFunc: function() { return "Hello world!"; } }; myObj.myFunc(); // = "Hello world!" -// Когда функции прикрепленные к объекту вызываются, они могут получить доступ -// к данным объекта, ипользуя ключевое слово this. +// Когда функции, прикрепленные к объекту, вызываются, они могут получить доступ +// к этому объекту с помощью ключевого слова this. myObj = { myString: "Hello world!", - myFunc: function(){ + myFunc: function() { return this.myString; } }; myObj.myFunc(); // = "Hello world!" -// Содержание this определяется исходя из того, как была вызвана функция, а -// не места её определения. По этой причине наша функция не будет работать вне -// контекста объекта. +// Какое это значение имеет к тому, как вызвана функция и где она определена. +// Итак, наша функция не работает, если она вызывается не в контексте объекта. var myFunc = myObj.myFunc; myFunc(); // = undefined -// И напротив, функция может быть присвоена объекту и получить доступ к нему -// через this, даже если она не была прикреплена к объекту в момент её создания. -var myOtherFunc = function(){ - return this.myString.toUpperCase(); +// И наоборот, функция может быть присвоена объекту и получать доступ к нему +// через this, даже если она не была присвоена при объявлении. +var myOtherFunc = function() { } myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" -// Также можно указать контекс выполнения фунции с помощью 'call' или 'apply'. -var anotherFunc = function(s){ +// Мы можем также указать контекст для выполнения функции, когда мы вызываем ее +// с помощью call или apply. +var anotherFunc = function(s) { return this.myString + s; } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -// Функция 'apply' очень похожа, но принимает массив со списком аргументов. - +// Функция apply аналогична, но принимает массив аргументов. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -// Это может быть удобно, когда работаешь с фунцией принимающей на вход -// последовательность аргументов и нужно передать их в виде массива. - +// Это полезно при работе с функцией, которая принимает последовательность +// аргументов, и вы хотите передать массив. Math.min(42, 6, 27); // = 6 -Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min([42, 6, 27]); // = NaN (не сработает!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Однако, 'call' и 'apply' не имеют постоянного эффекта. Если вы хотите -// зафиксировать контекст для функции, используйте bind. - +// Но, call и apply - временные. Когда мы хотим связать функцию, мы можем +// использовать bind. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -// bind также можно использовать чтобы частично передать аргументы в -// функцию (каррировать). - -var product = function(a, b){ return a * b; } +// Bind также может использоваться, для частичного применения (каррирование) функции +var product = function(a, b) { return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// Когда функция вызывается с ключевым словом new, создается новый объект. -// Данный объект становится доступным функции через ключевое слово this. -// Функции спроектированные вызываться таким способом называются конструкторами. - -var MyConstructor = function(){ +// Когда вы вызываете функцию с помощью ключевого слова new создается новый объект, +// и создает доступ к функции при помощи this. Такие функции называют конструкторами. +var MyConstructor = function() { this.myNumber = 5; } myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Любой объект в JavaScript имеет 'прототип'. Когда вы пытаетесь получить -// доступ к свойству не объявленному в данном объекте, интерпретатор будет -// искать его в прототипе. +// Каждый объект в JavaScript имеет свойтво prototype. Когда вы хотите получить +// доступ к свойтву объекта, которое не существует в этом объекте, интерпритатор +// будет искать это свойство в прототипе. -// Некоторые реализации JS позволяют получить доступ к прототипу с помощью -// "волшебного" свойства __proto__. До момента пока оно не являются стандартным, -// __proto__ полезно лишь для изучения прототипов в JavaScript. Мы разберемся -// со стандартными способами работы с прототипом несколько позже. +// Некоторые реализации языка позволяют получить доступ к объекту прототипа +// через свойство __proto__. Несмотря на то, что это может быть полезно для +// понимания прототипов, это не часть стандарта; мы увидим стандартные способы +// использования прототипов позже. var myObj = { myString: "Hello world!" }; var myPrototype = { meaningOfLife: 42, - myFunc: function(){ + 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__ не является стандартом, и нет стандартного -// способа изменить прототип у созданного объекта. Однако, есть два способа -// создать объект с заданным прототипом. +// Мы упомянули, что свойтсво __proto__ нестандартно, и нет никакого стандартного +// способа, чтобы изменить прототип существующего объекта. Однако, есть два +// способа создать новый объект с заданным прототипом. -// Первый способ - Object.create, был добавлен в JS относительно недавно, и -// потому не доступен в более ранних реализациях языка. +// Первый способ это Object.create, который появился в ECMAScript 5 и есть еще +// не во всех реализациях языка. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 -// Второй вариан доступен везде и связан с конструкторами. Конструкторы имеют -// свойство prototype. Это вовсе не прототип функции конструктора, напротив, -// это прототип, который присваевается новым объектам, созданным с этим -// конструктором с помощью ключевого слова new. +// Второй способ, который работает везде, имеет дело с конструкторами. +// У конструкторов есть свойство с именем prototype. Это не прототип +// функции-конструктора; напротив, это прототип для новых объектов, которые +// будут созданы с помощью этого конструктора и ключевого слова new MyConstructor.prototype = { myNumber: 5, - getMyNumber: function(){ + getMyNumber: function() { return this.myNumber; } }; @@ -480,42 +453,41 @@ 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 приводится к false +if (0) { + // Этот код не выполнятся, потому что 0 - это ложь. } -if (Number(0)){ - // Этот фрагмент кода *будет* выпонен, так как Number(0) приводится к true. +if (Number(0)) { + // Этот код выполнится, потому что Number(0) это истина. } -// Однако, оберточные объекты и обычные встроенные типы имеют общие прототипы, -// следовательно вы можете расширить функциональность строки, например. -String.prototype.firstCharacter = function(){ +// Впрочем, обертки это объекты и их можно расширять, например: +String.prototype.firstCharacter = function() { return this.charAt(0); } "abc".firstCharacter(); // = "a" -// Этот факт часто используется для создания полифилов(polyfill) - реализации -// новых возможностей JS в его более старых версиях для того чтобы их можно было -// использовать в устаревших браузерах. +// Это часто используется в полифиллах, которые реализуют новые возможности +// JavaScript в старой реализации языка, так что они могут быть использованы в +// старых средах, таких как устаревшие браузеры. -// Например, мы упомянули, что Object.create не доступен во всех версиях -// JavaScript, но мы можем создать полифилл. -if (Object.create === undefined){ // не переопределяем, если есть - Object.create = function(proto){ - // создаем временный конструктор с заданным прототипом +// Например, мы упомянули, что Object.create доступен не во всех реализациях, но +// мы сможем использовать его с этим полифиллом: +if (Object.create === undefined) { // не перезаписывать метод, если он существует + Object.create = function(proto) { + // создать временный конструктор с правильным прототипом var Constructor = function(){}; Constructor.prototype = proto; - // создаём новый объект с правильным прототипом + // затем использовать его для создания нового объекта, на основе прототипа return new Constructor(); } } @@ -523,21 +495,16 @@ if (Object.create === undefined){ // не переопределяем, если ## Что еще почитать -[Современный учебник JavaScript](http://learn.javascript.ru/) от Ильи Кантора -является довольно качественным и глубоким учебным материалом, освещающим все -особенности современного языка. Помимо учебника на том же домене можно найти -[перевод спецификации ECMAScript 5.1](http://es5.javascript.ru/) и справочник по -возможностям языка. - -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) позволяет -довольно быстро изучить основные тонкие места в работе с JS, но фокусируется -только на таких моментах +[Современный учебник JavaScript (Илья Кантор)](http://learn.javascript.ru) - +качественный учебник по JavaScript на русском языке. -[Справочник](https://developer.mozilla.org/ru/docs/JavaScript) от MDN -(Mozilla Development Network) содержит информацию о возможностях языка на -английском. +[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) - +предоставляет отличную документацию для JavaScript, как он используется в браузерах. +Кроме того, это вики, поэтому, если вы знаете больше, вы можете помочь другим, +делясь своими знаниями. -Название проекта ["Принципы написания консистентного, идиоматического кода на -JavaScript"](https://github.com/rwaldron/idiomatic.js/tree/master/translations/ru_RU) -говорит само за себя. +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) - это +подробное руководство всех неинтуитивных особенностей языка. +[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) - можно +найти ответ почти на любой ваш вопрос, а если его нет, то задать вопрос самому. -- cgit v1.2.3 From 1a559fe83493cba67961e5009de068dae1ddcc53 Mon Sep 17 00:00:00 2001 From: "a.gonchar" Date: Wed, 24 Dec 2014 16:40:47 +0300 Subject: fix minor typos in javascript-ru #901 --- ru-ru/javascript-ru.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index dc35d18c..d7599e7e 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -12,7 +12,7 @@ lang: ru-ru JavaScript был создан в 1995 году Бренданом Айком, работающим в компании Netscape. Изначально он был задуман как простой язык сценариев для веб-сайтов, дополняющий Java для более сложных веб-приложений, но его тесная интеграция с веб-страницами -и втроенная поддержка браузерами привели к тому, что он стал более распространынным, +и втроенная поддержка браузерами привели к тому, что он стал более распространённым, чем Java в веб-интерфейсах. JavaScript не ограничивается только веб-браузером, например, Node.js, программная @@ -53,7 +53,7 @@ doStuff() // Включая деление с остатком. 5 / 2; // = 2.5 -// Побитовые операции так же имеются; Они производят операции, используя +// Побитовые операции также имеются; они производят операции, используя // двоичное представление числа, и возвращают новую последовательность из // 32 бит (число) в качестве результата. 1 << 2; // = 4 @@ -394,7 +394,7 @@ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 // Каждый объект в JavaScript имеет свойтво prototype. Когда вы хотите получить -// доступ к свойтву объекта, которое не существует в этом объекте, интерпритатор +// доступ к свойтву объекта, которое не существует в этом объекте, интерпретатор // будет искать это свойство в прототипе. // Некоторые реализации языка позволяют получить доступ к объекту прототипа @@ -417,7 +417,7 @@ myObj.meaningOfLife; // = 42 // Для функций это так же работает. myObj.myFunc(); // = "hello world!" -// Если интерпритатор не найдет свойство в прототипе, то продожит поиск в +// Если интерпретатор не найдет свойство в прототипе, то продожит поиск в // прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true -- cgit v1.2.3 From dd5803183c2c73cc8bd0aae05797c1493c334055 Mon Sep 17 00:00:00 2001 From: finico Date: Wed, 24 Dec 2014 22:32:24 +0300 Subject: [javascript/ru] needs correct typos #902 --- ru-ru/javascript-ru.html.markdown | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index d7599e7e..9efc2835 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -9,10 +9,10 @@ translators: lang: ru-ru --- -JavaScript был создан в 1995 году Бренданом Айком, работающим в компании Netscape. +JavaScript был создан в 1995 году Бренданом Айком, работавшим в компании Netscape. Изначально он был задуман как простой язык сценариев для веб-сайтов, дополняющий Java для более сложных веб-приложений, но его тесная интеграция с веб-страницами -и втроенная поддержка браузерами привели к тому, что он стал более распространённым, +и встроенная поддержка браузерами привели к тому, что он стал более распространённым, чем Java в веб-интерфейсах. JavaScript не ограничивается только веб-браузером, например, Node.js, программная @@ -27,7 +27,7 @@ Google Chrome, становится все более популярной. // Выражения заканчиваються точкой с запятой ; doStuff(); -// ... но они необязательны, так как точки с запятой автоматически вставляются +// ... но она необязательна, так как точки с запятой автоматически вставляются // везде, где есть символ новой строки, за некоторыми исключениями. doStuff() @@ -113,18 +113,18 @@ null === undefined; // = false // Вы можете получить доступ к любому символу строки, используя метод charAt "This is a string".charAt(0); // = 'T' -// ...или используйте метод substring чтобы получить более крупные части +// ...или используйте метод substring, чтобы получить более крупные части "Hello world".substring(0, 5); // = "Hello" -// length это свойство, для его получения не нужно использовать () +// length - это свойство, для его получения не нужно использовать () "Hello".length; // = 5 -// Так же есть null и undefined +// Также есть null и undefined null; // используется для обозначения намеренного значения "ничего" undefined; // используется для обозначения переменных, не имеющих // присвоенного значения (хотя переменная объявлена) -// false, null, undefined, NaN, 0 и "" это ложь; все остальное - истина. +// false, null, undefined, NaN, 0 и "" - это ложь; все остальное - истина. // Следует отметить, что 0 это ложь, а "0" - истина, несмотря на то, что 0 == "0". /////////////////////////////////// @@ -138,22 +138,22 @@ var someVar = 5; // если вы пропустите слово var, вы не получите сообщение об ошибке... someOtherVar = 10; -// ...но ваша переменная будет создана в глобальном контексте, а не в текущем -// гед вы ее объявили. +// ...но ваша переменная будет создана в глобальном контексте, а не в текущем, +// где вы ее объявили. -// Переменным объявленным без присвоения устанавливается значение undefined. +// Переменным, объявленным без присвоения, устанавливается значение undefined. var someThirdVar; // = undefined // У математических операций есть сокращённые формы: someVar += 5; // как someVar = someVar + 5; someVar теперь имеет значение 10 someVar *= 10; // теперь someVar имеет значение 100 -// а так же специальные операторы инкремент и декремент для увеличения и +// а также специальные операторы инкремент и декремент для увеличения и // уменьшения переменной на единицу соответственно someVar++; // теперь someVar имеет значение 101 someVar--; // обратно 100 -// Массивы это нумерованные списки из значений любого типа. +// Массивы - это нумерованные списки содержащие значения любого типа. var myArray = ["Hello", 45, true]; // Их элементы могут быть доступны при помощи синтаксиса с квадратными скобками. -- cgit v1.2.3 From e8d9163796ea76a028d5e23e7f833863425872f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=20Polykanine=20A=2EK=2EA=2E=20Menelion=20Elens=C3=BA?= =?UTF-8?q?l=C3=AB?= Date: Mon, 12 Jan 2015 02:33:53 +0200 Subject: [javascript/ru] Translating JavaScript guide into Russian --- ru-ru/javascript-ru.html.markdown | 266 +++++++++++++++++++------------------- 1 file changed, 136 insertions(+), 130 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 9efc2835..e7398c88 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -6,6 +6,7 @@ contributors: filename: javascript-ru.js translators: - ["Alexey Gonchar", "http://github.com/finico"] + - ["Andre Polykanine", "https://github.com/Oire"] lang: ru-ru --- @@ -15,7 +16,7 @@ Java для более сложных веб-приложений, но его и встроенная поддержка браузерами привели к тому, что он стал более распространённым, чем Java в веб-интерфейсах. -JavaScript не ограничивается только веб-браузером, например, Node.js, программная +JavaScript не ограничивается только веб-браузером: например, Node.js, программная платформа, позволяющая выполнять JavaScript, основанная на движке V8 от браузера Google Chrome, становится все более популярной. @@ -24,7 +25,7 @@ Google Chrome, становится все более популярной. /* а многострочные комментарии начинаются с звёздочка-слэш и заканчиваются символами слэш-звёздочка */ -// Выражения заканчиваються точкой с запятой ; +// Инструкции могут заканчиваться точкой с запятой ; doStuff(); // ... но она необязательна, так как точки с запятой автоматически вставляются @@ -53,12 +54,12 @@ doStuff() // Включая деление с остатком. 5 / 2; // = 2.5 -// Побитовые операции также имеются; они производят операции, используя -// двоичное представление числа, и возвращают новую последовательность из -// 32 бит (число) в качестве результата. +// Побитовые операции также имеются; когда вы проводите такую операцию, +// ваше число с плавающей запятой переводится в целое со знаком +// длиной *до* 32 разрядов. 1 << 2; // = 4 -// Приоритет в выражениях явно задаётся скобками. +// Приоритет в выражениях можно явно задать скобками. (1 + 3) * 2; // = 8 // Есть три специальных значения, которые не являются реальными числами: @@ -71,10 +72,10 @@ true; false; // Строки создаются при помощи двойных или одинарных кавычек. -'abc'; -"Hello, world"; +'абв'; +"Привет, мир!"; -// Для логического отрицания используется символ восклицательного знака. +// Для логического отрицания используется восклицательный знак. !true; // = false !false; // = true @@ -92,8 +93,8 @@ false; 2 <= 2; // = true 2 >= 2; // = true -// Строки конкатенируются при помощи оператора + -"Hello " + "world!"; // = "Hello world!" +// Строки объединяются при помощи оператора + +"привет, " + "мир!"; // = "Привет, мир!" // и сравниваются при помощи < и > "a" < "b"; // = true @@ -102,7 +103,7 @@ false; "5" == 5; // = true null == undefined; // = true -// ...а если использовать === +// ...если только не использовать === "5" === 5; // = false null === undefined; // = false @@ -111,31 +112,33 @@ null === undefined; // = false "13" + !0; // '13true' // Вы можете получить доступ к любому символу строки, используя метод charAt -"This is a string".charAt(0); // = 'T' +"Это строка".charAt(0); // = 'Э' // ...или используйте метод substring, чтобы получить более крупные части -"Hello world".substring(0, 5); // = "Hello" +"Привет, мир".substring(0, 6); // = "Привет" // length - это свойство, для его получения не нужно использовать () -"Hello".length; // = 5 +"Привет".length; // = 6 // Также есть null и undefined -null; // используется для обозначения намеренного значения "ничего" +null; // Намеренное отсутствие значения undefined; // используется для обозначения переменных, не имеющих - // присвоенного значения (хотя переменная объявлена) + // присвоенного значения (хотя непосредственно undefined + // является значением) -// false, null, undefined, NaN, 0 и "" - это ложь; все остальное - истина. -// Следует отметить, что 0 это ложь, а "0" - истина, несмотря на то, что 0 == "0". +// false, null, undefined, NaN, 0 и "" — это ложь; всё остальное - истина. +// Следует отметить, что 0 — это ложь, а "0" — истина, несмотря на то, что +// 0 == "0". /////////////////////////////////// // 2. Переменные, Массивы и Объекты -// Переменные объявляются при помощи ключевого слова var. JavaScript - язык с +// Переменные объявляются при помощи ключевого слова var. JavaScript — язык с // динамической типизацией, поэтому не нужно явно указывать тип. Для присваивания // значения переменной используется символ = var someVar = 5; -// если вы пропустите слово var, вы не получите сообщение об ошибке... +// если вы пропустите слово var, вы не получите сообщение об ошибке, ... someOtherVar = 10; // ...но ваша переменная будет создана в глобальном контексте, а не в текущем, @@ -148,34 +151,33 @@ var someThirdVar; // = undefined someVar += 5; // как someVar = someVar + 5; someVar теперь имеет значение 10 someVar *= 10; // теперь someVar имеет значение 100 -// а также специальные операторы инкремент и декремент для увеличения и -// уменьшения переменной на единицу соответственно +// Ещё более краткая запись увеличения и уменьшения на единицу: someVar++; // теперь someVar имеет значение 101 -someVar--; // обратно 100 +someVar--; // вернулись к 100 -// Массивы - это нумерованные списки содержащие значения любого типа. -var myArray = ["Hello", 45, true]; +// Массивы — это нумерованные списки, содержащие значения любого типа. +var myArray = ["Привет", 45, true]; // Их элементы могут быть доступны при помощи синтаксиса с квадратными скобками. // Индексы массивов начинаются с нуля. myArray[1]; // = 45 -// Массивы можно изменять, как и их длину. -myArray.push("World"); +// Массивы можно изменять, как и их длину, +myArray.push("Мир"); myArray.length; // = 4 -// Добавлять и редактировать определенный элемент -myArray[3] = "Hello"; +// добавлять и редактировать определённый элемент +myArray[3] = "Привет"; -// Объекты в JavaScript похожи на "словари" или ассоциативные массиы в других +// Объекты в JavaScript похожи на словари или ассоциативные массивы в других // языках: неупорядоченный набор пар ключ-значение. -var myObj = {key1: "Hello", key2: "World"}; +var myObj = {key1: "Привет", key2: "Мир"}; -// Ключи это строки, но кавычки необязательны, если строка удовлетворяет +// Ключи — это строки, но кавычки необязательны, если строка удовлетворяет // ограничениям для имён переменных. Значения могут быть любых типов. var myObj = {myKey: "myValue", "my other key": 4}; -// Атрибуты объектов можно также получить, используя квадратные скобки, +// Атрибуты объектов можно также получить, используя квадратные скобки myObj["my other key"]; // = 4 // или через точку, при условии, что ключ является допустимым идентификатором. @@ -184,16 +186,16 @@ myObj.myKey; // = "myValue" // Объекты изменяемы; можно изменять значения и добавлять новые ключи. myObj.myThirdKey = true; -// Если вы попытаетесь получить доступ к несуществующему свойству, +// Если вы попытаетесь получить доступ к несуществующему значению, // вы получите undefined. myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Логика и управляющие конструкции. -// Синтаксис для этого раздела почти такой же как в Java. +// Синтаксис для этого раздела почти такой же, как в Java. -// Эта конструкция работает, как и следовало ожидать. +// Условная конструкция работает, как и следовало ожидать, var count = 1; if (count == 3) { // выполняется, если count равен 3 @@ -203,50 +205,51 @@ if (count == 3) { // выполняется, если не 3 и не 4 } -// Как это делает while. +// ...как и цикл while. while (true){ // Бесконечный цикл! } -// Циклы do-while такие же как while, но они всегда выполняются хотя бы раз. +// Цикл do-while такой же, как while, но он всегда выполняется хотя бы раз. var input do { input = getInput(); } while (!isValid(input)) -// цикл for является таким же, как C и Java: +// цикл for такой же, как в C и Java: // инициализация; условие; шаг. for (var i = 0; i < 5; i++) { - // будет запущен 5 раз + // выполнится 5 раз } -// && это логическое И, || это логическое ИЛИ -if (house.size == "big" && house.colour == "blue") { +// && — это логическое И, || — это логическое ИЛИ +if (house.size == "big" && house.color == "blue") { house.contains = "bear"; } -if (colour == "red" || colour == "blue") { +if (color == "red" || color == "blue") { // цвет красный или синий } -// || используется как "короткий цикл вычисления" для присваивания переменных. +// && и || используют сокращённое вычисление, что полезно +// для задания значений по умолчанию. var name = otherName || "default"; -// Оператор switch выполняет проверку на равенство пр помощи === -// используйте break чтобы прервать выполнение после каждого case -// или выполнение пойдёт далее, игнорируя при этом остальные проверки. -grade = 'B'; +// Оператор switch выполняет проверку на равенство при помощи === +// используйте break, чтобы прервать выполнение после каждого case, +// или выполнение пойдёт далее даже после правильного варианта. +grade = 4; switch (grade) { - case 'A': - console.log("Great job"); + case 5: + console.log("Отлично"); break; - case 'B': - console.log("OK job"); + case 4: + console.log("Хорошо"); break; - case 'C': - console.log("You can do better"); + case 3: + console.log("Можете и лучше"); break; default: - console.log("Oy vey"); + console.log("Ой-вей!"); break; } @@ -273,33 +276,33 @@ function myFunction() } myFunction(); // = undefined -// JavaScript функции - это объекты, поэтому они могут быть переприсвоены на -// различные имена переменных и передаваться другим функциям в качестве аргументов, -// например, когда назначается обработчик события: +// В JavaScript функции — это объекты первого класса, поэтому они могут быть +// присвоены различным именам переменных и передаваться другим функциям +// в качестве аргументов, например, когда назначается обработчик события: function myFunction() { // этот код будет вызван через 5 секунд } setTimeout(myFunction, 5000); // Примечание: setTimeout не является частью языка, но реализован в браузерах и Node.js -// Функции не обязательно должны иметь имя при объявлении - вы можете написать -// анонимное определение функции непосредственно в агрументе другой функции. +// Функции не обязательно должны иметь имя при объявлении — вы можете написать +// анонимное определение функции непосредственно в аргументе другой функции. setTimeout(function() { // этот код будет вызван через 5 секунд }, 5000); -// В JavaScript есть область видимости функции; функции имеют свою область -// видимости, а другие блоки - нет. +// В JavaScript есть область видимости; функции имеют свою область +// видимости, а другие блоки — нет. if (true) { var i = 5; } -i; // = 5 - не undefined как ожидалось бы в языках с блочной областью видимости +i; // = 5, а не undefined, как ожидалось бы в языках с блочной областью видимости // Это привело к общепринятому шаблону "самозапускающихся анонимных функций", // которые препятствуют проникновению переменных в глобальную область видимости (function() { var temporary = 5; - // Мы можем получить доступ к глобальной области для записи в "глобальный объект", + // Мы можем получить доступ к глобальной области для записи в «глобальный объект», // который в веб-браузере всегда window. Глобальный объект может иметь другое // имя в таких платформах, как Node.js window.permanent = 10; @@ -309,100 +312,101 @@ permanent; // = 10 // Одной из самых мощных возможностей JavaScript являются замыкания. Если функция // определена внутри другой функции, то внутренняя функция имеет доступ к -// переменным внешней функции, даже после того, как контекст выполнения выйдет из +// переменным внешней функции даже после того, как контекст выполнения выйдет из // внешней функции. function sayHelloInFiveSeconds(name) { - var prompt = "Hello, " + name + "!"; + var prompt = "Привет, " + name + "!"; // Внутренние функции по умолчанию помещаются в локальную область видимости, - // как если бы они были объявлены с var. + // как если бы они были объявлены с помощью var. function inner() { alert(prompt); } setTimeout(inner, 5000); - // setTimeout асинхронна, поэтому функция sayHelloInFiveSeconds сразу выйдет - // и тело setTimeout будет вызвано позже. Однако, поскольку внутренняя - // функция "замкнута", она по-прежнему имеет доступ к переменной prompt, - // когда sayHelloInFiveSeconds вызывется. + // setTimeout асинхронна, поэтому функция sayHelloInFiveSeconds сразу выйдет, + // после чего setTimeout вызовет функцию inner. Однако поскольку функция inner + // «замкнута» вокруг sayHelloInFiveSeconds, она по-прежнему имеет доступ к переменной prompt + // на то время, когда она наконец будет вызвана. } -sayHelloInFiveSeconds("Adam"); // откроется окно с "Hello, Adam!" через 5 секунд +sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!» /////////////////////////////////// -// 5. Подробнее про Объекты, Конструкторы и Прототипы +// 5. Подробнее об объектах; конструкторы и прототипы // Объекты могут содержать в себе функции. var myObj = { myFunc: function() { - return "Hello world!"; + return "Привет, мир!"; } }; -myObj.myFunc(); // = "Hello world!" +myObj.myFunc(); // = "Привет, мир!" -// Когда функции, прикрепленные к объекту, вызываются, они могут получить доступ +// Когда вызываются функции, прикреплённые к объекту, они могут получить доступ // к этому объекту с помощью ключевого слова this. myObj = { - myString: "Hello world!", + myString: "Привет, мир!", myFunc: function() { return this.myString; } }; -myObj.myFunc(); // = "Hello world!" +myObj.myFunc(); // = "Привет, мир!" -// Какое это значение имеет к тому, как вызвана функция и где она определена. -// Итак, наша функция не работает, если она вызывается не в контексте объекта. +// Значение this зависит от того, как функция вызывается, +// а не от того, где она определена. Таким образом, наша функция не работает, +// если она вызывается не в контексте объекта. var myFunc = myObj.myFunc; myFunc(); // = undefined // И наоборот, функция может быть присвоена объекту и получать доступ к нему -// через this, даже если она не была присвоена при объявлении. +// через this, даже если она не была прикреплена к нему при объявлении. var myOtherFunc = function() { } myObj.myOtherFunc = myOtherFunc; -myObj.myOtherFunc(); // = "HELLO WORLD!" +myObj.myOtherFunc(); // = "ПРИВЕТ, МИР!" -// Мы можем также указать контекст для выполнения функции, когда мы вызываем ее -// с помощью call или apply. +// Мы можем также указать контекст для выполнения функции при её вызове, +// используя call или apply. var anotherFunc = function(s) { return this.myString + s; } -anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" +anotherFunc.call(myObj, " И привет, Луна!"); // = "Привет, мир! И привет, Луна!" -// Функция apply аналогична, но принимает массив аргументов. -anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" +// Функция apply почти такая же, но принимает в качестве списка аргументов массив. +anotherFunc.apply(myObj, [" И привет, Солнце!"]); // = "Привет, мир! И привет, Солнце!" // Это полезно при работе с функцией, которая принимает последовательность -// аргументов, и вы хотите передать массив. +// аргументов, а вы хотите передать массив. Math.min(42, 6, 27); // = 6 -Math.min([42, 6, 27]); // = NaN (не сработает!) +Math.min([42, 6, 27]); // = NaN (Ой-ой!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Но, call и apply - временные. Когда мы хотим связать функцию, мы можем -// использовать bind. +// Но call и apply — только временные. Когда мы хотим связать функцию с объектом, +// мы можем использовать bind. var boundFunc = anotherFunc.bind(myObj); -boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" +boundFunc(" И привет, Сатурн!"); // = "Привет, мир! И привет, Сатурн!" -// Bind также может использоваться, для частичного применения (каррирование) функции +// Bind также может использоваться для частичного применения (каррирования) функции var product = function(a, b) { return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// Когда вы вызываете функцию с помощью ключевого слова new создается новый объект, -// и создает доступ к функции при помощи this. Такие функции называют конструкторами. +// Когда вы вызываете функцию с помощью ключевого слова new, создается новый объект, +// доступный функции при помощи this. Такие функции называют конструкторами. var MyConstructor = function() { this.myNumber = 5; } myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Каждый объект в JavaScript имеет свойтво prototype. Когда вы хотите получить -// доступ к свойтву объекта, которое не существует в этом объекте, интерпретатор +// У каждого объекта в JavaScript есть прототип. Когда вы хотите получить +// доступ к свойству объекта, которое не существует в этом объекте, интерпретатор // будет искать это свойство в прототипе. -// Некоторые реализации языка позволяют получить доступ к объекту прототипа -// через свойство __proto__. Несмотря на то, что это может быть полезно для -// понимания прототипов, это не часть стандарта; мы увидим стандартные способы +// Некоторые реализации языка позволяют получить доступ к прототипу объекта +// через «магическое» свойство __proto__. Несмотря на то, что это может быть полезно +// для понимания прототипов, это не часть стандарта; мы увидим стандартные способы // использования прототипов позже. var myObj = { - myString: "Hello world!" + myString: "Привет, мир!" }; var myPrototype = { meaningOfLife: 42, @@ -414,34 +418,34 @@ var myPrototype = { myObj.__proto__ = myPrototype; myObj.meaningOfLife; // = 42 -// Для функций это так же работает. -myObj.myFunc(); // = "hello world!" +// Для функций это тоже работает. +myObj.myFunc(); // = "Привет, мир!" -// Если интерпретатор не найдет свойство в прототипе, то продожит поиск в -// прототипе прототипа и так далее. +// Если интерпретатор не найдёт свойство в прототипе, то продожит поиск +// в прототипе прототипа и так далее. myPrototype.__proto__ = { myBoolean: true }; myObj.myBoolean; // = true // Здесь не участвует копирование; каждый объект хранит ссылку на свой прототип. -// Это означает, что мы можем изменить прототип и наши изменения будут отражены везде +// Это означает, что мы можем изменить прототип, и наши изменения будут отражены везде. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// Мы упомянули, что свойтсво __proto__ нестандартно, и нет никакого стандартного -// способа, чтобы изменить прототип существующего объекта. Однако, есть два +// Мы упомянули, что свойство __proto__ нестандартно, и нет никакого стандартного +// способа, чтобы изменить прототип существующего объекта. Однако есть два // способа создать новый объект с заданным прототипом. -// Первый способ это Object.create, который появился в ECMAScript 5 и есть еще -// не во всех реализациях языка. +// Первый способ — это Object.create, который появился в JavaScript недавно, +// а потому доступен ещё не во всех реализациях языка. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 // Второй способ, который работает везде, имеет дело с конструкторами. -// У конструкторов есть свойство с именем prototype. Это не прототип +// У конструкторов есть свойство с именем prototype. Это *не* прототип // функции-конструктора; напротив, это прототип для новых объектов, которые -// будут созданы с помощью этого конструктора и ключевого слова new +// будут созданы с помощью этого конструктора и ключевого слова new. MyConstructor.prototype = { myNumber: 5, getMyNumber: function() { @@ -453,8 +457,8 @@ myNewObj2.getMyNumber(); // = 5 myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 -// У встроенных типов, таких как строки и числа также есть конструкторы, которые -// создают эквивалентые объекты-обертки. +// У встроенных типов, таких, как строки и числа, также есть конструкторы, которые +// создают эквивалентные объекты-обёртки. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true @@ -464,47 +468,49 @@ typeof myNumber; // = 'number' typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0) { - // Этот код не выполнятся, потому что 0 - это ложь. + // Этот код не выполнится, потому что 0 - это ложь. } if (Number(0)) { - // Этот код выполнится, потому что Number(0) это истина. + // Этот код *выполнится*, потому что Number(0) истинно. } -// Впрочем, обертки это объекты и их можно расширять, например: +// Впрочем, объекты-обёртки и встроенные типы имеют общие прототипы, +// поэтому вы можете расширить функционал строк, например: String.prototype.firstCharacter = function() { return this.charAt(0); } "abc".firstCharacter(); // = "a" -// Это часто используется в полифиллах, которые реализуют новые возможности +// Это часто используется в т.н. полифилах, которые реализуют новые возможности // JavaScript в старой реализации языка, так что они могут быть использованы в -// старых средах, таких как устаревшие браузеры. +// старых средах, таких, как устаревшие браузеры. // Например, мы упомянули, что Object.create доступен не во всех реализациях, но -// мы сможем использовать его с этим полифиллом: -if (Object.create === undefined) { // не перезаписывать метод, если он существует +// мы сможем использовать его с помощью такого полифила: +if (Object.create === undefined) { // не перезаписываем метод, если он существует Object.create = function(proto) { - // создать временный конструктор с правильным прототипом + // создаём временный конструктор с правильным прототипом var Constructor = function(){}; Constructor.prototype = proto; - // затем использовать его для создания нового объекта, на основе прототипа + // затем используем его для создания нового, + // правильно прототипированного объекта return new Constructor(); } } ``` -## Что еще почитать +## Что ещё почитать -[Современный учебник JavaScript (Илья Кантор)](http://learn.javascript.ru) - +[Современный учебник JavaScript (Илья Кантор)](http://learn.javascript.ru) — качественный учебник по JavaScript на русском языке. -[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) - +[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) — предоставляет отличную документацию для JavaScript, как он используется в браузерах. Кроме того, это вики, поэтому, если вы знаете больше, вы можете помочь другим, делясь своими знаниями. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) - это -подробное руководство всех неинтуитивных особенностей языка. +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) — это +подробное руководство по всем неинтуитивным особенностей языка. -[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) - можно +[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) — можно найти ответ почти на любой ваш вопрос, а если его нет, то задать вопрос самому. -- cgit v1.2.3 From d02448f78946d098ea0c906c2622bb4e16235b79 Mon Sep 17 00:00:00 2001 From: Yuichi Motoyama Date: Tue, 13 Jan 2015 09:29:15 +0900 Subject: [julia/ja] Added missing `lang: ja-jp` Sorry, I missed writing `lang: ja-jp` in #894, and made a new Julia language tree in the top page. --- ja-jp/julia-jp.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown index 0c1d7e49..0c3160a2 100644 --- a/ja-jp/julia-jp.html.markdown +++ b/ja-jp/julia-jp.html.markdown @@ -5,6 +5,7 @@ contributors: translators: - ["Yuichi Motoyama", "https://github.com/yomichi"] filename: learnjulia-jp.jl +lang: ja-jp --- Julia は科学技術計算向けに作られた、同図像性を持った(homoiconic) プログラミング言語です。 -- cgit v1.2.3 From a7918fb33c82ae350326064d74a98411e8c79995 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Tue, 13 Jan 2015 11:46:28 +0300 Subject: [brainfuck/ru] Translating Brainfuck guide into Russian --- ru-ru/brainfuck-ru.html.markdown | 83 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 ru-ru/brainfuck-ru.html.markdown diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown new file mode 100644 index 00000000..f6e27ed2 --- /dev/null +++ b/ru-ru/brainfuck-ru.html.markdown @@ -0,0 +1,83 @@ +--- +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 представлен массивом из 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. -- cgit v1.2.3 From dd5588a2194b4e1f98fc4cee8a2fc277f6eae2f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20Ara=C3=BAjo?= Date: Tue, 13 Jan 2015 10:26:08 -0300 Subject: [C++/en] translated to [C++/pt-br] --- pt-br/c++-pt.html.markdown | 591 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 591 insertions(+) create mode 100644 pt-br/c++-pt.html.markdown diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown new file mode 100644 index 00000000..243627cb --- /dev/null +++ b/pt-br/c++-pt.html.markdown @@ -0,0 +1,591 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +C++ é uma linguagem de programação de sistemas que, +C++ is a systems programming language that, +[de acordo com seu inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +foi concebida para + +- ser um "C melhor" +- suportar abstração de dados +- suportar programação orientada a objetos +- suportar programação genérica + +Embora sua sintaxe pode ser mais difícil ou complexa do que as linguagens mais +recentes, C++ é amplamente utilizado porque compila para instruções nativas que +podem ser executadas diretamente pelo processador e oferece um controlo rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os +genéricos, exceções e classes. Esta combinação de velocidade e funcionalidade +faz C++ uma das linguagens de programação mais utilizadas. + +```c++ +////////////////// +// Comparação com C +////////////////// + +// C ++ é quase um super conjunto de C e compartilha sua sintaxe básica para +// declarações de variáveis, tipos primitivos, e funções. No entanto, C++ varia +// em algumas das seguintes maneiras: + +// A função main() em C++ deve retornar um int, embora void main() é aceita +// pela maioria dos compiladores (gcc, bumbum, etc.) +// Este valor serve como o status de saída do programa. +// Veja http://en.wikipedia.org/wiki/Exit_status para mais informações. + +int main(int argc, char** argv) +{ + // Argumentos de linha de comando são passados em pelo argc e argv da mesma + // forma que eles estão em C. + // argc indica o número de argumentos, + // e argv é um array de strings, feito C (char*) representado os argumentos + // O primeiro argumento é o nome pelo qual o programa foi chamado. + // argc e argv pode ser omitido se você não se importa com argumentos, + // dando a assinatura da função de int main() + + // Uma saída de status de 0 indica sucesso. + return 0; +} + +// Em C++, caracteres literais são um byte. +sizeof('c') == 1 + +// Em C, caracteres literais são do mesmo tamanho que ints. +sizeof('c') == sizeof(10) + +// C++ tem prototipagem estrita +void func(); // função que não aceita argumentos + +// Em C +void func(); // função que pode aceitar qualquer número de argumentos + +// Use nullptr em vez de NULL em C++ +int* ip = nullptr; + +// Cabeçalhos padrão C estão disponíveis em C++, +// mas são prefixados com "c" e não têm sufixo .h + +#include + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////////////////// +// Sobrecarga de função +/////////////////////// + +// C++ suporta sobrecarga de função +// desde que cada função tenha parâmetros diferentes. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // Funciona para void print(const char*) + print(15); // Funciona para void print(int) +} + +///////////////////////////// +// Parâmetros padrão de função +///////////////////////////// + +// Você pode fornecer argumentos padrões para uma função se eles não são +// fornecidos pelo chamador. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Faça alguma coisa com os ints aqui +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Argumentos padrões devem estar no final da lista de argumentos. + +void invalidDeclaration(int a = 1, int b) // Erro! +{ +} + + +///////////// +// Namespaces (nome de espaços) +///////////// + +// Namespaces fornecem escopos distintos para variável, função e outras +// declarações. Namespaces podem estar aninhados. + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // Fim do namespace aninhado +} // Fim do namespace First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // Assuma que tudo é do namespace "Second" a menos que especificado de + // outra forma. + using namespace Second; + + foo(); // imprime "This is Second::foo" + First::Nested::foo(); // imprime "This is First::Nested::foo" + ::foo(); // imprime "This is global foo" +} + +/////////////// +// Entrada/Saída +/////////////// + +// C ++ usa a entrada e saída de fluxos (streams) +// cin, cout, and cerr representa stdin, stdout, and stderr. +// << É o operador de inserção e >> é o operador de extração. + +#include // Inclusão para o I/O streams + +using namespace std; // Streams estão no namespace std (biblioteca padrão) + +int main() +{ + int myInt; + + // Imprime na saída padrão (ou terminal/tela) + cout << "Enter your favorite number:\n"; + // Pega a entrada + cin >> myInt; + + // cout também pode ser formatado + cout << "Your favorite number is " << myInt << "\n"; + // imprime "Your favorite number is " + + cerr << "Usado para mensagens de erro"; +} + +////////// +// Strings +////////// + +// Strings em C++ são objetos e têm muitas funções de membro +#include + +using namespace std; // Strings também estão no namespace std (bib. padrão) + +string myString = "Hello"; +string myOtherString = " World"; + +// + é usado para concatenação. +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// Em C++, strings são mutáveis e têm valores semânticos. +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// Referência +///////////// + +// Além de indicadores como os de C, C++ têm _referências_. Esses são tipos de +// ponteiro que não pode ser reatribuída uma vez definidos e não pode ser nulo. +// Eles também têm a mesma sintaxe que a própria variável: Não * é necessário +// para _dereferencing_ e & (endereço de) não é usado para atribuição. + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // Isso cria uma referência para foo. +fooRef += ". Hi!"; // Modifica foo através da referência +cout << fooRef; // Imprime "I am foo. Hi!" + +// Não realocar "fooRef". Este é o mesmo que "foo = bar", e foo == "I am bar" +// depois desta linha. + +fooRef = bar; + +const string& barRef = bar; // Cria uma referência const para bar. +// Como C, valores const (e ponteiros e referências) não podem ser modificado. +barRef += ". Hi!"; // Erro, referência const não pode ser modificada. + +////////////////////////////////////////// +// Classes e programação orientada a objeto +////////////////////////////////////////// + +// Primeiro exemplo de classes +#include + +// Declara a classe. +// As classes são geralmente declarado no cabeçalho arquivos (.h ou .hpp). +class Dog { + // Variáveis de membro e funções são privadas por padrão. + std::string name; + int weight; + +// Todos os membros a seguir este são públicos até que "private:" ou +// "protected:" é encontrado. +public: + + // Construtor padrão + Dog(); + + // Declarações de função Membro (implementações a seguir) + // Note que usamos std :: string aqui em vez de colocar + // using namespace std; + // acima. + // Nunca coloque uma declaração "using namespace" em um cabeçalho. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // Funções que não modificam o estado do objecto devem ser marcadas como + // const. Isso permite que você chamá-los se for dada uma referência const + // para o objeto. Além disso, observe as funções devem ser explicitamente + // declarados como _virtual_, a fim de ser substituídas em classes + // derivadas. As funções não são virtuais por padrão por razões de + // performance. + + virtual void print() const; + + // As funções também podem ser definidas no interior do corpo da classe. + // Funções definidas como tal são automaticamente embutidas. + void bark() const { std::cout << name << " barks!\n" } + + // Junto com os construtores, C++ fornece destruidores. + // Estes são chamados quando um objeto é excluído ou fica fora do escopo. + // Isto permite paradigmas poderosos, como RAII + // (veja abaixo) + // Destruidores devem ser virtual para permitir que as classes de ser + // derivada desta. + virtual ~Dog(); + +}; // Um ponto e vírgula deve seguir a definição de classe. + +// Funções membro da classe geralmente são implementados em arquivos .cpp. +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// Objetos (como strings) devem ser passados por referência +// se você está modificando-os ou referência const se você não é. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Observe que "virtual" só é necessária na declaração, não a definição. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // imprime "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.printDog(); // imprime "Dog is Barkley and weighs 10 kg" + return 0; +} // imprime "Goodbye Barkley" + +// herança: + +// Essa classe herda tudo público e protegido da classe Dog +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // Substituir o comportamento da função de impressão de todas OwnedDogs. + // Ver http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // Para uma introdução mais geral, se você não estiver familiarizado com o + // polimorfismo subtipo. A palavra-chave override é opcional, mas torna-se + // na verdade você está substituindo o método em uma classe base. + void print() const override; + +private: + std::string owner; +}; + +// Enquanto isso, no arquivo .cpp correspondente: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Chame a função de impressão na classe Dog base de + std::cout << "Dog is owned by " << owner << "\n"; + // Prints "Dog is and weights " + // "Dog is owned by " +} + +////////////////////////////////////////// +// Inicialização e Sobrecarga de Operadores +////////////////////////////////////////// + +// Em C ++, você pode sobrecarregar o comportamento dos operadores, tais como +// +, -, *, /, etc. Isto é feito através da definição de uma função que é +// chamado sempre que o operador é usado. + +#include +using namespace std; + +class Point { +public: + // Variáveis membro pode ser dado valores padrão desta maneira. + double x = 0; + double y = 0; + + // Define um construtor padrão que não faz nada + // mas inicializar o Point para o valor padrão (0, 0) + Point() { }; + + // A sintaxe a seguir é conhecido como uma lista de inicialização + // e é a maneira correta de inicializar os valores de membro de classe + Point (double a, double b) : + x(a), + y(b) + { /* Não fazer nada, exceto inicializar os valores */ } + + // Sobrecarrega o operador +. + Point operator+(const Point& rhs) const; + + // Sobrecarregar o operador +=. + Point& operator+=(const Point& rhs); + + // Ele também faria sentido para adicionar os operadores - e -=, + // mas vamos pular para sermos breves. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Criar um novo ponto que é a soma de um e 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); + // Isto chama que o operador ponto + + // Ressalte-se a chamadas (função)+ com direito como seu parâmetro... + Point result = up + right; + // Imprime "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////////// +// Tratamento de Exceções +///////////////////////// + +// A biblioteca padrão fornece alguns tipos de exceção +// (see http://en.cppreference.com/w/cpp/error/exception) +// mas qualquer tipo pode ser jogado como uma exceção +#include + +// Todas as exceções lançadas dentro do bloco try pode ser capturado por +// manipuladores de captura subseqüentes +try { + // Não aloca exceções no heap usando _new_. + throw std::exception("A problem occurred"); +} +// Capturar exceções por referência const se eles são objetos +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// Captura qualquer exceção não capturada pelos blocos _catch_ anteriores +} catch (...) +{ + std::cout << "Exceção desconhecida encontrada"; + throw; // Re-lança a exceção +} + +/////// +// RAII +/////// + +// RAII significa alocação de recursos é de inicialização. +// Muitas vezes, é considerado o paradigma mais poderoso em C++, e é o +// conceito simples que um construtor para um objeto adquire recursos daquele +// objeto e o destruidor liberá-los. + +// Para entender como isso é útil, +// Considere uma função que usa um identificador de arquivo C: +void doSomethingWithAFile(const char* filename) +{ + // Para começar, assuma que nada pode falhar. + + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Feche o arquivo. +} + +// Infelizmente, as coisas são levemente complicadas para tratamento de erros. +// Suponha que fopen pode falhar, e que doSomethingWithTheFile e +// doSomethingElseWithIt retornam códigos de erro se eles falharem. (As +// exceções são a forma preferida de lidar com o fracasso, mas alguns +// programadores, especialmente aqueles com um conhecimento em C, discordam +// sobre a utilidade de exceções). Agora temos que verificar cada chamada para +// o fracasso e fechar o identificador de arquivo se ocorreu um problema. + +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura + if (fh == nullptr) // O ponteiro retornado é nulo em caso de falha. + reuturn false; // Relate o fracasso para o chamador. + + // Suponha cada função retorne false, se falhar + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return false; // Propague o erro. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return false; // Propague o erro. + } + + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return true; // Indica sucesso +} + +// Programadores C frequentemente limpam isso um pouco usando Goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + reuturn false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indica sucesso + +failure: + fclose(fh); + return false; // Propague o erro. +} + +// Se as funções indicam erros usando exceções, +// as coisas são um pouco mais limpo, mas ainda abaixo do ideal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura. + if (fh == nullptr) + throw std::exception("Não pode abrir o arquivo."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Certifique-se de fechar o arquivo se ocorrer um erro. + throw; // Em seguida, re-lance a exceção. + } + + fclose(fh); // Feche o arquivo + // Tudo ocorreu com sucesso! +} + +// Compare isso com o uso de C++ classe fluxo de arquivo (fstream) fstream usa +// seu destruidor para fechar o arquivo. Lembre-se de cima que destruidores são +// automaticamente chamado sempre que um objeto cai fora do âmbito. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream é curto para o fluxo de arquivo de entrada + std::ifstream fh(filename); // Abra o arquivo + + // faça alguma coisa com o arquivo + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // O arquivo é automaticamente fechado aqui pelo destructor + +// Isto tem _grandes_ vantagens: +// 1. Não importa o que aconteça, +// o recurso (neste caso, o identificador de ficheiro) irá ser limpo. +// Depois de escrever o destruidor corretamente, +// É _impossível_ esquecer de fechar e vazar o recurso +// 2. Nota-se que o código é muito mais limpo. +// As alças destructor fecham o arquivo por trás das cenas +// sem que você precise se preocupar com isso. +// 3. O código é seguro de exceção. +// Uma exceção pode ser jogado em qualquer lugar na função e a limpeza +// irá ainda ocorrer. + +// Todos códigos C++ usam RAII extensivamente para todos os recursos. +// Outros exemplos incluem +// - Memória usa unique_ptr e shared_ptr +// - Contentores - a lista da biblioteca ligada padrão, +// vetor (i.e. array de autodimensionamento), mapas hash, e assim por diante +// tudo é automaticamente destruído quando eles saem de escopo +// - Mutex usa lock_guard e unique_lock +``` +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 -- cgit v1.2.3 From 4fc9c89f64e64c3dce19eec7adecd4efb009c162 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Tue, 13 Jan 2015 19:19:24 +0300 Subject: Fix small mistackes. --- ru-ru/brainfuck-ru.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown index f6e27ed2..500ac010 100644 --- a/ru-ru/brainfuck-ru.html.markdown +++ b/ru-ru/brainfuck-ru.html.markdown @@ -12,10 +12,10 @@ Brainfuck (пишется маленькими буквами, кроме нач маленький Тьюринг-полный язык программирования лишь с 8 командами. ``` -Любой символ игнорируется кроме "><+-.,[]" (исключая кавычки). +Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, -и указателем, указывающего на текущую ячейку. +и указателем с позицией в текущей ячейке. Всего восемь команд: + : Увеличивает значение на единицу в текущей ячейке. @@ -29,22 +29,22 @@ Brainfuck представлен массивом из 30000 ячеек, ини ] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. В противном случае, вернуться назад к соответствующей [ . -[ и ] образуют цикл while. Очевидно, они должны быть сбалансированы. +[ и ] образуют цикл while. Естественно, они должны быть сбалансированы. -Давайте рассмотрим некоторые базовые brainfuck программы. +Давайте рассмотрим некоторые базовые brainfuck-программы. ++++++ [ > ++++++++++ < - ] > +++++ . -Эта программа выводит букву 'A'. Сначала, программа увеличивает значение -ячейки №1 до 6. Ячейка #1 будет использоваться циклом. Затем, программа входит +Эта программа выводит букву 'A'. Сначала программа увеличивает значение +ячейки №1 до 6. Ячейка №1 будет использоваться циклом. Затем программа входит в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] и идет дальше). -В этот момент, мы в ячейке №1, которая имеет значение 0, значение ячейки №2 -пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, и затем -выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, +В этот момент мы находимся в ячейке №1, которая имеет значение 0, значение +ячейки №2 пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, +и затем выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, так что 'A' выводится на терминал. @@ -53,11 +53,11 @@ Brainfuck представлен массивом из 30000 ячеек, ини Данная программа считывает символ из пользовательского ввода и копирует символ в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается -до тех пор пока, ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение -ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2, и +до тех пор, пока ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение +ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2 и затем выводим символ ASCII. -Также, имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете +Также имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете легко написать и так: ,[>+<-]>. @@ -71,13 +71,13 @@ Brainfuck представлен массивом из 30000 ячеек, ини Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется -проблема: В конце внутреннего цикла, ячейка №2 равна нулю. В этом случае, +проблема: В конце внутреннего цикла ячейка №2 равна нулю. В этом случае, внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. Итак, ячейка №3 - результат. ``` Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать -свою собственную brainfuck программу или интерпретатор на другом языке. +свою собственную brainfuck-программу или интерпретатор на другом языке. Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте -написать brainfuck интерпретатор... на языке brainfuck. +написать brainfuck-интерпретатор... на языке brainfuck. -- cgit v1.2.3 From dff86ae3cb5618609f8238cca20c2493b5ffc240 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 13 Jan 2015 20:09:14 +0000 Subject: Update common-lisp-pt.html.markdown --- pt-br/common-lisp-pt.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown index ce654846..03a7c15c 100644 --- a/pt-br/common-lisp-pt.html.markdown +++ b/pt-br/common-lisp-pt.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Paul Nathan", "https://github.com/pnathan"] translators: - ["Édipo Luis Féderle", "https://github.com/edipofederle"] +lang: pt-br --- ANSI Common Lisp é uma linguagem de uso geral, multi-paradigma, designada -- cgit v1.2.3 From ecc5d89841ec2417c8d68f0c84347760cf69c140 Mon Sep 17 00:00:00 2001 From: P1start Date: Thu, 15 Jan 2015 15:14:19 +1300 Subject: [rust/en] Update the Rust tutorial This adjusts the English Rust tutorial for changes to the language and generally tweaks a few other things. Fixes #860. --- rust.html.markdown | 169 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 102 insertions(+), 67 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 3717a7d9..dcb54733 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -7,9 +7,13 @@ filename: learnrust.rs Rust is an in-development programming language developed by Mozilla Research. It is relatively unique among systems languages in that it can assert memory -safety *at compile time*. Rust’s first alpha release occurred in January -2012, and development moves so quickly that at the moment the use of stable -releases is discouraged, and instead one should use nightly builds. +safety *at compile time* without resorting to garbage collection. Rust’s first +release, 0.1, occurred in January 2012, and development moves so quickly that at +the moment the use of stable releases is discouraged, and instead one should use +nightly builds. On January 9 2015, Rust 1.0 Alpha was released, and the rate of +changes to the Rust compiler that break existing code has dropped significantly +since. However, a complete guarantee of backward compatibility will not exist +until the final 1.0 release. Although Rust is a relatively low-level language, Rust has some functional concepts that are generally found in higher-level languages. This makes @@ -24,7 +28,8 @@ Rust not only fast, but also easy and efficient to code in. /////////////// // Functions -fn add2(x: int, y: int) -> int { +// `i32` is the type for 32-bit signed integers +fn add2(x: i32, y: i32) -> i32 { // Implicit return (no semicolon) x + y } @@ -34,71 +39,90 @@ fn main() { // Numbers // // Immutable bindings - let x: int = 1; + let x: i32 = 1; // Integer/float suffixes - let y: int = 13i; + let y: i32 = 13i32; let f: f64 = 1.3f64; // Type inference - let implicit_x = 1i; - let implicit_f = 1.3f64; + // Most of the time, the Rust compiler can infer what type a variable is, so + // you don’t have to write an explicit type annotation. + // Throughout this tutorial, types are explicitly annotated in many places, + // but only for demonstrative purposes. Type inference can handle this for + // you most of the time. + let implicit_x = 1; + let implicit_f = 1.3; - // Maths - let sum = x + y + 13i; + // Arithmetic + let sum = x + y + 13; // Mutable variable let mut mutable = 1; + mutable = 4; mutable += 2; // Strings // - + // String literals - let x: &'static str = "hello world!"; + let x: &str = "hello world!"; // Printing println!("{} {}", f, x); // 1.3 hello world - // A `String` - a heap-allocated string + // A `String` – a heap-allocated string let s: String = "hello world".to_string(); - // A string slice - an immutable view into another string - // This is basically an immutable pointer to a string - it doesn’t - // actually contain the characters of a string, just a pointer to + // A string slice – an immutable view into another string + // This is basically an immutable pointer to a string – it doesn’t + // actually contain the contents of a string, just a pointer to // something that does (in this case, `s`) - let s_slice: &str = s.as_slice(); + let s_slice: &str = &*s; println!("{} {}", s, s_slice); // hello world hello world // Vectors/arrays // // A fixed-size array - let four_ints: [int, ..4] = [1, 2, 3, 4]; + let four_ints: [i32; 4] = [1, 2, 3, 4]; - // A dynamically-sized vector - let mut vector: Vec = vec![1, 2, 3, 4]; + // A dynamic array (vector) + let mut vector: Vec = vec![1, 2, 3, 4]; vector.push(5); - // A slice - an immutable view into a vector or array + // A slice – an immutable view into a vector or array // This is much like a string slice, but for vectors - let slice: &[int] = vector.as_slice(); + let slice: &[i32] = &*vector; + + // Use `{:?}` to print something debug-style + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuples // - println!("{} {}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + // A tuple is a fixed-size set of values of possibly different types + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // Destructuring `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // Indexing + println!("{}", x.1); // hello ////////////// // 2. Types // ////////////// - + // Struct struct Point { - x: int, - y: int, + x: i32, + y: i32, } let origin: Point = Point { x: 0, y: 0 }; - // Tuple struct - struct Point2(int, int); + // A struct with unnamed fields, called a ‘tuple struct’ + struct Point2(i32, i32); let origin2 = Point2(0, 0); @@ -110,16 +134,16 @@ fn main() { Down, } - let up = Up; + let up = Direction::Up; // Enum with fields - enum OptionalInt { - AnInt(int), + enum OptionalI32 { + AnI32(i32), Nothing, } - let two: OptionalInt = AnInt(2); - let nothing: OptionalInt = Nothing; + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; // Generics // @@ -140,10 +164,10 @@ fn main() { } } - let a_foo = Foo { bar: 1i }; + let a_foo = Foo { bar: 1 }; println!("{}", a_foo.get_bar()); // 1 - // Traits (interfaces) // + // Traits (known as interfaces or typeclasses in other languages) // trait Frobnicate { fn frobnicate(self) -> Option; @@ -155,30 +179,31 @@ fn main() { } } - println!("{}", a_foo.frobnicate()); // Some(1) + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) ///////////////////////// // 3. Pattern matching // ///////////////////////// - - let foo = AnInt(1); + + let foo = OptionalI32::AnI32(1); match foo { - AnInt(n) => println!("it’s an int: {}", n), - Nothing => println!("it’s nothing!"), + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), } // Advanced pattern matching - struct FooBar { x: int, y: OptionalInt } - let bar = FooBar { x: 15, y: AnInt(32) }; + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; match bar { - FooBar { x: 0, y: AnInt(0) } => + FooBar { x: 0, y: OptionalI32::AnI32(0) } => println!("The numbers are zero!"), - FooBar { x: n, y: AnInt(m) } if n == m => + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => println!("The numbers are the same"), - FooBar { x: n, y: AnInt(m) } => + FooBar { x: n, y: OptionalI32::AnI32(m) } => println!("Different numbers: {} {}", n, m), - FooBar { x: _, y: Nothing } => + FooBar { x: _, y: OptionalI32::Nothing } => println!("The second number is Nothing!"), } @@ -187,19 +212,20 @@ fn main() { ///////////////////// // `for` loops/iteration - let array = [1i, 2, 3]; + let array = [1, 2, 3]; for i in array.iter() { println!("{}", i); } - for i in range(0u, 10) { + // Ranges + for i in 0u32..10 { print!("{} ", i); } println!(""); // prints `0 1 2 3 4 5 6 7 8 9 ` // `if` - if 1i == 1 { + if 1 == 1 { println!("Maths is working!"); } else { println!("Oh no..."); @@ -213,7 +239,7 @@ fn main() { }; // `while` loop - while 1i == 1 { + while 1 == 1 { println!("The universe is operating normally."); } @@ -225,40 +251,49 @@ fn main() { ///////////////////////////////// // 5. Memory safety & pointers // ///////////////////////////////// - - // Owned pointer - only one thing can ‘own’ this pointer at a time - let mut mine: Box = box 3; + + // Owned pointer – only one thing can ‘own’ this pointer at a time + // This means that when the `Box` leaves its scope, it can be automatically deallocated safely. + let mut mine: Box = Box::new(3); *mine = 5; // dereference + // Here, `now_its_mine` takes ownership of `mine`. In other words, `mine` is moved. let mut now_its_mine = mine; *now_its_mine += 2; + println!("{}", now_its_mine); // 7 - // println!("{}", mine); // this would error + // println!("{}", mine); // this would not compile because `now_its_mine` now owns the pointer - // Reference - an immutable pointer that refers to other data - let mut var = 4i; + // Reference – an immutable pointer that refers to other data + // When a reference is taken to a value, we say that the value has been ‘borrowed’. + // While a value is borrowed immutably, it cannot be mutated or moved. + // A borrow lasts until the end of the scope it was created in. + let mut var = 4; var = 3; - let ref_var: &int = &var; + let ref_var: &i32 = &var; + println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); - // var = 5; // this would error - // *ref_var = 6; // this would too + // var = 5; // this would not compile because `var` is borrowed + // *ref_var = 6; // this would too, because `ref_var` is an immutable reference // Mutable reference - let mut var2 = 4i; - let ref_var2: &mut int = &mut var2; + // While a value is mutably borrowed, it cannot be accessed at all. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; *ref_var2 += 2; + println!("{}", *ref_var2); // 6 - // var2 = 2; // this would error + // var2 = 2; // this would not compile because `var2` is borrowed } ``` ## Further reading -There’s a lot more to Rust—this is just the basics of Rust so you can -understand the most important things. To learn more about Rust, read [The Rust -Guide](http://doc.rust-lang.org/guide.html) and check out the -[/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel -on irc.mozilla.org are also always keen to help newcomers. +There’s a lot more to Rust—this is just the basics of Rust so you can understand +the most important things. To learn more about Rust, read [The Rust Programming +Language](http://doc.rust-lang.org/book/index.html) and check out the +[/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel on +irc.mozilla.org are also always keen to help newcomers. You can also try out features of Rust with an online compiler at the official [Rust playpen](http://play.rust-lang.org) or on the main -- 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 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 0c227ddf87f8ea4bd849dbd98886a815178affad Mon Sep 17 00:00:00 2001 From: Kirushan Rasendran 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 f0daae643482918fce3c75b012087dc19f883d25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Wed, 21 Oct 2015 23:30:42 -0200 Subject: translation to pt-br translation to pt-br completed --- pt-br/pogo.html.markdown | 76 ++++++++++++++++++++++++------------------------ 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/pt-br/pogo.html.markdown b/pt-br/pogo.html.markdown index 80972c98..5dc81ec0 100644 --- a/pt-br/pogo.html.markdown +++ b/pt-br/pogo.html.markdown @@ -3,7 +3,8 @@ language: pogoscript contributors: - ["Tim Macfarlane", "http://github.com/refractalize"] - ["Cássio Böck", "https://github.com/cassiobsilva"] -filename: learnPogo.pogo +filename: learnPogo-pt-br.pogo +lang: pt-br --- Pogoscript é uma linguagem de programação que possui tipos primitivos concorrents @@ -26,7 +27,7 @@ temperature at (a) altitude := else 32 - a / 100 -// chamada de uma função +// declarando uma função current temperature = temperature at 3200 altitude // essa função cria um novo objeto com métodos @@ -43,7 +44,7 @@ position (x, y) = { // `self` é similiar ao `this` no Javascript, com exceção de que `self` não // é redefinido em cada nova função -// chamada de métodos +// declaração de métodos position (7, 2).distance from position (position (5, 1)) // assim como no Javascript, objetos também são hashes @@ -117,14 +118,13 @@ spark (position, color: 'black', velocity: {x = 0, y = 0}) = { red = spark (position 1 1, color: 'red') fast black = spark (position 1 1, velocity: {x = 10, y = 0}) -// functions can unsplat arguments too +// funções também podem ser utilizadas para realizar o "unsplat" de argumentos 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 +// 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 () @@ -138,40 +138,40 @@ render each @(spark) into canvas context @(c) ) ctx.stroke () -// asynchronous calls +// chamadas assíncronas -// 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 +// 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. E/S assíncrona é maravilhosa para a performance e +// torna a 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 mosquitos +// mais fácil -// Node.js includes the `fs` module for accessing the file system. -// Let's list the contents of a directory +// 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()` 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()`. +// `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 praticamente 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()`. -// to catch asynchronous errors while calling asynchronous functions +// para se obter erros ao utilizar funções assíncronas 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 +// 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 nas exceções síncronas -// all the other control structures work with asynchronous calls too -// here's `if else` +// todo o controle de estrutura funciona com chamadas assíncronas também +// aqui um exemplo de `if else` config = if (fs.stat! 'config.json'.is file ()) JSON.parse (fs.read file! 'config.json' 'utf-8') @@ -180,23 +180,23 @@ config = 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 +// para executar duas chamadas assíncronas de forma concorrente, use o +// operador `?`. +// O operador `?` retorna um *future* que pode ser executado aguardando +// o resultado, novamente utilizando o operador `o` -// we don't wait for either of these calls to finish +// nós não esperamos nenhuma dessas chamadas serem concluídas a = fs.stat? 'a.txt' b = fs.stat? 'b.txt' -// now we wait for the calls to finish and print the results +// 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)" -// futures in Pogoscript are analogous to Promises +// no Pogoscript, futures são semelhantes a Promises ``` +E encerramos por aqui. -That's it. +Baixe o [Node.js](http://nodejs.org/) e execute `npm install pogo`. -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! +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 4c9f38665d291e4abe2c7d57e633f5aed9eb72ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Thu, 22 Oct 2015 00:35:27 -0200 Subject: grammar fixes Portuguese changes to a better text understanding --- pt-br/pogo.html.markdown | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/pt-br/pogo.html.markdown b/pt-br/pogo.html.markdown index 5dc81ec0..124b32f7 100644 --- a/pt-br/pogo.html.markdown +++ b/pt-br/pogo.html.markdown @@ -41,7 +41,7 @@ position (x, y) = { Math.sqrt (dx * dx + dy * dy) } -// `self` é similiar ao `this` no Javascript, com exceção de que `self` não +// `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 @@ -91,7 +91,7 @@ false @or true 2 >= 2 2 > 1 -// todos do Javascript também são suportados +// os operadores padrão do Javascript também são suportados // definindo seu próprio operador (p1) plus (p2) = @@ -142,9 +142,10 @@ render each @(spark) into canvas context @(c) // 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. E/S assíncrona é maravilhosa para a performance e -// torna a 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 mosquitos +// 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. @@ -155,12 +156,11 @@ 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 praticamente 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()`. +// 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()`. -// para se obter erros ao utilizar funções assíncronas +// obtendo erros ao utilizar funções assíncronas try another directory listing = fs.readdir! 'a-missing-dir' @@ -168,9 +168,9 @@ 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 nas exceções síncronas +// `try catch` mais externo do evento, assim como é feito em exceções síncronas -// todo o controle de estrutura funciona com chamadas assíncronas também +// 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 ()) @@ -182,8 +182,8 @@ config = // para executar duas chamadas assíncronas de forma concorrente, use o // operador `?`. -// O operador `?` retorna um *future* que pode ser executado aguardando -// o resultado, novamente utilizando o operador `o` +// 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' -- cgit v1.2.3 From 9fcfa2c91feb2af119e67c9d1897340e87f03daa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Thu, 22 Oct 2015 00:37:46 -0200 Subject: File name changed --- pt-br/pogo-pt.html.markdown | 202 ++++++++++++++++++++++++++++++++++++++++++++ pt-br/pogo.html.markdown | 202 -------------------------------------------- 2 files changed, 202 insertions(+), 202 deletions(-) create mode 100644 pt-br/pogo-pt.html.markdown delete mode 100644 pt-br/pogo.html.markdown diff --git a/pt-br/pogo-pt.html.markdown b/pt-br/pogo-pt.html.markdown new file mode 100644 index 00000000..124b32f7 --- /dev/null +++ b/pt-br/pogo-pt.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-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/pogo.html.markdown b/pt-br/pogo.html.markdown deleted file mode 100644 index 124b32f7..00000000 --- a/pt-br/pogo.html.markdown +++ /dev/null @@ -1,202 +0,0 @@ ---- -language: pogoscript -contributors: - - ["Tim Macfarlane", "http://github.com/refractalize"] - - ["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 1f9096f79ae9ad1e132b1f601f003c10ed2e5b96 Mon Sep 17 00:00:00 2001 From: hack1m Date: Thu, 22 Oct 2015 15:42:48 +0800 Subject: [CoffeeScript/ms-my] Added Malay (Malaysia) translation for CoffeeScript --- ms-my/coffeescript-my.html.markdown | 105 ++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 ms-my/coffeescript-my.html.markdown diff --git a/ms-my/coffeescript-my.html.markdown b/ms-my/coffeescript-my.html.markdown new file mode 100644 index 00000000..bb67478f --- /dev/null +++ b/ms-my/coffeescript-my.html.markdown @@ -0,0 +1,105 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +filename: coffeescript.coffee +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +CoffeeScript adalah bahasa kecil yang menyusun/kompil satu-per-satu menjadi setara JavaScript, dan tidak ada interpretasi di runtime. +Sebagai salah satu pengganti kepada JavaScript, CoffeeScript mencuba yang terbaik untuk output kod JavaScript yang mudah dibaca, cantik-dicetak dan berfungsi lancar, yang mana berfungsi baik pada setiap runtime JavaScript. + +Lihat juga [Laman sesawang CoffeeScript](http://coffeescript.org/), yang mana ada tutorial lengkap untuk CoffeeScript. + +```coffeescript +# CoffeeScript adalah bahasa hipster. +# Ia beredar mengikut trend kebanyakkan bahasa moden. +# Jadi komen sama seperti Ruby dan Python, ia menggunakan simbol nombor. + +### +Blok komen seperti ini, dan ia terjemah terus ke '/ *'s dan '* /'s +untuk keputusan kod JavaScript. + +Sebelum meneruskan anda perlu faham kebanyakkan daripada +JavaScript adalah semantik. +### + +# Menetapkan: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Bersyarat: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Fungsi: +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 + "..."; +#}; + +# Julat: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objek: +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); } +# }; + +# Splats: +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); +# }; + +# Kewujudan: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Pemahaman array: +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); +# } +#} +``` + +## Sumber tambahan + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) -- cgit v1.2.3 From a657d0d559014cc676abfaf06cb57dddd07b0853 Mon Sep 17 00:00:00 2001 From: hack1m Date: Thu, 22 Oct 2015 16:33:02 +0800 Subject: Added ms for filename --- ms-my/coffeescript-my.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ms-my/coffeescript-my.html.markdown b/ms-my/coffeescript-my.html.markdown index bb67478f..9820a561 100644 --- a/ms-my/coffeescript-my.html.markdown +++ b/ms-my/coffeescript-my.html.markdown @@ -3,7 +3,7 @@ language: coffeescript contributors: - ["Tenor Biel", "http://github.com/L8D"] - ["Xavier Yao", "http://github.com/xavieryao"] -filename: coffeescript.coffee +filename: coffeescript-ms.coffee translators: - ["hack1m", "https://github.com/hack1m"] lang: ms-my -- cgit v1.2.3 From b238a58c9768d3b7694c4f02cbfe5ba2cac0015a Mon Sep 17 00:00:00 2001 From: payet-s Date: Wed, 21 Oct 2015 17:48:04 +0200 Subject: [python/en] Fix typos --- python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 42a52bcf..753d6e8c 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -15,8 +15,8 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020, -it is though recommended to start learnign Python with Python 3. +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 and 3.x at the same time, -- cgit v1.2.3 From c69ef3115bb900a5b2f716ebd9791a38ca113ab7 Mon Sep 17 00:00:00 2001 From: labrack Date: Thu, 22 Oct 2015 13:06:15 -0400 Subject: [php/en] Un-beef a comment block closing Somebody beefed a closing on the 'Late Static Binding' Comment block, causing the next 18 or so lines to be included in the comment instead of parsed for syntax properly. --- php.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/php.html.markdown b/php.html.markdown index 127e601b..403fc41d 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -723,7 +723,7 @@ $cls = new SomeOtherNamespace\MyClass(); /********************** * Late Static Binding * -* / +*/ class ParentClass { public static function who() { -- cgit v1.2.3 From db4160710dee1ee76d750c35452294c3134061fa Mon Sep 17 00:00:00 2001 From: Hunter Stevens Date: Fri, 23 Oct 2015 13:14:38 -0400 Subject: Remove "feedback", fix link markdown --- javascript.html.markdown | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index c1c59de1..cce488e1 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -16,10 +16,6 @@ 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. -Feedback would be highly appreciated! You can reach me at -[@adambrenecki](https://twitter.com/adambrenecki), or -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). - ```js // Comments are like C's. Single-line comments start with two slashes, /* and multiline comments start with slash-star @@ -534,28 +530,32 @@ if (Object.create === undefined){ // don't overwrite it if it exists ## Further Reading -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. +The [Mozilla Developer Network][1] 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][2] 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][3]. + +[Learn Javascript by Example and with Challenges][4] is a variant of this +reference with built-in challenges. -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) +[JavaScript Garden][5] is an in-depth guide of all the counter-intuitive parts +of the language. -[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: The Definitive Guide][6] is a classic guide and reference book. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. +In addition to direct contributors to this article, some content is adapted from +Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the +Mozilla Developer Network. -[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. +[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 a1a45c7dff31d953f693efad49ed1293b3d79d49 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 23 Oct 2015 23:01:30 +0200 Subject: [go/de] fixed some typos --- de-de/go-de.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 7e61bf81..d3a192fe 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -25,7 +25,7 @@ aktive Community. zeiliger Kommentar */ // Eine jede Quelldatei beginnt mit einer Paket-Klausel. -// "main" ist ein besonderer Pkaetname, da er ein ausführbares Programm +// "main" ist ein besonderer Paketname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. package main @@ -38,7 +38,7 @@ import ( "strconv" // Zeichenkettenmanipulation ) -// Es folgt die Definition einer Funktions, in diesem Fall von "main". Auch hier +// 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! func main() { @@ -56,7 +56,7 @@ func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. // Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu - // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen. + // folgern, die Variable zu deklarieren und ihr einen Wert zuzuweisen. y := 4 // Eine Funktion mit mehreren Rückgabewerten. @@ -147,7 +147,7 @@ func learnFlowControl() { if false { // nicht hier } else { - // sonder hier! spielt die Musik + // sondern hier! spielt die Musik } // Benutzen Sie ein "switch" Statement anstatt eine Anreihung von if-s @@ -166,7 +166,7 @@ func learnFlowControl() { // Ab hier gilt wieder: x == 1 // For ist die einzige Schleifenform in Go, sie hat aber mehrere Formen: - for { // Endloschleife + for { // Endlosschleife break // nur ein Spaß continue // wird nie ausgeführt } @@ -263,10 +263,10 @@ func learnConcurrency() { // Auslesen und dann Ausgeben der drei berechneten Werte. // Man kann nicht im voraus feststellen in welcher Reihenfolge die Werte // ankommen. - fmt.Println(<-c, <-c, <-c) // mit dem Kannal rechts ist <- der Empfangs-Operator + fmt.Println(<-c, <-c, <-c) // mit dem Kanal rechts ist <- der Empfangs-Operator - cs := make(chan string) // ein weiterer Kannal, diesmal für strings - cc := make(chan chan string) // ein Kannal für string Kannäle + cs := make(chan string) // ein weiterer Kanal, diesmal für strings + cc := make(chan chan string) // ein Kanal für string Kanäle // Start einer neuen Goroutine, nur um einen Wert zu senden go func() { c <- 84 }() @@ -283,7 +283,7 @@ func learnConcurrency() { fmt.Println("wird nicht passieren.") } // Hier wird eine der beiden Goroutines fertig sein, die andere nicht. - // Sie wird warten bis der Wert den sie sendet von dem Kannal gelesen wird. + // Sie wird warten bis der Wert den sie sendet von dem Kanal gelesen wird. learnWebProgramming() // Go kann es und Sie hoffentlich auch bald. } @@ -301,7 +301,7 @@ func learnWebProgramming() { // Methode implementieren: ServeHTTP func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Senden von Daten mit einer Methode des http.ResponseWriter - w.Write([]byte("Sie habe Go in Y Minuten gelernt!")) + w.Write([]byte("Sie haben Go in Y Minuten gelernt!")) } ``` -- cgit v1.2.3 From 8e4d294227590194285cec139bae5930d470eaf2 Mon Sep 17 00:00:00 2001 From: Jana Trestikova Date: Fri, 23 Oct 2015 23:54:45 +0200 Subject: Fix typos undestanding -> understanding uninterupted -> uninterrupted --- chapel.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 7252a3e4..866e92d2 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -629,7 +629,7 @@ for (i, j) in zip( toThisArray.domain, -100..#5 ){ } writeln( toThisArray ); -// This is all very important in undestanding why the statement +// This is all very important in understanding why the statement // var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j; // exhibits a runtime error. // Even though the domain of the array and the loop-expression are @@ -914,7 +914,7 @@ proc main(){ [ val in myBigArray ] val = 1 / val; // Parallel operation // Atomic variables, common to many languages, are ones whose operations - // occur uninterupted. Multiple threads can both modify atomic variables + // occur uninterrupted. Multiple threads can both modify atomic variables // and can know that their values are safe. // Chapel atomic variables can be of type bool, int, uint, and real. var uranium: atomic int; -- cgit v1.2.3 From 9aad08bf78196758a568ec1272c94029221c2dd5 Mon Sep 17 00:00:00 2001 From: Amru Eliwat Date: Fri, 23 Oct 2015 23:13:29 -0700 Subject: Fixed typos for 'overriding' and 'reference' and fixed formatting issue that may have caused confusion --- d.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index 80c1dc65..6f3710ab 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -199,8 +199,8 @@ 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: +include interfaces, abstract classes, +and overriding methods. D does inheritance just like Java: Extend one class, implement as many interfaces as you please. We've seen D's OOP facilities, but let's switch gears. D offers @@ -247,7 +247,7 @@ void main() { // and take advantage of as many cores as we have available. auto arr = new double[1_000_000]; - // Use an index, and an array element by referece, + // Use an index, and an array element by reference, // and just call parallel on the array! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); -- cgit v1.2.3 From 4edbfa9e0394a4abb9301391cdebcc857559a5c7 Mon Sep 17 00:00:00 2001 From: Amru Eliwat Date: Fri, 23 Oct 2015 23:17:35 -0700 Subject: Fixed 'modeling' and 'compatibility' typos --- fsharp.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 76318d7d..a2a87d57 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -335,10 +335,10 @@ module DataTypeExamples = let worker = Worker jdoe // ------------------------------------ - // Modelling with types + // Modeling with types // ------------------------------------ - // Union types are great for modelling state without using flags + // Union types are great for modeling state without using flags type EmailAddress = | ValidEmailAddress of string | InvalidEmailAddress of string @@ -526,7 +526,7 @@ module AsyncExample = |> Async.RunSynchronously // start them off // ================================================ -// .NET compatability +// .NET compatibility // ================================================ module NetCompatibilityExamples = -- cgit v1.2.3 From a019e2c16bbad5a4dd396f952cdfeb733eed6978 Mon Sep 17 00:00:00 2001 From: Saurabh Sandav Date: Sat, 24 Oct 2015 12:22:11 +0530 Subject: [lua/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 0809215f..3d95c146 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 behavior. +-- behavior. 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 4de15e41b3d47963ab7749a6a4dc6704d5d3af27 Mon Sep 17 00:00:00 2001 From: Robert Brown Date: Sat, 24 Oct 2015 13:56:20 +0100 Subject: correct minor grammar and formatting to improve readability --- go.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index a857a76c..dc684227 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -108,12 +108,13 @@ can include line breaks.` // Same string type. bs := []byte("a slice") // Type conversion syntax. // Because they are dynamic, slices can be appended to on-demand. - // To append elements to a slice, built-in append() function is used. + // To append elements to a slice, the built-in append() function is used. // First argument is a slice to which we are appending. Commonly, // the array variable is updated in place, as in example below. s := []int{1, 2, 3} // Result is a slice of length 3. s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can // pass a reference to a slice or a slice literal like this, with a // trailing ellipsis, meaning take a slice and unpack its elements, -- cgit v1.2.3 From 069e127ff83820ba809bc437bfadda9839d91062 Mon Sep 17 00:00:00 2001 From: chris-hranj Date: Sat, 24 Oct 2015 23:53:17 -0400 Subject: update Data Structures section to show outputs --- scala.html.markdown | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 7f545196..192e03d7 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -278,21 +278,21 @@ val text = if (x == 10) "yeah" else "nope" ///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) -a(0) -a(3) +a(0) // Int = 1 +a(3) // Int = 5 a(21) // Throws an exception val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") -m("fork") -m("spoon") +m("fork") // java.lang.String = tenedor +m("spoon") // java.lang.String = cuchara m("bottle") // Throws an exception val safeM = m.withDefaultValue("no lo se") -safeM("bottle") +safeM("bottle") // java.lang.String = no lo se val s = Set(1, 3, 7) -s(0) -s(1) +s(0) // Boolean = false +s(1) // Boolean = true /* Look up the documentation of map here - * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map @@ -313,15 +313,16 @@ s(1) // Why have this? val divideInts = (x: Int, y: Int) => (x / y, x % y) -divideInts(10, 3) // The function divideInts gives you the result and the remainder +// The function divideInts gives you the result and the remainder +divideInts(10, 3) // (Int, Int) = (3,1) // To access the elements of a tuple, use _._n where n is the 1-based index of // the element -val d = divideInts(10, 3) +val d = divideInts(10, 3) // (Int, Int) = (3,1) -d._1 +d._1 // Int = 3 -d._2 +d._2 // Int = 1 ///////////////////////////////////////////////// -- cgit v1.2.3 From d9d8de0d229443534272e2a1976fb7f0e69631b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A1ssio=20B=C3=B6ck?= Date: Sun, 25 Oct 2015 15:44:35 -0200 Subject: Translator section added Changed my name from contributor section to the translator section --- pt-br/pogo-pt.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/pt-br/pogo-pt.html.markdown b/pt-br/pogo-pt.html.markdown index 124b32f7..80dcfcd5 100644 --- a/pt-br/pogo-pt.html.markdown +++ b/pt-br/pogo-pt.html.markdown @@ -2,6 +2,7 @@ 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 -- cgit v1.2.3 From 8323f873c4079132d92e5d4a9f355489ea38abca Mon Sep 17 00:00:00 2001 From: Diego Ponce Date: Sun, 25 Oct 2015 13:38:15 -0600 Subject: Fix typos --- es-es/markdown-es.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index d90e3eb5..bc481df7 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -11,7 +11,7 @@ lang: es-es Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta fácilmente a HTML (y, actualmente, otros formatos también). -¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! +¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! ```markdown @@ -44,7 +44,7 @@ Esto es un h2 ------------- - *Este texto está en itálicas.* @@ -62,7 +62,7 @@ Markdown en Github, también tenemos: --> ~~Este texto está tachado.~~ - Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido? -- cgit v1.2.3 From ee4bef264c71252900858a5bbfe00d2e0644eedd Mon Sep 17 00:00:00 2001 From: Jefftree Date: Sun, 25 Oct 2015 15:55:44 -0400 Subject: Added alternative way to enter math mode for latex --- latex.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/latex.html.markdown b/latex.html.markdown index 9b7b4feb..31231a70 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -106,6 +106,9 @@ Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ % 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! -- cgit v1.2.3 From 341b92141c28b13cac8b41913f25a50a0a8b6066 Mon Sep 17 00:00:00 2001 From: Tyler Date: Sun, 25 Oct 2015 17:15:23 -0600 Subject: Update CSS for clarity. - More relevant introduction - More consistent and clear wording - More consistent formatting --- css.html.markdown | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/css.html.markdown b/css.html.markdown index d8f30ca3..8ee4f4b9 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -6,20 +6,21 @@ contributors: - ["Geoffrey Liu", "https://github.com/g-liu"] - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] + - ["Tyler Mumford", "https://tylermumford.com"] filename: learncss.css --- -In the early days of the web there were no visual elements, just pure text. But with further development of web browsers, fully visual web pages also became common. +Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**. -CSS helps maintain separation between the content (HTML) and the look-and-feel of a web page. +CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors. -CSS lets you target different elements on an HTML page and assign different visual properties to them. +This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3. -This guide has been written for CSS 2, though CSS 3 is fast becoming popular. - -**NOTE:** Because CSS produces visual results, in order to learn it, you need try everything in a CSS playground like [dabblet](http://dabblet.com/). +**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/). The main focus of this article is on the syntax and some general tips. +## Syntax + ```css /* comments appear inside slash-asterisk, just like this line! there are no "one-line comments"; this is the only comment style */ @@ -28,7 +29,7 @@ The main focus of this article is on the syntax and some general tips. ## SELECTORS #################### */ -/* the selector is used to target an element on a page. +/* the selector is used to target an element on a page. */ selector { property: value; /* more properties...*/ } /* @@ -69,7 +70,7 @@ div { } [otherAttr|='en'] { font-size:smaller; } -/* You can concatenate different selectors to create a narrower selector. Don't +/* You can combine different selectors to create a more focused selector. Don't put spaces between them. */ div.some-class[attr$='ue'] { } @@ -92,7 +93,7 @@ div.some-parent.class-name { } .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 */ + element only when it is in a particular state */ /* for example, when the cursor hovers over an element */ selector:hover { } @@ -103,7 +104,7 @@ selector:visited { } /* or hasn't been visited */ selected:link { } -/* or an element in focus */ +/* or an element is in focus */ selected:focus { } /* any element that is the first child of its parent */ @@ -156,10 +157,10 @@ selector { 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: 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 */ + color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */ /* Images as backgrounds of elements */ background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ @@ -194,7 +195,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. 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. +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. This process is called cascading, hence the name Cascading Style Sheets. @@ -238,10 +239,10 @@ Most of the features in CSS 2 (and many in CSS 3) are available across all brows ## Resources -* 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/) +* [CanIUse](http://caniuse.com) (Detailed compatibility info) +* [Dabblet](http://dabblet.com/) (CSS playground) +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference) ## Further Reading -- cgit v1.2.3 From d41fdbcba9a8d764ffcd1eaca453c7870567784f Mon Sep 17 00:00:00 2001 From: Kristian Date: Mon, 26 Oct 2015 17:56:28 +1000 Subject: Fixed typo in docs + Added a better description for 'nil' --- ruby.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index 998b4bf7..a3fc859e 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -49,7 +49,7 @@ You shouldn't either 10.* 5 #=> 50 # Special values are objects -nil # Nothing to see here +nil # equivalent to null in other languages true # truth false # falsehood @@ -122,7 +122,7 @@ puts "I'm printing!" # print to the output without a newline print "I'm printing!" -#=> I'm printing! => nill +#=> I'm printing! => nil # Variables x = 25 #=> 25 -- cgit v1.2.3 From b31fda3a8e9f4d0ff021dc707f1e47af4add90ac Mon Sep 17 00:00:00 2001 From: Jody Leonard Date: Mon, 26 Oct 2015 19:38:36 -0400 Subject: Edit variable-length array example The current example seems to be trying to set a size for a char buffer, use fgets to populate that buffer, and then use strtoul to convert the char content to an unsigned integer. However, this doesn't work as intended (in fact, it results in printing "sizeof array = 0"), and so adapt to a simpler fscanf example. Also remove some ambiguous language in the example output. --- c.html.markdown | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/c.html.markdown b/c.html.markdown index 3d632eab..7c2386ef 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -148,15 +148,10 @@ int main (int argc, char** argv) printf("Enter the array size: "); // ask the user for an array size int size; fscanf(stdin, "%d", &size); - char buf[size]; - fgets(buf, sizeof buf, stdin); - - // strtoul parses a string to an unsigned integer - size_t size2 = strtoul(buf, NULL, 10); - int var_length_array[size2]; // declare the VLA + 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: + // Example: // > Enter the array size: 10 // > sizeof array = 40 -- cgit v1.2.3 From 469541783d5ef25395d6bfe343a414c383236468 Mon Sep 17 00:00:00 2001 From: sholland Date: Mon, 26 Oct 2015 22:21:02 -0500 Subject: [fsharp/en] correct a few simple mistakes change github flavored markdown programming language to fsharp correct typos --- fsharp.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 76318d7d..4cc233e3 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. -```csharp +```fsharp // single line comments use a double slash (* multi line comments use (* . . . *) pair @@ -248,7 +248,7 @@ module SequenceExamples = // sequences can use yield and // can contain subsequences let strange = seq { - // "yield! adds one element + // "yield" adds one element yield 1; yield 2; // "yield!" adds a whole subsequence @@ -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 @@ -426,7 +426,7 @@ module ActivePatternExamples = // ----------------------------------- // You can create partial matching patterns as well - // Just use undercore in the defintion, and return Some if matched. + // Just use underscore in the defintion, and return Some if matched. let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None -- cgit v1.2.3 From 9c3c3dff4518671e82cd3324c0d6fdddd506dfd3 Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:04:34 +0800 Subject: Added resources to read for Javascript --- javascript.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index cce488e1..dc573b0e 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -547,6 +547,11 @@ of the language. [JavaScript: The Definitive Guide][6] is a classic guide and reference book. +[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. + + In addition to direct contributors to this article, some content is adapted from Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the Mozilla Developer Network. @@ -559,3 +564,5 @@ Mozilla Developer Network. [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 3015cfb4367ffe7e06df5232cb4aa5924194715d Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:14:13 +0800 Subject: Rename go.html.markdown to go-hu.html.markdown --- hu-hu/go-hu.html.markdown | 337 ++++++++++++++++++++++++++++++++++++++++++++++ hu-hu/go.html.markdown | 337 ---------------------------------------------- 2 files changed, 337 insertions(+), 337 deletions(-) create mode 100644 hu-hu/go-hu.html.markdown delete mode 100644 hu-hu/go.html.markdown diff --git a/hu-hu/go-hu.html.markdown b/hu-hu/go-hu.html.markdown new file mode 100644 index 00000000..638c9489 --- /dev/null +++ b/hu-hu/go-hu.html.markdown @@ -0,0 +1,337 @@ +--- +language: Go +lang: hu-hu +filename: learngo-hu.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] +translators: + - ["Szabó Krisztián", "https://github.com/thenonameguy/"] + - ["Árpád Goretity", "https://github.com/H2CO3"] +--- + +A Go programozási nyelv az életszerű feladatok könnyebb elvégzése miatt született. +A mai legújabb programozási trendeket elkerülve, +praktikus megoldást nyújt a valós, üzleti problémákra. + +C-szerű szintaktikával és statikus típuskezeléssel rendelkezik. +A fordító szempillantás alatt végez és egy gyorsan futó,statikus futtatható állományt hoz létre. +A nyelv könnyen érthető, folyamatok közötti csatornákon áthaladó üzenetekkel kommunikáló konkurens programozást tesz lehetővé, így könnyen ki lehet használni +a mai számítógépek több magos processzorait, ez nagy rendszerek építéséhez ideális. + +A Go alap könyvtára mindenre területre kiterjed, ennek köszönhetően a nyelvnek egyre növekvő tábora van. + +```go +// Egy soros komment +/* Több + soros komment */ + +// Minden forrás fájl egy csomag-definícióval kezdődik, ez hasonlít a Python +// csomagkezelésére +// A main egy különleges csomagnév, ennek a fordítása futtatható állományt hoz +// létre egy könyvtár helyett. +package main + +// Az import rész meghatározza melyik csomagokat kívánjuk használni ebben a +// forrásfájlban +import ( + "fmt" // A Go alap könyvtárának része + "net/http" // Beépített webszerver! + "strconv" // Stringek átalakítására szolgáló csomag +) + +// Függvénydeklarálás, a main nevű függvény a program kezdőpontja. +func main() { + // Println kiírja a beadott paramétereket a standard kimenetre. + // Ha más csomagot függvényeit akarjuk használni, akkor azt jelezni kell a + // csomag nevével + fmt.Println("Hello world!") + + // Meghívunk egy másik függvényt ebből a csomagból + beyondHello() +} + +// A függvények paraméterei zárójelek között vannak. +// Ha nincsenek paraméterek, akkor is kötelező a zárójel-pár. +func beyondHello() { + var x int // Változó deklaráció, használat előtt muszáj ezt megtenni. + x = 3 // Változó értékadás + // "Rövid" deklaráció is létezik, ez az érték alapján deklarálja, + // definiálja és értéket is ad a változónak + y := 4 + sum, prod := learnMultiple(x, y) // a függvényeknek több + // visszatérési értéke is lehet + fmt.Println("sum:", sum, "prod:", prod) // egyszerű kiíratás + learnTypes() +} + +// A funkcióknak elnevezett visszatérési értékük is lehet +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // visszatérünk két értékkel + /* + sum = x + y + prod = x * y + return + Ez ugyanezzel az eredménnyel járt volna, mint a fenti sor. + Üres return esetén, az elnevezett visszatérési változók + aktuális értékeikkel térnek vissza. */ +} + +// Beépített típusok +func learnTypes() { + // Rövid deklarálás az esetek többségében elég lesz a változókhoz + s := "Tanulj Go-t!" // string típus + + s2 := `A "nyers" stringekben lehetnek + újsorok is!` // de ettől még ez is ugyanolyan string mint az s, nincs külön + // típusa + + // nem ASCII karakterek. Minden Go forrás UTF-8 és a stringek is azok. + g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert + // tárol + + f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites + // lebegőpontos szám + c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva + + // Var szintaxis változótípus-definiálással + var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az + // int-nél + var pi float32 = 22. / 7 + + // Rövid deklarásnál átalakítás is lehetséges + n := byte('\n') // byte típus, ami megegyezik az uint8-al + + // A tömböknek fordítás-időben fixált méretük van + var a4 [4]int // egy tömb 4 int-tel, mind 0-ra inicializálva + a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi + // értékekre + + // A "szeleteknek" (slices) dinamikus a méretük. A szeleteknek és a tömböknek is + // megvannak az előnyeik de a szeleteket sokkal gyakrabban használjuk. + s3 := []int{4, 5, 9} // vesd össze a3-mal, nincsenek pontok. + s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva + var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva + bs := []byte("a slice") // típus konverzió szintaxisa + + p, q := learnMemory() // deklarál két mutatót (p,q), két int-re + fmt.Println(*p, *q) // * követi a mutatót. Ez a sor kiírja a két int értékét. + + // A map a dinamikusan növelhető asszociatív tömb része a nyelvnek, hasonlít + // a hash és dictionary típusokra más nyelvekben. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // A felhasználatlan változók fordítás-idejű hibát okoznak a Go-ban. + // Az aláhúzással "használod" a változókat, de eldobod az értéküket. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Kiíratás is természetesen használatnak minősül + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() +} + +// A Go nyelvben szemétgyűjtés (garbage collection) működik. Megtalálhatók benne +// mutatók, de nincs pointeraritmetika. Ez azt jelenti, hogy üres (null) mutatóval még +// mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet. +func learnMemory() (p, q *int) { + // Elnevezett visszatérési változóknak int-re mutató a típusa + p = new(int) // a beépített "new" funkció, egy típusnak elegendő memóriát + // allokál, és visszaad rá egy mutatót. + // Az allokált int nullázva van, p többé nem üres mutató. + s := make([]int, 20) // allokáljunk 20 int változót egy memóriaterületen. + s[3] = 7 // adjunk értéket az egyiknek + r := -2 // hozzánk létre egy lokális változót + return &s[3], &r // A & megadja a memóriacímét a változónak +} + +func expensiveComputation() int { + return 1e6 +} + +func learnFlowControl() { + // Az elágazásoknak kötelező a kapcsos zárójel, a zárójel nem szükséges. + if true { + fmt.Println("megmondtam") + } + // A kód formátumát a nyelvvel járó "go" parancssori program "go fmt" + // parancsa szabványosítja + if false { + // így lehet + } else { + // if/else-t csinálni + } + // Használjunk switchet a hosszabb elágazások alkalmazása helyett. + x := 1 + switch x { + case 0: + case 1: + // Az "esetek" nem "esnek át", tehát + case 2: + // ez nem fog lefutni, nincs szükség break-ekre. + } + // A for ciklus sem használ zárójeleket + for x := 0; x < 3; x++ { + fmt.Println("iteráció", x) + } + // itt az x == 1. + + // A for az egyetlen ciklus fajta a Go-ban, de több formája van. + for { // végtelen ciklus + break // csak vicceltem + continue // soha nem fut le + } + + //Akárcsak a for-nál, az if-nél is lehet rövid deklarálással egy lokális változót létrehozni, + //ami a blokk összes if/else szerkezetén keresztül érvényes marad. + if y := expensiveComputation(); y > x { + x = y + } + // Függvényeket használhatjuk closure-ként is. + xBig := func() bool { + return x > 100 // a switch felett deklarált x-et használjuk itt + } + fmt.Println("xBig:", xBig()) // igaz (utoljára 1e6 lett az értéke az x-nek) + x /= 1e5 // így most már x == 10 + fmt.Println("xBig:", xBig()) // 10 pedig kisebb mint 100, tehát hamis + + // Ha nagyon-nagyon szükséges, akkor használhatjuk a jó öreg goto-t. + goto love +love: + + learnInterfaces() // Itt kezdődnek az érdekes dolgok! +} + +// Definiáljuk a Stringert egy olyan interfésznek, amelynek egy metódusa van, a +// String, ami visszatér egy stringgel. +type Stringer interface { + String() string +} + +// Definiáljuk a pair-t egy olyan struktúrának amelynek két int változója van, +// x és y. +type pair struct { + x, y int +} + +// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interfészt. +func (p pair) String() string { // p lesz a "fogadó" (receiver) + // Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s + // megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // A kapcsos zárójellel jelezzük, hogy egyből inicializálni + // szeretnénk a struktúra változóit a sorrendnek megfelelően. + p := pair{3, 4} + fmt.Println(p.String()) // meghívjuk a p String metódusát. + var i Stringer // deklaráljuk i-t Stringer típusú interfésznek + i = p // lehetséges, mert a pair struktúra eleget tesz a + // Stringer interfésznek + // Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb. + fmt.Println(i.String()) + + // Az fmt csomag függvényei automatikusan meghívják a String függvényt + // hogy megtudják egy objektum szöveges reprezentációját. + fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja + // a String metódust. + fmt.Println(i) // dettó + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" szokásos megoldás arra, hogy jól működött-e a függvény. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok hamis lesz, mert az 1 nincs benne a map-ban. + fmt.Println("nincs meg") + } else { + fmt.Print(x) // x lenne az érték, ha benne lenne a map-ban. + } + // A hiba érték többet is elmond a függvény kimeneteléről, mint hogy minden + // "ok" volt-e + if _, err := strconv.Atoi("non-int"); err != nil { // _ eldobja az értéket, + // úgy se lesz jó jelen + // esetben + // kiírja, hogy "strconv.ParseInt: parsing "non-int": invalid syntax" + fmt.Println(err) + } + // Az interfészekre még visszatérünk, addig is jöjjön a konkurens programozás! + learnConcurrency() +} + +// c egy csatorna, egy konkurens-biztos kommunikációs objektum. +func inc(i int, c chan int) { + c <- i + 1 // <- a "küldés" operátor, ha a bal oldalán csatorna van, így + // i+1-et küld be a csatornába +} + +// Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat +func learnConcurrency() { + // Ugyanaz a make függvény, amivel korábban szeleteket hoztunk létre. + // A make allokál map-eket, szeleteket és csatornákat. + c := make(chan int) + // Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek + // megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig + // paralellizálva/egymás mellett. Mind a 3 ugyanabba a csatornába küldi az + // eredményeket. + go inc(0, c) // A go utasítás indít el goroutine-okat. + go inc(10, c) + go inc(-805, c) + // Beolvassuk 3x a csatornából az eredményeket és kiírjuk őket a kimenetre. + // Nem lehet tudni milyen sorrendben fognak érkezni az eredmények! + fmt.Println(<-c, <-c, <-c) // hogyha a jobb oldalon csatorna van, akkor a + // "<-" a beolvasó/kapó operátor + + cs := make(chan string) // még egy csatorna, ez stringekkel kommunikál + cc := make(chan chan string) // egy csatorna csatornával + go func() { c <- 84 }() // indítsunk egy új goroutine-t, csak azért + // hogy küldjünk egy számot + go func() { cs <- "wordy" }() // ugyanez, csak a cs csatornába stringet + // küldünk + // A select olyan mint a switch, csak feltételek helyett csatorna műveletek + // vannak. Véletlenszerűen kiválasztja az első olyan esetet, ahol létrejöhet + // kommunikáció. + select { + case i := <-c: // a megkapott értéket el lehet tárolni egy változóban + fmt.Println("ez egy", i) + case <-cs: // vagy el lehet dobni az értékét + fmt.Println("ez egy string volt") + case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni + fmt.Println("sose futok le :'( ") + } + // Ezen a ponton vagy c vagy a cs goroutine-ja lefutott. + // Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik + // blokkolva vár. + + learnWebProgramming() // a Go képes rá. Te is képes akarsz rá lenni. +} + +// Egy függvény a http csomagból elindít egy webszervert. +func learnWebProgramming() { + // A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd. + // Második paramétere egy interfész, pontosabban a http.Handler interfész. + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // nem felejtjük el kiírni az esetleges hibákat! +} + +// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az +// egyetlen metódusát, a ServeHTTP-t. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-rel + w.Write([]byte("Megtanultad a Go-t Y perc alatt!")) +} +``` + +## További olvasmányok + +Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/). +Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten, és sok érdekességet olvashatsz. + +A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember. + +Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a legjobb praktikákat kilesheted a standard könyvtárból. +TIPP: a dokumentációban kattints egy függvény nevére és rögtön megmutatja a hozzá tartozó kódot! + +Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a +[gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel. diff --git a/hu-hu/go.html.markdown b/hu-hu/go.html.markdown deleted file mode 100644 index 638c9489..00000000 --- a/hu-hu/go.html.markdown +++ /dev/null @@ -1,337 +0,0 @@ ---- -language: Go -lang: hu-hu -filename: learngo-hu.go -contributors: - - ["Sonia Keys", "https://github.com/soniakeys"] -translators: - - ["Szabó Krisztián", "https://github.com/thenonameguy/"] - - ["Árpád Goretity", "https://github.com/H2CO3"] ---- - -A Go programozási nyelv az életszerű feladatok könnyebb elvégzése miatt született. -A mai legújabb programozási trendeket elkerülve, -praktikus megoldást nyújt a valós, üzleti problémákra. - -C-szerű szintaktikával és statikus típuskezeléssel rendelkezik. -A fordító szempillantás alatt végez és egy gyorsan futó,statikus futtatható állományt hoz létre. -A nyelv könnyen érthető, folyamatok közötti csatornákon áthaladó üzenetekkel kommunikáló konkurens programozást tesz lehetővé, így könnyen ki lehet használni -a mai számítógépek több magos processzorait, ez nagy rendszerek építéséhez ideális. - -A Go alap könyvtára mindenre területre kiterjed, ennek köszönhetően a nyelvnek egyre növekvő tábora van. - -```go -// Egy soros komment -/* Több - soros komment */ - -// Minden forrás fájl egy csomag-definícióval kezdődik, ez hasonlít a Python -// csomagkezelésére -// A main egy különleges csomagnév, ennek a fordítása futtatható állományt hoz -// létre egy könyvtár helyett. -package main - -// Az import rész meghatározza melyik csomagokat kívánjuk használni ebben a -// forrásfájlban -import ( - "fmt" // A Go alap könyvtárának része - "net/http" // Beépített webszerver! - "strconv" // Stringek átalakítására szolgáló csomag -) - -// Függvénydeklarálás, a main nevű függvény a program kezdőpontja. -func main() { - // Println kiírja a beadott paramétereket a standard kimenetre. - // Ha más csomagot függvényeit akarjuk használni, akkor azt jelezni kell a - // csomag nevével - fmt.Println("Hello world!") - - // Meghívunk egy másik függvényt ebből a csomagból - beyondHello() -} - -// A függvények paraméterei zárójelek között vannak. -// Ha nincsenek paraméterek, akkor is kötelező a zárójel-pár. -func beyondHello() { - var x int // Változó deklaráció, használat előtt muszáj ezt megtenni. - x = 3 // Változó értékadás - // "Rövid" deklaráció is létezik, ez az érték alapján deklarálja, - // definiálja és értéket is ad a változónak - y := 4 - sum, prod := learnMultiple(x, y) // a függvényeknek több - // visszatérési értéke is lehet - fmt.Println("sum:", sum, "prod:", prod) // egyszerű kiíratás - learnTypes() -} - -// A funkcióknak elnevezett visszatérési értékük is lehet -func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // visszatérünk két értékkel - /* - sum = x + y - prod = x * y - return - Ez ugyanezzel az eredménnyel járt volna, mint a fenti sor. - Üres return esetén, az elnevezett visszatérési változók - aktuális értékeikkel térnek vissza. */ -} - -// Beépített típusok -func learnTypes() { - // Rövid deklarálás az esetek többségében elég lesz a változókhoz - s := "Tanulj Go-t!" // string típus - - s2 := `A "nyers" stringekben lehetnek - újsorok is!` // de ettől még ez is ugyanolyan string mint az s, nincs külön - // típusa - - // nem ASCII karakterek. Minden Go forrás UTF-8 és a stringek is azok. - g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert - // tárol - - f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites - // lebegőpontos szám - c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva - - // Var szintaxis változótípus-definiálással - var u uint = 7 // unsigned, az implementáció dönti el mekkora, akárcsak az - // int-nél - var pi float32 = 22. / 7 - - // Rövid deklarásnál átalakítás is lehetséges - n := byte('\n') // byte típus, ami megegyezik az uint8-al - - // A tömböknek fordítás-időben fixált méretük van - var a4 [4]int // egy tömb 4 int-tel, mind 0-ra inicializálva - a3 := [...]int{3, 1, 5} // egy tömb 3 int-tel, láthatóan inicalizálva egyedi - // értékekre - - // A "szeleteknek" (slices) dinamikus a méretük. A szeleteknek és a tömböknek is - // megvannak az előnyeik de a szeleteket sokkal gyakrabban használjuk. - s3 := []int{4, 5, 9} // vesd össze a3-mal, nincsenek pontok. - s4 := make([]int, 4) // allokál 4 int-et, mind 0-ra inicializálva - var d2 [][]float64 // ez csak deklaráció, semmi sincs még allokálva - bs := []byte("a slice") // típus konverzió szintaxisa - - p, q := learnMemory() // deklarál két mutatót (p,q), két int-re - fmt.Println(*p, *q) // * követi a mutatót. Ez a sor kiírja a két int értékét. - - // A map a dinamikusan növelhető asszociatív tömb része a nyelvnek, hasonlít - // a hash és dictionary típusokra más nyelvekben. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 - - // A felhasználatlan változók fordítás-idejű hibát okoznak a Go-ban. - // Az aláhúzással "használod" a változókat, de eldobod az értéküket. - _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Kiíratás is természetesen használatnak minősül - fmt.Println(s, c, a4, s3, d2, m) - - learnFlowControl() -} - -// A Go nyelvben szemétgyűjtés (garbage collection) működik. Megtalálhatók benne -// mutatók, de nincs pointeraritmetika. Ez azt jelenti, hogy üres (null) mutatóval még -// mindig hibázhatsz, de hozzáadni/műveleteket végezni már nem lehet. -func learnMemory() (p, q *int) { - // Elnevezett visszatérési változóknak int-re mutató a típusa - p = new(int) // a beépített "new" funkció, egy típusnak elegendő memóriát - // allokál, és visszaad rá egy mutatót. - // Az allokált int nullázva van, p többé nem üres mutató. - s := make([]int, 20) // allokáljunk 20 int változót egy memóriaterületen. - s[3] = 7 // adjunk értéket az egyiknek - r := -2 // hozzánk létre egy lokális változót - return &s[3], &r // A & megadja a memóriacímét a változónak -} - -func expensiveComputation() int { - return 1e6 -} - -func learnFlowControl() { - // Az elágazásoknak kötelező a kapcsos zárójel, a zárójel nem szükséges. - if true { - fmt.Println("megmondtam") - } - // A kód formátumát a nyelvvel járó "go" parancssori program "go fmt" - // parancsa szabványosítja - if false { - // így lehet - } else { - // if/else-t csinálni - } - // Használjunk switchet a hosszabb elágazások alkalmazása helyett. - x := 1 - switch x { - case 0: - case 1: - // Az "esetek" nem "esnek át", tehát - case 2: - // ez nem fog lefutni, nincs szükség break-ekre. - } - // A for ciklus sem használ zárójeleket - for x := 0; x < 3; x++ { - fmt.Println("iteráció", x) - } - // itt az x == 1. - - // A for az egyetlen ciklus fajta a Go-ban, de több formája van. - for { // végtelen ciklus - break // csak vicceltem - continue // soha nem fut le - } - - //Akárcsak a for-nál, az if-nél is lehet rövid deklarálással egy lokális változót létrehozni, - //ami a blokk összes if/else szerkezetén keresztül érvényes marad. - if y := expensiveComputation(); y > x { - x = y - } - // Függvényeket használhatjuk closure-ként is. - xBig := func() bool { - return x > 100 // a switch felett deklarált x-et használjuk itt - } - fmt.Println("xBig:", xBig()) // igaz (utoljára 1e6 lett az értéke az x-nek) - x /= 1e5 // így most már x == 10 - fmt.Println("xBig:", xBig()) // 10 pedig kisebb mint 100, tehát hamis - - // Ha nagyon-nagyon szükséges, akkor használhatjuk a jó öreg goto-t. - goto love -love: - - learnInterfaces() // Itt kezdődnek az érdekes dolgok! -} - -// Definiáljuk a Stringert egy olyan interfésznek, amelynek egy metódusa van, a -// String, ami visszatér egy stringgel. -type Stringer interface { - String() string -} - -// Definiáljuk a pair-t egy olyan struktúrának amelynek két int változója van, -// x és y. -type pair struct { - x, y int -} - -// Definiáljunk egy metódust a pair struktúrának, ezzel teljesítve a Stringer interfészt. -func (p pair) String() string { // p lesz a "fogadó" (receiver) - // Sprintf az fmt csomag egy publikus függvénye, műkődése megegyezik a C-s - // megfelelőjével. A pontokkal érjük el a mindenkori p struktúra elemeit - return fmt.Sprintf("(%d, %d)", p.x, p.y) -} - -func learnInterfaces() { - // A kapcsos zárójellel jelezzük, hogy egyből inicializálni - // szeretnénk a struktúra változóit a sorrendnek megfelelően. - p := pair{3, 4} - fmt.Println(p.String()) // meghívjuk a p String metódusát. - var i Stringer // deklaráljuk i-t Stringer típusú interfésznek - i = p // lehetséges, mert a pair struktúra eleget tesz a - // Stringer interfésznek - // Meghívjuk i String metódusát, az eredmény ugyanaz, mint az előbb. - fmt.Println(i.String()) - - // Az fmt csomag függvényei automatikusan meghívják a String függvényt - // hogy megtudják egy objektum szöveges reprezentációját. - fmt.Println(p) // ugyan az az eredmény mint az előbb, a Println meghívja - // a String metódust. - fmt.Println(i) // dettó - - learnErrorHandling() -} - -func learnErrorHandling() { - // ", ok" szokásos megoldás arra, hogy jól működött-e a függvény. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok hamis lesz, mert az 1 nincs benne a map-ban. - fmt.Println("nincs meg") - } else { - fmt.Print(x) // x lenne az érték, ha benne lenne a map-ban. - } - // A hiba érték többet is elmond a függvény kimeneteléről, mint hogy minden - // "ok" volt-e - if _, err := strconv.Atoi("non-int"); err != nil { // _ eldobja az értéket, - // úgy se lesz jó jelen - // esetben - // kiírja, hogy "strconv.ParseInt: parsing "non-int": invalid syntax" - fmt.Println(err) - } - // Az interfészekre még visszatérünk, addig is jöjjön a konkurens programozás! - learnConcurrency() -} - -// c egy csatorna, egy konkurens-biztos kommunikációs objektum. -func inc(i int, c chan int) { - c <- i + 1 // <- a "küldés" operátor, ha a bal oldalán csatorna van, így - // i+1-et küld be a csatornába -} - -// Az inc-et fogjuk arra használni, hogy konkurensen megnöveljünk számokat -func learnConcurrency() { - // Ugyanaz a make függvény, amivel korábban szeleteket hoztunk létre. - // A make allokál map-eket, szeleteket és csatornákat. - c := make(chan int) - // Indítsunk három konkurens goroutine-t. A számok konkurensen lesznek - // megnövelve, ha a számítógép képes rá és jól be van állítva, akkor pedig - // paralellizálva/egymás mellett. Mind a 3 ugyanabba a csatornába küldi az - // eredményeket. - go inc(0, c) // A go utasítás indít el goroutine-okat. - go inc(10, c) - go inc(-805, c) - // Beolvassuk 3x a csatornából az eredményeket és kiírjuk őket a kimenetre. - // Nem lehet tudni milyen sorrendben fognak érkezni az eredmények! - fmt.Println(<-c, <-c, <-c) // hogyha a jobb oldalon csatorna van, akkor a - // "<-" a beolvasó/kapó operátor - - cs := make(chan string) // még egy csatorna, ez stringekkel kommunikál - cc := make(chan chan string) // egy csatorna csatornával - go func() { c <- 84 }() // indítsunk egy új goroutine-t, csak azért - // hogy küldjünk egy számot - go func() { cs <- "wordy" }() // ugyanez, csak a cs csatornába stringet - // küldünk - // A select olyan mint a switch, csak feltételek helyett csatorna műveletek - // vannak. Véletlenszerűen kiválasztja az első olyan esetet, ahol létrejöhet - // kommunikáció. - select { - case i := <-c: // a megkapott értéket el lehet tárolni egy változóban - fmt.Println("ez egy", i) - case <-cs: // vagy el lehet dobni az értékét - fmt.Println("ez egy string volt") - case <-cc: // üres csatorna, soha nem fog rajta semmi se érkezni - fmt.Println("sose futok le :'( ") - } - // Ezen a ponton vagy c vagy a cs goroutine-ja lefutott. - // Amelyik hamarabb végzett, annak a megfelelő case-e lefutott, a másik - // blokkolva vár. - - learnWebProgramming() // a Go képes rá. Te is képes akarsz rá lenni. -} - -// Egy függvény a http csomagból elindít egy webszervert. -func learnWebProgramming() { - // A ListenAndServe első paramétre egy TCP port, amin kiszolgálunk majd. - // Második paramétere egy interfész, pontosabban a http.Handler interfész. - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // nem felejtjük el kiírni az esetleges hibákat! -} - -// Csináljunk a pair-ból egy http.Handler-t úgy, hogy implementáljuk az -// egyetlen metódusát, a ServeHTTP-t. -func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Minden kapcsolatra elküldjük ezt a http.ResponseWriter-rel - w.Write([]byte("Megtanultad a Go-t Y perc alatt!")) -} -``` - -## További olvasmányok - -Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/). -Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten, és sok érdekességet olvashatsz. - -A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember. - -Ha pedig jobban bele akarod vetni magad a Go-ba, akkor a legjobb praktikákat kilesheted a standard könyvtárból. -TIPP: a dokumentációban kattints egy függvény nevére és rögtön megmutatja a hozzá tartozó kódot! - -Ha pedig a nyelvnek egy bizonyos részéről szeretnél hasonló leírást találni, akkor a -[gobyexample.com](https://gobyexample.com/)-on megtalálod, amit keresel. -- cgit v1.2.3 From f1d18e7e493c468f372598620837fedfb07271bf Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:14:30 +0800 Subject: Rename ruby.html.markdown to ruby-hu.html.markdown --- hu-hu/ruby-hu.html.markdown | 555 ++++++++++++++++++++++++++++++++++++++++++++ hu-hu/ruby.html.markdown | 555 -------------------------------------------- 2 files changed, 555 insertions(+), 555 deletions(-) create mode 100644 hu-hu/ruby-hu.html.markdown delete mode 100644 hu-hu/ruby.html.markdown diff --git a/hu-hu/ruby-hu.html.markdown b/hu-hu/ruby-hu.html.markdown new file mode 100644 index 00000000..169f2b8e --- /dev/null +++ b/hu-hu/ruby-hu.html.markdown @@ -0,0 +1,555 @@ +--- +language: ruby +lang: hu-hu +filenev: 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"] + translators: + - ["Zsolt Prontvai", "https://github.com/prozsolt"] +--- + +```ruby +# Ez egy komment + +=begin +Ez egy többsoros komment +Senki sem használja +Neked sem kellene +=end + +# Először is: Minden objektum + +# A számok objektumok + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Néhány alapvető számtani művelet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# A számtani művelet csak szintaktikus cukor +# az objektumon történő függvény hívásra +1.+(3) #=> 4 +10.* 5 #=> 50 + +# A speciális értékek objektumok +nil # Nincs itt semmi látnivaló +true # igaz +false # hamis + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Egyenlőség +1 == 1 #=> true +2 == 1 #=> false + +# Egyenlőtlenség +1 != 1 #=> false +2 != 1 #=> true + +# A false-on kívül, nil az egyetlen hamis érték + +!nil #=> true +!false #=> true +!0 #=> false + +# Még több összehasonlítás +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Logikai operátorok +true && false #=> false +true || false #=> true +!true #=> false + +# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb +# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak +# amíg egyikük igaz vagy hamis értékkel nem tér vissza. + +# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel +# tért vissza. +csinalj_valamit() and csinalj_valami_mast() +# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel +# tért vissza. +csinalj_valamit() or log_error() + + +# A sztringek objektumok + +'Én egy sztring vagyok'.class #=> String +"Én is egy sztring vagyok".class #=> String + +helykitolto = 'interpolációt használhatok' +"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem" +#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem" + +# A szimpla idézőjelet preferáljuk, ahol csak lehet, +# mert a dupla idézőjel extra számításokat végez. + +# Kombinálhatunk sztringeket, de nem számokkal +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# kiírás a kimenetre +puts "Írok" + +# Változók +x = 25 #=> 25 +x #=> 25 + +# Értékadás az adott értékkel tér vissza +# Ez azt jelenti, hogy használhatunk többszörös értékadást: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Konvencióból, snake_case változó neveket használj +snake_case = true + +# Leíró változó neveket használj +ut_a_projekt_gyokerehez = '/jo/nev/' +ut = '/rossz/nev/' + +# A szimbólumok (objektumok) +# A szimbólumok megváltoztathatatlan, újra felhasználható konstans, +# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják, +# hogy effektíven közvetítsünk konkrét, értelmes értékeket + +:fuggoben.class #=> Symbol + +statusz = :fuggoben + +statusz == :fuggoben #=> true + +statusz == 'fuggoben' #=> false + +statusz == :jovahagyott #=> false + +# Tömbök + +# Ez egy tömb +tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# A tömmbök különböző tipusú dolgokat tartalmazhat + +[1, 'hello', false] #=> [1, "hello", false] + +# Tömbök indexelhetőek +# Az elejéről +tomb[0] #=> 1 +tomb[12] #=> nil + +# Akárcsak a számtani műveletek [var] hozzáférés +# is csak szintaktikus cukor +# a [] függvény hívására az objektumon +tomb.[] 0 #=> 1 +tomb.[] 12 #=> nil + +# A végéről +tomb[-1] #=> 5 + +# Kezdőértékkel és hosszal +tomb[2, 3] #=> [3, 4, 5] + +# Tömb megfordítása +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Vagy tartománnyal +tomb[1..3] #=> [2, 3, 4] + +# Így adhatunk a tömbhöz +tomb << 6 #=> [1, 2, 3, 4, 5, 6] +# Vagy így +tomb.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Ellenőrízük, hogy a tömb tartalmaz egy elemet +tomb.include?(1) #=> true + +# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal +# Hash-eket kapcsos zárójellel jelöljük +hash = { 'szin' => 'zold', 'szam' => 5 } + +hash.keys #=> ['szin', 'szam'] + +# Hash-ekben könnyen kreshetünk a kulcs segítségével: +hash['szin'] #=> 'zold' +hash['szam'] #=> 5 + +# Nem létező kulcsra keresve nil-t kapunk: +hash['nincs itt semmi'] #=> nil + +# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot +# használunk kulcsnak + +uj_hash = { defcon: 3, action: true } + +uj_hash.keys #=> [:defcon, :action] + +# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben +uj_hash.has_key?(:defcon) #=> true +uj_hash.has_value?(3) #=> true + +# Tip: A tömbök és hash-ek is felsorolhatóak +# Sok közös függvényük van, akár az each, map, count, és több + +# Kontroll Struktúrák + +if true + 'ha állítás' +elsif false + 'különben ha, opcionális' +else + 'különben, szintén opcionális' +end + +for szamlalo in 1..5 + puts "iteracio #{szamlalo}" +end +#=> iteracio 1 +#=> iteracio 2 +#=> iteracio 3 +#=> iteracio 4 +#=> iteracio 5 + +# HOWEVER, No-one uses for loops. +# Instead you should use the "each" method and pass it a block. +# A block is a bunch of code that you can pass to a method like "each". +# It is analogous to lambdas, anonymous functions or closures in other +# programming languages. +# +# The "each" method of a range runs the block once for each element of the range. +# The block is passed a counter as a parameter. +# Calling the "each" method with a block looks like this: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# You can also surround blocks in curly brackets: +(1..5).each { |counter| puts "iteration #{counter}" } + +# The contents of data structures can also be iterated using each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +jegy = '4' + +case jegy +when '5' + puts 'Kitünő' +when '4' + puts 'Jó' +when '3' + puts 'Közepes' +when '2' + puts 'Elégsége' +when '1' + puts 'Elégtelen' +else + puts 'Alternatív értékelés, hm?' +end +#=> "Jó" + +# case-ek tartományokat is használhatnak +jegy = 82 +case jegy +when 90..100 + puts 'Hurrá!' +when 80...90 + puts 'Jó munka' +else + puts 'Megbuktál!' +end +#=> "Jó munka" + +# kivétel kezelés: +begin + # kód ami kivételt dobhat + raise NoMemoryError, 'Megtelt a memória' +rescue NoMemoryError => kivetel_valtozo + puts 'NoMemoryError-t dobott', kivetel_valtozo +rescue RuntimeError => mas_kivetel_valtozo + puts 'RuntimeError dobott most' +else + puts 'Ez akkor fut ha nem dob kivételt' +ensure + puts 'Ez a kód mindenképpen lefut' +end + +# Függvények + +def ketszeres(x) + x * 2 +end + +# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel +ketszeres(2) #=> 4 + +# Zárójelezés opcionális, ha az eredmény félreérthetetlen +ketszeres 3 #=> 6 + +ketszeres ketszeres 3 #=> 12 + +def osszeg(x, y) + x + y +end + +# Függvény argumentumait vesszővel választjuk el. +osszeg 3, 4 #=> 7 + +osszeg osszeg(3, 4), 5 #=> 12 + +# yield +# Minden függvénynek van egy implicit, opcionális block paramétere +# 'yield' kulcsszóval hívhatjuk + +def korulvesz + puts '{' + yield + puts '}' +end + +korulvesz { puts 'hello world' } + +# { +# hello world +# } + + +# Fuggvénynek átadhatunk blokkot +# "&" jelöli az átadott blokk referenciáját +def vendegek(&block) + block.call 'valami_argumentum' +end + +# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva +# Erre való a splat operátor ("*") +def vendegek(*array) + array.each { |vendeg| puts vendeg } +end + +# Osztályt a class kulcsszóval definiálhatunk +class Ember + + # Az osztály változó. Az osztály minden példánnyával megvan osztva + @@faj = 'H. sapiens' + + # Alap inicializáló + def initialize(nev, kor = 0) + # Hozzárendeli az argumentumot a "nev" példány változóhoz + @nev = nev + # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni + @kor = kor + end + + # Alap setter függvény + def nev=(nev) + @nev = nev + end + + # Alap getter függvény + def nev + @nev + end + + # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük + attr_accessor :nev + + # Getter/setter függvények egyenként is kreálhatóak + attr_reader :nev + attr_writer :nev + + # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a + # példány függvényektől + # Az osztályn hívhatóak, nem a példányon + def self.mond(uzenet) + puts uzenet + end + + def faj + @@faj + end +end + + +# Példányosítsuk az osztályt +jim = Ember.new('Jim Halpert') + +dwight = Ember.new('Dwight K. Schrute') + +# Hívjunk meg pár függvényt +jim.faj #=> "H. sapiens" +jim.nev #=> "Jim Halpert" +jim.nev = "Jim Halpert II" #=> "Jim Halpert II" +jim.nev #=> "Jim Halpert II" +dwight.faj #=> "H. sapiens" +dwight.nev #=> "Dwight K. Schrute" + +# Hívjuk meg az osztály függvényt +Ember.mond('Hi') #=> "Hi" + +# Változók szókjait az elnevezésük definiálja +# $ kezdetű változók globálisak +$var = "Én egy globális változó vagyok" +defined? $var #=> "global-variable" + +# Változók amik @-al kezdődnek példány szkópjuk van +@var = "Én egy példány változó vagyok" +defined? @var #=> "instance-variable" + +# Változók amik @@-al kezdődnek példány szkópjuk van +@@var = "Én egy osztály változó vagyok" +defined? @@var #=> "class variable" + +# Változók amik nagy betűvel kezdődnek a konstansok +Var = "Konstans vagyok" +defined? Var #=> "constant" + +# Az osztály is objetum. Tehát az osztálynak lehet példány változója +# Az osztályváltozón osztozik minden pédány és leszármazott + +# Ős osztály +class Ember + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(ertek) + @@foo = ertek + end +end + +# Leszarmazott osztály +class Dolgozo < Ember +end + +Ember.foo # 0 +Dolgozo.foo # 0 + +Ember.foo = 2 # 2 +Dolgozo.foo # 2 + +# Az osztálynak példány változóját nem látja az osztály leszármazottja. + +class Ember + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(ertek) + @bar = ertek + end +end + +class Doctor < Ember +end + +Ember.bar # 0 +Doctor.bar # nil + +module ModulePelda + def foo + 'foo' + end +end + +# Modulok include-olása a fügvényeiket az osztály példányaihoz köti. +# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti. + +class Szemely + include ModulePelda +end + +class Konyv + extend ModulePelda +end + +Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class +Szemely.new.foo # => 'foo' +Konyv.foo # => 'foo' +Konyv.new.foo # => NoMethodError: undefined method `foo' + +# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult + +module ConcernPelda + 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 Valami + include ConcernPelda +end + +Valami.bar # => 'bar' +Valami.qux # => NoMethodError: undefined method `qux' +Valami.new.bar # => NoMethodError: undefined method `bar' +Valami.new.qux # => 'qux' +``` + +## Egyéb források + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) +- [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/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) diff --git a/hu-hu/ruby.html.markdown b/hu-hu/ruby.html.markdown deleted file mode 100644 index 169f2b8e..00000000 --- a/hu-hu/ruby.html.markdown +++ /dev/null @@ -1,555 +0,0 @@ ---- -language: ruby -lang: hu-hu -filenev: 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"] - translators: - - ["Zsolt Prontvai", "https://github.com/prozsolt"] ---- - -```ruby -# Ez egy komment - -=begin -Ez egy többsoros komment -Senki sem használja -Neked sem kellene -=end - -# Először is: Minden objektum - -# A számok objektumok - -3.class #=> Fixnum - -3.to_s #=> "3" - - -# Néhány alapvető számtani művelet -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 -2**5 #=> 32 - -# A számtani művelet csak szintaktikus cukor -# az objektumon történő függvény hívásra -1.+(3) #=> 4 -10.* 5 #=> 50 - -# A speciális értékek objektumok -nil # Nincs itt semmi látnivaló -true # igaz -false # hamis - -nil.class #=> NilClass -true.class #=> TrueClass -false.class #=> FalseClass - -# Egyenlőség -1 == 1 #=> true -2 == 1 #=> false - -# Egyenlőtlenség -1 != 1 #=> false -2 != 1 #=> true - -# A false-on kívül, nil az egyetlen hamis érték - -!nil #=> true -!false #=> true -!0 #=> false - -# Még több összehasonlítás -1 < 10 #=> true -1 > 10 #=> false -2 <= 2 #=> true -2 >= 2 #=> true - -# Logikai operátorok -true && false #=> false -true || false #=> true -!true #=> false - -# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb -# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak -# amíg egyikük igaz vagy hamis értékkel nem tér vissza. - -# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel -# tért vissza. -csinalj_valamit() and csinalj_valami_mast() -# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel -# tért vissza. -csinalj_valamit() or log_error() - - -# A sztringek objektumok - -'Én egy sztring vagyok'.class #=> String -"Én is egy sztring vagyok".class #=> String - -helykitolto = 'interpolációt használhatok' -"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem" -#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem" - -# A szimpla idézőjelet preferáljuk, ahol csak lehet, -# mert a dupla idézőjel extra számításokat végez. - -# Kombinálhatunk sztringeket, de nem számokkal -'hello ' + 'world' #=> "hello world" -'hello ' + 3 #=> TypeError: can't convert Fixnum into String -'hello ' + 3.to_s #=> "hello 3" - -# kiírás a kimenetre -puts "Írok" - -# Változók -x = 25 #=> 25 -x #=> 25 - -# Értékadás az adott értékkel tér vissza -# Ez azt jelenti, hogy használhatunk többszörös értékadást: - -x = y = 10 #=> 10 -x #=> 10 -y #=> 10 - -# Konvencióból, snake_case változó neveket használj -snake_case = true - -# Leíró változó neveket használj -ut_a_projekt_gyokerehez = '/jo/nev/' -ut = '/rossz/nev/' - -# A szimbólumok (objektumok) -# A szimbólumok megváltoztathatatlan, újra felhasználható konstans, -# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják, -# hogy effektíven közvetítsünk konkrét, értelmes értékeket - -:fuggoben.class #=> Symbol - -statusz = :fuggoben - -statusz == :fuggoben #=> true - -statusz == 'fuggoben' #=> false - -statusz == :jovahagyott #=> false - -# Tömbök - -# Ez egy tömb -tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] - -# A tömmbök különböző tipusú dolgokat tartalmazhat - -[1, 'hello', false] #=> [1, "hello", false] - -# Tömbök indexelhetőek -# Az elejéről -tomb[0] #=> 1 -tomb[12] #=> nil - -# Akárcsak a számtani műveletek [var] hozzáférés -# is csak szintaktikus cukor -# a [] függvény hívására az objektumon -tomb.[] 0 #=> 1 -tomb.[] 12 #=> nil - -# A végéről -tomb[-1] #=> 5 - -# Kezdőértékkel és hosszal -tomb[2, 3] #=> [3, 4, 5] - -# Tömb megfordítása -a=[1,2,3] -a.reverse! #=> [3,2,1] - -# Vagy tartománnyal -tomb[1..3] #=> [2, 3, 4] - -# Így adhatunk a tömbhöz -tomb << 6 #=> [1, 2, 3, 4, 5, 6] -# Vagy így -tomb.push(6) #=> [1, 2, 3, 4, 5, 6] - -# Ellenőrízük, hogy a tömb tartalmaz egy elemet -tomb.include?(1) #=> true - -# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal -# Hash-eket kapcsos zárójellel jelöljük -hash = { 'szin' => 'zold', 'szam' => 5 } - -hash.keys #=> ['szin', 'szam'] - -# Hash-ekben könnyen kreshetünk a kulcs segítségével: -hash['szin'] #=> 'zold' -hash['szam'] #=> 5 - -# Nem létező kulcsra keresve nil-t kapunk: -hash['nincs itt semmi'] #=> nil - -# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot -# használunk kulcsnak - -uj_hash = { defcon: 3, action: true } - -uj_hash.keys #=> [:defcon, :action] - -# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben -uj_hash.has_key?(:defcon) #=> true -uj_hash.has_value?(3) #=> true - -# Tip: A tömbök és hash-ek is felsorolhatóak -# Sok közös függvényük van, akár az each, map, count, és több - -# Kontroll Struktúrák - -if true - 'ha állítás' -elsif false - 'különben ha, opcionális' -else - 'különben, szintén opcionális' -end - -for szamlalo in 1..5 - puts "iteracio #{szamlalo}" -end -#=> iteracio 1 -#=> iteracio 2 -#=> iteracio 3 -#=> iteracio 4 -#=> iteracio 5 - -# HOWEVER, No-one uses for loops. -# Instead you should use the "each" method and pass it a block. -# A block is a bunch of code that you can pass to a method like "each". -# It is analogous to lambdas, anonymous functions or closures in other -# programming languages. -# -# The "each" method of a range runs the block once for each element of the range. -# The block is passed a counter as a parameter. -# Calling the "each" method with a block looks like this: - -(1..5).each do |counter| - puts "iteration #{counter}" -end -#=> iteration 1 -#=> iteration 2 -#=> iteration 3 -#=> iteration 4 -#=> iteration 5 - -# You can also surround blocks in curly brackets: -(1..5).each { |counter| puts "iteration #{counter}" } - -# The contents of data structures can also be iterated using each. -array.each do |element| - puts "#{element} is part of the array" -end -hash.each do |key, value| - puts "#{key} is #{value}" -end - -counter = 1 -while counter <= 5 do - puts "iteration #{counter}" - counter += 1 -end -#=> iteration 1 -#=> iteration 2 -#=> iteration 3 -#=> iteration 4 -#=> iteration 5 - -jegy = '4' - -case jegy -when '5' - puts 'Kitünő' -when '4' - puts 'Jó' -when '3' - puts 'Közepes' -when '2' - puts 'Elégsége' -when '1' - puts 'Elégtelen' -else - puts 'Alternatív értékelés, hm?' -end -#=> "Jó" - -# case-ek tartományokat is használhatnak -jegy = 82 -case jegy -when 90..100 - puts 'Hurrá!' -when 80...90 - puts 'Jó munka' -else - puts 'Megbuktál!' -end -#=> "Jó munka" - -# kivétel kezelés: -begin - # kód ami kivételt dobhat - raise NoMemoryError, 'Megtelt a memória' -rescue NoMemoryError => kivetel_valtozo - puts 'NoMemoryError-t dobott', kivetel_valtozo -rescue RuntimeError => mas_kivetel_valtozo - puts 'RuntimeError dobott most' -else - puts 'Ez akkor fut ha nem dob kivételt' -ensure - puts 'Ez a kód mindenképpen lefut' -end - -# Függvények - -def ketszeres(x) - x * 2 -end - -# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel -ketszeres(2) #=> 4 - -# Zárójelezés opcionális, ha az eredmény félreérthetetlen -ketszeres 3 #=> 6 - -ketszeres ketszeres 3 #=> 12 - -def osszeg(x, y) - x + y -end - -# Függvény argumentumait vesszővel választjuk el. -osszeg 3, 4 #=> 7 - -osszeg osszeg(3, 4), 5 #=> 12 - -# yield -# Minden függvénynek van egy implicit, opcionális block paramétere -# 'yield' kulcsszóval hívhatjuk - -def korulvesz - puts '{' - yield - puts '}' -end - -korulvesz { puts 'hello world' } - -# { -# hello world -# } - - -# Fuggvénynek átadhatunk blokkot -# "&" jelöli az átadott blokk referenciáját -def vendegek(&block) - block.call 'valami_argumentum' -end - -# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva -# Erre való a splat operátor ("*") -def vendegek(*array) - array.each { |vendeg| puts vendeg } -end - -# Osztályt a class kulcsszóval definiálhatunk -class Ember - - # Az osztály változó. Az osztály minden példánnyával megvan osztva - @@faj = 'H. sapiens' - - # Alap inicializáló - def initialize(nev, kor = 0) - # Hozzárendeli az argumentumot a "nev" példány változóhoz - @nev = nev - # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni - @kor = kor - end - - # Alap setter függvény - def nev=(nev) - @nev = nev - end - - # Alap getter függvény - def nev - @nev - end - - # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük - attr_accessor :nev - - # Getter/setter függvények egyenként is kreálhatóak - attr_reader :nev - attr_writer :nev - - # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a - # példány függvényektől - # Az osztályn hívhatóak, nem a példányon - def self.mond(uzenet) - puts uzenet - end - - def faj - @@faj - end -end - - -# Példányosítsuk az osztályt -jim = Ember.new('Jim Halpert') - -dwight = Ember.new('Dwight K. Schrute') - -# Hívjunk meg pár függvényt -jim.faj #=> "H. sapiens" -jim.nev #=> "Jim Halpert" -jim.nev = "Jim Halpert II" #=> "Jim Halpert II" -jim.nev #=> "Jim Halpert II" -dwight.faj #=> "H. sapiens" -dwight.nev #=> "Dwight K. Schrute" - -# Hívjuk meg az osztály függvényt -Ember.mond('Hi') #=> "Hi" - -# Változók szókjait az elnevezésük definiálja -# $ kezdetű változók globálisak -$var = "Én egy globális változó vagyok" -defined? $var #=> "global-variable" - -# Változók amik @-al kezdődnek példány szkópjuk van -@var = "Én egy példány változó vagyok" -defined? @var #=> "instance-variable" - -# Változók amik @@-al kezdődnek példány szkópjuk van -@@var = "Én egy osztály változó vagyok" -defined? @@var #=> "class variable" - -# Változók amik nagy betűvel kezdődnek a konstansok -Var = "Konstans vagyok" -defined? Var #=> "constant" - -# Az osztály is objetum. Tehát az osztálynak lehet példány változója -# Az osztályváltozón osztozik minden pédány és leszármazott - -# Ős osztály -class Ember - @@foo = 0 - - def self.foo - @@foo - end - - def self.foo=(ertek) - @@foo = ertek - end -end - -# Leszarmazott osztály -class Dolgozo < Ember -end - -Ember.foo # 0 -Dolgozo.foo # 0 - -Ember.foo = 2 # 2 -Dolgozo.foo # 2 - -# Az osztálynak példány változóját nem látja az osztály leszármazottja. - -class Ember - @bar = 0 - - def self.bar - @bar - end - - def self.bar=(ertek) - @bar = ertek - end -end - -class Doctor < Ember -end - -Ember.bar # 0 -Doctor.bar # nil - -module ModulePelda - def foo - 'foo' - end -end - -# Modulok include-olása a fügvényeiket az osztály példányaihoz köti. -# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti. - -class Szemely - include ModulePelda -end - -class Konyv - extend ModulePelda -end - -Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class -Szemely.new.foo # => 'foo' -Konyv.foo # => 'foo' -Konyv.new.foo # => NoMethodError: undefined method `foo' - -# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult - -module ConcernPelda - 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 Valami - include ConcernPelda -end - -Valami.bar # => 'bar' -Valami.qux # => NoMethodError: undefined method `qux' -Valami.new.bar # => NoMethodError: undefined method `bar' -Valami.new.qux # => 'qux' -``` - -## Egyéb források - -- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) -- [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/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online. -- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) -- cgit v1.2.3 From d684a44259348f52ed86d6e02b773f83b1547fad Mon Sep 17 00:00:00 2001 From: Leonardy Kristianto Date: Wed, 28 Oct 2015 02:15:29 +0800 Subject: Rename css.html.markdown to css-ta.html.markdown --- ta_in/css-ta.html.markdown | 254 +++++++++++++++++++++++++++++++++++++++++++++ ta_in/css.html.markdown | 254 --------------------------------------------- 2 files changed, 254 insertions(+), 254 deletions(-) create mode 100644 ta_in/css-ta.html.markdown delete mode 100644 ta_in/css.html.markdown diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown new file mode 100644 index 00000000..56f94ed0 --- /dev/null +++ b/ta_in/css-ta.html.markdown @@ -0,0 +1,254 @@ +--- +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) 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 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 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 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 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 cdd64ecee34af20ed101ba5dc8d7dc73a8189c15 Mon Sep 17 00:00:00 2001 From: Vipul Sharma 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 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 03ef96b2f11133701a3db64b9133f634a9709e94 Mon Sep 17 00:00:00 2001 From: Raphael Nascimento 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 fe1c5e86ede2786580c414bf608bb09d5c7ceb40 Mon Sep 17 00:00:00 2001 From: Nasgul 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 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 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 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 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 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 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?= 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 #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 // 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 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 +// Interface extends { +// // 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 +// abstract extends { +// // 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 +// 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: + // final () + + // 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" 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 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 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 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 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 - +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,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: +```markdown ~~This text is rendered with strikethrough.~~ -- cgit v1.2.3 From 9a152c0490ba38e791ba1444d74dcf184d3c847e Mon Sep 17 00:00:00 2001 From: Jacob Ward 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 also varies in implementation from one parser to a next. This + -## 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._ @@ -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 + + ~~This text is rendered with strikethrough.~~ -- cgit v1.2.3 From 5afca01bdfb7dab2e6086a63bb80444aae9831cb Mon Sep 17 00:00:00 2001 From: Liam Demafelix 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 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. --> - + # This is an

-- cgit v1.2.3 From 55101d6ca7bd51b3b3c850ad51f24d7980a288d6 Mon Sep 17 00:00:00 2001 From: IvanEh 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 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 +``` ### rm -- cgit v1.2.3 From 9530122a1c956a25adb71bfd9cc1c516ff67d2f3 Mon Sep 17 00:00:00 2001 From: Fernando Valverde 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() // 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() // 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 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 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 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 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 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 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 HTML tags have been provided for output readability " ---> @@ -314,8 +318,13 @@ ColdFusion is a scripting language for web development.

#getWorld()#

``` +### 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 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 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 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 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 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 *result; +Result *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 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 [] 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 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 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 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 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 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 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 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 COUNTRIES = HashSet() {{ + private static final Set COUNTRIES = new HashSet() {{ add("DENMARK"); add("SWEDEN"); add("FINLAND"); -- cgit v1.2.3 From b5cb14703ac99e70ecd6c1ec2abd9a2b5dbde54d Mon Sep 17 00:00:00 2001 From: Niko Weh 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 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 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 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 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 0156044d6f4f0630e1f82989b905a9f2a625e1a7 Mon Sep 17 00:00:00 2001 From: Kristy Vuong 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 - +text you want to be in that element by a number of hashes (#). --> # This is an

## This is an

### This is an

@@ -31,7 +31,7 @@ text you want to be in that element by a number of hashes (#) --> ##### This is an

###### This is an
- + This is an h1 ============= @@ -39,7 +39,7 @@ This is an h2 ------------- - + *This text is in italics.* _And so is this text._ @@ -85,7 +85,7 @@ There's a
above me! > How neat is that? - + * Item * Item @@ -103,21 +103,21 @@ or - Item - One last item - + 1. Item one 2. Item two 3. Item three +render the numbers in order, but this may not be a good idea. --> 1. Item one 1. Item two 1. Item three - + 1. Item one 2. Item two @@ -136,13 +136,13 @@ This checkbox below will be a checked HTML checkbox. +a line with four spaces or a tab. --> This is code So is this +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! - + \`\`\`ruby def foobar @@ -174,11 +174,11 @@ with or without spaces. --> +the text to display in hard brackets [] followed by the url in parentheses (). --> [Click me!](http://test.com/) - + [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/). - + [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. --> - + [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") - + ![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\*. - + Your computer crashed? Try sending a Ctrl+Alt+Del -- cgit v1.2.3 From fd16cf95ae0a96424f1cd78ffb3ac99138eda4ff Mon Sep 17 00:00:00 2001 From: Niko Weh 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 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 c990b720e4416fd5c516af906ba548d0b2b12f0f Mon Sep 17 00:00:00 2001 From: Reinoud Kruithof 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 + + + + 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 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 38506983bb1d589734268b62bb87b4bad4601733 Mon Sep 17 00:00:00 2001 From: Willie Zhu Date: Sat, 31 Oct 2015 15:27:44 -0400 Subject: [edn/en] Fix grammar --- edn.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/edn.html.markdown b/edn.html.markdown index 0a0dc9b5..d0bdddfc 100644 --- a/edn.html.markdown +++ b/edn.html.markdown @@ -5,13 +5,13 @@ contributors: - ["Jason Yeo", "https://github.com/jsyeo"] --- -Extensible Data Notation or EDN for short is a format for serializing data. +Extensible Data Notation (EDN) is a format for serializing data. -The notation is used internally by Clojure to represent programs and it also +The notation is used internally by Clojure to represent programs. It is 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. +Clojure, there are implementations of EDN for many other languages. -The main benefit of EDN over JSON and YAML is that it is extensible, which we +The main benefit of EDN over JSON and YAML is that it is extensible. We will see how it is extended later on. ```Clojure @@ -59,7 +59,7 @@ false ; Vectors allow random access [:gelato 1 2 -2] -; Maps are associative data structures that associates the key with its value +; Maps are associative data structures that associate the key with its value {:eggs 2 :lemon-juice 3.5 :butter 1} @@ -68,7 +68,7 @@ false {[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. +; You may use commas for readability. They are treated as whitespace. ; Sets are collections that contain unique elements. #{:a :b 88 "huat"} @@ -82,11 +82,11 @@ false #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. +; 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 +; 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}") -- cgit v1.2.3 From f5b8d838006d4d461389d35568786bbe7dd4d48c Mon Sep 17 00:00:00 2001 From: ComSecNinja Date: Sat, 31 Oct 2015 22:10:04 +0200 Subject: Translate Go-tutorial to Finnish --- fi-fi/go-fi.html.markdown | 428 ++++++++++++++++++++++++++++++++++++++++++++ fi-fi/go.html.markdown | 440 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 868 insertions(+) create mode 100644 fi-fi/go-fi.html.markdown create mode 100644 fi-fi/go.html.markdown diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown new file mode 100644 index 00000000..dc684227 --- /dev/null +++ b/fi-fi/go-fi.html.markdown @@ -0,0 +1,428 @@ +--- +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"] +--- + +Go was created out of the need to get work done. It's not the latest trend +in computer science, but it is the newest fastest way to solve real-world +problems. + +It has familiar concepts of imperative languages with static typing. +It's fast to compile and fast to execute, it adds easy-to-understand +concurrency to leverage today's multi-core CPUs, and has features to +help with large-scale programming. + +Go comes with a great standard library and an enthusiastic community. + +```go +// Single line comment +/* Multi- + line comment */ + +// A package clause starts every source file. +// Main is a special name declaring an executable rather than a library. +package main + +// Import declaration declares library packages referenced in this file. +import ( + "fmt" // A package in the Go standard library. + "io/ioutil" // Implements some I/O utility functions. + m "math" // Math library with local alias m. + "net/http" // Yes, a web server! + "strconv" // String conversions. +) + +// A function definition. Main is special. It is the entry point for the +// executable program. Love it or hate it, Go uses brace brackets. +func main() { + // Println outputs a line to stdout. + // Qualify it with the package name, fmt. + fmt.Println("Hello world!") + + // Call another function within this package. + beyondHello() +} + +// Functions have parameters in parentheses. +// If there are no parameters, empty parentheses are still required. +func beyondHello() { + var x int // Variable declaration. Variables must be declared before use. + x = 3 // Variable assignment. + // "Short" declarations use := to infer the type, declare, and assign. + y := 4 + sum, prod := learnMultiple(x, y) // Function returns two values. + fmt.Println("sum:", sum, "prod:", prod) // Simple output. + learnTypes() // < y minutes, learn more! +} + +/* <- multiline comment +Functions can have parameters and (multiple!) return values. +Here `x`, `y` are the arguments and `sum`, `prod` is the signature (what's returned). +Note that `x` and `sum` receive the type `int`. +*/ +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // Return two values. +} + +// Some built-in types and literals. +func learnTypes() { + // Short declaration usually gives you what you want. + str := "Learn Go!" // string type. + + s2 := `A "raw" string literal +can include line breaks.` // Same string type. + + // Non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for int32, holds a unicode code point. + + f := 3.14195 // float64, an IEEE-754 64-bit floating point number. + c := 3 + 4i // complex128, represented internally with two float64's. + + // var syntax with initializers. + var u uint = 7 // Unsigned, but implementation dependent size as with int. + var pi float32 = 22. / 7 + + // Conversion syntax with a short declaration. + n := byte('\n') // byte is an alias for uint8. + + // Arrays have size fixed at compile time. + var a4 [4]int // An array of 4 ints, initialized to all 0. + a3 := [...]int{3, 1, 5} // An array initialized with a fixed size of three + // elements, with values 3, 1, and 5. + + // Slices have dynamic size. Arrays and slices each have advantages + // but use cases for slices are much more common. + s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. + s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. + var d2 [][]float64 // Declaration only, nothing allocated here. + bs := []byte("a slice") // Type conversion syntax. + + // Because they are dynamic, slices can be appended to on-demand. + // To append elements to a slice, the built-in append() function is used. + // First argument is a slice to which we are appending. Commonly, + // the array variable is updated in place, as in example below. + s := []int{1, 2, 3} // Result is a slice of length 3. + s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + + // To append another slice, instead of list of atomic elements we can + // pass a reference to a slice or a slice literal like this, with a + // trailing ellipsis, meaning take a slice and unpack its elements, + // appending them to slice s. + s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] + + p, q := learnMemory() // Declares p, q to be type pointer to int. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + + // Maps are a dynamically growable associative array type, like the + // hash or dictionary types of some other languages. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Unused variables are an error in Go. + // The underscore lets you "use" a variable but discard its value. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Output of course counts as using a variable. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // Back in the flow. +} + +// It is possible, unlike in many other languages for functions in go +// to have named return values. +// Assigning a name to the type being returned in the function declaration line +// allows us to easily return from multiple points in a function as well as to +// only use the return keyword, without anything further. +func learnNamedReturns(x, y int) (z int) { + z = x * y + return // z is implicit here, because we named it earlier. +} + +// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// You can make a mistake with a nil pointer, but not by incrementing a pointer. +func learnMemory() (p, q *int) { + // Named return values p and q have type pointer to int. + p = new(int) // Built-in function new allocates memory. + // The allocated int is initialized to 0, p is no longer nil. + s := make([]int, 20) // Allocate 20 ints as a single block of memory. + s[3] = 7 // Assign one of them. + r := -2 // Declare another local variable. + return &s[3], &r // & takes the address of an object. +} + +func expensiveComputation() float64 { + return m.Exp(10) +} + +func learnFlowControl() { + // If statements require brace brackets, and do not require parentheses. + if true { + fmt.Println("told ya") + } + // Formatting is standardized by the command line command "go fmt." + if false { + // Pout. + } else { + // Gloat. + } + // Use switch in preference to chained if statements. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Cases don't "fall through". + /* + There is a `fallthrough` keyword however, see: + https://github.com/golang/go/wiki/Switch#fall-through + */ + case 43: + // Unreached. + default: + // Default case is optional. + } + // Like if, for doesn't use parens either. + // Variables declared in for and if are local to their scope. + for x := 0; x < 3; x++ { // ++ is a statement. + fmt.Println("iteration", x) + } + // x == 42 here. + + // For is the only loop statement in Go, but it has alternate forms. + for { // Infinite loop. + break // Just kidding. + continue // Unreached. + } + + // You can use range to iterate over an array, a slice, a string, a map, or a channel. + // range returns one (channel) or two values (array, slice, string and map). + for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} { + // for each pair in the map, print key and value + fmt.Printf("key=%s, value=%d\n", key, value) + } + + // As with for, := in an if statement means to declare and assign + // y first, then test y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Function literals are closures. + xBig := func() bool { + return x > 10000 // References x declared above switch statement. + } + fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x). + x = 1.3e3 // This makes x == 1300 + fmt.Println("xBig:", xBig()) // false now. + + // What's more is function literals may be defined and called inline, + // acting as an argument to function, as long as: + // a) function literal is called immediately (), + // b) result type matches expected type of argument. + fmt.Println("Add + double two numbers: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Called with args 10 and 2 + // => Add + double two numbers: 24 + + // When you need it, you'll love it. + goto love +love: + + learnFunctionFactory() // func returning func is fun(3)(3) + learnDefer() // A quick detour to an important keyword. + learnInterfaces() // Good stuff coming up! +} + +func learnFunctionFactory() { + // Next two are equivalent, with second being more practical + fmt.Println(sentenceFactory("summer")("A beautiful", "day!")) + + d := sentenceFactory("summer") + fmt.Println(d("A beautiful", "day!")) + fmt.Println(d("A lazy", "afternoon!")) +} + +// Decorators are common in other languages. Same can be done in Go +// with function literals that accept arguments. +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // new string + } +} + +func learnDefer() (ok bool) { + // Deferred statements are executed just before the function returns. + defer fmt.Println("deferred statements execute in reverse (LIFO) order.") + defer fmt.Println("\nThis line is being printed first because") + // Defer is commonly used to close a file, so the function closing the + // file stays close to the function opening the file. + return true +} + +// Define Stringer as an interface type with one method, String. +type Stringer interface { + String() string +} + +// Define pair as a struct with two fields, ints named x and y. +type pair struct { + x, y int +} + +// Define a method on type pair. Pair now implements Stringer. +func (p pair) String() string { // p is called the "receiver" + // Sprintf is another public function in package fmt. + // Dot syntax references fields of p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Brace syntax is a "struct literal". It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. + p := pair{3, 4} + fmt.Println(p.String()) // Call String method of p, of type pair. + var i Stringer // Declare i of interface type Stringer. + i = p // Valid because pair implements Stringer + // Call String method of i, of type Stringer. Output same as above. + fmt.Println(i.String()) + + // Functions in the fmt package call the String method to ask an object + // for a printable representation of itself. + fmt.Println(p) // Output same as above. Println calls String method. + fmt.Println(i) // Output same as above. + + learnVariadicParams("great", "learning", "here!") +} + +// Functions can have variadic parameters. +func learnVariadicParams(myStrings ...interface{}) { + // Iterate each value of the variadic. + // The underbar here is ignoring the index argument of the array. + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // Pass variadic value as a variadic parameter. + fmt.Println("params:", fmt.Sprintln(myStrings...)) + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" idiom used to tell if something worked or not. + m := map[int]string{3: "three", 4: "four"} + if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. + fmt.Println("no one there") + } else { + fmt.Print(x) // x would be the value, if it were in the map. + } + // An error value communicates not just "ok" but more about the problem. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value + // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // We'll revisit interfaces a little later. Meanwhile, + learnConcurrency() +} + +// c is a channel, a concurrency-safe communication object. +func inc(i int, c chan int) { + c <- i + 1 // <- is the "send" operator when a channel appears on the left. +} + +// We'll use inc to increment some numbers concurrently. +func learnConcurrency() { + // Same make function used earlier to make a slice. Make allocates and + // initializes slices, maps, and channels. + c := make(chan int) + // Start three concurrent goroutines. Numbers will be incremented + // concurrently, perhaps in parallel if the machine is capable and + // properly configured. All three send to the same channel. + go inc(0, c) // go is a statement that starts a new goroutine. + go inc(10, c) + go inc(-805, c) + // Read three results from the channel and print them out. + // There is no telling in what order the results will arrive! + fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. + + cs := make(chan string) // Another channel, this one handles strings. + ccs := make(chan chan string) // A channel of string channels. + go func() { c <- 84 }() // Start a new goroutine just to send a value. + go func() { cs <- "wordy" }() // Again, for cs this time. + // Select has syntax like a switch statement but each case involves + // a channel operation. It selects a case at random out of the cases + // that are ready to communicate. + select { + case i := <-c: // The value received can be assigned to a variable, + fmt.Printf("it's a %T", i) + case <-cs: // or the value received can be discarded. + fmt.Println("it's a string") + case <-ccs: // Empty channel, not ready for communication. + fmt.Println("didn't happen.") + } + // At this point a value was taken from either c or cs. One of the two + // goroutines started above has completed, the other will remain blocked. + + learnWebProgramming() // Go does it. You want to do it too. +} + +// A single function from package http starts a web server. +func learnWebProgramming() { + + // First parameter of ListenAndServe is TCP address to listen to. + // Second parameter is an interface, specifically http.Handler. + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // don't ignore errors + }() + + requestServer() +} + +// Make pair an http.Handler by implementing its only method, ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Serve data with a method of http.ResponseWriter. + w.Write([]byte("You learned Go in Y minutes!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWebserver said: `%s`", string(body)) +} +``` + +## Further Reading + +The root of all things Go is the [official Go web site](http://golang.org/). +There you can follow the tutorial, play interactively, and read lots. +Aside from a tour, [the docs](https://golang.org/doc/) contain information on +how to write clean and effective Go code, package and command docs, and release history. + +The language definition itself is highly recommended. It's easy to read +and amazingly short (as language definitions go these days.) + +You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. + +On the reading list for students of Go is the [source code to the standard +library](http://golang.org/src/pkg/). Comprehensively documented, it +demonstrates the best of readable and understandable Go, Go style, and Go +idioms. Or you can click on a function name in [the +documentation](http://golang.org/pkg/) and the source code comes up! + +Another great resource to learn Go is [Go by example](https://gobyexample.com/). + +Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information. diff --git a/fi-fi/go.html.markdown b/fi-fi/go.html.markdown new file mode 100644 index 00000000..714d4e06 --- /dev/null +++ b/fi-fi/go.html.markdown @@ -0,0 +1,440 @@ +--- +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: + - ["Timo Virkkunen", "https://github.com/ComSecNinja"] +--- + +Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi, +mutta se on uusin nopein tapa ratkaista oikean maailman ongelmia. + +Sillä on staattisesti tyypitetyistä imperatiivisista kielistä tuttuja +konsepteja. Se kääntyy ja suorittuu nopeasti, lisää helposti käsitettävän +samanaikaisten komentojen suorittamisen nykyaikaisten moniytimisten +prosessoreiden hyödyntämiseksi ja antaa käyttäjälle ominaisuuksia suurten +projektien käsittelemiseksi. + +Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön. + +```go +// Yhden rivin kommentti +/* Useamman + rivin kommentti */ + +// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto. +// Main on erityinen nimi joka ilmoittaa +// suoritettavan tiedoston kirjaston sijasta. +package main + +// Import -lauseke ilmoittaa tässä tiedostossa käytetyt kirjastot. +import ( + "fmt" // Paketti Go:n oletuskirjastosta. + "io/ioutil" // Implementoi hyödyllisiä I/O -funktioita. + m "math" // Matematiikkakirjasto jolla on paikallinen nimi m. + "net/http" // Kyllä, web-palvelin! + "strconv" // Kirjainjonojen muuntajia. +) + +// Funktion määrittelijä. Main on erityinen: se on ohjelman suorittamisen +// aloittamisen alkupiste. Rakasta tai vihaa sitä, Go käyttää aaltosulkeita. +func main() { + // Println tulostaa rivin stdoutiin. + // Se tulee paketin fmt mukana, joten paketin nimi on mainittava. + fmt.Println("Hei maailma!") + + // Kutsu toista funktiota tämän paketin sisällä. + beyondHello() +} + +// Funktioilla voi olla parametrejä sulkeissa. +// Vaikkei parametrejä olisikaan, sulkeet ovat silti pakolliset. +func beyondHello() { + var x int // Muuttujan ilmoittaminen: ne täytyy ilmoittaa ennen käyttöä. + x = 3 // Arvon antaminen muuttujalle. + // "Lyhyet" ilmoitukset käyttävät := joka päättelee tyypin, ilmoittaa + // sekä antaa arvon muuttujalle. + y := 4 + sum, prod := learnMultiple(x, y) // Funktio palauttaa kaksi arvoa. + fmt.Println("summa:", sum, "tulo:", prod) // Yksinkertainen tuloste. + learnTypes() // < y minuuttia, opi lisää! +} + +/* <- usean rivin kommentti +Funktioilla voi olla parametrejä ja (useita!) palautusarvoja. +Tässä `x`, `y` ovat argumenttejä ja `sum`, `prod` ovat ne, mitä palautetaan. +Huomaa että `x` ja `sum` saavat tyyin `int`. +*/ +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // Palauta kaksi arvoa. +} + +// Sisäänrakennettuja tyyppejä ja todellisarvoja. +func learnTypes() { + // Lyhyt ilmoitus antaa yleensä haluamasi. + str := "Opi Go!" // merkkijonotyyppi. + + s2 := `"raaka" todellisarvoinen merrkijono +voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi. + + // Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8. + g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen. + + f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku. + c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla. + + // var -syntaksi alkuarvoilla. + var u uint = 7 // Etumerkitön, toteutus riippuvainen koosta kuten int. + var pi float32 = 22. / 7 + + // Muuntosyntaksi lyhyellä ilmoituksella. + n := byte('\n') // byte on leminimi uint8:lle. + + // Listoilla on kiinteä koko kääntöhetkellä. + var a4 [4]int // 4 int:in lista, alkiot ovat alustettu nolliksi. + a3 := [...]int{3, 1, 5} // Listan alustaja jonka kiinteäksi kooksi tulee 3 + // alkiota, jotka saavat arvot 3, 1, ja 5. + + // Siivuilla on muuttuva koko. Sekä listoilla että siivuilla on puolensa, + // mutta siivut ovat yleisempiä käyttötapojensa vuoksi. + s3 := []int{4, 5, 9} // Vertaa a3: ei sananheittoa (...). + s4 := make([]int, 4) // Varaa 4 int:n siivun, alkiot alustettu nolliksi. + var d2 [][]float64 // Vain ilmoitus, muistia ei varata. + bs := []byte("a slice") // Tyypinmuuntosyntaksi. + + // Koska siivut ovat dynaamisia, niitä voidaan yhdistellä sellaisinaan. + // Lisätäksesi alkioita siivuun, käytä sisäänrakennettua append()-funktiota. + // Ensimmäinen argumentti on siivu, johon alkoita lisätään. + s := []int{1, 2, 3} // Tuloksena on kolmen alkion pituinen lista. + s = append(s, 4, 5, 6) // Lisätty kolme alkiota. Siivun pituudeksi tulee 6. + fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6] + + // Lisätäksesi siivun toiseen voit antaa append-funktiolle referenssin + // siivuun tai todellisarvoiseen siivuun lisäämällä sanaheiton argumentin + // perään. Tämä tapa purkaa siivun alkiot ja lisää ne siivuun s. + s = append(s, []int{7, 8, 9}...) // 2. argumentti on todellisarvoinen siivu. + fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6 7 8 9] + + p, q := learnMemory() // Ilmoittaa p ja q olevan tyyppiä osoittaja int:iin. + fmt.Println(*p, *q) // * seuraa osoittajaa. Tämä tulostaa kaksi int:ä. + + // Kartat ovat dynaamisesti kasvavia assosiatiivisia listoja, kuten hash tai + // dictionary toisissa kielissä. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Käyttämättömät muuttujat ovat virheitä Go:ssa. + // Alaviiva antaa sinun "käyttää" muuttujan mutta hylätä sen arvon. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Tulostaminen tietysti lasketaan muuttujan käyttämiseksi. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // Takaisin flowiin. +} + +// Go:ssa on useista muista kielistä poiketen mahdollista käyttää nimettyjä +// palautusarvoja. +// Nimen antaminen palautettavan arvon tyypille funktion ilmoitusrivillä +// mahdollistaa helpon palaamisen useasta eri funktion suorituskohdasta sekä +// pelkän return-lausekkeen käytön ilman muita mainintoja. +func learnNamedReturns(x, y int) (z int) { + z = x * y + return // z on epäsuorasti tässä, koska nimesimme sen aiemmin. +} + +// Go kerää kaikki roskansa. Siinä on osoittajia mutta ei niiden laskentoa. +// Voit tehdä virheen mitättömällä osoittajalla, mutta et +// kasvattamalla osoittajaa. +func learnMemory() (p, q *int) { + // Nimetyillä palautusarvoilla p ja q on tyyppi osoittaja int:iin. + p = new(int) // Sisäänrakennettu funktio new varaa muistia. + // Varattu int on alustettu nollaksi, p ei ole enää mitätön. + s := make([]int, 20) // Varaa 20 int:ä yhteen kohtaan muistissa. + s[3] = 7 // Anna yhdelle niistä arvo. + r := -2 // Ilmoita toinen paikallinen muuttuja. + return &s[3], &r // & ottaa asian osoitteen muistissa. +} + +func expensiveComputation() float64 { + return m.Exp(10) +} + +func learnFlowControl() { + // If -lausekkeet vaativat aaltosulkeet mutta ei tavallisia sulkeita. + if true { + fmt.Println("mitä mä sanoin") + } + // Muotoilu on standardoitu käyttämällä komentorivin komentoa "go fmt". + if false { + // Nyrpistys. + } else { + // Nautinto. + } + // Käytä switch -lauseketta ketjutettujen if -lausekkeiden sijasta. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Tapaukset eivät "tipu läpi". + /* + Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso: + https://github.com/golang/go/wiki/Switch#fall-through + */ + case 43: + // Saavuttamaton. + default: + // Oletustapaus (default) on valinnainen. + } + // Kuten if, for -lauseke ei myöskään käytä tavallisia sulkeita. + // for- ja if- lausekkeissa ilmoitetut muuttujat ovat paikallisia niiden + // piireissä. + for x := 0; x < 3; x++ { // ++ on lauseke. Sama kuin "x = x + 1". + fmt.Println("iteraatio", x) + } + // x == 42 tässä. + + // For on kielen ainoa silmukkalauseke mutta sillä on vaihtoehtosia muotoja. + for { // Päättymätön silmukka. + break // Kunhan vitsailin. + continue // Saavuttamaton. + } + + // Voit käyttää range -lauseketta iteroidaksesi listojen, siivujen, merkki- + // jonojen, karttojen tai kanavien läpi. range palauttaa yhden (kanava) tai + // kaksi arvoa (lista, siivu, merkkijono ja kartta). + for key, value := range map[string]int{"yksi": 1, "kaksi": 2, "kolme": 3} { + // jokaista kartan paria kohden, tulosta avain ja arvo + fmt.Printf("avain=%s, arvo=%d\n", key, value) + } + + // Kuten for -lausekkeessa := if -lausekkeessa tarkoittaa ilmoittamista ja + // arvon asettamista. + // Aseta ensin y, sitten testaa onko y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Todellisarvoiset funktiot ovat sulkeumia. + xBig := func() bool { + return x > 10000 // Viittaa ylempänä ilmoitettuun x:ään. + } + fmt.Println("xBig:", xBig()) // tosi (viimeisin arvo on e^10). + x = 1.3e3 // Tämä tekee x == 1300 + fmt.Println("xBig:", xBig()) // epätosi nyt. + + // Lisäksi todellisarvoiset funktiot voidaan samalla sekä ilmoittaa että + // kutsua, jolloin niitä voidaan käyttää funtioiden argumentteina kunhan: + // a) todellisarvoinen funktio kutsutaan välittömästi (), + // b) palautettu tyyppi vastaa odotettua argumentin tyyppiä. + fmt.Println("Lisää ja tuplaa kaksi numeroa: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Kutsuttu argumenteilla 10 ja 2 + // => Lisää ja tuplaa kaksi numeroa: 24 + + // Kun tarvitset sitä, rakastat sitä. + goto love +love: + + learnFunctionFactory() // Funktioita palauttavat funktiot + learnDefer() // Nopea kiertoreitti tärkeään avainsanaan. + learnInterfaces() // Hyvää kamaa tulossa! +} + +func learnFunctionFactory() { + // Seuraavat kaksi ovat vastaavia, mutta toinen on käytännöllisempi + fmt.Println(sentenceFactory("kesä")("Kaunis", "päivä!")) + + d := sentenceFactory("kesä") + fmt.Println(d("Kaunis", "päivä!")) + fmt.Println(d("Laiska", "iltapäivä!")) +} + +// Somisteet ovat yleisiä toisissa kielissä. Sama saavutetaan Go:ssa käyttämällä +// todellisarvoisia funktioita jotka ottavat vastaan argumentteja. +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // uusi jono + } +} + +func learnDefer() (ok bool) { + // Lykätyt lausekkeet suoritetaan juuri ennen funktiosta palaamista. + defer fmt.Println("lykätyt lausekkeet suorittuvat") + defer fmt.Println("käänteisessä järjestyksessä (LIFO).") + defer fmt.Println("\nTämä rivi tulostuu ensin, koska") + // Defer -lauseketta käytetään yleisesti tiedoston sulkemiseksi, jotta + // tiedoston sulkeva funktio pysyy lähellä sen avannutta funktiota. + return true +} + +// Määrittele Stringer rajapintatyypiksi jolla on +// yksi jäsenfunktio eli metodi, String. +type Stringer interface { + String() string +} + +// Määrittele pair rakenteeksi jossa on kaksi kenttää, x ja y tyyppiä int. +type pair struct { + x, y int +} + +// Määrittele jäsenfunktio pair:lle. Pair tyydyttää nyt Stringer -rajapinnan. +func (p pair) String() string { // p:tä kutsutaan nimellä "receiver" + // Sprintf on toinen julkinen funktio paketissa fmt. + // Pistesyntaksilla viitataan P:n kenttiin. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Aaltosuljesyntaksi on "todellisarvoinen rakenne". Se todentuu alustetuksi + // rakenteeksi. := -syntaksi ilmoittaa ja alustaa p:n täksi rakenteeksi. + p := pair{3, 4} + fmt.Println(p.String()) // Kutsu p:n (tyyppiä pair) jäsenfunktiota String. + var i Stringer // Ilmoita i Stringer-rajapintatyypiksi. + i = p // Pätevä koska pair tyydyttää rajapinnan Stringer. + // Kutsu i:n (Stringer) jäsenfunktiota String. Tuloste on sama kuin yllä. + fmt.Println(i.String()) + + // Funktiot fmt-paketissa kutsuvat argumenttien String-jäsenfunktiota + // selvittääkseen onko niistä saatavilla tulostettavaa vastinetta. + fmt.Println(p) // Tuloste on sama kuin yllä. Println kutsuu String-metodia. + fmt.Println(i) // Tuloste on sama kuin yllä. + + learnVariadicParams("loistavaa", "oppimista", "täällä!") +} + +// Funktioilla voi olla muuttuva eli variteettinen +// määrä argumentteja eli parametrejä. +func learnVariadicParams(myStrings ...interface{}) { + // Iteroi jokaisen argumentin läpi. + // Tässä alaviivalla sivuutetaan argumenttilistan kunkin kohdan indeksi. + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // Luovuta variteettinen arvo variteettisena parametrinä. + fmt.Println("params:", fmt.Sprintln(myStrings...)) + + learnErrorHandling() +} + +func learnErrorHandling() { + // "; ok" -muotoa käytetään selvittääksemme toimiko jokin vai ei. + m := map[int]string{3: "kolme", 4: "neljä"} + if x, ok := m[1]; !ok { // ok on epätosi koska 1 ei ole kartassa. + fmt.Println("ei ketään täällä") + } else { + fmt.Print(x) // x olisi arvo jos se olisi kartassa. + } + // Virhearvo voi kertoa muutakin ongelmasta. + if _, err := strconv.Atoi("ei-luku"); err != nil { // _ sivuuttaa arvon + // tulostaa strconv.ParseInt: parsing "ei-luku": invalid syntax + fmt.Println(err) + } + // Palaamme rajapintoihin hieman myöhemmin. Sillä välin, + learnConcurrency() +} + +// c on kanava, samanaikaisturvallinen viestintäolio. +func inc(i int, c chan int) { + c <- i + 1 // <- on "lähetysoperaattori" kun kanava on siitä vasemmalla. +} + +// Käytämme inc -funktiota samanaikaiseen lukujen lisäämiseen. +func learnConcurrency() { + // Sama make -funktio jota käytimme aikaisemmin siivun luomiseksi. Make + // varaa muistin ja alustaa siivut, kartat ja kanavat. + c := make(chan int) + // Aloita kolme samanaikaista gorutiinia (goroutine). Luvut kasvavat + // samanaikaisesti ja ehkäpä rinnakkain jos laite on kykenevä ja oikein + // määritelty. Kaikki kolme lähettävät samalle kanavalle. + go inc(0, c) // go -lauseke aloittaa uuden gorutiinin. + go inc(10, c) + go inc(-805, c) + // Lue kolme palautusarvoa kanavalta ja tulosta ne. + // Niiden saapumisjärjestystä ei voida taata! + // <- on "vastaanotto-operaattori" jos kanava on oikealla + fmt.Println(<-c, <-c, <-c) + + cs := make(chan string) // Toinen kanava joka käsittelee merkkijonoja. + ccs := make(chan chan string) // Kanava joka käsittelee merkkijonokanavia. + go func() { c <- 84 }() // Aloita uusi gorutiini arvon lähettämiseksi. + go func() { cs <- "sanaa" }() // Uudestaan, mutta cs -kanava tällä kertaa. + // Select -lausekkeella on syntaksi kuten switch -lausekkeella mutta + // jokainen tapaus sisältää kanavaoperaation. Se valitsee satunnaisen + // tapauksen niistä kanavista, jotka ovat kommunikaatiovalmiita + select { + case i := <-c: // Vastaanotettu arvo voidaan antaa muuttujalle + fmt.Printf("se on %T", i) + case <-cs: // tai vastaanotettu arvo voidaan sivuuttaa. + fmt.Println("se on merkkijono") + case <-ccs: // Tyhjä kanava; ei valmis kommunikaatioon. + fmt.Println("ei tapahtunut.") + } + // Tässä vaiheessa arvo oli otettu joko c:ltä tai cs:ltä. Yksi kahdesta + // ylempänä aloitetusta gorutiinista on valmistunut, toinen pysyy tukossa. + + learnWebProgramming() // Go tekee sitä. Sinäkin haluat tehdä sitä. +} + +// Yksittäinen funktio http -paketista aloittaa web-palvelimen. +func learnWebProgramming() { + + // ListenAndServe:n ensimmäinen parametri on TCP-osoite, jota kuunnellaan. + // Toinen parametri on rajapinta, http.Handler. + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // älä sivuuta virheitä. + }() + + requestServer() +} + +// Tee pair:sta http.Handler implementoimalla sen ainoa metodi, ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Tarjoa dataa metodilla http.ResponseWriter. + w.Write([]byte("Opit Go:n Y minuutissa!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWeb-palvelin sanoo: `%s`", string(body)) +} +``` + +## Lisää luettavaa + +Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/). +Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon. +Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa +siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta. + +Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja +yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.) + +Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm). +Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org) +[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista. + +Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/). +Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista, +-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja +lähdekoodi tulee esille! + +Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/). + +Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia +Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile). -- cgit v1.2.3 From 0234e6eee1ed26f2135c271a198a4b0517d5bb2e Mon Sep 17 00:00:00 2001 From: ComSecNinja Date: Sat, 31 Oct 2015 22:16:50 +0200 Subject: Changes to follow style guide --- fi-fi/go-fi.html.markdown | 496 ++++++++++++++++++++++++---------------------- fi-fi/go.html.markdown | 440 ---------------------------------------- 2 files changed, 254 insertions(+), 682 deletions(-) delete mode 100644 fi-fi/go.html.markdown diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index dc684227..8a0ca245 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -2,7 +2,7 @@ name: Go category: language language: Go -filename: learngo.go +filename: learngo-fi.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] - ["Christopher Bess", "https://github.com/cbess"] @@ -11,154 +11,157 @@ contributors: - ["Jose Donizetti", "https://github.com/josedonizetti"] - ["Alexej Friesen", "https://github.com/heyalexej"] - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Timo Virkkunen", "https://github.com/ComSecNinja"] --- -Go was created out of the need to get work done. It's not the latest trend -in computer science, but it is the newest fastest way to solve real-world -problems. +Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi, +mutta se on uusin nopein tapa ratkaista oikean maailman ongelmia. -It has familiar concepts of imperative languages with static typing. -It's fast to compile and fast to execute, it adds easy-to-understand -concurrency to leverage today's multi-core CPUs, and has features to -help with large-scale programming. +Sillä on staattisesti tyypitetyistä imperatiivisista kielistä tuttuja +konsepteja. Se kääntyy ja suorittuu nopeasti, lisää helposti käsitettävän +samanaikaisten komentojen suorittamisen nykyaikaisten moniytimisten +prosessoreiden hyödyntämiseksi ja antaa käyttäjälle ominaisuuksia suurten +projektien käsittelemiseksi. -Go comes with a great standard library and an enthusiastic community. +Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön. ```go -// Single line comment -/* Multi- - line comment */ +// Yhden rivin kommentti +/* Useamman + rivin kommentti */ -// A package clause starts every source file. -// Main is a special name declaring an executable rather than a library. +// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto. +// Main on erityinen nimi joka ilmoittaa +// suoritettavan tiedoston kirjaston sijasta. package main -// Import declaration declares library packages referenced in this file. +// Import -lauseke ilmoittaa tässä tiedostossa käytetyt kirjastot. import ( - "fmt" // A package in the Go standard library. - "io/ioutil" // Implements some I/O utility functions. - m "math" // Math library with local alias m. - "net/http" // Yes, a web server! - "strconv" // String conversions. + "fmt" // Paketti Go:n oletuskirjastosta. + "io/ioutil" // Implementoi hyödyllisiä I/O -funktioita. + m "math" // Matematiikkakirjasto jolla on paikallinen nimi m. + "net/http" // Kyllä, web-palvelin! + "strconv" // Kirjainjonojen muuntajia. ) -// A function definition. Main is special. It is the entry point for the -// executable program. Love it or hate it, Go uses brace brackets. +// Funktion määrittelijä. Main on erityinen: se on ohjelman suorittamisen +// aloittamisen alkupiste. Rakasta tai vihaa sitä, Go käyttää aaltosulkeita. func main() { - // Println outputs a line to stdout. - // Qualify it with the package name, fmt. - fmt.Println("Hello world!") + // Println tulostaa rivin stdoutiin. + // Se tulee paketin fmt mukana, joten paketin nimi on mainittava. + fmt.Println("Hei maailma!") - // Call another function within this package. + // Kutsu toista funktiota tämän paketin sisällä. beyondHello() } -// Functions have parameters in parentheses. -// If there are no parameters, empty parentheses are still required. +// Funktioilla voi olla parametrejä sulkeissa. +// Vaikkei parametrejä olisikaan, sulkeet ovat silti pakolliset. func beyondHello() { - var x int // Variable declaration. Variables must be declared before use. - x = 3 // Variable assignment. - // "Short" declarations use := to infer the type, declare, and assign. + var x int // Muuttujan ilmoittaminen: ne täytyy ilmoittaa ennen käyttöä. + x = 3 // Arvon antaminen muuttujalle. + // "Lyhyet" ilmoitukset käyttävät := joka päättelee tyypin, ilmoittaa + // sekä antaa arvon muuttujalle. y := 4 - sum, prod := learnMultiple(x, y) // Function returns two values. - fmt.Println("sum:", sum, "prod:", prod) // Simple output. - learnTypes() // < y minutes, learn more! + sum, prod := learnMultiple(x, y) // Funktio palauttaa kaksi arvoa. + fmt.Println("summa:", sum, "tulo:", prod) // Yksinkertainen tuloste. + learnTypes() // < y minuuttia, opi lisää! } -/* <- multiline comment -Functions can have parameters and (multiple!) return values. -Here `x`, `y` are the arguments and `sum`, `prod` is the signature (what's returned). -Note that `x` and `sum` receive the type `int`. +/* <- usean rivin kommentti +Funktioilla voi olla parametrejä ja (useita!) palautusarvoja. +Tässä `x`, `y` ovat argumenttejä ja `sum`, `prod` ovat ne, mitä palautetaan. +Huomaa että `x` ja `sum` saavat tyyin `int`. */ func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // Return two values. + return x + y, x * y // Palauta kaksi arvoa. } -// Some built-in types and literals. +// Sisäänrakennettuja tyyppejä ja todellisarvoja. func learnTypes() { - // Short declaration usually gives you what you want. - str := "Learn Go!" // string type. + // Lyhyt ilmoitus antaa yleensä haluamasi. + str := "Opi Go!" // merkkijonotyyppi. - s2 := `A "raw" string literal -can include line breaks.` // Same string type. + s2 := `"raaka" todellisarvoinen merrkijono +voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi. - // Non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for int32, holds a unicode code point. + // Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8. + g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen. - f := 3.14195 // float64, an IEEE-754 64-bit floating point number. - c := 3 + 4i // complex128, represented internally with two float64's. + f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku. + c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla. - // var syntax with initializers. - var u uint = 7 // Unsigned, but implementation dependent size as with int. + // var -syntaksi alkuarvoilla. + var u uint = 7 // Etumerkitön, toteutus riippuvainen koosta kuten int. var pi float32 = 22. / 7 - // Conversion syntax with a short declaration. - n := byte('\n') // byte is an alias for uint8. - - // Arrays have size fixed at compile time. - var a4 [4]int // An array of 4 ints, initialized to all 0. - a3 := [...]int{3, 1, 5} // An array initialized with a fixed size of three - // elements, with values 3, 1, and 5. - - // Slices have dynamic size. Arrays and slices each have advantages - // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. - s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. - var d2 [][]float64 // Declaration only, nothing allocated here. - bs := []byte("a slice") // Type conversion syntax. - - // Because they are dynamic, slices can be appended to on-demand. - // To append elements to a slice, the built-in append() function is used. - // First argument is a slice to which we are appending. Commonly, - // the array variable is updated in place, as in example below. - s := []int{1, 2, 3} // Result is a slice of length 3. - s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] - - // To append another slice, instead of list of atomic elements we can - // pass a reference to a slice or a slice literal like this, with a - // trailing ellipsis, meaning take a slice and unpack its elements, - // appending them to slice s. - s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] - - p, q := learnMemory() // Declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. - - // Maps are a dynamically growable associative array type, like the - // hash or dictionary types of some other languages. + // Muuntosyntaksi lyhyellä ilmoituksella. + n := byte('\n') // byte on leminimi uint8:lle. + + // Listoilla on kiinteä koko kääntöhetkellä. + var a4 [4]int // 4 int:in lista, alkiot ovat alustettu nolliksi. + a3 := [...]int{3, 1, 5} // Listan alustaja jonka kiinteäksi kooksi tulee 3 + // alkiota, jotka saavat arvot 3, 1, ja 5. + + // Siivuilla on muuttuva koko. Sekä listoilla että siivuilla on puolensa, + // mutta siivut ovat yleisempiä käyttötapojensa vuoksi. + s3 := []int{4, 5, 9} // Vertaa a3: ei sananheittoa (...). + s4 := make([]int, 4) // Varaa 4 int:n siivun, alkiot alustettu nolliksi. + var d2 [][]float64 // Vain ilmoitus, muistia ei varata. + bs := []byte("a slice") // Tyypinmuuntosyntaksi. + + // Koska siivut ovat dynaamisia, niitä voidaan yhdistellä sellaisinaan. + // Lisätäksesi alkioita siivuun, käytä sisäänrakennettua append()-funktiota. + // Ensimmäinen argumentti on siivu, johon alkoita lisätään. + s := []int{1, 2, 3} // Tuloksena on kolmen alkion pituinen lista. + s = append(s, 4, 5, 6) // Lisätty kolme alkiota. Siivun pituudeksi tulee 6. + fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6] + + // Lisätäksesi siivun toiseen voit antaa append-funktiolle referenssin + // siivuun tai todellisarvoiseen siivuun lisäämällä sanaheiton argumentin + // perään. Tämä tapa purkaa siivun alkiot ja lisää ne siivuun s. + s = append(s, []int{7, 8, 9}...) // 2. argumentti on todellisarvoinen siivu. + fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6 7 8 9] + + p, q := learnMemory() // Ilmoittaa p ja q olevan tyyppiä osoittaja int:iin. + fmt.Println(*p, *q) // * seuraa osoittajaa. Tämä tulostaa kaksi int:ä. + + // Kartat ovat dynaamisesti kasvavia assosiatiivisia listoja, kuten hash tai + // dictionary toisissa kielissä. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 - // Unused variables are an error in Go. - // The underscore lets you "use" a variable but discard its value. + // Käyttämättömät muuttujat ovat virheitä Go:ssa. + // Alaviiva antaa sinun "käyttää" muuttujan mutta hylätä sen arvon. _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs - // Output of course counts as using a variable. + // Tulostaminen tietysti lasketaan muuttujan käyttämiseksi. fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() // Back in the flow. + learnFlowControl() // Takaisin flowiin. } -// It is possible, unlike in many other languages for functions in go -// to have named return values. -// Assigning a name to the type being returned in the function declaration line -// allows us to easily return from multiple points in a function as well as to -// only use the return keyword, without anything further. +// Go:ssa on useista muista kielistä poiketen mahdollista käyttää nimettyjä +// palautusarvoja. +// Nimen antaminen palautettavan arvon tyypille funktion ilmoitusrivillä +// mahdollistaa helpon palaamisen useasta eri funktion suorituskohdasta sekä +// pelkän return-lausekkeen käytön ilman muita mainintoja. func learnNamedReturns(x, y int) (z int) { z = x * y - return // z is implicit here, because we named it earlier. + return // z on epäsuorasti tässä, koska nimesimme sen aiemmin. } -// Go is fully garbage collected. It has pointers but no pointer arithmetic. -// You can make a mistake with a nil pointer, but not by incrementing a pointer. +// Go kerää kaikki roskansa. Siinä on osoittajia mutta ei niiden laskentoa. +// Voit tehdä virheen mitättömällä osoittajalla, mutta et +// kasvattamalla osoittajaa. func learnMemory() (p, q *int) { - // Named return values p and q have type pointer to int. - p = new(int) // Built-in function new allocates memory. - // The allocated int is initialized to 0, p is no longer nil. - s := make([]int, 20) // Allocate 20 ints as a single block of memory. - s[3] = 7 // Assign one of them. - r := -2 // Declare another local variable. - return &s[3], &r // & takes the address of an object. + // Nimetyillä palautusarvoilla p ja q on tyyppi osoittaja int:iin. + p = new(int) // Sisäänrakennettu funktio new varaa muistia. + // Varattu int on alustettu nollaksi, p ei ole enää mitätön. + s := make([]int, 20) // Varaa 20 int:ä yhteen kohtaan muistissa. + s[3] = 7 // Anna yhdelle niistä arvo. + r := -2 // Ilmoita toinen paikallinen muuttuja. + return &s[3], &r // & ottaa asian osoitteen muistissa. } func expensiveComputation() float64 { @@ -166,234 +169,241 @@ func expensiveComputation() float64 { } func learnFlowControl() { - // If statements require brace brackets, and do not require parentheses. + // If -lausekkeet vaativat aaltosulkeet mutta ei tavallisia sulkeita. if true { - fmt.Println("told ya") + fmt.Println("mitä mä sanoin") } - // Formatting is standardized by the command line command "go fmt." + // Muotoilu on standardoitu käyttämällä komentorivin komentoa "go fmt". if false { - // Pout. + // Nyrpistys. } else { - // Gloat. + // Nautinto. } - // Use switch in preference to chained if statements. + // Käytä switch -lauseketta ketjutettujen if -lausekkeiden sijasta. x := 42.0 switch x { case 0: case 1: case 42: - // Cases don't "fall through". + // Tapaukset eivät "tipu läpi". /* - There is a `fallthrough` keyword however, see: + Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso: https://github.com/golang/go/wiki/Switch#fall-through */ case 43: - // Unreached. + // Saavuttamaton. default: - // Default case is optional. + // Oletustapaus (default) on valinnainen. } - // Like if, for doesn't use parens either. - // Variables declared in for and if are local to their scope. - for x := 0; x < 3; x++ { // ++ is a statement. - fmt.Println("iteration", x) + // Kuten if, for -lauseke ei myöskään käytä tavallisia sulkeita. + // for- ja if- lausekkeissa ilmoitetut muuttujat ovat paikallisia niiden + // piireissä. + for x := 0; x < 3; x++ { // ++ on lauseke. Sama kuin "x = x + 1". + fmt.Println("iteraatio", x) } - // x == 42 here. + // x == 42 tässä. - // For is the only loop statement in Go, but it has alternate forms. - for { // Infinite loop. - break // Just kidding. - continue // Unreached. + // For on kielen ainoa silmukkalauseke mutta sillä on vaihtoehtosia muotoja. + for { // Päättymätön silmukka. + break // Kunhan vitsailin. + continue // Saavuttamaton. } - // You can use range to iterate over an array, a slice, a string, a map, or a channel. - // range returns one (channel) or two values (array, slice, string and map). - for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} { - // for each pair in the map, print key and value - fmt.Printf("key=%s, value=%d\n", key, value) + // Voit käyttää range -lauseketta iteroidaksesi listojen, siivujen, merkki- + // jonojen, karttojen tai kanavien läpi. range palauttaa yhden (kanava) tai + // kaksi arvoa (lista, siivu, merkkijono ja kartta). + for key, value := range map[string]int{"yksi": 1, "kaksi": 2, "kolme": 3} { + // jokaista kartan paria kohden, tulosta avain ja arvo + fmt.Printf("avain=%s, arvo=%d\n", key, value) } - // As with for, := in an if statement means to declare and assign - // y first, then test y > x. + // Kuten for -lausekkeessa := if -lausekkeessa tarkoittaa ilmoittamista ja + // arvon asettamista. + // Aseta ensin y, sitten testaa onko y > x. if y := expensiveComputation(); y > x { x = y } - // Function literals are closures. + // Todellisarvoiset funktiot ovat sulkeumia. xBig := func() bool { - return x > 10000 // References x declared above switch statement. + return x > 10000 // Viittaa ylempänä ilmoitettuun x:ään. } - fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x). - x = 1.3e3 // This makes x == 1300 - fmt.Println("xBig:", xBig()) // false now. - - // What's more is function literals may be defined and called inline, - // acting as an argument to function, as long as: - // a) function literal is called immediately (), - // b) result type matches expected type of argument. - fmt.Println("Add + double two numbers: ", + fmt.Println("xBig:", xBig()) // tosi (viimeisin arvo on e^10). + x = 1.3e3 // Tämä tekee x == 1300 + fmt.Println("xBig:", xBig()) // epätosi nyt. + + // Lisäksi todellisarvoiset funktiot voidaan samalla sekä ilmoittaa että + // kutsua, jolloin niitä voidaan käyttää funtioiden argumentteina kunhan: + // a) todellisarvoinen funktio kutsutaan välittömästi (), + // b) palautettu tyyppi vastaa odotettua argumentin tyyppiä. + fmt.Println("Lisää ja tuplaa kaksi numeroa: ", func(a, b int) int { return (a + b) * 2 - }(10, 2)) // Called with args 10 and 2 - // => Add + double two numbers: 24 + }(10, 2)) // Kutsuttu argumenteilla 10 ja 2 + // => Lisää ja tuplaa kaksi numeroa: 24 - // When you need it, you'll love it. + // Kun tarvitset sitä, rakastat sitä. goto love love: - learnFunctionFactory() // func returning func is fun(3)(3) - learnDefer() // A quick detour to an important keyword. - learnInterfaces() // Good stuff coming up! + learnFunctionFactory() // Funktioita palauttavat funktiot + learnDefer() // Nopea kiertoreitti tärkeään avainsanaan. + learnInterfaces() // Hyvää kamaa tulossa! } func learnFunctionFactory() { - // Next two are equivalent, with second being more practical - fmt.Println(sentenceFactory("summer")("A beautiful", "day!")) + // Seuraavat kaksi ovat vastaavia, mutta toinen on käytännöllisempi + fmt.Println(sentenceFactory("kesä")("Kaunis", "päivä!")) - d := sentenceFactory("summer") - fmt.Println(d("A beautiful", "day!")) - fmt.Println(d("A lazy", "afternoon!")) + d := sentenceFactory("kesä") + fmt.Println(d("Kaunis", "päivä!")) + fmt.Println(d("Laiska", "iltapäivä!")) } -// Decorators are common in other languages. Same can be done in Go -// with function literals that accept arguments. +// Somisteet ovat yleisiä toisissa kielissä. Sama saavutetaan Go:ssa käyttämällä +// todellisarvoisia funktioita jotka ottavat vastaan argumentteja. func sentenceFactory(mystring string) func(before, after string) string { return func(before, after string) string { - return fmt.Sprintf("%s %s %s", before, mystring, after) // new string + return fmt.Sprintf("%s %s %s", before, mystring, after) // uusi jono } } func learnDefer() (ok bool) { - // Deferred statements are executed just before the function returns. - defer fmt.Println("deferred statements execute in reverse (LIFO) order.") - defer fmt.Println("\nThis line is being printed first because") - // Defer is commonly used to close a file, so the function closing the - // file stays close to the function opening the file. + // Lykätyt lausekkeet suoritetaan juuri ennen funktiosta palaamista. + defer fmt.Println("lykätyt lausekkeet suorittuvat") + defer fmt.Println("käänteisessä järjestyksessä (LIFO).") + defer fmt.Println("\nTämä rivi tulostuu ensin, koska") + // Defer -lauseketta käytetään yleisesti tiedoston sulkemiseksi, jotta + // tiedoston sulkeva funktio pysyy lähellä sen avannutta funktiota. return true } -// Define Stringer as an interface type with one method, String. +// Määrittele Stringer rajapintatyypiksi jolla on +// yksi jäsenfunktio eli metodi, String. type Stringer interface { String() string } -// Define pair as a struct with two fields, ints named x and y. +// Määrittele pair rakenteeksi jossa on kaksi kenttää, x ja y tyyppiä int. type pair struct { x, y int } -// Define a method on type pair. Pair now implements Stringer. -func (p pair) String() string { // p is called the "receiver" - // Sprintf is another public function in package fmt. - // Dot syntax references fields of p. +// Määrittele jäsenfunktio pair:lle. Pair tyydyttää nyt Stringer -rajapinnan. +func (p pair) String() string { // p:tä kutsutaan nimellä "receiver" + // Sprintf on toinen julkinen funktio paketissa fmt. + // Pistesyntaksilla viitataan P:n kenttiin. return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { - // Brace syntax is a "struct literal". It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. + // Aaltosuljesyntaksi on "todellisarvoinen rakenne". Se todentuu alustetuksi + // rakenteeksi. := -syntaksi ilmoittaa ja alustaa p:n täksi rakenteeksi. p := pair{3, 4} - fmt.Println(p.String()) // Call String method of p, of type pair. - var i Stringer // Declare i of interface type Stringer. - i = p // Valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. + fmt.Println(p.String()) // Kutsu p:n (tyyppiä pair) jäsenfunktiota String. + var i Stringer // Ilmoita i Stringer-rajapintatyypiksi. + i = p // Pätevä koska pair tyydyttää rajapinnan Stringer. + // Kutsu i:n (Stringer) jäsenfunktiota String. Tuloste on sama kuin yllä. fmt.Println(i.String()) - // Functions in the fmt package call the String method to ask an object - // for a printable representation of itself. - fmt.Println(p) // Output same as above. Println calls String method. - fmt.Println(i) // Output same as above. + // Funktiot fmt-paketissa kutsuvat argumenttien String-jäsenfunktiota + // selvittääkseen onko niistä saatavilla tulostettavaa vastinetta. + fmt.Println(p) // Tuloste on sama kuin yllä. Println kutsuu String-metodia. + fmt.Println(i) // Tuloste on sama kuin yllä. - learnVariadicParams("great", "learning", "here!") + learnVariadicParams("loistavaa", "oppimista", "täällä!") } -// Functions can have variadic parameters. +// Funktioilla voi olla muuttuva eli variteettinen +// määrä argumentteja eli parametrejä. func learnVariadicParams(myStrings ...interface{}) { - // Iterate each value of the variadic. - // The underbar here is ignoring the index argument of the array. + // Iteroi jokaisen argumentin läpi. + // Tässä alaviivalla sivuutetaan argumenttilistan kunkin kohdan indeksi. for _, param := range myStrings { fmt.Println("param:", param) } - // Pass variadic value as a variadic parameter. + // Luovuta variteettinen arvo variteettisena parametrinä. fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } func learnErrorHandling() { - // ", ok" idiom used to tell if something worked or not. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map. - fmt.Println("no one there") + // "; ok" -muotoa käytetään selvittääksemme toimiko jokin vai ei. + m := map[int]string{3: "kolme", 4: "neljä"} + if x, ok := m[1]; !ok { // ok on epätosi koska 1 ei ole kartassa. + fmt.Println("ei ketään täällä") } else { - fmt.Print(x) // x would be the value, if it were in the map. + fmt.Print(x) // x olisi arvo jos se olisi kartassa. } - // An error value communicates not just "ok" but more about the problem. - if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value - // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' + // Virhearvo voi kertoa muutakin ongelmasta. + if _, err := strconv.Atoi("ei-luku"); err != nil { // _ sivuuttaa arvon + // tulostaa strconv.ParseInt: parsing "ei-luku": invalid syntax fmt.Println(err) } - // We'll revisit interfaces a little later. Meanwhile, + // Palaamme rajapintoihin hieman myöhemmin. Sillä välin, learnConcurrency() } -// c is a channel, a concurrency-safe communication object. +// c on kanava, samanaikaisturvallinen viestintäolio. func inc(i int, c chan int) { - c <- i + 1 // <- is the "send" operator when a channel appears on the left. + c <- i + 1 // <- on "lähetysoperaattori" kun kanava on siitä vasemmalla. } -// We'll use inc to increment some numbers concurrently. +// Käytämme inc -funktiota samanaikaiseen lukujen lisäämiseen. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and - // initializes slices, maps, and channels. + // Sama make -funktio jota käytimme aikaisemmin siivun luomiseksi. Make + // varaa muistin ja alustaa siivut, kartat ja kanavat. c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented - // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. - go inc(0, c) // go is a statement that starts a new goroutine. + // Aloita kolme samanaikaista gorutiinia (goroutine). Luvut kasvavat + // samanaikaisesti ja ehkäpä rinnakkain jos laite on kykenevä ja oikein + // määritelty. Kaikki kolme lähettävät samalle kanavalle. + go inc(0, c) // go -lauseke aloittaa uuden gorutiinin. go inc(10, c) go inc(-805, c) - // Read three results from the channel and print them out. - // There is no telling in what order the results will arrive! - fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator. - - cs := make(chan string) // Another channel, this one handles strings. - ccs := make(chan chan string) // A channel of string channels. - go func() { c <- 84 }() // Start a new goroutine just to send a value. - go func() { cs <- "wordy" }() // Again, for cs this time. - // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases - // that are ready to communicate. + // Lue kolme palautusarvoa kanavalta ja tulosta ne. + // Niiden saapumisjärjestystä ei voida taata! + // <- on "vastaanotto-operaattori" jos kanava on oikealla + fmt.Println(<-c, <-c, <-c) + + cs := make(chan string) // Toinen kanava joka käsittelee merkkijonoja. + ccs := make(chan chan string) // Kanava joka käsittelee merkkijonokanavia. + go func() { c <- 84 }() // Aloita uusi gorutiini arvon lähettämiseksi. + go func() { cs <- "sanaa" }() // Uudestaan, mutta cs -kanava tällä kertaa. + // Select -lausekkeella on syntaksi kuten switch -lausekkeella mutta + // jokainen tapaus sisältää kanavaoperaation. Se valitsee satunnaisen + // tapauksen niistä kanavista, jotka ovat kommunikaatiovalmiita select { - case i := <-c: // The value received can be assigned to a variable, - fmt.Printf("it's a %T", i) - case <-cs: // or the value received can be discarded. - fmt.Println("it's a string") - case <-ccs: // Empty channel, not ready for communication. - fmt.Println("didn't happen.") + case i := <-c: // Vastaanotettu arvo voidaan antaa muuttujalle + fmt.Printf("se on %T", i) + case <-cs: // tai vastaanotettu arvo voidaan sivuuttaa. + fmt.Println("se on merkkijono") + case <-ccs: // Tyhjä kanava; ei valmis kommunikaatioon. + fmt.Println("ei tapahtunut.") } - // At this point a value was taken from either c or cs. One of the two - // goroutines started above has completed, the other will remain blocked. + // Tässä vaiheessa arvo oli otettu joko c:ltä tai cs:ltä. Yksi kahdesta + // ylempänä aloitetusta gorutiinista on valmistunut, toinen pysyy tukossa. - learnWebProgramming() // Go does it. You want to do it too. + learnWebProgramming() // Go tekee sitä. Sinäkin haluat tehdä sitä. } -// A single function from package http starts a web server. +// Yksittäinen funktio http -paketista aloittaa web-palvelimen. func learnWebProgramming() { - // First parameter of ListenAndServe is TCP address to listen to. - // Second parameter is an interface, specifically http.Handler. + // ListenAndServe:n ensimmäinen parametri on TCP-osoite, jota kuunnellaan. + // Toinen parametri on rajapinta, http.Handler. go func() { err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // don't ignore errors + fmt.Println(err) // älä sivuuta virheitä. }() requestServer() } -// Make pair an http.Handler by implementing its only method, ServeHTTP. +// Tee pair:sta http.Handler implementoimalla sen ainoa metodi, ServeHTTP. func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Serve data with a method of http.ResponseWriter. - w.Write([]byte("You learned Go in Y minutes!")) + // Tarjoa dataa metodilla http.ResponseWriter. + w.Write([]byte("Opit Go:n Y minuutissa!")) } func requestServer() { @@ -401,28 +411,30 @@ func requestServer() { fmt.Println(err) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) - fmt.Printf("\nWebserver said: `%s`", string(body)) + fmt.Printf("\nWeb-palvelin sanoo: `%s`", string(body)) } ``` -## Further Reading +## Lisää luettavaa -The root of all things Go is the [official Go web site](http://golang.org/). -There you can follow the tutorial, play interactively, and read lots. -Aside from a tour, [the docs](https://golang.org/doc/) contain information on -how to write clean and effective Go code, package and command docs, and release history. +Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/). +Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon. +Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa +siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta. -The language definition itself is highly recommended. It's easy to read -and amazingly short (as language definitions go these days.) +Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja +yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.) -You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. +Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm). +Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org) +[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista. -On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it -demonstrates the best of readable and understandable Go, Go style, and Go -idioms. Or you can click on a function name in [the -documentation](http://golang.org/pkg/) and the source code comes up! +Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/). +Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista, +-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja +lähdekoodi tulee esille! -Another great resource to learn Go is [Go by example](https://gobyexample.com/). +Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/). -Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information. +Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia +Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile). diff --git a/fi-fi/go.html.markdown b/fi-fi/go.html.markdown deleted file mode 100644 index 714d4e06..00000000 --- a/fi-fi/go.html.markdown +++ /dev/null @@ -1,440 +0,0 @@ ---- -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: - - ["Timo Virkkunen", "https://github.com/ComSecNinja"] ---- - -Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi, -mutta se on uusin nopein tapa ratkaista oikean maailman ongelmia. - -Sillä on staattisesti tyypitetyistä imperatiivisista kielistä tuttuja -konsepteja. Se kääntyy ja suorittuu nopeasti, lisää helposti käsitettävän -samanaikaisten komentojen suorittamisen nykyaikaisten moniytimisten -prosessoreiden hyödyntämiseksi ja antaa käyttäjälle ominaisuuksia suurten -projektien käsittelemiseksi. - -Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön. - -```go -// Yhden rivin kommentti -/* Useamman - rivin kommentti */ - -// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto. -// Main on erityinen nimi joka ilmoittaa -// suoritettavan tiedoston kirjaston sijasta. -package main - -// Import -lauseke ilmoittaa tässä tiedostossa käytetyt kirjastot. -import ( - "fmt" // Paketti Go:n oletuskirjastosta. - "io/ioutil" // Implementoi hyödyllisiä I/O -funktioita. - m "math" // Matematiikkakirjasto jolla on paikallinen nimi m. - "net/http" // Kyllä, web-palvelin! - "strconv" // Kirjainjonojen muuntajia. -) - -// Funktion määrittelijä. Main on erityinen: se on ohjelman suorittamisen -// aloittamisen alkupiste. Rakasta tai vihaa sitä, Go käyttää aaltosulkeita. -func main() { - // Println tulostaa rivin stdoutiin. - // Se tulee paketin fmt mukana, joten paketin nimi on mainittava. - fmt.Println("Hei maailma!") - - // Kutsu toista funktiota tämän paketin sisällä. - beyondHello() -} - -// Funktioilla voi olla parametrejä sulkeissa. -// Vaikkei parametrejä olisikaan, sulkeet ovat silti pakolliset. -func beyondHello() { - var x int // Muuttujan ilmoittaminen: ne täytyy ilmoittaa ennen käyttöä. - x = 3 // Arvon antaminen muuttujalle. - // "Lyhyet" ilmoitukset käyttävät := joka päättelee tyypin, ilmoittaa - // sekä antaa arvon muuttujalle. - y := 4 - sum, prod := learnMultiple(x, y) // Funktio palauttaa kaksi arvoa. - fmt.Println("summa:", sum, "tulo:", prod) // Yksinkertainen tuloste. - learnTypes() // < y minuuttia, opi lisää! -} - -/* <- usean rivin kommentti -Funktioilla voi olla parametrejä ja (useita!) palautusarvoja. -Tässä `x`, `y` ovat argumenttejä ja `sum`, `prod` ovat ne, mitä palautetaan. -Huomaa että `x` ja `sum` saavat tyyin `int`. -*/ -func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // Palauta kaksi arvoa. -} - -// Sisäänrakennettuja tyyppejä ja todellisarvoja. -func learnTypes() { - // Lyhyt ilmoitus antaa yleensä haluamasi. - str := "Opi Go!" // merkkijonotyyppi. - - s2 := `"raaka" todellisarvoinen merrkijono -voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi. - - // Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8. - g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen. - - f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku. - c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla. - - // var -syntaksi alkuarvoilla. - var u uint = 7 // Etumerkitön, toteutus riippuvainen koosta kuten int. - var pi float32 = 22. / 7 - - // Muuntosyntaksi lyhyellä ilmoituksella. - n := byte('\n') // byte on leminimi uint8:lle. - - // Listoilla on kiinteä koko kääntöhetkellä. - var a4 [4]int // 4 int:in lista, alkiot ovat alustettu nolliksi. - a3 := [...]int{3, 1, 5} // Listan alustaja jonka kiinteäksi kooksi tulee 3 - // alkiota, jotka saavat arvot 3, 1, ja 5. - - // Siivuilla on muuttuva koko. Sekä listoilla että siivuilla on puolensa, - // mutta siivut ovat yleisempiä käyttötapojensa vuoksi. - s3 := []int{4, 5, 9} // Vertaa a3: ei sananheittoa (...). - s4 := make([]int, 4) // Varaa 4 int:n siivun, alkiot alustettu nolliksi. - var d2 [][]float64 // Vain ilmoitus, muistia ei varata. - bs := []byte("a slice") // Tyypinmuuntosyntaksi. - - // Koska siivut ovat dynaamisia, niitä voidaan yhdistellä sellaisinaan. - // Lisätäksesi alkioita siivuun, käytä sisäänrakennettua append()-funktiota. - // Ensimmäinen argumentti on siivu, johon alkoita lisätään. - s := []int{1, 2, 3} // Tuloksena on kolmen alkion pituinen lista. - s = append(s, 4, 5, 6) // Lisätty kolme alkiota. Siivun pituudeksi tulee 6. - fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6] - - // Lisätäksesi siivun toiseen voit antaa append-funktiolle referenssin - // siivuun tai todellisarvoiseen siivuun lisäämällä sanaheiton argumentin - // perään. Tämä tapa purkaa siivun alkiot ja lisää ne siivuun s. - s = append(s, []int{7, 8, 9}...) // 2. argumentti on todellisarvoinen siivu. - fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6 7 8 9] - - p, q := learnMemory() // Ilmoittaa p ja q olevan tyyppiä osoittaja int:iin. - fmt.Println(*p, *q) // * seuraa osoittajaa. Tämä tulostaa kaksi int:ä. - - // Kartat ovat dynaamisesti kasvavia assosiatiivisia listoja, kuten hash tai - // dictionary toisissa kielissä. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 - - // Käyttämättömät muuttujat ovat virheitä Go:ssa. - // Alaviiva antaa sinun "käyttää" muuttujan mutta hylätä sen arvon. - _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs - // Tulostaminen tietysti lasketaan muuttujan käyttämiseksi. - fmt.Println(s, c, a4, s3, d2, m) - - learnFlowControl() // Takaisin flowiin. -} - -// Go:ssa on useista muista kielistä poiketen mahdollista käyttää nimettyjä -// palautusarvoja. -// Nimen antaminen palautettavan arvon tyypille funktion ilmoitusrivillä -// mahdollistaa helpon palaamisen useasta eri funktion suorituskohdasta sekä -// pelkän return-lausekkeen käytön ilman muita mainintoja. -func learnNamedReturns(x, y int) (z int) { - z = x * y - return // z on epäsuorasti tässä, koska nimesimme sen aiemmin. -} - -// Go kerää kaikki roskansa. Siinä on osoittajia mutta ei niiden laskentoa. -// Voit tehdä virheen mitättömällä osoittajalla, mutta et -// kasvattamalla osoittajaa. -func learnMemory() (p, q *int) { - // Nimetyillä palautusarvoilla p ja q on tyyppi osoittaja int:iin. - p = new(int) // Sisäänrakennettu funktio new varaa muistia. - // Varattu int on alustettu nollaksi, p ei ole enää mitätön. - s := make([]int, 20) // Varaa 20 int:ä yhteen kohtaan muistissa. - s[3] = 7 // Anna yhdelle niistä arvo. - r := -2 // Ilmoita toinen paikallinen muuttuja. - return &s[3], &r // & ottaa asian osoitteen muistissa. -} - -func expensiveComputation() float64 { - return m.Exp(10) -} - -func learnFlowControl() { - // If -lausekkeet vaativat aaltosulkeet mutta ei tavallisia sulkeita. - if true { - fmt.Println("mitä mä sanoin") - } - // Muotoilu on standardoitu käyttämällä komentorivin komentoa "go fmt". - if false { - // Nyrpistys. - } else { - // Nautinto. - } - // Käytä switch -lauseketta ketjutettujen if -lausekkeiden sijasta. - x := 42.0 - switch x { - case 0: - case 1: - case 42: - // Tapaukset eivät "tipu läpi". - /* - Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso: - https://github.com/golang/go/wiki/Switch#fall-through - */ - case 43: - // Saavuttamaton. - default: - // Oletustapaus (default) on valinnainen. - } - // Kuten if, for -lauseke ei myöskään käytä tavallisia sulkeita. - // for- ja if- lausekkeissa ilmoitetut muuttujat ovat paikallisia niiden - // piireissä. - for x := 0; x < 3; x++ { // ++ on lauseke. Sama kuin "x = x + 1". - fmt.Println("iteraatio", x) - } - // x == 42 tässä. - - // For on kielen ainoa silmukkalauseke mutta sillä on vaihtoehtosia muotoja. - for { // Päättymätön silmukka. - break // Kunhan vitsailin. - continue // Saavuttamaton. - } - - // Voit käyttää range -lauseketta iteroidaksesi listojen, siivujen, merkki- - // jonojen, karttojen tai kanavien läpi. range palauttaa yhden (kanava) tai - // kaksi arvoa (lista, siivu, merkkijono ja kartta). - for key, value := range map[string]int{"yksi": 1, "kaksi": 2, "kolme": 3} { - // jokaista kartan paria kohden, tulosta avain ja arvo - fmt.Printf("avain=%s, arvo=%d\n", key, value) - } - - // Kuten for -lausekkeessa := if -lausekkeessa tarkoittaa ilmoittamista ja - // arvon asettamista. - // Aseta ensin y, sitten testaa onko y > x. - if y := expensiveComputation(); y > x { - x = y - } - // Todellisarvoiset funktiot ovat sulkeumia. - xBig := func() bool { - return x > 10000 // Viittaa ylempänä ilmoitettuun x:ään. - } - fmt.Println("xBig:", xBig()) // tosi (viimeisin arvo on e^10). - x = 1.3e3 // Tämä tekee x == 1300 - fmt.Println("xBig:", xBig()) // epätosi nyt. - - // Lisäksi todellisarvoiset funktiot voidaan samalla sekä ilmoittaa että - // kutsua, jolloin niitä voidaan käyttää funtioiden argumentteina kunhan: - // a) todellisarvoinen funktio kutsutaan välittömästi (), - // b) palautettu tyyppi vastaa odotettua argumentin tyyppiä. - fmt.Println("Lisää ja tuplaa kaksi numeroa: ", - func(a, b int) int { - return (a + b) * 2 - }(10, 2)) // Kutsuttu argumenteilla 10 ja 2 - // => Lisää ja tuplaa kaksi numeroa: 24 - - // Kun tarvitset sitä, rakastat sitä. - goto love -love: - - learnFunctionFactory() // Funktioita palauttavat funktiot - learnDefer() // Nopea kiertoreitti tärkeään avainsanaan. - learnInterfaces() // Hyvää kamaa tulossa! -} - -func learnFunctionFactory() { - // Seuraavat kaksi ovat vastaavia, mutta toinen on käytännöllisempi - fmt.Println(sentenceFactory("kesä")("Kaunis", "päivä!")) - - d := sentenceFactory("kesä") - fmt.Println(d("Kaunis", "päivä!")) - fmt.Println(d("Laiska", "iltapäivä!")) -} - -// Somisteet ovat yleisiä toisissa kielissä. Sama saavutetaan Go:ssa käyttämällä -// todellisarvoisia funktioita jotka ottavat vastaan argumentteja. -func sentenceFactory(mystring string) func(before, after string) string { - return func(before, after string) string { - return fmt.Sprintf("%s %s %s", before, mystring, after) // uusi jono - } -} - -func learnDefer() (ok bool) { - // Lykätyt lausekkeet suoritetaan juuri ennen funktiosta palaamista. - defer fmt.Println("lykätyt lausekkeet suorittuvat") - defer fmt.Println("käänteisessä järjestyksessä (LIFO).") - defer fmt.Println("\nTämä rivi tulostuu ensin, koska") - // Defer -lauseketta käytetään yleisesti tiedoston sulkemiseksi, jotta - // tiedoston sulkeva funktio pysyy lähellä sen avannutta funktiota. - return true -} - -// Määrittele Stringer rajapintatyypiksi jolla on -// yksi jäsenfunktio eli metodi, String. -type Stringer interface { - String() string -} - -// Määrittele pair rakenteeksi jossa on kaksi kenttää, x ja y tyyppiä int. -type pair struct { - x, y int -} - -// Määrittele jäsenfunktio pair:lle. Pair tyydyttää nyt Stringer -rajapinnan. -func (p pair) String() string { // p:tä kutsutaan nimellä "receiver" - // Sprintf on toinen julkinen funktio paketissa fmt. - // Pistesyntaksilla viitataan P:n kenttiin. - return fmt.Sprintf("(%d, %d)", p.x, p.y) -} - -func learnInterfaces() { - // Aaltosuljesyntaksi on "todellisarvoinen rakenne". Se todentuu alustetuksi - // rakenteeksi. := -syntaksi ilmoittaa ja alustaa p:n täksi rakenteeksi. - p := pair{3, 4} - fmt.Println(p.String()) // Kutsu p:n (tyyppiä pair) jäsenfunktiota String. - var i Stringer // Ilmoita i Stringer-rajapintatyypiksi. - i = p // Pätevä koska pair tyydyttää rajapinnan Stringer. - // Kutsu i:n (Stringer) jäsenfunktiota String. Tuloste on sama kuin yllä. - fmt.Println(i.String()) - - // Funktiot fmt-paketissa kutsuvat argumenttien String-jäsenfunktiota - // selvittääkseen onko niistä saatavilla tulostettavaa vastinetta. - fmt.Println(p) // Tuloste on sama kuin yllä. Println kutsuu String-metodia. - fmt.Println(i) // Tuloste on sama kuin yllä. - - learnVariadicParams("loistavaa", "oppimista", "täällä!") -} - -// Funktioilla voi olla muuttuva eli variteettinen -// määrä argumentteja eli parametrejä. -func learnVariadicParams(myStrings ...interface{}) { - // Iteroi jokaisen argumentin läpi. - // Tässä alaviivalla sivuutetaan argumenttilistan kunkin kohdan indeksi. - for _, param := range myStrings { - fmt.Println("param:", param) - } - - // Luovuta variteettinen arvo variteettisena parametrinä. - fmt.Println("params:", fmt.Sprintln(myStrings...)) - - learnErrorHandling() -} - -func learnErrorHandling() { - // "; ok" -muotoa käytetään selvittääksemme toimiko jokin vai ei. - m := map[int]string{3: "kolme", 4: "neljä"} - if x, ok := m[1]; !ok { // ok on epätosi koska 1 ei ole kartassa. - fmt.Println("ei ketään täällä") - } else { - fmt.Print(x) // x olisi arvo jos se olisi kartassa. - } - // Virhearvo voi kertoa muutakin ongelmasta. - if _, err := strconv.Atoi("ei-luku"); err != nil { // _ sivuuttaa arvon - // tulostaa strconv.ParseInt: parsing "ei-luku": invalid syntax - fmt.Println(err) - } - // Palaamme rajapintoihin hieman myöhemmin. Sillä välin, - learnConcurrency() -} - -// c on kanava, samanaikaisturvallinen viestintäolio. -func inc(i int, c chan int) { - c <- i + 1 // <- on "lähetysoperaattori" kun kanava on siitä vasemmalla. -} - -// Käytämme inc -funktiota samanaikaiseen lukujen lisäämiseen. -func learnConcurrency() { - // Sama make -funktio jota käytimme aikaisemmin siivun luomiseksi. Make - // varaa muistin ja alustaa siivut, kartat ja kanavat. - c := make(chan int) - // Aloita kolme samanaikaista gorutiinia (goroutine). Luvut kasvavat - // samanaikaisesti ja ehkäpä rinnakkain jos laite on kykenevä ja oikein - // määritelty. Kaikki kolme lähettävät samalle kanavalle. - go inc(0, c) // go -lauseke aloittaa uuden gorutiinin. - go inc(10, c) - go inc(-805, c) - // Lue kolme palautusarvoa kanavalta ja tulosta ne. - // Niiden saapumisjärjestystä ei voida taata! - // <- on "vastaanotto-operaattori" jos kanava on oikealla - fmt.Println(<-c, <-c, <-c) - - cs := make(chan string) // Toinen kanava joka käsittelee merkkijonoja. - ccs := make(chan chan string) // Kanava joka käsittelee merkkijonokanavia. - go func() { c <- 84 }() // Aloita uusi gorutiini arvon lähettämiseksi. - go func() { cs <- "sanaa" }() // Uudestaan, mutta cs -kanava tällä kertaa. - // Select -lausekkeella on syntaksi kuten switch -lausekkeella mutta - // jokainen tapaus sisältää kanavaoperaation. Se valitsee satunnaisen - // tapauksen niistä kanavista, jotka ovat kommunikaatiovalmiita - select { - case i := <-c: // Vastaanotettu arvo voidaan antaa muuttujalle - fmt.Printf("se on %T", i) - case <-cs: // tai vastaanotettu arvo voidaan sivuuttaa. - fmt.Println("se on merkkijono") - case <-ccs: // Tyhjä kanava; ei valmis kommunikaatioon. - fmt.Println("ei tapahtunut.") - } - // Tässä vaiheessa arvo oli otettu joko c:ltä tai cs:ltä. Yksi kahdesta - // ylempänä aloitetusta gorutiinista on valmistunut, toinen pysyy tukossa. - - learnWebProgramming() // Go tekee sitä. Sinäkin haluat tehdä sitä. -} - -// Yksittäinen funktio http -paketista aloittaa web-palvelimen. -func learnWebProgramming() { - - // ListenAndServe:n ensimmäinen parametri on TCP-osoite, jota kuunnellaan. - // Toinen parametri on rajapinta, http.Handler. - go func() { - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // älä sivuuta virheitä. - }() - - requestServer() -} - -// Tee pair:sta http.Handler implementoimalla sen ainoa metodi, ServeHTTP. -func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Tarjoa dataa metodilla http.ResponseWriter. - w.Write([]byte("Opit Go:n Y minuutissa!")) -} - -func requestServer() { - resp, err := http.Get("http://localhost:8080") - fmt.Println(err) - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - fmt.Printf("\nWeb-palvelin sanoo: `%s`", string(body)) -} -``` - -## Lisää luettavaa - -Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/). -Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon. -Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa -siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta. - -Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja -yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.) - -Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm). -Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org) -[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista. - -Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/). -Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista, --tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja -lähdekoodi tulee esille! - -Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/). - -Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia -Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile). -- cgit v1.2.3 From 39b58bacb761d591c7e89e8de8ddfe713672f4ab Mon Sep 17 00:00:00 2001 From: ComSecNinja Date: Sat, 31 Oct 2015 22:27:44 +0200 Subject: More style guide abiding changes --- fi-fi/go-fi.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index 8a0ca245..9ed4e0d2 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -13,6 +13,7 @@ contributors: - ["Clayton Walker", "https://github.com/cwalk"] translators: - ["Timo Virkkunen", "https://github.com/ComSecNinja"] +lang: fi-fi --- Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi, -- cgit v1.2.3 From bc8af24706f5f1056327c7566d398ae694671d83 Mon Sep 17 00:00:00 2001 From: Frederik Andersen Date: Sat, 31 Oct 2015 22:16:39 +0100 Subject: Update dart.html.markdown typo --- dart.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dart.html.markdown b/dart.html.markdown index f7601271..fc7b220e 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -498,7 +498,7 @@ main() { ## Further Reading -Dart has a comprehenshive web-site. It covers API reference, tutorials, articles and more, including a +Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a useful Try Dart online. http://www.dartlang.org/ http://try.dartlang.org/ -- cgit v1.2.3 From b42f739fa4422fb947f681b5716ae3644014ebf2 Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Sun, 1 Nov 2015 02:54:52 +0530 Subject: Fix a typo is 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 cba7cd45..675cf5d3 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -723,7 +723,7 @@ code_native(square_area, (Float64,)) # ret # # Note that julia will use floating point instructions if any of the -# arguements are floats. +# arguments are floats. # Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 -- cgit v1.2.3 From b8999e88ed3d9317725c79987a379871a6eb8988 Mon Sep 17 00:00:00 2001 From: Pranit Bauva Date: Sun, 1 Nov 2015 03:06:03 +0530 Subject: Add Pranit Bauva to the contributors list of julia.html.markdown --- julia.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/julia.html.markdown b/julia.html.markdown index 675cf5d3..220b52a4 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -2,6 +2,7 @@ language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] + - ["Pranit Bauva", "http://github.com/pranitbauva1997"] filename: learnjulia.jl --- -- cgit v1.2.3 From d59c326fe0d90e01f31ff10d89d7fe37a2f654e6 Mon Sep 17 00:00:00 2001 From: ComSecNinja Date: Sat, 31 Oct 2015 23:37:23 +0200 Subject: Translate markdown/en 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 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 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 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 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 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