public RemoteCall<Tuple2<Utf8String, Uint256>> getInfo() { final Function function = new Function(FUNC_GETINFO, Arrays.<Type>asList(), Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}, new TypeReference<Uint256>() {})); returnnew RemoteCall<Tuple2<Utf8String, Uint256>>( new Callable<Tuple2<Utf8String, Uint256>>() { @Override public Tuple2<Utf8String, Uint256> call()throws Exception { List<Type> results = executeCallMultipleValueReturn(function); returnnew Tuple2<Utf8String, Uint256>( (Utf8String) results.get(0), (Uint256) results.get(1)); } }); }
public RemoteCall<TransactionReceipt> setInfo(Utf8String _fName, Uint256 _age){ final Function function = new Function( FUNC_SETINFO, Arrays.<Type>asList(_fName, _age), Collections.<TypeReference<?>>emptyList()); return executeRemoteCallTransaction(function); }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath {
/** * @dev Multiplies two numbers, throws on overflow. */ functionmul(uint256 a, uint256 b) internalpurereturns (uint256) { if (a == 0) { return0; } uint256 c = a * b; assert(c / a == b); return c; }
/** * @dev Integer division of two numbers, truncating the quotient. */ functiondiv(uint256 a, uint256 b) internalpurereturns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ functionsub(uint256 a, uint256 b) internalpurereturns (uint256) { assert(b <= a); return a - b; }
/** * @dev Adds two numbers, throws on overflow. */ functionadd(uint256 a, uint256 b) internalpurereturns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
pragma solidity ^0.4.19; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner;
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ functionOwnable() public{ owner = msg.sender; }
/** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ functiontransferOwnership(address newOwner) publiconlyOwner{ require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
// A function with the signature `last_completed_migration()`, returning a uint, is required. uint public last_completed_migration;
modifier restricted() { if (msg.sender == owner) _ }
functionMigrations() { owner = msg.sender; }
// A function with the signature `setCompleted(uint)` is required. functionsetCompleted(uint completed) restricted{ last_completed_migration = completed; }
// Deploy A, then deploy B, passing in A's newly deployed address deployer.deploy(A).then(function() { return deployer.deploy(B, A.address); });
如果你想更清晰,你也可以选择实现一个Promise链。
网络相关
要实现不同条件的不同部署步骤,移植代码中需要第二个参数network。示例如下:
1 2 3 4 5 6
module.exports = function(deployer, network) { // Add demo data if we're not deploying to the live network. if (network != "live") { deployer.exec("add_demo_data.js"); } }
string public standard = 'yuyangray'; string public name; //代币名称 string public symbol; //代币符号比如'$' //代币单位,展示的小数点后面多少个0,和以太币一样后面是是18个0 uint8 public decimals = 2;
uint256 public totalSupply; //代币总量 /* 这里每个地址对应的是代币的数量,而不是捐赠的以太币的数量 */ mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value); //转帐通知事件
contract BloggerCoin is StandardToken { string public name = "BloggerCoin"; string public symbol = "BLC"; uint8 public decimals = 2; uint256 public INITIAL_SUPPLY = 666666;
// Since enum types are not part of the ABI, the signature of "getChoice" // will automatically be changed to "getChoice() returns (uint8)" // for all matters external to Solidity. The integer type used is just // large enough to hold all enum values, i.e. if you have more values, // `uint16` will be used and so on. functiongetChoice() returns (ActionChoices) { return choice; }
//不能通过`external`的方式调用一个`internal` //Member "internalFunc" not found or not visible after argument-dependent lookup in contract FuntionTest //this.internalFunc();
contract FunctionTest1{ functionexternalCall(FuntionTest ft){ //调用另一个合约的外部函数 ft.externalFunc(); //不能调用另一个合约的内部函数 //Error: Member "internalFunc" not found or not visible after argument-dependent lookup in contract FuntionTest //ft.internalFunc(); } }
functiong() { // Declares and assigns the variables. Specifying the type explicitly is not possible. var (x, b, y) = f(); // Assigns to a pre-existing variable. (x, y) = (2, 7); // Common trick to swap values -- does not work for non-value storage types. (x, y) = (y, x); // Components can be left out (also for variable declarations). // If the tuple ends in an empty component, // the rest of the values are discarded. (data.length,) = f(); // Sets the length to 7 // The same can be done on the left side. (,data[3]) = f(); // Sets data[3] to 2 // Components can only be left out at the left-hand-side of assignments, with // one exception: (x,) = (1,); // (1,) is the only way to specify a 1-component tuple, because (1) is // equivalent to 1. } }
contract Sharer { functionsendHalf(address addr) payablereturns (uint balance) { if (!addr.send(msg.value / 2)) throw; // also reverts the transfer to Sharer returnthis.balance; } }
functionf(uint a) privatereturns(uint b) { return a + 1; } functionsetData(uint a) { data = a; } functiongetData() publicreturns(uint) { return data; } functioncompute(uint a, uint b) internalreturns (uint) { return a+b; } }
contract D { functionreadData() { C c = new C(); uint local = c.f(7); // error: member "f" is not visible c.setData(3); local = c.getData(); local = c.compute(3, 5); // error: member "compute" is not visible } }
contract E is C { functiong() { C c = new C(); uint val = compute(3, 5); // acces to internal member (from derivated to parent contract) } }
// This contract only defines a modifier but does not use // it - it will be used in derived contracts. // The function body is inserted where the special symbol // "_;" in the definition of a modifier appears. // This means that if the owner calls this function, the // function is executed and otherwise, an exception is // thrown. modifier onlyOwner { if (msg.sender != owner) throw; // require(msg.sender == owner); _; } }
contract mortal is owned { // This contract inherits the "onlyOwner"-modifier from // "owned" and applies it to the "close"-function, which // causes that calls to "close" only have an effect if // they are made by the stored owner. functionclose() onlyOwner{ selfdestruct(owner); } }
// It is important to also provide the // "payable" keyword here, otherwise the function will // automatically reject all Ether sent to it. functionregister() payablecosts(price) { registeredAddresses[msg.sender] = true; }
/// This function is protected by a mutex, which means that /// reentrant calls from within msg.sender.call cannot call f again. /// The `return 7` statement assigns 7 to the return value but still /// executes the statement `locked = false` in the modifier. functionf() noReentrancyreturns (uint) { if (!msg.sender.call()) throw; return7; } }
contract Test { // This function is called for all messages sent to // this contract (there is no other function). // Sending Ether to this contract will cause an exception, // because the fallback function does not have the "payable" // modifier. function() { x = 1; } uint x; }
// This contract keeps all Ether sent to it with no way to get it back. contract Sink { function() payable{ } }
contract Caller { functioncallTest(Test test) { test.call(0xabcdef01); // hash does not exist // results in test.x becoming == 1.
// The following call will fail, reject the // Ether and return false: test.send(2 ether); } }
// Use "is" to derive from another contract. Derived // contracts can access all non-private members including // internal functions and state variables. These cannot be // accessed externally via `this`, though. contract mortal is owned { functionkill() { if (msg.sender == owner) selfdestruct(owner); } }
// These abstract contracts are only provided to make the // interface known to the compiler. Note the function // without body. If a contract does not implement all // functions it can only be used as an interface. contract Config { functionlookup(uint id) returns (address adr); } contractNameReg{ functionregister(bytes32 name); functionunregister(); } // Multipleinheritanceispossible. Notethat "owned" is // alsoabaseclassof "mortal", yetthereisonlyasingle // instanceof "owned" (as for virtual inheritance in C++). contractnamedisowned, mortal{ functionnamed(bytes32 name) { Config config = Config(0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970); NameReg(config.lookup(1)).register(name); }
// Functions can be overridden by another function with the same name and // the same number/types of inputs. If the overriding function has different // types of output parameters, that causes an error. // Both local and message-based function calls take these overrides // into account. functionkill() { if (msg.sender == owner) { Config config = Config(0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970); NameReg(config.lookup(1)).unregister(); // It is still possible to call a specific // overridden function. mortal.kill(); } } }
// If a constructor takes an argument, it needs to be // provided in the header (or modifier-invocation-style at // the constructor of the derived contract (see below)). contract PriceFeed is owned, mortal, named("GoldFeed") { functionupdateInfo(uint newInfo) { if (msg.sender == owner) info = newInfo; }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner;
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ functionOwnable() public{ owner = msg.sender; }
/** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ functiontransferOwnership(address newOwner) publiconlyOwner{ require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
functionmul(uint256 a, uint256 b) internalpurereturns (uint256) { if (a == 0) { return0; } uint256 c = a * b; assert(c / a == b); return c; }
functiondiv(uint256 a, uint256 b) internalpurereturns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
functionsub(uint256 a, uint256 b) internalpurereturns (uint256) { assert(b <= a); return a - b; }
functionadd(uint256 a, uint256 b) internalpurereturns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
SafeMath 库允许使用 using 关键字,它可以自动把库的所有方法添加给一个数据类型:
1 2 3 4 5
using SafeMath for uint; // 这下我们可以为任何 uint 调用这些方法了 uint test = 2; test = test.mul(3); // test 等于 6 了 test = test.add(5); // test 等于 11 了
所以简而言之, SafeMath 的 add, sub, mul, 和 div 方法只做简单的四则运算,然后在发生溢出或下溢的时候抛出错误。
HashNet采用分层分片共识机制, 上层网络中的节点称为全节点(full node),主要负责下层分片建立、下层分片重组、新局部全节点加入、局部全节点退出,不参与全局共识,也不参与记账,这避免了形成性能瓶颈的风险,极大的提高了交易吞吐量。下层网络中的节点称为局部全节点(local full node),形成各个分片,片内进行交易达成共识,采用后缀匹配法确保每笔交易只由一个特定的分片处理,避免了双重支付,同时片间通过异步机制同步各个片内的共识结果,从而达到每个局部全节点拥有全局账本。
defmain(): keyword = input("input keyword about images you want to download: ") num = input("input the number that you want: ") path = make_dir(keyword) run(keyword, path, num)
import requests import re import os from pyquery import PyQuery as pq
defget_page(url): headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36', 'accept-language': 'zh-CN,zh;q=0.9', 'cache-control': 'max-age=0', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' } response = requests.get(url=url,headers=headers) response.encoding = "utf-8" # print(response.status_code) if response.status_code == 200: return response.text returnNone
if __name__ == '__main__': keyword = input("input keyword about news that you want to download: ") numStart = input("input the start number that you want: ") numEnd = input("input the end number that you want: ")
for page in range(int(numStart), int(numEnd)): url = 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&medium=2&word=' + keyword + '&pn=' + str(page*10) result = pq(get_page(url)) print('\nnow the page is '+str(page) + ' and the url is ' + url) for item in range(result('.result').size()): url = pq(result('.result').eq(item).html())('a').attr('href') try: # 下载文章 d = pq(url=url) title = d('.article-title').text() print('now the article is ' + title) print('now the url is ' + url + '\n') ifnot os.path.exists(title): os.mkdir(title) fobj = open(title + '/' + title + '.txt', 'w+') fobj.write(d('.article-title').text()) for i in range(d('.bjh-p').size()): fobj.write('\n' + d('.bjh-p').eq(i).text()) fobj.close() # 下载图片 for imgIndex in range(d('.img-container').size()): img_data = requests.get(pq(d('.img-container').eq(imgIndex).html())('img').attr('src'), timeout=10).content with open(title + "/" + str(imgIndex) + ".jpg", "wb") as f: f.write(img_data) f.close() except Exception as e: print('there is a error when parsing this article, maybe it is not exist.')
funcmain() { const ( a = iota//0 b //1 c //2 d = "ha"//独立值,iota += 1 e //"ha" iota += 1 f = 100//iota +=1 g //100 iota +=1 h = iota//7,恢复计数 i //8 ) fmt.Println(a,b,c,d,e,f,g,h,i) }
funcmain() { //这是我们使用range去求一个slice的和。使用数组跟这个很类似 nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } fmt.Println("sum:", sum) //在数组上使用range将传入index和值两个变量。上面那个例子我们不需要使用该元素的序号,所以我们使用空白符"_"省略了。有时侯我们确实需要知道它的索引。 for i, num := range nums { if num == 3 { fmt.Println("index:", i) } } //range也可以用在map的键值对上。 kvs := map[string]string{"a": "apple", "b": "banana"} for k, v := range kvs { fmt.Printf("%s -> %s\n", k, v) } //range也可以用来枚举Unicode字符串。第一个参数是字符的索引,第二个是字符(Unicode的值)本身。 for i, c := range"go" { fmt.Println(i, c) } }
Map类型
1 2 3 4 5
/* 声明变量,默认 map 是 nil */ var map_variable map[key_data_type]value_data_type
/* 使用 make 函数 */ map_variable := make(map[key_data_type]value_data_type)
funcmain(){ var wg sync.WaitGroup wg.Add(2) gofunc() { defer wg.Done() for i := 0; i < 10000; i++ { fmt.Printf("Hello,Go.This is %d\n", i) } }() gofunc() { defer wg.Done() for i := 0; i < 10000; i++ { fmt.Printf("Hello,World.This is %d\n", i) } }() wg.Wait() }