summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--cs-cz/elm.html.markdown4
-rw-r--r--elm.html.markdown4
-rw-r--r--fr-fr/php-fr.html.markdown2
-rw-r--r--go.html.markdown2
-rw-r--r--javascript.html.markdown5
-rw-r--r--latex.html.markdown2
-rw-r--r--perl6.html.markdown4
-rw-r--r--pt-br/elm-pt.html.markdown4
-rw-r--r--ru-ru/python3-ru.html.markdown3
-rw-r--r--solidity.html.markdown205
-rw-r--r--typescript.html.markdown2
-rw-r--r--yaml.html.markdown81
-rw-r--r--zh-cn/javascript-cn.html.markdown7
-rw-r--r--zh-cn/kotlin-cn.html.markdown33
14 files changed, 186 insertions, 172 deletions
diff --git a/cs-cz/elm.html.markdown b/cs-cz/elm.html.markdown
index f19f9e8b..42ec89e5 100644
--- a/cs-cz/elm.html.markdown
+++ b/cs-cz/elm.html.markdown
@@ -75,8 +75,8 @@ List.head [] -- Nothing
-- K získání hodnot z dvojice použijte funkce first a second.
-- (Toto je pouze zkratka. Brzy si ukážeme, jak na to "správně".)
-fst ("elm", 42) -- "elm"
-snd ("elm", 42) -- 42
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
-- Prázná n-tice, neboli "unit", se občas používá jako zástupný symbol.
-- Je to jediná hodnota svého typu, který se také nazývá "Unit".
diff --git a/elm.html.markdown b/elm.html.markdown
index 23ae9eeb..ad80adc9 100644
--- a/elm.html.markdown
+++ b/elm.html.markdown
@@ -72,8 +72,8 @@ List.head [] -- Nothing
-- Access the elements of a pair with the first and second functions.
-- (This is a shortcut; we'll come to the "real way" in a bit.)
-fst ("elm", 42) -- "elm"
-snd ("elm", 42) -- 42
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
-- The empty tuple, or "unit", is sometimes used as a placeholder.
-- It is the only value of its type, also called "Unit".
diff --git a/fr-fr/php-fr.html.markdown b/fr-fr/php-fr.html.markdown
index d001f1d4..45a02d75 100644
--- a/fr-fr/php-fr.html.markdown
+++ b/fr-fr/php-fr.html.markdown
@@ -10,8 +10,6 @@ translators:
lang: fr-fr
---
-This document describes PHP 5+.
-
Ce document décrit PHP 5+.
```php
diff --git a/go.html.markdown b/go.html.markdown
index e5263cf6..47d9c234 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -180,7 +180,7 @@ func learnFlowControl() {
if true {
fmt.Println("told ya")
}
- // Formatting is standardized by the command line command "go fmt."
+ // Formatting is standardized by the command line command "go fmt".
if false {
// Pout.
} else {
diff --git a/javascript.html.markdown b/javascript.html.markdown
index 199c3c09..e7066291 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -607,6 +607,10 @@ some of the more complicated examples.
[Javascript: The Right Way][10] is a guide intended to introduce new developers
to JavaScript and help experienced developers learn more about its best practices.
+[Javascript:Info][11] is a modern javascript tutorial covering the basics (core language and working with a browser)
+as well as advanced topics with concise explanations.
+
+
In addition to direct contributors to this article, some content is adapted from
Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the
Mozilla Developer Network.
@@ -622,3 +626,4 @@ Mozilla Developer Network.
[8]: http://eloquentjavascript.net/
[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version
[10]: http://jstherightway.org/
+[11]: https://javascript.info/
diff --git a/latex.html.markdown b/latex.html.markdown
index a3866892..c9b1d8fb 100644
--- a/latex.html.markdown
+++ b/latex.html.markdown
@@ -255,7 +255,7 @@ There exists two main types of links: visible URL \\
% You can not add extra-spaces or special symbols into shadowing text since it
% will cause mistakes during the compilation
-This package also produces list of tumbnails in the output pdf document and
+This package also produces list of thumbnails in the output pdf document and
active links in the table of contents.
\section{End}
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 2821f0d4..04f9c6e3 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1366,7 +1366,7 @@ sub add($a, $b) { $a + $b }
say [[&add]] 1, 2, 3; #=> 6
## * Zip meta-operator
-## This one is an infix meta-operator than also can be used as a "normal"
+## This one is an infix meta-operator that also can be used as a "normal"
## operator. It takes an optional binary function (by default, it just creates
## a pair), and will pop one value off of each array and call its binary
## function on these until it runs out of elements. It returns an array with
@@ -1659,7 +1659,7 @@ sub MAIN($name) { say "Hello, $name !" }
## Usage:
## t.pl <name>
-## And since it's a regular Perl 6 sub, you can haz multi-dispatch:
+## And since it's a regular Perl 6 sub, you can have multi-dispatch:
## (using a "Bool" for the named argument so that we can do `--replace`
## instead of `--replace=1`)
subset File of Str where *.IO.d; # convert to IO object to check the file exists
diff --git a/pt-br/elm-pt.html.markdown b/pt-br/elm-pt.html.markdown
index 78a4f1b7..d2469a93 100644
--- a/pt-br/elm-pt.html.markdown
+++ b/pt-br/elm-pt.html.markdown
@@ -76,8 +76,8 @@ List.head [] -- Nothing
-- Acesse os elementos de um par com as funções first e second.
-- (Este é um atalho; nós iremos para o "caminho real" em breve.)
-fst ("elm", 42) -- "elm"
-snd ("elm", 42) -- 42
+Tuple.first ("elm", 42) -- "elm"
+Tuple.second ("elm", 42) -- 42
-- Uma tupla vazia ou "unidade" às vezes é utilizada como um placeholder.
-- É o único valor de seu tipo, também chamado de "Unit".
diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown
index 2b6b59a7..bf80fed2 100644
--- a/ru-ru/python3-ru.html.markdown
+++ b/ru-ru/python3-ru.html.markdown
@@ -106,6 +106,9 @@ False or True #=> True
# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим.
"Привет " + "мир!" #=> "Привет мир!"
+# Строки можно умножать.
+"aa" * 4 #=> "aaaaaaaa"
+
# Со строкой можно работать, как со списком символов
"Это строка"[0] #=> 'Э'
diff --git a/solidity.html.markdown b/solidity.html.markdown
index c1f910fd..a0f8cd40 100644
--- a/solidity.html.markdown
+++ b/solidity.html.markdown
@@ -37,8 +37,8 @@ features are typically marked, and subject to change. Pull requests welcome.
// simple_bank.sol (note .sol extension)
/* **** START EXAMPLE **** */
-// Declare the source file compiler version.
-pragma solidity ^0.4.2;
+// Declare the source file compiler version
+pragma solidity ^0.4.19;
// Start with Natspec comment (the three slashes)
// used for documentation - and as descriptive data for UI elements/actions
@@ -65,7 +65,7 @@ contract SimpleBank { // CapWords
event LogDepositMade(address accountAddress, uint amount);
// Constructor, can receive one or many variables here; only one allowed
- function SimpleBank() {
+ function SimpleBank() public {
// msg provides details about the message that's sent to the contract
// msg.sender is contract caller (address of contract creator)
owner = msg.sender;
@@ -73,7 +73,11 @@ contract SimpleBank { // CapWords
/// @notice Deposit ether into bank
/// @return The balance of the user after the deposit is made
- function deposit() public returns (uint) {
+ function deposit() public payable returns (uint) {
+ // Use 'require' to test user inputs, 'assert' for internal invariants
+ // Here we are making sure that there isn't an overflow issue
+ require((balances[msg.sender] + msg.value) >= balances[msg.sender]);
+
balances[msg.sender] += msg.value;
// no "this." or "self." required with state variable
// all values set to data type's initial value by default
@@ -88,18 +92,17 @@ contract SimpleBank { // CapWords
/// @param withdrawAmount amount you want to withdraw
/// @return The balance remaining for the user
function withdraw(uint withdrawAmount) public returns (uint remainingBal) {
- if(balances[msg.sender] >= withdrawAmount) {
- // Note the way we deduct the balance right away, before sending - due to
- // the risk of a recursive call that allows the caller to request an amount greater
- // than their balance
- balances[msg.sender] -= withdrawAmount;
-
- if (!msg.sender.send(withdrawAmount)) {
- // increment back only on fail, as may be sending to contract that
- // has overridden 'send' on the receipt end
- balances[msg.sender] += withdrawAmount;
- }
- }
+ require(withdrawAmount <= balances[msg.sender]);
+
+ // Note the way we deduct the balance right away, before sending
+ // Every .transfer/.send from this contract can call an external function
+ // This may allow the caller to request an amount greater
+ // than their balance using a recursive call
+ // Aim to commit state before calling external functions, including .transfer/.send
+ balances[msg.sender] -= withdrawAmount;
+
+ // this automatically throws on a failure, which means the updated balance is reverted
+ msg.sender.transfer(withdrawAmount);
return balances[msg.sender];
}
@@ -108,18 +111,9 @@ contract SimpleBank { // CapWords
/// @return The balance of the user
// 'constant' prevents function from editing state variables;
// allows function to run locally/off blockchain
- function balance() constant returns (uint) {
+ function balance() constant public returns (uint) {
return balances[msg.sender];
}
-
- // Fallback function - Called if other functions don't match call or
- // sent ether without data
- // Typically, called when invalid data is sent
- // Added so ether sent to this contract is reverted if the contract fails
- // otherwise, the sender's money is transferred to contract
- function () {
- throw; // throw reverts state to before call
- }
}
// ** END EXAMPLE **
@@ -137,6 +131,11 @@ int256 constant a = 8; // same effect as line above, here the 256 is explicit
uint constant VERSION_ID = 0x123A1; // A hex constant
// with 'constant', compiler replaces each occurrence with actual value
+// All state variables (those outside a function)
+// are by default 'internal' and accessible inside contract
+// and in all contracts that inherit ONLY
+// Need to explicitly set to 'public' to allow external contracts to access
+int256 public a = 8;
// For int and uint, can explicitly set space in steps of 8 up to 256
// e.g., int8, int16, int24
@@ -145,6 +144,12 @@ int64 c;
uint248 e;
// Be careful that you don't overflow, and protect against attacks that do
+// For example, for an addition, you'd do:
+uint256 c = a + b;
+assert(c >= a); // assert tests for internal invariants; require is used for user inputs
+// For more examples of common arithmetic issues, see Zeppelin's SafeMath library
+// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
+
// No random functions built in, use other contracts for randomness
@@ -165,14 +170,14 @@ address public owner;
// a getter is automatically created, but NOT a setter
// All addresses can be sent ether
-owner.send(SOME_BALANCE); // returns false on failure
-if (owner.send) {} // REMEMBER: wrap in 'if', as contract addresses have
+owner.transfer(SOME_BALANCE); // fails and reverts on failure
+
+// Can also do a lower level .send call, which returns a false if it failed
+if (owner.send) {} // REMEMBER: wrap send in 'if', as contract addresses have
// functions executed on send and these can fail
// Also, make sure to deduct balances BEFORE attempting a send, as there is a risk of a recursive
// call that can drain the contract
-// can override send by defining your own
-
// Can check balance
owner.balance; // the balance of the owner (user or contract)
@@ -213,7 +218,7 @@ uint x = 5;
// Destructuring/Tuples
-(x, y) = (2, 7); // assign/swap multiple value
+(x, y) = (2, 7); // assign/swap multiple values
// 2. DATA STRUCTURES
@@ -250,7 +255,7 @@ delete balances; // sets all elements to 0
// mapping, without knowing source keys - can build data structure
// on top to do this
-// Structs and enums
+// Structs
struct Bank {
address owner;
uint balance;
@@ -273,7 +278,7 @@ state = State.Created;
// enums can be explicitly converted to ints
uint createdState = uint(State.Created); // 0
-// Data locations: Memory vs. storage vs. stack - all complex types (arrays,
+// Data locations: Memory vs. storage vs. calldata - all complex types (arrays,
// structs) have a data location
// 'memory' does not persist, 'storage' does
// Default is 'storage' for local and state variables; 'memory' for func params
@@ -292,13 +297,13 @@ uint createdState = uint(State.Created); // 0
// 4. Global Variables of note
// ** this **
this; // address of contract
-// often used at end of contract life to send remaining balance to party
+// often used at end of contract life to transfer remaining balance to party
this.balance;
this.someFunction(); // calls func externally via call, not via internal jump
// ** msg - Current message received by the contract ** **
msg.sender; // address of sender
-msg.value; // amount of ether provided to this contract in wei
+msg.value; // amount of ether provided to this contract in wei, the function should be marked "payable"
msg.data; // bytes, complete call data
msg.gas; // remaining gas
@@ -308,6 +313,8 @@ tx.gasprice; // gas price of the transaction
// ** block - Information about current block **
now; // current time (approximately), alias for block.timestamp (uses Unix time)
+// Note that this can be manipulated by miners, so use carefully
+
block.number; // current block number
block.difficulty; // current block difficulty
block.blockhash(1); // returns bytes32, only works for most recent 256 blocks
@@ -334,9 +341,10 @@ function increment(uint x, uint y) returns (uint x, uint y) {
// Call previous functon
uint (a,b) = increment(1,1);
-// 'constant' indicates that function does not/cannot change persistent vars
+// 'constant' (alias for 'view')
+// indicates that function does not/cannot change persistent vars
// Constant function execute locally, not on blockchain
-uint y;
+uint y = 1;
function increment(uint x) constant returns (uint x) {
x += 1;
@@ -344,13 +352,21 @@ function increment(uint x) constant returns (uint x) {
// y is a state variable, and can't be changed in a constant function
}
+// 'pure' is more strict than 'constant', and does not
+// even allow reading of state vars
+// The exact rules are more complicated, so see more about
+// constant/pure:
+// http://solidity.readthedocs.io/en/develop/contracts.html#view-functions
+
// 'Function Visibility specifiers'
// These can be placed where 'constant' is, including:
-// public - visible externally and internally (default)
-// external
+// public - visible externally and internally (default for function)
+// external - only visible externally (including a call made with this.)
// private - only visible in the current contract
// internal - only visible in current contract, and those deriving from it
+// Generally, a good idea to mark each function explicitly
+
// Functions hoisted - and can assign a function to a variable
function a() {
var z = b;
@@ -361,8 +377,15 @@ function b() {
}
+// All functions that receive ether must be marked 'payable'
+function depositEther() public payable {
+ balances[msg.sender] += msg.value;
+}
+
// Prefer loops to recursion (max call stack depth is 1024)
+// Also, don't setup loops that you haven't bounded,
+// as this can hit the gas limit
// B. Events
// Events are notify external parties; easy to search and
@@ -378,7 +401,8 @@ event LogSent(address indexed from, address indexed to, uint amount); // note ca
// Call
Sent(from, to, amount);
-// For an external party (a contract or external entity), to watch:
+// For an external party (a contract or external entity), to watch using
+// the Web3 Javascript library:
Coin.Sent().watch({}, '', function(error, result) {
if (!error) {
console.log("Coin transfer: " + result.args.amount +
@@ -398,10 +422,10 @@ Coin.Sent().watch({}, '', function(error, result) {
// '_' (underscore) often included as last line in body, and indicates
// function being called should be placed there
-modifier onlyAfter(uint _time) { if (now <= _time) throw; _ }
-modifier onlyOwner { if (msg.sender == owner) _ }
+modifier onlyAfter(uint _time) { require (now >= _time); _; }
+modifier onlyOwner { require(msg.sender == owner) _; }
// commonly used with state machines
-modifier onlyIfState (State currState) { if (currState != State.A) _ }
+modifier onlyIfStateA (State currState) { require(currState == State.A) _; }
// Append right after function declaration
function changeOwner(newOwner)
@@ -415,12 +439,10 @@ onlyIfState(State.A)
// underscore can be included before end of body,
// but explicitly returning will skip, so use carefully
modifier checkValue(uint amount) {
- _
+ _;
if (msg.value > amount) {
uint amountToRefund = amount - msg.value;
- if (!msg.sender.send(amountToRefund)) {
- throw;
- }
+ msg.sender.transfer(amountToRefund);
}
}
@@ -437,22 +459,21 @@ modifier checkValue(uint amount) {
// amount of gas for a block of code - and will fail if that is exceeded
// For example:
for(uint x = 0; x < refundAddressList.length; x++) {
- if (!refundAddressList[x].send(SOME_AMOUNT)) {
- throw;
- }
+ refundAddressList[x].transfer(SOME_AMOUNT);
}
// Two errors above:
-// 1. A failure on send stops the loop from completing, tying up money
+// 1. A failure on transfer stops the loop from completing, tying up money
// 2. This loop could be arbitrarily long (based on the amount of users who need refunds), and
// therefore may always fail as it exceeds the max gas for a block
// Instead, you should let people withdraw individually from their subaccount, and mark withdrawn
+// e.g., favor pull payments over push payments
// 7. OBJECTS/CONTRACTS
// A. Calling external contract
-contract infoFeed {
+contract InfoFeed {
function info() returns (uint ret) { return 42; }
}
@@ -502,23 +523,10 @@ function someAbstractFunction(uint x);
import "filename";
import "github.com/ethereum/dapp-bin/library/iterable_mapping.sol";
-// Importing under active development
-// Cannot currently be done at command line
-
// 8. OTHER KEYWORDS
-// A. Throwing
-// Throwing
-throw; // reverts unused money to sender, state is reverted
-// Can't currently catch
-
-// Common design pattern is:
-if (!addr.send(123)) {
- throw;
-}
-
-// B. Selfdestruct
+// A. Selfdestruct
// selfdestruct current contract, sending funds to address (often creator)
selfdestruct(SOME_ADDRESS);
@@ -543,7 +551,7 @@ function remove() {
// that is private needs to be obfuscated (e.g., hashed w/secret)
// Steps: 1. Commit to something, 2. Reveal commitment
-sha3("some_bid_amount", "some secret"); // commit
+keccak256("some_bid_amount", "some secret"); // commit
// call contract's reveal function in the future
// showing bid plus secret that hashes to SHA3
@@ -617,6 +625,7 @@ contract SomeOracle {
// ** START EXAMPLE **
// CrowdFunder.sol
+pragma solidity ^0.4.19;
/// @title CrowdFunder
/// @author nemild
@@ -650,22 +659,20 @@ contract CrowdFunder {
event LogWinnerPaid(address winnerAddress);
modifier inState(State _state) {
- if (state != _state) throw;
- _
+ require(state == _state);
+ _;
}
modifier isCreator() {
- if (msg.sender != creator) throw;
- _
+ require(msg.sender == creator);
+ _;
}
- // Wait 6 months after final contract state before allowing contract destruction
+ // Wait 24 weeks after final contract state before allowing contract destruction
modifier atEndOfLifecycle() {
- if(!((state == State.ExpiredRefund || state == State.Successful) &&
- completeAt + 6 months < now)) {
- throw;
- }
- _
+ require(((state == State.ExpiredRefund || state == State.Successful) &&
+ completeAt + 24 weeks < now));
+ _;
}
function CrowdFunder(
@@ -673,6 +680,7 @@ contract CrowdFunder {
string _campaignUrl,
address _fundRecipient,
uint _minimumToRaise)
+ public
{
creator = msg.sender;
fundRecipient = _fundRecipient;
@@ -683,7 +691,9 @@ contract CrowdFunder {
function contribute()
public
+ payable
inState(State.Fundraising)
+ returns(uint256 id)
{
contributions.push(
Contribution({
@@ -699,7 +709,9 @@ contract CrowdFunder {
return contributions.length - 1; // return id
}
- function checkIfFundingCompleteOrExpired() {
+ function checkIfFundingCompleteOrExpired()
+ public
+ {
if (totalRaised > minimumToRaise) {
state = State.Successful;
payOut();
@@ -715,31 +727,23 @@ contract CrowdFunder {
public
inState(State.Successful)
{
- if(!fundRecipient.send(this.balance)) {
- throw;
- }
-
-
+ fundRecipient.transfer(this.balance);
LogWinnerPaid(fundRecipient);
}
- function getRefund(id)
- public
+ function getRefund(uint256 id)
inState(State.ExpiredRefund)
+ public
+ returns(bool)
{
- if (contributions.length <= id || id < 0 || contributions[id].amount == 0 ) {
- throw;
- }
+ require(contributions.length > id && id >= 0 && contributions[id].amount != 0 );
- uint amountToRefund = contributions[id].amount;
+ uint256 amountToRefund = contributions[id].amount;
contributions[id].amount = 0;
- if(!contributions[id].contributor.send(amountToSend)) {
- contributions[id].amount = amountToSend;
- return false;
- }
+ contributions[id].contributor.transfer(amountToRefund);
- return true;
+ return true;
}
function removeContract()
@@ -750,8 +754,6 @@ contract CrowdFunder {
selfdestruct(msg.sender);
// creator gets all money that hasn't be claimed
}
-
- function () { throw; }
}
// ** END EXAMPLE **
@@ -798,6 +800,7 @@ someContractAddress.callcode('function_name');
// 13. STYLE NOTES
// Based on Python's PEP8 style guide
+// Full Style guide: http://solidity.readthedocs.io/en/develop/style-guide.html
// Quick summary:
// 4 spaces for indentation
@@ -825,11 +828,16 @@ someContractAddress.callcode('function_name');
## Additional resources
- [Solidity Docs](https://solidity.readthedocs.org/en/latest/)
+- [Smart Contract Best Practices](https://github.com/ConsenSys/smart-contract-best-practices)
- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide.
-- [Browser-based Solidity Editor](http://chriseth.github.io/browser-solidity/)
+- [EthFiddle - The JsFiddle for Solidity](https://ethfiddle.com/)
+- [Browser-based Solidity Editor](https://remix.ethereum.org/)
- [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity)
- [Modular design strategies for Ethereum Contracts](https://docs.erisindustries.com/tutorials/solidity/)
+## Important libraries
+- [Zeppelin](https://github.com/OpenZeppelin/zeppelin-solidity/): Libraries that provide common contract patterns (crowdfuding, safemath, etc)
+
## Sample contracts
- [Dapp Bin](https://github.com/ethereum/dapp-bin)
- [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts)
@@ -841,9 +849,6 @@ someContractAddress.callcode('function_name');
- [Smart Contract Security](https://blog.ethereum.org/2016/06/10/smart-contract-security/)
- [Hacking Distributed Blog](http://hackingdistributed.com/)
-## Information purposefully excluded
-- Libraries
-
## Style
- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy
diff --git a/typescript.html.markdown b/typescript.html.markdown
index 10f01ebc..acc258b4 100644
--- a/typescript.html.markdown
+++ b/typescript.html.markdown
@@ -29,7 +29,7 @@ let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
-// Use const keyword for constant variables
+// Use const keyword for constants
const numLivesForCat = 9;
numLivesForCat = 1; // Error
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 3b32a069..52658453 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -2,8 +2,8 @@
language: yaml
filename: learnyaml.yaml
contributors:
- - ["Adam Brenecki", "https://github.com/adambrenecki"]
- - ["Suhas SG", "https://github.com/jargnar"]
+- [Adam Brenecki, 'https://github.com/adambrenecki']
+- [Suhas SG, 'https://github.com/jargnar']
---
YAML is a data serialisation language designed to be directly writable and
@@ -11,7 +11,7 @@ readable by humans.
It's a strict superset of JSON, with the addition of syntactically
significant newlines and indentation, like Python. Unlike Python, however,
-YAML doesn't allow literal tab characters at all.
+YAML doesn't allow literal tab characters for indentation.
```yaml
# Comments in YAML look like this.
@@ -32,8 +32,10 @@ boolean: true
null_value: null
key with spaces: value
# Notice that strings don't need to be quoted. However, they can be.
-however: "A string, enclosed in quotes."
-"Keys can be quoted too.": "Useful if you want to put a ':' in your key."
+however: 'A string, enclosed in quotes.'
+'Keys can be quoted too.': "Useful if you want to put a ':' in your key."
+single quotes: 'have ''one'' escape pattern'
+double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more."
# Multiple-line strings can be written either as a 'literal block' (using |),
# or a 'folded block' (using '>').
@@ -59,12 +61,12 @@ folded_style: >
# COLLECTION TYPES #
####################
-# Nesting is achieved by indentation.
+# Nesting uses indentation. 2 space indent is preferred (but not required).
a_nested_map:
- key: value
- another_key: Another Value
- another_nested_map:
- hello: hello
+ key: value
+ another_key: Another Value
+ another_nested_map:
+ hello: hello
# Maps don't have to have string keys.
0.25: a float key
@@ -72,8 +74,8 @@ a_nested_map:
# Keys can also be complex, like multi-line objects
# We use ? followed by a space to indicate the start of a complex key.
? |
- This is a key
- that has multiple lines
+ This is a key
+ that has multiple lines
: and this is its value
# YAML also allows mapping between sequences with the complex key syntax
@@ -83,22 +85,26 @@ a_nested_map:
- Real Madrid
: [ 2001-01-01, 2002-02-02 ]
-# Sequences (equivalent to lists or arrays) look like this:
+# Sequences (equivalent to lists or arrays) look like this
+# (note that the '-' counts as indentation):
a_sequence:
- - Item 1
- - Item 2
- - 0.5 # sequences can contain disparate types.
- - Item 4
- - key: value
- another_key: another_value
- -
- - This is a sequence
- - inside another sequence
+- Item 1
+- Item 2
+- 0.5 # sequences can contain disparate types.
+- Item 4
+- key: value
+ another_key: another_value
+-
+ - This is a sequence
+ - inside another sequence
+- - - Nested sequence indicators
+ - can be collapsed
# Since YAML is a superset of JSON, you can also write JSON-style maps and
# sequences:
json_map: {"key": "value"}
json_seq: [3, 2, 1, "takeoff"]
+and quotes are optional: {key: [3, 2, 1, takeoff]}
#######################
# EXTRA YAML FEATURES #
@@ -111,15 +117,15 @@ other_anchor: *anchor_name
# Anchors can be used to duplicate/inherit properties
base: &base
- name: Everyone has same name
+ name: Everyone has same name
foo: &foo
- <<: *base
- age: 10
+ <<: *base
+ age: 10
bar: &bar
- <<: *base
- age: 20
+ <<: *base
+ age: 20
# foo and bar would also have name: Everyone has same name
@@ -147,22 +153,23 @@ date: 2002-12-14
# The !!binary tag indicates that a string is actually a base64-encoded
# representation of a binary blob.
gif_file: !!binary |
- R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
- OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
- +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
- AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
# YAML also has a set type, which looks like this:
set:
- ? item1
- ? item2
- ? item3
+ ? item1
+ ? item2
+ ? item3
+or: {item1, item2, item3}
# Like Python, sets are just maps with null values; the above is equivalent to:
set2:
- item1: null
- item2: null
- item3: null
+ item1: null
+ item2: null
+ item3: null
```
### More Resources
diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown
index bdef0099..360f7c65 100644
--- a/zh-cn/javascript-cn.html.markdown
+++ b/zh-cn/javascript-cn.html.markdown
@@ -12,12 +12,9 @@ translators:
lang: zh-cn
---
-Javascript于1995年由网景公司的Brendan Eich发明。
-最初发明的目的是作为一个简单的网站脚本语言,来作为
-复杂网站应用java的补充。但由于它与网页结合度很高并且由浏览器内置支持,
-所以javascript变得比java在前端更为流行了。
+Javascript 于 1995 年由网景公司的 Brendan Eich 发明。最初它作为一种简单的,用于开发网站的脚本语言而被发明出来,是用于开发复杂网站的 Java 的补充。但由于它与网页结合度很高并且在浏览器中得到内置的支持,所以在网页前端领域 Javascript 变得比 Java 更流行了。
-不过 JavaScript 可不仅仅只用于浏览器: Node.js,一个基于Google Chrome V8引擎的独立运行时环境,也越来越流行。
+不过,Javascript 不仅用于网页浏览器,一个名为 Node.js 的项目提供了面向 Google Chrome V8 引擎的独立运行时环境,它正在变得越来越流行。
很欢迎来自您的反馈,您可以通过下列方式联系到我:
[@adambrenecki](https://twitter.com/adambrenecki), 或者
diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown
index 5d655029..f6dcd847 100644
--- a/zh-cn/kotlin-cn.html.markdown
+++ b/zh-cn/kotlin-cn.html.markdown
@@ -22,7 +22,7 @@ package com.learnxinyminutes.kotlin
/*
Kotlin程序的入口点是一个"main"函数
-该函数传递一个包含任何命令行参数的数组。
+该函数传递一个包含所有命令行参数的数组。
*/
fun main(args: Array<String>) {
/*
@@ -67,10 +67,10 @@ fun helloWorld(val name : String) {
模板表达式从一个美元符号($)开始。
*/
val fooTemplateString = "$fooString has ${fooString.length} characters"
- println(fooTemplateString)
+ println(fooTemplateString) // => 输出 My String Is Here! has 18 characters
/*
- 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。
+ 当某个变量的值可以为 null 的时候,我们必须明确指定它是可为空的。
在变量声明处的类型后面加上?来标识它是可为空的。
我们可以用?.操作符来访问可为空的变量。
我们可以用?:操作符来指定一个在变量为空时使用的替代值。
@@ -96,24 +96,24 @@ fun helloWorld(val name : String) {
println(hello()) // => Hello, world!
/*
- 用"vararg"关键字来修饰一个函数的参数来允许可变参数传递给该函数
+ 函数的可变参数可使用 "vararg" 关键字来修饰
*/
fun varargExample(vararg names: Int) {
println("Argument has ${names.size} elements")
}
- varargExample() // => Argument has 0 elements
- varargExample(1) // => Argument has 1 elements
- varargExample(1, 2, 3) // => Argument has 3 elements
+ varargExample() // => 传入 0 个参数
+ varargExample(1) // => 传入 1 个参数
+ varargExample(1, 2, 3) // => 传入 3 个参数
/*
- 当函数只包含一个单独的表达式时,大括号可以被省略。
- 函数体可以被指定在一个=符号后面。
+ 当函数只包含一个单独的表达式时,大括号可以省略。
+ 函数体可以写在一个=符号后面。
*/
fun odd(x: Int): Boolean = x % 2 == 1
println(odd(6)) // => false
println(odd(7)) // => true
- // 如果返回值类型可以被推断,那么我们不需要指定它。
+ // 如果返回值类型可以推断,那么我们不需要指定它。
fun even(x: Int) = x % 2 == 0
println(even(6)) // => true
println(even(7)) // => false
@@ -122,15 +122,14 @@ fun helloWorld(val name : String) {
fun not(f: (Int) -> Boolean) : (Int) -> Boolean {
return {n -> !f.invoke(n)}
}
- // 命名函数可以用::运算符被指定为参数。
+ // 普通函数可以用::运算符传入引用作为函数参数。
val notOdd = not(::odd)
val notEven = not(::even)
- // 匿名函数可以被指定为参数。
+ // lambda 表达式可以直接作为参数传递。
val notZero = not {n -> n == 0}
/*
- 如果一个匿名函数只有一个参数
- 那么它的声明可以被省略(连同->)。
- 这个参数的名字是"it"。
+ 如果一个 lambda 表达式只有一个参数
+ 那么它的声明可以省略(连同->),内部以 "it" 引用。
*/
val notPositive = not {it > 0}
for (i in 0..4) {
@@ -152,7 +151,7 @@ fun helloWorld(val name : String) {
注意,Kotlin没有"new"关键字。
*/
val fooExampleClass = ExampleClass(7)
- // 可以使用一个点号来调用成员函数。
+ // 可以使用一个点号来调用成员方法。
println(fooExampleClass.memberFunction(4)) // => 11
/*
如果使用"infix"关键字来标记一个函数
@@ -162,7 +161,7 @@ fun helloWorld(val name : String) {
/*
数据类是创建只包含数据的类的一个简洁的方法。
- "hashCode"、"equals"和"toString"方法将被自动生成。
+ "hashCode"、"equals"和"toString"方法将自动生成。
*/
data class DataClassExample (val x: Int, val y: Int, val z: Int)
val fooData = DataClassExample(1, 2, 4)