prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>mainapp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from flask import Flask, jsonify, request, abort, make_response from futu_server_api import * from db import save_update_token from db import delete_tokens from db import list_cards import logging import logging.config import json app = Flask(__name__) logging.config.fileConfig('./conf/log.ini') no_db_logger = logging.getLogger() def check_parameters(pjson): if not pjson or not 'app_account' in pjson or not 'card' in pjson or not 'appid' in pjson: no_db_logger.info('No Parameter') abort(400) cli = {'account':pjson['app_account'], 'card':pjson['card'], 'appid':pjson['appid']} return client(cli['account'], cli['card'], cli['appid']) def log_handler(myjson, mytitle): if 'ClientWarning' in myjson: return '%s' % myjson['ClientWarning'] elif myjson['result_code'] == 0: return 'SUCCESS' else: return 'FAIL ,REASON OF FAILURE:%s ,PARAMETER:%s' % (myjson['error_msg'], request.json) @app.route('/') def hello_world(): no_db_logger.info('server start#####') return 'hello 22222222 world!' @app.route('/api/v1/tradetoken', methods=['POST']) def trade_token(): trade_pswd = request.json['trade_pswd'] account = request.json['app_account'] card = request.json['card'] appid = request.json['appid'] cc = check_parameters(request.json) message = cc.get_trade_token(trade_pswd) if message['result_code'] != 0 and message['error_msg'] == 'didn\'t get accesstoken': no_db_logger.info('didn\'t get accesstoken') return json.dumps({'result_code':2,'error_msg':'didn\'t get accesstoken'}, ensure_ascii=False) if message['result_code'] == 0: token = message['data']['trade_token'] save_update_token(account, appid, None, token, card, True) return jsonify(**message) @app.route('/api/v1/account', methods=['POST']) def get_account_detail(): cc = check_parameters(request.json) message = cc.get_account_detail() logtext = log_handler(message, '获取账户信息') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/cash', methods=['POST']) def get_account_cash(): cc = check_parameters(request.json) message = cc.get_account_cash() logtext = log_handler(message, '获取账户现金') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/portfolio', methods=['POST']) def get_account_portfolio(): cc = check_parameters(request.json) message = cc.get_account_portfolio() logtext = log_handler(message, '获取账户持仓') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_orders', methods=['POST']) def get_list_orders(): date_begin = request.json['date_begin'] date_end = request.json['date_end'] cc = check_parameters(request.json) message = cc.get_list_orders() logtext = log_handler(message, '获取订单列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_trades', methods=['POST']) def get_list_trades(): cc = check_parameters(request.json) message = cc.get_list_trades() logtext = log_handler(message, '获取交易列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/place_order', methods=['POST']) def place_order(): code = request.json['code'] quantity = request.json['quantity'] price = request.json['price'] side = request.json['side'] ltype = request.json['type'] cc = check_parameters(request.json) message = cc.place_order(code, quantity, price, side, ltype) logtext = log_handler(message, '下单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/change_order', methods=['POST']) def change_order(): order_id = request.json['order_id'] quantity =<|fim_middle|>n['quantity'] price = request.json['price'] cc = check_parameters(request.json) message = cc.change_order(order_id, quantity, price) logtext = log_handler(message, '改单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/cancle_order', methods=['POST']) def cancle_order(): order_id = request.json['order_id'] cc = check_parameters(request.json) message = cc.cancel_order(order_id) logtext = log_handler(message, '撤单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/ap1/v1/save_token', methods=['POST']) def save_token(): account = request.json['app_account'] appid = request.json['appid'] market = request.json['market'] token = request.json['token'] card = request.json['card'] card_desc = request.json['text'] DB_result = save_update_token(account, appid, market, token, card, False, card_desc) if DB_result == 'success': no_db_logger.info('token save success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token save fail') return json.dumps({'result_code':1,'error_msg':'token保存失败'}, ensure_ascii=False) @app.route('/api/v1/delete_token', methods=['POST']) def delete_token(): appid = request.json['appid'] account = request.json['app_account'] DB_result = delete_tokens(account, appid) if DB_result == 'success': no_db_logger.info('token delete success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token delete fail') return json.dumps({'result_code':1,'error_msg':'token删除失败'}, ensure_ascii=False) @app.route('/api/v1/list_card', methods=['POST']) def list_card(): appid = request.json['appid'] account = request.json['app_account'] cards = list_cards(account, appid) message = dict(cards=cards) if isinstance(cards, list): no_db_logger.info('list cards success') return json.dumps({'result_code':0,'error_msg':'','data':message}, ensure_ascii=False) else: no_db_logger.info('list cards fail') return json.dumps({'result_code':1,'error_msg':'查询账户卡号失败'}, ensure_ascii=False) if __name__ == '__main__': app.run() <|fim▁end|>
request.jso
<|file_name|>mainapp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from flask import Flask, jsonify, request, abort, make_response from futu_server_api import * from db import save_update_token from db import delete_tokens from db import list_cards import logging import logging.config import json app = Flask(__name__) logging.config.fileConfig('./conf/log.ini') no_db_logger = logging.getLogger() def check_parameters(pjson): if not pjson or not 'app_account' in pjson or not 'card' in pjson or not 'appid' in pjson: no_db_logger.info('No Parameter') abort(400) cli = {'account':pjson['app_account'], 'card':pjson['card'], 'appid':pjson['appid']} return client(cli['account'], cli['card'], cli['appid']) def log_handler(myjson, mytitle): if 'ClientWarning' in myjson: return '%s' % myjson['ClientWarning'] elif myjson['result_code'] == 0: return 'SUCCESS' else: return 'FAIL ,REASON OF FAILURE:%s ,PARAMETER:%s' % (myjson['error_msg'], request.json) @app.route('/') def hello_world(): no_db_logger.info('server start#####') return 'hello 22222222 world!' @app.route('/api/v1/tradetoken', methods=['POST']) def trade_token(): trade_pswd = request.json['trade_pswd'] account = request.json['app_account'] card = request.json['card'] appid = request.json['appid'] cc = check_parameters(request.json) message = cc.get_trade_token(trade_pswd) if message['result_code'] != 0 and message['error_msg'] == 'didn\'t get accesstoken': no_db_logger.info('didn\'t get accesstoken') return json.dumps({'result_code':2,'error_msg':'didn\'t get accesstoken'}, ensure_ascii=False) if message['result_code'] == 0: token = message['data']['trade_token'] save_update_token(account, appid, None, token, card, True) return jsonify(**message) @app.route('/api/v1/account', methods=['POST']) def get_account_detail(): cc = check_parameters(request.json) message = cc.get_account_detail() logtext = log_handler(message, '获取账户信息') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/cash', methods=['POST']) def get_account_cash(): cc = check_parameters(request.json) message = cc.get_account_cash() logtext = log_handler(message, '获取账户现金') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/portfolio', methods=['POST']) def get_account_portfolio(): cc = check_parameters(request.json) message = cc.get_account_portfolio() logtext = log_handler(message, '获取账户持仓') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_orders', methods=['POST']) def get_list_orders(): date_begin = request.json['date_begin'] date_end = request.json['date_end'] cc = check_parameters(request.json) message = cc.get_list_orders() logtext = log_handler(message, '获取订单列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_trades', methods=['POST']) def get_list_trades(): cc = check_parameters(request.json) message = cc.get_list_trades() logtext = log_handler(message, '获取交易列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/place_order', methods=['POST']) def place_order(): code = request.json['code'] quantity = request.json['quantity'] price = request.json['price'] side = request.json['side'] ltype = request.json['type'] cc = check_parameters(request.json) message = cc.place_order(code, quantity, price, side, ltype) logtext = log_handler(message, '下单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/change_order', methods=['POST']) def change_order(): order_id = request.json['order_id'] quantity = request.json['quantity'] price = request.json['price'] cc = check_parameters(request.json) message = cc.change_order(order_id, quantity, price) logtext = log_handler(message, '改单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/cancle_order', methods=['POST']) def cancle_order(): order_id = request.json['order_id'] cc = check_par<|fim_middle|>est.json) message = cc.cancel_order(order_id) logtext = log_handler(message, '撤单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/ap1/v1/save_token', methods=['POST']) def save_token(): account = request.json['app_account'] appid = request.json['appid'] market = request.json['market'] token = request.json['token'] card = request.json['card'] card_desc = request.json['text'] DB_result = save_update_token(account, appid, market, token, card, False, card_desc) if DB_result == 'success': no_db_logger.info('token save success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token save fail') return json.dumps({'result_code':1,'error_msg':'token保存失败'}, ensure_ascii=False) @app.route('/api/v1/delete_token', methods=['POST']) def delete_token(): appid = request.json['appid'] account = request.json['app_account'] DB_result = delete_tokens(account, appid) if DB_result == 'success': no_db_logger.info('token delete success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token delete fail') return json.dumps({'result_code':1,'error_msg':'token删除失败'}, ensure_ascii=False) @app.route('/api/v1/list_card', methods=['POST']) def list_card(): appid = request.json['appid'] account = request.json['app_account'] cards = list_cards(account, appid) message = dict(cards=cards) if isinstance(cards, list): no_db_logger.info('list cards success') return json.dumps({'result_code':0,'error_msg':'','data':message}, ensure_ascii=False) else: no_db_logger.info('list cards fail') return json.dumps({'result_code':1,'error_msg':'查询账户卡号失败'}, ensure_ascii=False) if __name__ == '__main__': app.run() <|fim▁end|>
ameters(requ
<|file_name|>mainapp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from flask import Flask, jsonify, request, abort, make_response from futu_server_api import * from db import save_update_token from db import delete_tokens from db import list_cards import logging import logging.config import json app = Flask(__name__) logging.config.fileConfig('./conf/log.ini') no_db_logger = logging.getLogger() def check_parameters(pjson): if not pjson or not 'app_account' in pjson or not 'card' in pjson or not 'appid' in pjson: no_db_logger.info('No Parameter') abort(400) cli = {'account':pjson['app_account'], 'card':pjson['card'], 'appid':pjson['appid']} return client(cli['account'], cli['card'], cli['appid']) def log_handler(myjson, mytitle): if 'ClientWarning' in myjson: return '%s' % myjson['ClientWarning'] elif myjson['result_code'] == 0: return 'SUCCESS' else: return 'FAIL ,REASON OF FAILURE:%s ,PARAMETER:%s' % (myjson['error_msg'], request.json) @app.route('/') def hello_world(): no_db_logger.info('server start#####') return 'hello 22222222 world!' @app.route('/api/v1/tradetoken', methods=['POST']) def trade_token(): trade_pswd = request.json['trade_pswd'] account = request.json['app_account'] card = request.json['card'] appid = request.json['appid'] cc = check_parameters(request.json) message = cc.get_trade_token(trade_pswd) if message['result_code'] != 0 and message['error_msg'] == 'didn\'t get accesstoken': no_db_logger.info('didn\'t get accesstoken') return json.dumps({'result_code':2,'error_msg':'didn\'t get accesstoken'}, ensure_ascii=False) if message['result_code'] == 0: token = message['data']['trade_token'] save_update_token(account, appid, None, token, card, True) return jsonify(**message) @app.route('/api/v1/account', methods=['POST']) def get_account_detail(): cc = check_parameters(request.json) message = cc.get_account_detail() logtext = log_handler(message, '获取账户信息') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/cash', methods=['POST']) def get_account_cash(): cc = check_parameters(request.json) message = cc.get_account_cash() logtext = log_handler(message, '获取账户现金') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/portfolio', methods=['POST']) def get_account_portfolio(): cc = check_parameters(request.json) message = cc.get_account_portfolio() logtext = log_handler(message, '获取账户持仓') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_orders', methods=['POST']) def get_list_orders(): date_begin = request.json['date_begin'] date_end = request.json['date_end'] cc = check_parameters(request.json) message = cc.get_list_orders() logtext = log_handler(message, '获取订单列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_trades', methods=['POST']) def get_list_trades(): cc = check_parameters(request.json) message = cc.get_list_trades() logtext = log_handler(message, '获取交易列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/place_order', methods=['POST']) def place_order(): code = request.json['code'] quantity = request.json['quantity'] price = request.json['price'] side = request.json['side'] ltype = request.json['type'] cc = check_parameters(request.json) message = cc.place_order(code, quantity, price, side, ltype) logtext = log_handler(message, '下单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/change_order', methods=['POST']) def change_order(): order_id = request.json['order_id'] quantity = request.json['quantity'] price = request.json['price'] cc = check_parameters(request.json) message = cc.change_order(order_id, quantity, price) logtext = log_handler(message, '改单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/cancle_order', methods=['POST']) def cancle_order(): order_id = request.json['order_id'] cc = check_parameters(request.json) message = cc.cancel_order(order_id) logtext = log_handler(message, '撤单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/ap1/v1/save_token', methods=['POST']) def save_token(): account = request.json['app_account'] appid = request.js<|fim_middle|>] market = request.json['market'] token = request.json['token'] card = request.json['card'] card_desc = request.json['text'] DB_result = save_update_token(account, appid, market, token, card, False, card_desc) if DB_result == 'success': no_db_logger.info('token save success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token save fail') return json.dumps({'result_code':1,'error_msg':'token保存失败'}, ensure_ascii=False) @app.route('/api/v1/delete_token', methods=['POST']) def delete_token(): appid = request.json['appid'] account = request.json['app_account'] DB_result = delete_tokens(account, appid) if DB_result == 'success': no_db_logger.info('token delete success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token delete fail') return json.dumps({'result_code':1,'error_msg':'token删除失败'}, ensure_ascii=False) @app.route('/api/v1/list_card', methods=['POST']) def list_card(): appid = request.json['appid'] account = request.json['app_account'] cards = list_cards(account, appid) message = dict(cards=cards) if isinstance(cards, list): no_db_logger.info('list cards success') return json.dumps({'result_code':0,'error_msg':'','data':message}, ensure_ascii=False) else: no_db_logger.info('list cards fail') return json.dumps({'result_code':1,'error_msg':'查询账户卡号失败'}, ensure_ascii=False) if __name__ == '__main__': app.run() <|fim▁end|>
on['appid'
<|file_name|>mainapp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from flask import Flask, jsonify, request, abort, make_response from futu_server_api import * from db import save_update_token from db import delete_tokens from db import list_cards import logging import logging.config import json app = Flask(__name__) logging.config.fileConfig('./conf/log.ini') no_db_logger = logging.getLogger() def check_parameters(pjson): if not pjson or not 'app_account' in pjson or not 'card' in pjson or not 'appid' in pjson: no_db_logger.info('No Parameter') abort(400) cli = {'account':pjson['app_account'], 'card':pjson['card'], 'appid':pjson['appid']} return client(cli['account'], cli['card'], cli['appid']) def log_handler(myjson, mytitle): if 'ClientWarning' in myjson: return '%s' % myjson['ClientWarning'] elif myjson['result_code'] == 0: return 'SUCCESS' else: return 'FAIL ,REASON OF FAILURE:%s ,PARAMETER:%s' % (myjson['error_msg'], request.json) @app.route('/') def hello_world(): no_db_logger.info('server start#####') return 'hello 22222222 world!' @app.route('/api/v1/tradetoken', methods=['POST']) def trade_token(): trade_pswd = request.json['trade_pswd'] account = request.json['app_account'] card = request.json['card'] appid = request.json['appid'] cc = check_parameters(request.json) message = cc.get_trade_token(trade_pswd) if message['result_code'] != 0 and message['error_msg'] == 'didn\'t get accesstoken': no_db_logger.info('didn\'t get accesstoken') return json.dumps({'result_code':2,'error_msg':'didn\'t get accesstoken'}, ensure_ascii=False) if message['result_code'] == 0: token = message['data']['trade_token'] save_update_token(account, appid, None, token, card, True) return jsonify(**message) @app.route('/api/v1/account', methods=['POST']) def get_account_detail(): cc = check_parameters(request.json) message = cc.get_account_detail() logtext = log_handler(message, '获取账户信息') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/cash', methods=['POST']) def get_account_cash(): cc = check_parameters(request.json) message = cc.get_account_cash() logtext = log_handler(message, '获取账户现金') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/portfolio', methods=['POST']) def get_account_portfolio(): cc = check_parameters(request.json) message = cc.get_account_portfolio() logtext = log_handler(message, '获取账户持仓') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_orders', methods=['POST']) def get_list_orders(): date_begin = request.json['date_begin'] date_end = request.json['date_end'] cc = check_parameters(request.json) message = cc.get_list_orders() logtext = log_handler(message, '获取订单列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_trades', methods=['POST']) def get_list_trades(): cc = check_parameters(request.json) message = cc.get_list_trades() logtext = log_handler(message, '获取交易列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/place_order', methods=['POST']) def place_order(): code = request.json['code'] quantity = request.json['quantity'] price = request.json['price'] side = request.json['side'] ltype = request.json['type'] cc = check_parameters(request.json) message = cc.place_order(code, quantity, price, side, ltype) logtext = log_handler(message, '下单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/change_order', methods=['POST']) def change_order(): order_id = request.json['order_id'] quantity = request.json['quantity'] price = request.json['price'] cc = check_parameters(request.json) message = cc.change_order(order_id, quantity, price) logtext = log_handler(message, '改单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/cancle_order', methods=['POST']) def cancle_order(): order_id = request.json['order_id'] cc = check_parameters(request.json) message = cc.cancel_order(order_id) logtext = log_handler(message, '撤单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/ap1/v1/save_token', methods=['POST']) def save_token(): account = request.json['app_account'] appid = request.json['appid'] market = request.json['market'] token = request.json['token'] card = request.json['card'] card_desc = request.json['text'] DB_result = save_update_token(account, appid, market, token, card, False, card_desc) if DB_result == 'success': no_db_logger.info('token save success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token save fail') return json.dumps({'result_code':1,'error_msg':'token保存失败'}, ensure_ascii=False) @app.route('/api/v1/delete_token', methods=['POST']) def delete_token(): appid = request.json['appid'] account = request.json['app_acco<|fim_middle|>sult = delete_tokens(account, appid) if DB_result == 'success': no_db_logger.info('token delete success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token delete fail') return json.dumps({'result_code':1,'error_msg':'token删除失败'}, ensure_ascii=False) @app.route('/api/v1/list_card', methods=['POST']) def list_card(): appid = request.json['appid'] account = request.json['app_account'] cards = list_cards(account, appid) message = dict(cards=cards) if isinstance(cards, list): no_db_logger.info('list cards success') return json.dumps({'result_code':0,'error_msg':'','data':message}, ensure_ascii=False) else: no_db_logger.info('list cards fail') return json.dumps({'result_code':1,'error_msg':'查询账户卡号失败'}, ensure_ascii=False) if __name__ == '__main__': app.run() <|fim▁end|>
unt'] DB_re
<|file_name|>mainapp.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from flask import Flask, jsonify, request, abort, make_response from futu_server_api import * from db import save_update_token from db import delete_tokens from db import list_cards import logging import logging.config import json app = Flask(__name__) logging.config.fileConfig('./conf/log.ini') no_db_logger = logging.getLogger() def check_parameters(pjson): if not pjson or not 'app_account' in pjson or not 'card' in pjson or not 'appid' in pjson: no_db_logger.info('No Parameter') abort(400) cli = {'account':pjson['app_account'], 'card':pjson['card'], 'appid':pjson['appid']} return client(cli['account'], cli['card'], cli['appid']) def log_handler(myjson, mytitle): if 'ClientWarning' in myjson: return '%s' % myjson['ClientWarning'] elif myjson['result_code'] == 0: return 'SUCCESS' else: return 'FAIL ,REASON OF FAILURE:%s ,PARAMETER:%s' % (myjson['error_msg'], request.json) @app.route('/') def hello_world(): no_db_logger.info('server start#####') return 'hello 22222222 world!' @app.route('/api/v1/tradetoken', methods=['POST']) def trade_token(): trade_pswd = request.json['trade_pswd'] account = request.json['app_account'] card = request.json['card'] appid = request.json['appid'] cc = check_parameters(request.json) message = cc.get_trade_token(trade_pswd) if message['result_code'] != 0 and message['error_msg'] == 'didn\'t get accesstoken': no_db_logger.info('didn\'t get accesstoken') return json.dumps({'result_code':2,'error_msg':'didn\'t get accesstoken'}, ensure_ascii=False) if message['result_code'] == 0: token = message['data']['trade_token'] save_update_token(account, appid, None, token, card, True) return jsonify(**message) @app.route('/api/v1/account', methods=['POST']) def get_account_detail(): cc = check_parameters(request.json) message = cc.get_account_detail() logtext = log_handler(message, '获取账户信息') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/cash', methods=['POST']) def get_account_cash(): cc = check_parameters(request.json) message = cc.get_account_cash() logtext = log_handler(message, '获取账户现金') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/account/portfolio', methods=['POST']) def get_account_portfolio(): cc = check_parameters(request.json) message = cc.get_account_portfolio() logtext = log_handler(message, '获取账户持仓') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_orders', methods=['POST']) def get_list_orders(): date_begin = request.json['date_begin'] date_end = request.json['date_end'] cc = check_parameters(request.json) message = cc.get_list_orders() logtext = log_handler(message, '获取订单列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_trades', methods=['POST']) def get_list_trades(): cc = check_parameters(request.json) message = cc.get_list_trades() logtext = log_handler(message, '获取交易列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/place_order', methods=['POST']) def place_order(): code = request.json['code'] quantity = request.json['quantity'] price = request.json['price'] side = request.json['side'] ltype = request.json['type'] cc = check_parameters(request.json) message = cc.place_order(code, quantity, price, side, ltype) logtext = log_handler(message, '下单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/change_order', methods=['POST']) def change_order(): order_id = request.json['order_id'] quantity = request.json['quantity'] price = request.json['price'] cc = check_parameters(request.json) message = cc.change_order(order_id, quantity, price) logtext = log_handler(message, '改单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/cancle_order', methods=['POST']) def cancle_order(): order_id = request.json['order_id'] cc = check_parameters(request.json) message = cc.cancel_order(order_id) logtext = log_handler(message, '撤单') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/ap1/v1/save_token', methods=['POST']) def save_token(): account = request.json['app_account'] appid = request.json['appid'] market = request.json['market'] token = request.json['token'] card = request.json['card'] card_desc = request.json['text'] DB_result = save_update_token(account, appid, market, token, card, False, card_desc) if DB_result == 'success': no_db_logger.info('token save success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token save fail') return json.dumps({'result_code':1,'error_msg':'token保存失败'}, ensure_ascii=False) @app.route('/api/v1/delete_token', methods=['POST']) def delete_token(): appid = request.json['appid'] account = request.json['app_account'] DB_result = delete_tokens(account, appid) if DB_result == 'success': no_db_logger.info('token delete success') return json.dumps({'result_code':0,'error_msg':''}, ensure_ascii=False) else: no_db_logger.info('token delete fail') return json.dumps({'result_code':1,'error_msg':'token删除失败'}, ensure_ascii=False) @app.route('/api/v1/list_card', methods=['POST']) def list_card(): appid = request.json['appid'] account = request.json['app_account'] card<|fim_middle|>cards(account, appid) message = dict(cards=cards) if isinstance(cards, list): no_db_logger.info('list cards success') return json.dumps({'result_code':0,'error_msg':'','data':message}, ensure_ascii=False) else: no_db_logger.info('list cards fail') return json.dumps({'result_code':1,'error_msg':'查询账户卡号失败'}, ensure_ascii=False) if __name__ == '__main__': app.run() <|fim▁end|>
s = list_
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|>student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name)<|fim▁hole|> elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : <|fim_middle|> def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice")
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): <|fim_middle|> def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
student_phoneNumber_name[x] = y return;
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): <|fim_middle|> Handler() print(student_phoneNumber_name)<|fim▁end|>
print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : <|fim_middle|> elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ")
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : <|fim_middle|> else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name))
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : <|fim_middle|> else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
print("name : " + name )
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : <|fim_middle|> else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
print(str(phone_number) + "Does not exist in record" + str(name))
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : <|fim_middle|> elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
print("Record is empty ")
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : <|fim_middle|> elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name)
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : <|fim_middle|> else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
break
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: <|fim_middle|> def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
print("Enter correct choice")
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : <|fim_middle|> return False Handler() print(student_phoneNumber_name)<|fim▁end|>
return student_phoneNumber_name[x]
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def <|fim_middle|>() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
Handler
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def <|fim_middle|>(x, y): student_phoneNumber_name[x] = y return; def SearchRecord(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
InsertRecord
<|file_name|>1_name_phone_number.py<|end_file_name|><|fim▁begin|> student_phoneNumber_name = {1: 'a', 3: 'c', 2: 'b'} def Handler() : while (1) : choice = eval(input("Enter :\t 1 - to search student name \n \t 2 - to insert new student record \n \t 0 - to quit\n")) print(choice) if (choice == 1) : if (student_phoneNumber_name) : phone_number = input("Enter student's phone number : ") name = SearchRecord(phone_number) if (name) : print("name : " + name ) else : print(str(phone_number) + "Does not exist in record" + str(name)) else : print("Record is empty ") elif (choice == 2) : phone_number = input("Enter student's phone number : ") name = input("Enter student's name : ") #best example to understand input() and raw_input() InsertRecord(phone_number, name) elif (choice == 0) : break else: print("Enter correct choice") def InsertRecord(x, y): student_phoneNumber_name[x] = y return; def <|fim_middle|>(x): print(x) if (x in student_phoneNumber_name) : return student_phoneNumber_name[x] return False Handler() print(student_phoneNumber_name)<|fim▁end|>
SearchRecord
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .fetch import FetchParser from .json_ld import JsonLdParser from .lom import LomParser from .lrmi import LrmiParser from .nsdl_dc import NsdlDcParser __all__ = [<|fim▁hole|> 'LomParser', 'LrmiParser', 'NsdlDcParser', ]<|fim▁end|>
'FetchParser', 'JsonLdParser',
<|file_name|>admin.py<|end_file_name|><|fim▁begin|><|fim▁hole|>class AccountFilterAdmin(admin.ModelAdmin): list_display = ('location', 'include_users', 'exclude_users') ordering = ('location',) admin.site.register(AccountFilter, AccountFilterAdmin)<|fim▁end|>
from django.contrib import admin from panoptes.tracking.models import AccountFilter
<|file_name|>admin.py<|end_file_name|><|fim▁begin|> from django.contrib import admin from panoptes.tracking.models import AccountFilter class AccountFilterAdmin(admin.ModelAdmin): <|fim_middle|> admin.site.register(AccountFilter, AccountFilterAdmin) <|fim▁end|>
list_display = ('location', 'include_users', 'exclude_users') ordering = ('location',)
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin<|fim▁hole|>from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants)<|fim▁end|>
from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): <|fim_middle|> <|fim▁end|>
""" Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants)
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): <|fim_middle|> def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test)
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): <|fim_middle|> def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): <|fim_middle|> def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks'])
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): <|fim_middle|> def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks'])
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): <|fim_middle|> <|fim▁end|>
""" Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants)
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def <|fim_middle|>(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
setUpClass
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def <|fim_middle|>(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
setUp
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def <|fim_middle|>(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
test_basic
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def <|fim_middle|>(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def test_access_before_api_transformer_order(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
test_no_user
<|file_name|>test_api.py<|end_file_name|><|fim▁begin|>""" Tests for Blocks api.py """ from django.test.client import RequestFactory from course_blocks.tests.helpers import EnableTransformerRegistryMixin from student.tests.factories import UserFactory from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import SampleCourseFactory from ..api import get_blocks class TestGetBlocks(EnableTransformerRegistryMixin, SharedModuleStoreTestCase): """ Tests for the get_blocks function """ @classmethod def setUpClass(cls): super(TestGetBlocks, cls).setUpClass() cls.course = SampleCourseFactory.create() # hide the html block cls.html_block = cls.store.get_item(cls.course.id.make_usage_key('html', 'html_x1a_1')) cls.html_block.visible_to_staff_only = True cls.store.update_item(cls.html_block, ModuleStoreEnum.UserID.test) def setUp(self): super(TestGetBlocks, self).setUp() self.user = UserFactory.create() self.request = RequestFactory().get("/dummy") self.request.user = self.user def test_basic(self): blocks = get_blocks(self.request, self.course.location, self.user) self.assertEquals(blocks['root'], unicode(self.course.location)) # subtract for (1) the orphaned course About block and (2) the hidden Html block self.assertEquals(len(blocks['blocks']), len(self.store.get_items(self.course.id)) - 2) self.assertNotIn(unicode(self.html_block.location), blocks['blocks']) def test_no_user(self): blocks = get_blocks(self.request, self.course.location) self.assertIn(unicode(self.html_block.location), blocks['blocks']) def <|fim_middle|>(self): """ Tests the order of transformers: access checks are made before the api transformer is applied. """ blocks = get_blocks(self.request, self.course.location, self.user, nav_depth=5, requested_fields=['nav_depth']) vertical_block = self.store.get_item(self.course.id.make_usage_key('vertical', 'vertical_x1a')) problem_block = self.store.get_item(self.course.id.make_usage_key('problem', 'problem_x1a_1')) vertical_descendants = blocks['blocks'][unicode(vertical_block.location)]['descendants'] self.assertIn(unicode(problem_block.location), vertical_descendants) self.assertNotIn(unicode(self.html_block.location), vertical_descendants) <|fim▁end|>
test_access_before_api_transformer_order
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|><|fim▁hole|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): <|fim_middle|> def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items()))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): <|fim_middle|> def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): <|fim_middle|> class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): <|fim_middle|> <|fim▁end|>
def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): <|fim_middle|> def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(0, score([]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): <|fim_middle|> def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(50, score([5]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): <|fim_middle|> def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(100, score([1]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): <|fim_middle|> def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(300, score([1,5,5,1]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): <|fim_middle|> def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(0, score([2,3,4,6]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): <|fim_middle|> def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(1000, score([1,1,1]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): <|fim_middle|> def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): <|fim_middle|> def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): <|fim_middle|> <|fim▁end|>
self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: <|fim_middle|> else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
return 1000
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: <|fim_middle|> def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
return num*100
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: <|fim_middle|> elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
return 100
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: <|fim_middle|> else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
return 50
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: <|fim_middle|> class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
return 0
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def <|fim_middle|>(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
score
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def <|fim_middle|>(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
score_of_three
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def <|fim_middle|>(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
score_of_one
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def <|fim_middle|>(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_an_empty_list_is_zero
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def <|fim_middle|>(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_a_single_roll_of_5_is_50
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def <|fim_middle|>(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_a_single_roll_of_1_is_100
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def <|fim_middle|>(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def <|fim_middle|>(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_single_2s_3s_4s_and_6s_are_zero
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def <|fim_middle|>(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_a_triple_1_is_1000
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def <|fim_middle|>(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_other_triples_is_100x
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def <|fim_middle|>(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def test_ones_not_left_out(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_score_of_mixed_is_sum
<|file_name|>about_scoring_project.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 1000 points # # * A set of three numbers (other than ones) is worth 100 times the # number. (e.g. three fives is 500 points). # # * A one (that is not part of a set of three) is worth 100 points. # # * A five (that is not part of a set of three) is worth 50 points. # # * Everything else is worth 0 points. # # # Examples: # # score([1,1,1,5,1]) => 1150 points # score([2,3,4,6,2]) => 0 points # score([3,4,5,3,3]) => 350 points # score([1,5,1,2,4]) => 250 points # # More scoring examples are given in the tests below: # # Your goal is to write the score method. from collections import Counter def score(dice): ''' Calculate the scores for results of up to fice dice rolls ''' return sum((score_of_three(k) * (v//3) + score_of_one(k) * (v%3) for k, v in Counter(dice).items())) def score_of_three(num): ''' Calculate score for set of three ''' if num == 1: return 1000 else: return num*100 def score_of_one(num): ''' Calculate score for a roll not in a set of three ''' if num == 1: return 100 elif num == 5: return 50 else: return 0 class AboutScoringProject(Koan): def test_score_of_an_empty_list_is_zero(self): self.assertEqual(0, score([])) def test_score_of_a_single_roll_of_5_is_50(self): self.assertEqual(50, score([5])) def test_score_of_a_single_roll_of_1_is_100(self): self.assertEqual(100, score([1])) def test_score_of_multiple_1s_and_5s_is_the_sum_of_individual_scores(self): self.assertEqual(300, score([1,5,5,1])) def test_score_of_single_2s_3s_4s_and_6s_are_zero(self): self.assertEqual(0, score([2,3,4,6])) def test_score_of_a_triple_1_is_1000(self): self.assertEqual(1000, score([1,1,1])) def test_score_of_other_triples_is_100x(self): self.assertEqual(200, score([2,2,2])) self.assertEqual(300, score([3,3,3])) self.assertEqual(400, score([4,4,4])) self.assertEqual(500, score([5,5,5])) self.assertEqual(600, score([6,6,6])) def test_score_of_mixed_is_sum(self): self.assertEqual(250, score([2,5,2,2,3])) self.assertEqual(550, score([5,5,5,5])) self.assertEqual(1150, score([1,1,1,5,1])) def <|fim_middle|>(self): self.assertEqual(300, score([1,2,2,2])) self.assertEqual(350, score([1,5,2,2,2]))<|fim▁end|>
test_ones_not_left_out
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now()<|fim▁hole|> sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'}<|fim▁end|>
self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature)
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: <|fim_middle|> <|fim▁end|>
account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'}
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): <|fim_middle|> def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
self.account_sid = account_sid self.account_token = token
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): <|fim_middle|> def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
self.server_ip = ip self.server_port = port self.soft_version = version
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): <|fim_middle|> def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
self.app_id = app_id
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): <|fim_middle|> def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'}
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): <|fim_middle|> <|fim▁end|>
now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'}
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def <|fim_middle|>(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
set_account
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def <|fim_middle|>(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
__init__
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def <|fim_middle|>(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
set_app_id
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def <|fim_middle|>(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def query_account_info(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
send_template_sms
<|file_name|>sdk.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- import hashlib import base64 import datetime import urllib2 import json class TemplateSMS: account_sid = '' account_token = '' app_id = '' server_ip = '' server_port = '' soft_version = '' timestamp = '' def set_account(self, account_sid, token): self.account_sid = account_sid self.account_token = token def __init__(self, ip, port, version): self.server_ip = ip self.server_port = port self.soft_version = version def set_app_id(self, app_id): self.app_id = app_id def send_template_sms(self, to, random, valid_min, temp_id): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/SMS/TemplateSMS?sig=" + sig src = self.account_sid + ":" + self.timestamp req = urllib2.Request(url) b = '["%s","%s"]' % (random, valid_min) body = '''{"to": "%s", "datas": %s, "templateId": "%s", "appId": "%s"}''' % (to, b, temp_id, self.app_id) req.add_data(body) auth = base64.encodestring(src).strip() req.add_header("Authorization", auth) req.add_header("Accept", 'application/json;') req.add_header("Content-Type", "application/json;charset=utf-8;") req.add_header("Host", "127.0.0.1") req.add_header("content-length", len(body)) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {'172001': 'network error'} def <|fim_middle|>(self): now_date = datetime.datetime.now() self.timestamp = now_date.strftime("%Y%m%d%H%M%S") signature = self.account_sid + self.account_token + self.timestamp sig = hashlib.md5() sig.update(signature) sig = sig.hexdigest().upper() url = "https://" + self.server_ip + ":" + self.server_port + "/" + self.soft_version + "/Accounts/" + \ self.account_sid + "/AccountInfo?sig=" + sig src = self.account_sid + ":" + self.timestamp auth = base64.encodestring(src).strip() req = urllib2.Request(url) req.add_header("Accept", "application/json") req.add_header("Content-Type", "application/jsoncharset=utf-8") req.add_header("Authorization", auth) try: res = urllib2.urlopen(req) data = res.read() res.close() locations = json.loads(data) return locations except: return {"statusCode": '172001'} <|fim▁end|>
query_account_info
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs<|fim▁hole|> with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main()<|fim▁end|>
def allInvsMatch(invsExpected, testnode): for x in range(60):
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): <|fim_middle|> # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
return format(hash, '064x')
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): <|fim_middle|> # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False;
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): <|fim_middle|> class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping()
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): <|fim_middle|> def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
SingleNodeConnCB.__init__(self) self.txinvs = []
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): <|fim_middle|> def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash))
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): <|fim_middle|> def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
with mininode_lock: self.txinvs = []
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): <|fim_middle|> class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
self.send_message(msg_feefilter(feerate)) self.sync_with_ping()
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): <|fim_middle|> if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs()
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): <|fim_middle|> def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
super().__init__() self.num_nodes = 2 self.setup_clean_chain = False
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node <|fim_middle|> def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1)
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): <|fim_middle|> if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs()
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): <|fim_middle|> time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
return True;
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): <|fim_middle|> def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
self.txinvs.append(hashToHex(i.hash))
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
FeeFilterTest().main()
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def <|fim_middle|>(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
hashToHex
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def <|fim_middle|>(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
allInvsMatch
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def <|fim_middle|>(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
__init__
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def <|fim_middle|>(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
on_inv
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def <|fim_middle|>(self): with mininode_lock: self.txinvs = [] def send_filter(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
clear_invs
<|file_name|>p2p-feefilter.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * import time ''' FeeFilterTest -- test processing of feefilter messages ''' def hashToHex(hash): return format(hash, '064x') # Wait up to 60 secs to see if the testnode has received all the expected invs def allInvsMatch(invsExpected, testnode): for x in range(60): with mininode_lock: if (sorted(invsExpected) == sorted(testnode.txinvs)): return True; time.sleep(1) return False; # TestNode: bare-bones "peer". Used to track which invs are received from a node # and to send the node feefilter messages. class TestNode(SingleNodeConnCB): def __init__(self): SingleNodeConnCB.__init__(self) self.txinvs = [] def on_inv(self, conn, message): for i in message.inv: if (i.type == 1): self.txinvs.append(hashToHex(i.hash)) def clear_invs(self): with mininode_lock: self.txinvs = [] def <|fim_middle|>(self, feerate): self.send_message(msg_feefilter(feerate)) self.sync_with_ping() class FeeFilterTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): # Node1 will be used to generate txs which should be relayed from Node0 # to our test node self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-debug", "-logtimemicros"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-debug", "-logtimemicros"])) connect_nodes(self.nodes[0], 1) def run_test(self): node1 = self.nodes[1] node0 = self.nodes[0] # Get out of IBD node1.generate(1) sync_blocks(self.nodes) node0.generate(21) sync_blocks(self.nodes) # Setup the p2p connections and start up the network thread. test_node = TestNode() connection = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node) test_node.add_connection(connection) NetworkThread().start() test_node.wait_for_verack() # Test that invs are received for all txs at feerate of 20 sat/byte node1.settxfee(Decimal("0.00020000")) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Set a filter of 15 sat/byte test_node.send_filter(15000) # Test that txs are still being received (paying 20 sat/byte) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Change tx fee rate to 10 sat/byte and test they are no longer received node1.settxfee(Decimal("0.00010000")) [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] sync_mempools(self.nodes) # must be sure node 0 has received all txs # Send one transaction from node0 that should be received, so that we # we can sync the test on receipt (if node1's txs were relayed, they'd # be received by the time this node0 tx is received). This is # unfortunately reliant on the current relay behavior where we batch up # to 35 entries in an inv, which means that when this next transaction # is eligible for relay, the prior transactions from node1 are eligible # as well. node0.settxfee(Decimal("0.00020000")) txids = [node0.sendtoaddress(node0.getnewaddress(), 1)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() # Remove fee filter and check that txs are received again test_node.send_filter(0) txids = [node1.sendtoaddress(node1.getnewaddress(), 1) for x in range(3)] assert(allInvsMatch(txids, test_node)) test_node.clear_invs() if __name__ == '__main__': FeeFilterTest().main() <|fim▁end|>
send_filter