Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def audio_send_stream(self, httptype=None, channel=None, path_file=None, encode=None): if httptype is None or channel is None: raise RuntimeError("Requires htttype and channel") file_audio = { 'file': open(path_file, 'rb'), } header = { 'content-type': 'Audio/' + encode, 'content-length': '9999999' } self.command_audio( 'audio.cgi?action=postAudio&httptype={0}&channel={1}'.format( httptype, channel), file_content=file_audio, http_header=header )
[ "\n Params:\n\n path_file - path to audio file\n channel: - integer\n httptype - type string (singlepart or multipart)\n\n singlepart: HTTP content is a continuos flow of audio packets\n multipart: HTTP content type is multipart/x-mixed-replace, and\n each audio packet ends with a boundary string\n\n Supported audio encode type according with documentation:\n PCM\n ADPCM\n G.711A\n G.711.Mu\n G.726\n G.729\n MPEG2\n AMR\n AAC\n\n " ]
Please provide a description of the function:def audio_stream_capture(self, httptype=None, channel=None, path_file=None): if httptype is None and channel is None: raise RuntimeError("Requires htttype and channel") ret = self.command( 'audio.cgi?action=getAudio&httptype={0}&channel={1}'.format( httptype, channel)) if path_file: with open(path_file, 'wb') as out_file: shutil.copyfileobj(ret.raw, out_file) return ret.raw
[ "\n Params:\n\n path_file - path to output file\n channel: - integer\n httptype - type string (singlepart or multipart)\n\n singlepart: HTTP content is a continuos flow of audio packets\n multipart: HTTP content type is multipart/x-mixed-replace, and\n each audio packet ends with a boundary string\n\n " ]
Please provide a description of the function:def approvecommittee(ctx, members, account): pprint(ctx.peerplays.approvecommittee(members, account=account))
[ " Approve committee member(s)\n " ]
Please provide a description of the function:def disapprovecommittee(ctx, members, account): pprint(ctx.peerplays.disapprovecommittee(members, account=account))
[ " Disapprove committee member(s)\n " ]
Please provide a description of the function:def getkey(ctx, pubkey): click.echo(ctx.peerplays.wallet.getPrivateKeyForPublicKey(pubkey))
[ " Obtain private key in WIF format\n " ]
Please provide a description of the function:def listkeys(ctx): t = PrettyTable(["Available Key"]) t.align = "l" for key in ctx.peerplays.wallet.getPublicKeys(): t.add_row([key]) click.echo(t)
[ " List all keys (for all networks)\n " ]
Please provide a description of the function:def listaccounts(ctx): t = PrettyTable(["Name", "Key", "Owner", "Active", "Memo"]) for key in ctx.blockchain.wallet.getPublicKeys(True): for account in ctx.blockchain.wallet.getAccountsFromPublicKey(key): account = Account(account) is_owner = key in [x[0] for x in account["owner"]["key_auths"]] is_active = key in [x[0] for x in account["active"]["key_auths"]] is_memo = key == account["options"]["memo_key"] t.add_row( [ account["name"], key, "x" if is_owner else "", "x" if is_active else "", "x" if is_memo else "", ] ) click.echo(t)
[ " List accounts (for the connected network)\n " ]
Please provide a description of the function:def importaccount(ctx, account, role): from peerplaysbase.account import PasswordKey password = click.prompt("Account Passphrase", hide_input=True) account = Account(account, peerplays_instance=ctx.peerplays) imported = False if role == "owner": owner_key = PasswordKey(account["name"], password, role="owner") owner_pubkey = format( owner_key.get_public_key(), ctx.peerplays.rpc.chain_params["prefix"] ) if owner_pubkey in [x[0] for x in account["owner"]["key_auths"]]: click.echo("Importing owner key!") owner_privkey = owner_key.get_private_key() ctx.peerplays.wallet.addPrivateKey(owner_privkey) imported = True if role == "active": active_key = PasswordKey(account["name"], password, role="active") active_pubkey = format( active_key.get_public_key(), ctx.peerplays.rpc.chain_params["prefix"] ) if active_pubkey in [x[0] for x in account["active"]["key_auths"]]: click.echo("Importing active key!") active_privkey = active_key.get_private_key() ctx.peerplays.wallet.addPrivateKey(active_privkey) imported = True if role == "memo": memo_key = PasswordKey(account["name"], password, role=role) memo_pubkey = format( memo_key.get_public_key(), ctx.peerplays.rpc.chain_params["prefix"] ) if memo_pubkey == account["memo_key"]: click.echo("Importing memo key!") memo_privkey = memo_key.get_private_key() ctx.peerplays.wallet.addPrivateKey(memo_privkey) imported = True if not imported: click.echo("No matching key(s) found. Password correct?")
[ " Import an account using an account password\n " ]
Please provide a description of the function:def sports(ctx): sports = Sports(peerplays_instance=ctx.peerplays) click.echo(pretty_print(sports, ctx=ctx))
[ " [bookie] List sports " ]
Please provide a description of the function:def eventgroups(ctx, sport): sport = Sport(sport, peerplays_instance=ctx.peerplays) click.echo(pretty_print(sport.eventgroups, ctx=ctx))
[ " [bookie] List event groups for a sport\n\n :param str sport: Sports id\n " ]
Please provide a description of the function:def events(ctx, eventgroup): eg = EventGroup(eventgroup, peerplays_instance=ctx.peerplays) click.echo(pretty_print(eg.events, ctx=ctx))
[ " [bookie] List events for an event group\n\n :param str eventgroup: Event Group id\n " ]
Please provide a description of the function:def bmgs(ctx, event): eg = Event(event, peerplays_instance=ctx.peerplays) click.echo(pretty_print(eg.bettingmarketgroups, ctx=ctx))
[ " [bookie] List betting market groups for an event\n\n :param str event: Event id\n " ]
Please provide a description of the function:def bettingmarkets(ctx, bmg): bmg = BettingMarketGroup(bmg, peerplays_instance=ctx.peerplays) click.echo(pretty_print(bmg.bettingmarkets, ctx=ctx))
[ " [bookie] List betting markets for bmg\n\n :param str bmg: Betting market id\n " ]
Please provide a description of the function:def rules(ctx): rules = Rules(peerplays_instance=ctx.peerplays) click.echo(pretty_print(rules, ctx=ctx))
[ " [bookie] List all rules\n " ]
Please provide a description of the function:def rule(ctx, rule): rule = Rule(rule, peerplays_instance=ctx.peerplays) t = PrettyTable([ "id", "name", ]) t.align = "l" t.add_row([ rule["id"], "\n".join(["{}: {}".format(v[0], v[1]) for v in rule["name"]]), ]) click.echo(str(t)) click.echo( "\n".join(["{}: {}".format(v[0], v[1]) for v in rule["description"]]) )
[ " [bookie] Show a specific rule\n\n :param str bmg: Betting market id\n " ]
Please provide a description of the function:def list(ctx, sport): from .ui import maplist2dict from tqdm import tqdm from treelib import Node, Tree tree = Tree() tree.create_node("sports", "root") def formatname(o): if "name" in o: name = o.get("name") elif "description" in o: name = o.get("description") else: name = [] return "{} ({})".format( maplist2dict(name).get("en"), o["id"] ) if sport: sports = [Sport(sport, peerplays_instance=ctx.peerplays)] else: sports = Sports() for sport in tqdm(sports): tree.create_node( formatname(sport), sport["id"], parent="root") for eg in tqdm(sport.eventgroups): tree.create_node( formatname(eg), eg["id"], parent=sport["id"]) for e in tqdm(eg.events): tree.create_node( formatname(e), e["id"], parent=eg["id"]) for bmg in tqdm(e.bettingmarketgroups): tree.create_node( formatname(bmg), bmg["id"], parent=e["id"]) for bm in tqdm(bmg.bettingmarkets): tree.create_node( formatname(bm), bm["id"], parent=bmg["id"]) tree.show()
[ " [bookie] list the entire thing\n " ]
Please provide a description of the function:def rpc(ctx, call, arguments, api): try: data = list(eval(d) for d in arguments) except: data = arguments ret = getattr(ctx.peerplays.rpc, call)(*data, api=api) pprint(ret)
[ " Construct RPC call directly\n \\b\n You can specify which API to send the call to:\n\n peerplays rpc --api bookie get_matched_bets_for_bettor 1.2.0\n\n You can also specify lists using\n\n peerplays rpc get_objects \"['2.0.0', '2.1.0']\"\n\n " ]
Please provide a description of the function:def assets(ctx): "List Assets" MAX_ASSET = 100000 assets = [] for i in range(0, MAX_ASSET): try: assets.append(Asset("1.3.{}".format(i))) except AssetDoesNotExistsException: break assetTable = PrettyTable() assetTable.field_names = ["ID", "Symbol", "Precision", "Description", "Max Supply"] for i in range (0, len(assets)): try: description = assets[i].description if description == "": description = "--" except AttributeError: description = "--" assetTable.add_row([assets[i].id, assets[i].symbol, assets[i].precision, description, assets[i].max_supply["amount"]]) click.echo(assetTable)
[]
Please provide a description of the function:def info(ctx, objects): if not objects: t = PrettyTable(["Key", "Value"]) t.align = "l" info = ctx.peerplays.rpc.get_dynamic_global_properties() for key in info: t.add_row([key, info[key]]) click.echo(t.get_string(sortby="Key")) for obj in objects: # Block if re.match("^[0-9]*$", obj): block = Block(obj, peerplays_instance=ctx.peerplays) if block: t = PrettyTable(["Key", "Value"]) t.align = "l" for key in sorted(block): value = block[key] if key == "transactions": value = json.dumps(value, indent=4) t.add_row([key, value]) click.echo(t) else: click.echo("Block number %s unknown" % obj) # Object Id elif len(obj.split(".")) == 3: data = ctx.peerplays.rpc.get_object(obj) if data: t = PrettyTable(["Key", "Value"]) t.align = "l" for key in sorted(data): value = data[key] if isinstance(value, dict) or isinstance(value, list): value = json.dumps(value, indent=4) t.add_row([key, value]) click.echo(t) else: click.echo("Object %s unknown" % obj) # Asset elif obj.upper() == obj: data = Asset(obj) t = PrettyTable(["Key", "Value"]) t.align = "l" for key in sorted(data): value = data[key] if isinstance(value, dict): value = json.dumps(value, indent=4) t.add_row([key, value]) click.echo(t) # Public Key elif re.match("^PPY.{48,55}$", obj): account = ctx.peerplays.wallet.getAccountFromPublicKey(obj) if account: t = PrettyTable(["Account"]) t.align = "l" t.add_row([account]) click.echo(t) else: click.echo("Public Key not known" % obj) # Account name elif re.match("^[a-zA-Z0-9\-\._]{2,64}$", obj): account = Account(obj, full=True) if account: t = PrettyTable(["Key", "Value"]) t.align = "l" for key in sorted(account): value = account[key] if isinstance(value, dict) or isinstance(value, list): value = json.dumps(value, indent=4) t.add_row([key, value]) click.echo(t) else: click.echo("Account %s unknown" % obj) else: click.echo("Couldn't identify object to read")
[ " Obtain all kinds of information\n " ]
Please provide a description of the function:def fees(ctx): from peerplaysbase.operationids import getOperationNameForId chain = Blockchain(peerplays_instance=ctx.peerplays) feesObj = chain.chainParameters().get("current_fees") fees = feesObj["parameters"] t = PrettyTable(["Operation", "Type", "Fee"]) t.align = "l" t.align["Fee"] = "r" for fee in fees: for f in fee[1]: t.add_row( [ getOperationNameForId(fee[0]), f, str(Amount({"amount": fee[1].get(f, 0), "asset_id": "1.3.0"})), ] ) click.echo(t)
[ " List fees\n " ]
Please provide a description of the function:def create_account( self, account_name, registrar=None, referrer="1.2.0", referrer_percent=50, owner_key=None, active_key=None, memo_key=None, password=None, additional_owner_keys=[], additional_active_keys=[], additional_owner_accounts=[], additional_active_accounts=[], proxy_account="proxy-to-self", storekeys=True, **kwargs ): if not registrar and self.config["default_account"]: registrar = self.config["default_account"] if not registrar: raise ValueError( "Not registrar account given. Define it with " "registrar=x, or set the default_account using 'peerplays'" ) if password and (owner_key or active_key or memo_key): raise ValueError("You cannot use 'password' AND provide keys!") try: Account(account_name, blockchain_instance=self) raise AccountExistsException except: pass referrer = Account(referrer, blockchain_instance=self) registrar = Account(registrar, blockchain_instance=self) " Generate new keys from password" from peerplaysbase.account import PasswordKey, PublicKey if password: active_key = PasswordKey(account_name, password, role="active") owner_key = PasswordKey(account_name, password, role="owner") memo_key = PasswordKey(account_name, password, role="memo") active_pubkey = active_key.get_public_key() owner_pubkey = owner_key.get_public_key() memo_pubkey = memo_key.get_public_key() active_privkey = active_key.get_private_key() # owner_privkey = owner_key.get_private_key() memo_privkey = memo_key.get_private_key() # store private keys if storekeys: # self.wallet.addPrivateKey(str(owner_privkey)) self.wallet.addPrivateKey(str(active_privkey)) self.wallet.addPrivateKey(str(memo_privkey)) elif owner_key and active_key and memo_key: active_pubkey = PublicKey(active_key, prefix=self.prefix) owner_pubkey = PublicKey(owner_key, prefix=self.prefix) memo_pubkey = PublicKey(memo_key, prefix=self.prefix) else: raise ValueError( "Call incomplete! Provide either a password or public keys!" ) owner = format(owner_pubkey, self.prefix) active = format(active_pubkey, self.prefix) memo = format(memo_pubkey, self.prefix) owner_key_authority = [[owner, 1]] active_key_authority = [[active, 1]] owner_accounts_authority = [] active_accounts_authority = [] # additional authorities for k in additional_owner_keys: owner_key_authority.append([k, 1]) for k in additional_active_keys: active_key_authority.append([k, 1]) for k in additional_owner_accounts: addaccount = Account(k, blockchain_instance=self) owner_accounts_authority.append([addaccount["id"], 1]) for k in additional_active_accounts: addaccount = Account(k, blockchain_instance=self) active_accounts_authority.append([addaccount["id"], 1]) # voting account voting_account = Account( proxy_account or "proxy-to-self", blockchain_instance=self ) op = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "registrar": registrar["id"], "referrer": referrer["id"], "referrer_percent": int(referrer_percent * 100), "name": account_name, "owner": { "account_auths": owner_accounts_authority, "key_auths": owner_key_authority, "address_auths": [], "weight_threshold": 1, }, "active": { "account_auths": active_accounts_authority, "key_auths": active_key_authority, "address_auths": [], "weight_threshold": 1, }, "options": { "memo_key": memo, "voting_account": voting_account["id"], "num_witness": 0, "num_committee": 0, "votes": [], "extensions": [], }, "extensions": {}, "prefix": self.prefix, } op = operations.Account_create(**op) return self.finalizeOp(op, registrar, "active", **kwargs)
[ " Create new account on PeerPlays\n\n The brainkey/password can be used to recover all generated keys\n (see `peerplaysbase.account` for more details.\n\n By default, this call will use ``default_account`` to\n register a new name ``account_name`` with all keys being\n derived from a new brain key that will be returned. The\n corresponding keys will automatically be installed in the\n wallet.\n\n .. warning:: Don't call this method unless you know what\n you are doing! Be sure to understand what this\n method does and where to find the private keys\n for your account.\n\n .. note:: Please note that this imports private keys\n (if password is present) into the wallet by\n default. However, it **does not import the owner\n key** for security reasons. Do NOT expect to be\n able to recover it from the wallet if you lose\n your password!\n\n :param str account_name: (**required**) new account name\n :param str registrar: which account should pay the registration fee\n (defaults to ``default_account``)\n :param str owner_key: Main owner key\n :param str active_key: Main active key\n :param str memo_key: Main memo_key\n :param str password: Alternatively to providing keys, one\n can provide a password from which the\n keys will be derived\n :param array additional_owner_keys: Additional owner public keys\n :param array additional_active_keys: Additional active public keys\n :param array additional_owner_accounts: Additional owner account\n names\n :param array additional_active_accounts: Additional acctive account\n names\n :param bool storekeys: Store new keys in the wallet (default:\n ``True``)\n :raises AccountExistsException: if the account already exists on\n the blockchain\n\n " ]
Please provide a description of the function:def disallow( self, foreign, permission="active", account=None, threshold=None, **kwargs ): if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") if permission not in ["owner", "active"]: raise ValueError("Permission needs to be either 'owner', or 'active") account = Account(account, blockchain_instance=self) authority = account[permission] try: pubkey = PublicKey(foreign, prefix=self.prefix) affected_items = list( filter(lambda x: x[0] == str(pubkey), authority["key_auths"]) ) authority["key_auths"] = list( filter(lambda x: x[0] != str(pubkey), authority["key_auths"]) ) except: try: foreign_account = Account(foreign, blockchain_instance=self) affected_items = list( filter( lambda x: x[0] == foreign_account["id"], authority["account_auths"], ) ) authority["account_auths"] = list( filter( lambda x: x[0] != foreign_account["id"], authority["account_auths"], ) ) except: raise ValueError("Unknown foreign account or unvalid public key") if not affected_items: raise ValueError("Changes nothing!") removed_weight = affected_items[0][1] # Define threshold if threshold: authority["weight_threshold"] = threshold # Correct threshold (at most by the amount removed from the # authority) try: self._test_weights_treshold(authority) except: log.critical( "The account's threshold will be reduced by %d" % (removed_weight) ) authority["weight_threshold"] -= removed_weight self._test_weights_treshold(authority) op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], permission: authority, "extensions": {}, } ) if permission == "owner": return self.finalizeOp(op, account["name"], "owner", **kwargs) else: return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Remove additional access to an account by some other public\n key or account.\n\n :param str foreign: The foreign account that will obtain access\n :param str permission: (optional) The actual permission to\n modify (defaults to ``active``)\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n :param int threshold: The threshold that needs to be reached\n by signatures to be able to interact\n " ]
Please provide a description of the function:def approvewitness(self, witnesses, account=None, **kwargs): if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) options = account["options"] if not isinstance(witnesses, (list, set, tuple)): witnesses = {witnesses} for witness in witnesses: witness = Witness(witness, blockchain_instance=self) options["votes"].append(witness["vote_id"]) options["votes"] = list(set(options["votes"])) options["num_witness"] = len( list(filter(lambda x: float(x.split(":")[0]) == 1, options["votes"])) ) op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Approve a witness\n\n :param list witnesses: list of Witness name or id\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def approvecommittee(self, committees, account=None, **kwargs): if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) options = account["options"] if not isinstance(committees, (list, set, tuple)): committees = {committees} for committee in committees: committee = Committee(committee, blockchain_instance=self) options["votes"].append(committee["vote_id"]) options["votes"] = list(set(options["votes"])) options["num_committee"] = len( list(filter(lambda x: float(x.split(":")[0]) == 0, options["votes"])) ) op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Approve a committee\n\n :param list committees: list of committee member name or id\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def sport_create(self, names, account=None, **kwargs): assert isinstance(names, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) op = operations.Sport_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "name": names, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Create a sport. This needs to be **proposed**.\n\n :param list names: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def sport_update(self, sport_id, names=[], account=None, **kwargs): assert isinstance(names, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) sport = Sport(sport_id) op = operations.Sport_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "sport_id": sport["id"], "new_name": names, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Update a sport. This needs to be **proposed**.\n\n :param str sport_id: The id of the sport to update\n :param list names: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def sport_delete(self, sport_id="0.0.0", account=None, **kwargs): if not account: if "default_account" in config: account = config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) sport = Sport(sport_id) op = operations.Sport_delete( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "sport_id": sport["id"], "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Remove a sport. This needs to be **proposed**.\n\n :param str sport_id: Sport ID to identify the Sport to be deleted\n\n :param str account: (optional) Account used to verify the operation\n " ]
Please provide a description of the function:def event_group_create(self, names, sport_id="0.0.0", account=None, **kwargs): assert isinstance(names, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") if sport_id[0] == "1": # Test if object exists Sport(sport_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "sport_create", sport_id ) account = Account(account) op = operations.Event_group_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "name": names, "sport_id": sport_id, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Create an event group. This needs to be **proposed**.\n\n :param list names: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param str sport_id: Sport ID to create the event group for\n (defaults to *relative* id ``0.0.0``)\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def event_group_update( self, event_group_id, names=[], sport_id="0.0.0", account=None, **kwargs ): assert isinstance(names, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") if sport_id[0] == "1": # Test if object exists Sport(sport_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "sport_create", sport_id ) account = Account(account) event_group = EventGroup(event_group_id) op = operations.Event_group_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "event_group_id": event_group["id"], "new_name": names, "new_sport_id": sport_id, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Update an event group. This needs to be **proposed**.\n\n :param str event_id: Id of the event group to update\n :param list names: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param str sport_id: Sport ID to create the event group for\n (defaults to *relative* id ``0.0.0``)\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def eventgroup_delete(self, event_group_id="0.0.0", account=None, **kwargs): if not account: if "default_account" in config: account = config["default_account"] if not account: raise ValueError("You need to provide an Account") account = Account(account) eventgroup = EventGroup(event_group_id) op = operations.Event_group_delete( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "event_group_id": eventgroup["id"], "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Delete an eventgroup. This needs to be **propose**.\n\n :param str event_group_id: ID of the event group to be deleted\n\n :param str account: (optional) Account used to verify the operation" ]
Please provide a description of the function:def event_create( self, name, season, start_time, event_group_id="0.0.0", account=None, **kwargs ): assert isinstance(season, list) assert isinstance( start_time, datetime ), "start_time needs to be a `datetime.datetime`" if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) if event_group_id[0] == "1": # Test if object exists EventGroup(event_group_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "event_group_create", event_group_id, ) op = operations.Event_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "name": name, "season": season, "start_time": formatTime(start_time), "event_group_id": event_group_id, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Create an event. This needs to be **proposed**.\n\n :param list name: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param list season: Internationalized season, e.g. ``[['de',\n 'Foo'], ['en', 'bar']]``\n :param str event_group_id: Event group ID to create the event for\n (defaults to *relative* id ``0.0.0``)\n :param datetime start_time: Time of the start of the event\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def event_update( self, event_id, name=None, season=None, start_time=None, event_group_id=None, status=None, account=None, **kwargs ): assert isinstance(season, list) assert isinstance( start_time, datetime ), "start_time needs to be a `datetime.datetime`" if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) event = Event(event_id) op_data = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "event_id": event["id"], "prefix": self.prefix, } # Do not try to update status of it doesn't change it on the chain if event["status"] == status: status = None if event_group_id: if event_group_id[0] == "1": # Test if object exists EventGroup(event_group_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "event_group_create", event_group_id, ) op_data.update({"new_event_group_id": event_group_id}) if name: op_data.update({"new_name": name}) if season: op_data.update({"new_season": season}) if start_time: op_data.update({"new_start_time": formatTime(start_time)}) if status: op_data.update({"new_status": status}) op = operations.Event_update(**op_data) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Update an event. This needs to be **proposed**.\n\n :param str event_id: Id of the event to update\n :param list name: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param list season: Internationalized season, e.g. ``[['de',\n 'Foo'], ['en', 'bar']]``\n :param str event_group_id: Event group ID to create the event for\n (defaults to *relative* id ``0.0.0``)\n :param datetime start_time: Time of the start of the event\n :param str status: Event status\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def event_update_status(self, event_id, status, scores=[], account=None, **kwargs): if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) event = Event(event_id) # Do not try to update status of it doesn't change it on the chain if event["status"] == status: status = None op = operations.Event_update_status( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "event_id": event["id"], "status": status, "scores": scores, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Update the status of an event. This needs to be **proposed**.\n\n :param str event_id: Id of the event to update\n :param str status: Event status\n :param list scores: List of strings that represent the scores of a\n match (defaults to [])\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def betting_market_rules_create(self, names, descriptions, account=None, **kwargs): assert isinstance(names, list) assert isinstance(descriptions, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) op = operations.Betting_market_rules_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "name": names, "description": descriptions, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Create betting market rules\n\n :param list names: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param list descriptions: Internationalized descriptions, e.g.\n ``[['de', 'Foo'], ['en', 'bar']]``\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n\n " ]
Please provide a description of the function:def betting_market_rules_update( self, rules_id, names, descriptions, account=None, **kwargs ): assert isinstance(names, list) assert isinstance(descriptions, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) rule = Rule(rules_id) op = operations.Betting_market_rules_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "betting_market_rules_id": rule["id"], "new_name": names, "new_description": descriptions, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Update betting market rules\n\n :param str rules_id: Id of the betting market rules to update\n :param list names: Internationalized names, e.g. ``[['de', 'Foo'],\n ['en', 'bar']]``\n :param list descriptions: Internationalized descriptions, e.g.\n ``[['de', 'Foo'], ['en', 'bar']]``\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n\n " ]
Please provide a description of the function:def betting_market_group_create( self, description, event_id="0.0.0", rules_id="0.0.0", asset=None, delay_before_settling=0, never_in_play=False, resolution_constraint="exactly_one_winner", account=None, **kwargs ): if not asset: asset = self.rpc.chain_params["core_symbol"] if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) asset = Asset(asset, blockchain_instance=self) if event_id[0] == "1": # Test if object exists Event(event_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "event_create", event_id ) if rules_id[0] == "1": # Test if object exists Rule(rules_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "betting_market_rules_create", rules_id, ) op = operations.Betting_market_group_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "description": description, "event_id": event_id, "rules_id": rules_id, "asset_id": asset["id"], "never_in_play": bool(never_in_play), "delay_before_settling": int(delay_before_settling), "resolution_constraint": resolution_constraint, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Create an betting market. This needs to be **proposed**.\n\n :param list description: Internationalized list of descriptions\n :param str event_id: Event ID to create this for (defaults to\n *relative* id ``0.0.0``)\n :param str rule_id: Rule ID to create this with (defaults to\n *relative* id ``0.0.0``)\n :param peerplays.asset.Asset asset: Asset to be used for this\n market\n :param int delay_before_settling: Delay in seconds before settling\n (defaults to 0 seconds - immediatelly)\n :param bool never_in_play: Set this market group as *never in play*\n (defaults to *False*)\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def betting_market_group_update( self, betting_market_group_id, description=None, event_id=None, rules_id=None, status=None, account=None, **kwargs ): if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) bmg = BettingMarketGroup(betting_market_group_id) # Do not try to update status of it doesn't change it on the chain if bmg["status"] == status: status = None op_data = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "betting_market_group_id": bmg["id"], "prefix": self.prefix, } if event_id: if event_id[0] == "1": # Test if object exists Event(event_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "event_create", event_id ) op_data.update({"new_event_id": event_id}) if rules_id: if rules_id[0] == "1": # Test if object exists Rule(rules_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "betting_market_rules_create", rules_id, ) op_data.update({"new_rules_id": rules_id}) if description: op_data.update({"new_description": description}) if status: op_data.update({"status": status}) op = operations.Betting_market_group_update(**op_data) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Update an betting market. This needs to be **proposed**.\n\n :param str betting_market_group_id: Id of the betting market group\n to update\n :param list description: Internationalized list of descriptions\n :param str event_id: Event ID to create this for\n :param str rule_id: Rule ID to create this with\n :param str status: New Status\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def betting_market_create( self, payout_condition, description, group_id="0.0.0", account=None, **kwargs ): assert isinstance(payout_condition, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) if group_id[0] == "1": # Test if object exists BettingMarketGroup(group_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "betting_market_group_create", group_id, ) op = operations.Betting_market_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "group_id": group_id, "description": description, "payout_condition": payout_condition, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Create an event group. This needs to be **proposed**.\n\n :param list payout_condition: Internationalized names, e.g.\n ``[['de', 'Foo'], ['en', 'bar']]``\n :param list description: Internationalized descriptions, e.g.\n ``[['de', 'Foo'], ['en', 'bar']]``\n :param str group_id: Group ID to create the market for (defaults to\n *relative* id ``0.0.0``)\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def betting_market_update( self, betting_market_id, payout_condition, description, group_id="0.0.0", account=None, **kwargs ): assert isinstance(payout_condition, list) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) market = BettingMarket(betting_market_id) if group_id[0] == "1": # Test if object exists BettingMarketGroup(group_id) else: # Test if object is proposed test_proposal_in_buffer( kwargs.get("append_to", self.propbuffer), "betting_market_group_create", group_id, ) op = operations.Betting_market_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "betting_market_id": market["id"], "new_group_id": group_id, "new_description": description, "new_payout_condition": payout_condition, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Update an event group. This needs to be **proposed**.\n\n :param str betting_market_id: Id of the betting market to update\n :param list payout_condition: Internationalized names, e.g.\n ``[['de', 'Foo'], ['en', 'bar']]``\n :param list description: Internationalized descriptions, e.g.\n ``[['de', 'Foo'], ['en', 'bar']]``\n :param str group_id: Group ID to create the market for (defaults to\n *relative* id ``0.0.0``)\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n " ]
Please provide a description of the function:def betting_market_resolve( self, betting_market_group_id, results, account=None, **kwargs ): assert isinstance(results, (list, set, tuple)) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) # Test if object exists BettingMarketGroup(betting_market_group_id) op = operations.Betting_market_group_resolve( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "betting_market_group_id": betting_market_group_id, "resolutions": results, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Create an betting market. This needs to be **proposed**.\n\n :param str betting_market_group_id: Market Group ID to resolve\n :param list results: Array of Result of the market (``win``,\n ``not_win``, or ``cancel``)\n :param str account: (optional) the account to allow access\n to (defaults to ``default_account``)\n\n Results take the form:::\n\n [\n [\"1.21.257\", \"win\"],\n [\"1.21.258\", \"not_win\"],\n [\"1.21.259\", \"cancel\"],\n ]\n\n " ]
Please provide a description of the function:def bet_place( self, betting_market_id, amount_to_bet, backer_multiplier, back_or_lay, account=None, **kwargs ): from . import GRAPHENE_BETTING_ODDS_PRECISION assert isinstance(amount_to_bet, Amount) assert back_or_lay in ["back", "lay"] if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) bm = BettingMarket(betting_market_id) op = operations.Bet_place( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "bettor_id": account["id"], "betting_market_id": bm["id"], "amount_to_bet": amount_to_bet.json(), "backer_multiplier": ( int(backer_multiplier * GRAPHENE_BETTING_ODDS_PRECISION) ), "back_or_lay": back_or_lay, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Place a bet\n\n :param str betting_market_id: The identifier for the market to bet\n in\n :param peerplays.amount.Amount amount_to_bet: Amount to bet with\n :param int backer_multiplier: Multipler for backer\n :param str back_or_lay: \"back\" or \"lay\" the bet\n :param str account: (optional) the account to bet (defaults\n to ``default_account``)\n " ]
Please provide a description of the function:def bet_cancel(self, bet_to_cancel, account=None, **kwargs): if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account) bet = Bet(bet_to_cancel) op = operations.Bet_cancel( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "bettor_id": account["id"], "bet_to_cancel": bet["id"], "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ " Cancel a bet\n\n :param str bet_to_cancel: The identifier that identifies the bet to\n cancel\n :param str account: (optional) the account that owns the bet\n (defaults to ``default_account``)\n " ]
Please provide a description of the function:def verbose(f): @click.pass_context def new_func(ctx, *args, **kwargs): global log verbosity = ["critical", "error", "warn", "info", "debug"][ int(min(ctx.obj.get("verbose", 0), 4)) ] log.setLevel(getattr(logging, verbosity.upper())) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) ch = logging.StreamHandler() ch.setLevel(getattr(logging, verbosity.upper())) ch.setFormatter(formatter) log.addHandler(ch) # GrapheneAPI logging if ctx.obj.get("verbose", 0) > 4: verbosity = ["critical", "error", "warn", "info", "debug"][ int(min(ctx.obj.get("verbose", 4) - 4, 4)) ] log = logging.getLogger("grapheneapi") log.setLevel(getattr(logging, verbosity.upper())) log.addHandler(ch) if ctx.obj.get("verbose", 0) > 8: verbosity = ["critical", "error", "warn", "info", "debug"][ int(min(ctx.obj.get("verbose", 8) - 8, 4)) ] log = logging.getLogger("graphenebase") log.setLevel(getattr(logging, verbosity.upper())) log.addHandler(ch) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
[ " Add verbose flags and add logging handlers\n " ]
Please provide a description of the function:def offline(f): @click.pass_context @verbose def new_func(ctx, *args, **kwargs): ctx.obj["offline"] = True ctx.peerplays = PeerPlays(**ctx.obj) ctx.blockchain = ctx.peerplays set_shared_peerplays_instance(ctx.peerplays) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
[ " This decorator allows you to access ``ctx.peerplays`` which is\n an instance of PeerPlays with ``offline=True``.\n " ]
Please provide a description of the function:def customchain(**kwargsChain): def wrap(f): @click.pass_context @verbose def new_func(ctx, *args, **kwargs): newoptions = ctx.obj newoptions.update(kwargsChain) ctx.peerplays = PeerPlays(**newoptions) ctx.blockchain = ctx.peerplays set_shared_peerplays_instance(ctx.peerplays) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f) return wrap
[ " This decorator allows you to access ``ctx.peerplays`` which is\n an instance of Peerplays. But in contrast to @chain, this is a\n decorator that expects parameters that are directed right to\n ``PeerPlays()``.\n\n ... code-block::python\n\n @main.command()\n @click.option(\"--worker\", default=None)\n @click.pass_context\n @customchain(foo=\"bar\")\n @unlock\n def list(ctx, worker):\n print(ctx.obj)\n\n " ]
Please provide a description of the function:def configfile(f): @click.pass_context def new_func(ctx, *args, **kwargs): ctx.config = yaml.load(open(ctx.obj["configfile"])) return ctx.invoke(f, *args, **kwargs) return update_wrapper(new_func, f)
[ " This decorator will parse a configuration file in YAML format\n and store the dictionary in ``ctx.blockchain.config``\n " ]
Please provide a description of the function:def allow(ctx, foreign_account, permission, weight, threshold, account): if not foreign_account: from peerplaysbase.account import PasswordKey pwd = click.prompt( "Password for Key Derivation", hide_input=True, confirmation_prompt=True ) foreign_account = format( PasswordKey(account, pwd, permission).get_public(), "PPY" ) pprint( ctx.peerplays.allow( foreign_account, weight=weight, account=account, permission=permission, threshold=threshold, ) )
[ " Add a key/account to an account's permission\n " ]
Please provide a description of the function:def disallow(ctx, foreign_account, permission, threshold, account): pprint( ctx.peerplays.disallow( foreign_account, account=account, permission=permission, threshold=threshold ) )
[ " Remove a key/account from an account's permission\n " ]
Please provide a description of the function:def history(ctx, account, limit, type, csv, exclude, raw): from peerplaysbase.operations import getOperationNameForId header = ["#", "time (block)", "operation", "details"] if csv: import csv t = csv.writer(sys.stdout, delimiter=";") t.writerow(header) else: t = PrettyTable(header) t.align = "r" t.align["details"] = "l" for a in account: account = Account(a, peerplays_instance=ctx.peerplays) for b in account.history(limit=limit, only_ops=type, exclude_ops=exclude): row = [ b["id"].split(".")[2], "%s" % (b["block_num"]), "{} ({})".format(getOperationNameForId(b["op"][0]), b["op"][0]), pprintOperation(b) if not raw else json.dumps(b, indent=4), ] if csv: t.writerow(row) else: t.add_row(row) if not csv: click.echo(t)
[ " Show history of an account\n " ]
Please provide a description of the function:def transfer(ctx, to, amount, asset, memo, account): pprint(ctx.peerplays.transfer(to, amount, asset, memo=memo, account=account))
[ " Transfer assets\n " ]
Please provide a description of the function:def balance(ctx, accounts): t = PrettyTable(["Account", "Amount"]) t.align = "r" for a in accounts: account = Account(a, peerplays_instance=ctx.peerplays) for b in account.balances: t.add_row([str(a), str(b)]) click.echo(str(t))
[ " Show Account balances\n " ]
Please provide a description of the function:def newaccount(ctx, accountname, account, password): pprint( ctx.peerplays.create_account(accountname, registrar=account, password=password) )
[ " Create a new account\n " ]
Please provide a description of the function:def changememokey(ctx, key, account): pprint(ctx.blockchain.update_memo_key(key, account=account))
[ " Change the memo key of an account\n " ]
Please provide a description of the function:def approvewitness(ctx, witnesses, account): pprint(ctx.peerplays.approvewitness(witnesses, account=account))
[ " Approve witness(es)\n " ]
Please provide a description of the function:def disapprovewitness(ctx, witnesses, account): pprint(ctx.peerplays.disapprovewitness(witnesses, account=account))
[ " Disapprove witness(es)\n " ]
Please provide a description of the function:def on_open(self, ws): self.login(self.user, self.password, api_id=1) self.database(api_id=1) self.cancel_all_subscriptions() # Subscribe to events on the Backend and give them a # callback number that allows us to identify the event if len(self.on_object): self.set_subscribe_callback(self.__events__.index("on_object"), False) if len(self.on_tx): self.set_pending_transaction_callback(self.__events__.index("on_tx")) if len(self.on_block): self.set_block_applied_callback(self.__events__.index("on_block")) if self.subscription_accounts and self.on_account: # Unfortunately, account subscriptions don't have their own # callback number self.accounts = self.get_full_accounts(self.subscription_accounts, True) if self.subscription_markets and self.on_market: for market in self.subscription_markets: # Technially, every market could have it's own # callback number self.subscribe_to_market( self.__events__.index("on_market"), market[0], market[1] ) # We keep the connetion alive by requesting a short object def ping(self): while 1: log.debug("Sending ping") self.get_objects(["2.8.0"]) time.sleep(self.keep_alive) self.keepalive = threading.Thread(target=ping, args=(self,)) self.keepalive.start()
[ " This method will be called once the websocket connection is\n established. It will\n\n * login,\n * register to the database api, and\n * subscribe to the objects defined if there is a\n callback/slot available for callbacks\n " ]
Please provide a description of the function:def on_message(self, ws, reply, *args): log.debug("Received message: %s" % str(reply)) data = {} try: data = json.loads(reply, strict=False) except ValueError: raise ValueError("API node returned invalid format. Expected JSON!") if data.get("method") == "notice": id = data["params"][0] if id >= len(self.__events__): log.critical("Received an id that is out of range\n\n" + str(data)) return # This is a "general" object change notification if id == self.__events__.index("on_object"): # Let's see if a specific object has changed for notice in data["params"][1]: try: if "id" in notice: self.process_notice(notice) else: for obj in notice: if "id" in obj: self.process_notice(obj) except Exception as e: log.critical( "Error in process_notice: {}\n\n{}".format( str(e), traceback.format_exc ) ) else: try: callbackname = self.__events__[id] log.info("Patching through to call %s" % callbackname) [getattr(self.events, callbackname)(x) for x in data["params"][1]] except Exception as e: log.critical( "Error in {}: {}\n\n{}".format( callbackname, str(e), traceback.format_exc() ) )
[ " This method is called by the websocket connection on every\n message that is received. If we receive a ``notice``, we\n hand over post-processing and signalling of events to\n ``process_notice``.\n " ]
Please provide a description of the function:def on_close(self, ws): log.debug("Closing WebSocket connection with {}".format(self.url)) if self.keepalive and self.keepalive.is_alive(): self.keepalive.do_run = False self.keepalive.join()
[ " Called when websocket connection is closed\n " ]
Please provide a description of the function:def run_forever(self): cnt = 0 while True: cnt += 1 self.url = next(self.urls) log.debug("Trying to connect to node %s" % self.url) try: # websocket.enableTrace(True) self.ws = websocket.WebSocketApp( self.url, on_message=self.on_message, # on_data=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open, ) self.ws.run_forever() except websocket.WebSocketException as exc: if self.num_retries >= 0 and cnt > self.num_retries: raise NumRetriesReached() sleeptime = (cnt - 1) * 2 if cnt < 10 else 10 if sleeptime: log.warning( "Lost connection to node during wsconnect(): %s (%d/%d) " % (self.url, cnt, self.num_retries) + "Retrying in %d seconds" % sleeptime ) time.sleep(sleeptime) except KeyboardInterrupt: self.ws.keep_running = False raise except Exception as e: log.critical("{}\n\n{}".format(str(e), traceback.format_exc()))
[ " This method is used to run the websocket app continuously.\n It will execute callbacks as defined and try to stay\n connected with the provided APIs\n " ]
Please provide a description of the function:def set(ctx, key, value): if key == "default_account" and value[0] == "@": value = value[1:] ctx.blockchain.config[key] = value
[ " Set configuration parameters\n " ]
Please provide a description of the function:def disapproveproposal(ctx, proposal, account): pprint(ctx.peerplays.disapproveproposal(proposal, account=account))
[ " Disapprove a proposal\n " ]
Please provide a description of the function:def approveproposal(ctx, proposal, account): pprint(ctx.peerplays.approveproposal(proposal, account=account))
[ " Approve a proposal\n " ]
Please provide a description of the function:def proposals(ctx, account): proposals = Proposals(account) t = PrettyTable( [ "id", "expiration", "proposer", "required approvals", "available approvals", "review period time", "proposal", ] ) t.align = "l" for proposal in proposals: if proposal.proposer: proposer = Account(proposal.proposer, peerplays_instance=ctx.peerplays)[ "name" ] else: proposer = "n/a" t.add_row( [ proposal["id"], proposal["expiration_time"], proposer, [ Account(x)["name"] for x in ( proposal["required_active_approvals"] + proposal["required_owner_approvals"] ) ], json.dumps( [Account(x)["name"] for x in proposal["available_active_approvals"]] + proposal["available_key_approvals"] + proposal["available_owner_approvals"], indent=1, ), proposal.get("review_period_time", None), json.dumps(proposal["proposed_transaction"], indent=4), ] ) click.echo(str(t))
[ " List proposals\n " ]
Please provide a description of the function:def get_network(self): props = self.get_chain_properties() chain_id = props["chain_id"] for k, v in known_chains.items(): if v["chain_id"] == chain_id: return v raise Exception("Connecting to unknown network!")
[ " Identify the connected network. This call returns a\n dictionary with keys chain_id, core_symbol and prefix\n " ]
Please provide a description of the function:def sign(ctx, file, account): if not file: # click.echo("Prompting for message. Terminate with CTRL-D") file = click.get_text_stream("stdin") m = Message(file.read(), peerplays_instance=ctx.peerplays) click.echo(m.sign(account))
[ " Sign a message with an account\n " ]
Please provide a description of the function:def register_dataframe_method(method): def inner(*args, **kwargs): class AccessorMethod(object): def __init__(self, pandas_obj): self._obj = pandas_obj @wraps(method) def __call__(self, *args, **kwargs): return method(self._obj, *args, **kwargs) register_dataframe_accessor(method.__name__)(AccessorMethod) return method return inner()
[ "Register a function as a method attached to the Pandas DataFrame.\n\n Example\n -------\n\n .. code-block:: python\n\n @register_dataframe_method\n def print_column(df, col):\n '''Print the dataframe column given'''\n print(df[col])\n " ]
Please provide a description of the function:def register_series_method(method): def inner(*args, **kwargs): class AccessorMethod(object): __doc__ = method.__doc__ def __init__(self, pandas_obj): self._obj = pandas_obj @wraps(method) def __call__(self, *args, **kwargs): return method(self._obj, *args, **kwargs) register_series_accessor(method.__name__)(AccessorMethod) return method return inner()
[ "Register a function as a method attached to the Pandas Series.\n " ]
Please provide a description of the function:def add_invites_to_user(cls, user, amount): stat, _ = InvitationStat.objects.get_or_create(user=user) if stat.invites_allocated != -1: stat.invites_allocated += amount stat.save()
[ "\n Add the specified number of invites to current allocated total.\n " ]
Please provide a description of the function:def add_invites(cls, amount): for user in get_user_model().objects.all(): cls.add_invites_to_user(user, amount)
[ "\n Add invites for all users.\n " ]
Please provide a description of the function:def topoff_user(cls, user, amount): stat, _ = cls.objects.get_or_create(user=user) remaining = stat.invites_remaining() if remaining != -1 and remaining < amount: stat.invites_allocated += (amount - remaining) stat.save()
[ "\n Ensure user has a minimum number of invites.\n " ]
Please provide a description of the function:def topoff(cls, amount): for user in get_user_model().objects.all(): cls.topoff_user(user, amount)
[ "\n Ensure all users have a minimum number of invites.\n " ]
Please provide a description of the function:def hexdump( src, length=16, sep='.', start = 0): ''' @brief Return {src} in hex dump. @param[in] length {Int} Nb Bytes by row. @param[in] sep {Char} For the text part, {sep} will be used for non ASCII char. @return {Str} The hexdump @note Full support for python2 and python3 ! ''' result = []; # Python3 support try: xrange(0,1); except NameError: xrange = range; for i in xrange(0, len(src), length): subSrc = src[i:i+length]; hexa = ''; isMiddle = False; for h in xrange(0,len(subSrc)): if h == length/2: hexa += ' '; h = subSrc[h]; if not isinstance(h, int): h = ord(h); h = hex(h).replace('0x',''); if len(h) == 1: h = '0'+h; hexa += h+' '; hexa = hexa.strip(' '); text = ''; for c in subSrc: if not isinstance(c, int): c = ord(c); if 0x20 <= c < 0x7F: text += chr(c); else: text += sep; if start == 0: result.append(('%08x: %-'+str(length*(2+1)+1)+'s |%s|') % (i, hexa, text)); else: result.append(('%08x(+%04x): %-'+str(length*(2+1)+1)+'s |%s|') % (start+i, i, hexa, text)); return '\n'.join(result);
[]
Please provide a description of the function:def parse_mini(memory_decriptor, buff): mms = MinidumpMemorySegment() mms.start_virtual_address = memory_decriptor.StartOfMemoryRange mms.size = memory_decriptor.Memory.DataSize mms.start_file_address = memory_decriptor.Memory.Rva mms.end_virtual_address = mms.start_virtual_address + mms.size return mms
[ "\n\t\tmemory_descriptor: MINIDUMP_MEMORY_DESCRIPTOR\n\t\tbuff: file_handle\n\t\t" ]
Please provide a description of the function:def parse(mod, buff): mm = MinidumpUnloadedModule() mm.baseaddress = mod.BaseOfImage mm.size = mod.SizeOfImage mm.checksum = mod.CheckSum mm.timestamp = mod.TimeDateStamp mm.name = MINIDUMP_STRING.get_from_rva(mod.ModuleNameRva, buff) mm.endaddress = mm.baseaddress + mm.size return mm
[ "\n\t\tmod: MINIDUMP_MODULE\n\t\tbuff: file handle\n\t\t" ]
Please provide a description of the function:def seek(self, offset, whence = 0): if whence == 0: t = self.current_segment.start_address + offset elif whence == 1: t = self.current_position + offset elif whence == 2: t = self.current_segment.end_address - offset else: raise Exception('Seek function whence value must be between 0-2') if not self.current_segment.inrange(t): raise Exception('Seek would cross memory segment boundaries (use move)') self.current_position = t return
[ "\n\t\tChanges the current address to an offset of offset. The whence parameter controls from which position should we count the offsets.\n\t\t0: beginning of the current memory segment\n\t\t1: from current position\n\t\t2: from the end of the current memory segment\n\t\tIf you wish to move out from the segment, use the 'move' function\n\t\t" ]
Please provide a description of the function:def align(self, alignment = None): if alignment is None: if self.reader.sysinfo.ProcessorArchitecture == PROCESSOR_ARCHITECTURE.AMD64: alignment = 8 else: alignment = 4 offset = self.current_position % alignment if offset == 0: return offset_to_aligned = (alignment - offset) % alignment self.seek(offset_to_aligned, 1) return
[ "\n\t\tRepositions the current reader to match architecture alignment\n\t\t" ]
Please provide a description of the function:def peek(self, length): t = self.current_position + length if not self.current_segment.inrange(t): raise Exception('Would read over segment boundaries!') return self.current_segment.data[self.current_position - self.current_segment.start_address :t - self.current_segment.start_address]
[ "\n\t\tReturns up to length bytes from the current memory segment\n\t\t" ]
Please provide a description of the function:def read(self, size = -1): if size < -1: raise Exception('You shouldnt be doing this') if size == -1: t = self.current_segment.remaining_len(self.current_position) if not t: return None old_new_pos = self.current_position self.current_position = self.current_segment.end_address return self.current_segment.data[old_new_pos - self.current_segment.start_address:] t = self.current_position + size if not self.current_segment.inrange(t): raise Exception('Would read over segment boundaries!') old_new_pos = self.current_position self.current_position = t return self.current_segment.data[old_new_pos - self.current_segment.start_address :t - self.current_segment.start_address]
[ "\n\t\tReturns data bytes of size size from the current segment. If size is -1 it returns all the remaining data bytes from memory segment\n\t\t" ]
Please provide a description of the function:def find(self, pattern): pos = self.current_segment.data.find(pattern) if pos == -1: return -1 return pos + self.current_position
[ "\n\t\tSearches for a pattern in the current memory segment\n\t\t" ]
Please provide a description of the function:def find_all(self, pattern): pos = [] last_found = -1 while True: last_found = self.current_segment.data.find(pattern, last_found + 1) if last_found == -1: break pos.append(last_found + self.current_segment.start_address) return pos
[ "\n\t\tSearches for all occurrences of a pattern in the current memory segment, returns all occurrences as a list\n\t\t" ]
Please provide a description of the function:def find_global(self, pattern): pos_s = self.reader.search(pattern) if len(pos_s) == 0: return -1 return pos_s[0]
[ "\n\t\tSearches for the pattern in the whole process memory space and returns the first occurrence.\n\t\tThis is exhaustive!\n\t\t" ]
Please provide a description of the function:def report_privilege_information(): "Report all privilege information assigned to the current process." privileges = get_privilege_information() print("found {0} privileges".format(privileges.count)) tuple(map(print, privileges))
[]
Please provide a description of the function:async def handle(self): # For each channel, launch its own listening coroutine listeners = [] for key, value in self.beat_config.items(): listeners.append(asyncio.ensure_future( self.listener(key) )) # For each beat configuration, launch it's own sending pattern emitters = [] for key, value in self.beat_config.items(): emitters.append(asyncio.ensure_future( self.emitters(key, value) )) # Wait for them all to exit await asyncio.wait(emitters) await asyncio.wait(listeners)
[ "\n Listens on all the provided channels and handles the messages.\n " ]
Please provide a description of the function:async def emitters(self, key, value): while True: await asyncio.sleep(value['schedule'].total_seconds()) await self.channel_layer.send(key, { "type": value['type'], "message": value['message'] })
[ "\n Single-channel emitter\n " ]
Please provide a description of the function:async def listener(self, channel): while True: message = await self.channel_layer.receive(channel) if not message.get("type", None): raise ValueError("Worker received message with no type.") # Make a scope and get an application instance for it scope = {"type": "channel", "channel": channel} instance_queue = self.get_or_create_application_instance(channel, scope) # Run the message into the app await instance_queue.put(message)
[ "\n Single-channel listener\n " ]
Please provide a description of the function:def overall_rating(object, category=""): try: ct = ContentType.objects.get_for_model(object) if category: rating = OverallRating.objects.get( object_id=object.pk, content_type=ct, category=category_value(object, category) ).rating or 0 else: rating = OverallRating.objects.filter( object_id=object.pk, content_type=ct ).aggregate(r=models.Avg("rating"))["r"] rating = Decimal(str(rating or "0")) except OverallRating.DoesNotExist: rating = 0 return rating
[ "\n Usage:\n {% overall_rating obj [category] as var %}\n " ]
Please provide a description of the function:def rating_count(obj): count = Rating.objects.filter( object_id=obj.pk, content_type=ContentType.objects.get_for_model(obj), ).exclude(rating=0).count() return count
[ "\n Total amount of users who have submitted a positive rating for this object.\n\n Usage:\n {% rating_count obj %}\n " ]
Please provide a description of the function:def set_pixel(self, x, y, value): if x < 0 or x > 7 or y < 0 or y > 7: # Ignore out of bounds pixels. return # Set green LED based on 1st bit in value. self.set_led(y * 16 + x, 1 if value & GREEN > 0 else 0) # Set red LED based on 2nd bit in value. self.set_led(y * 16 + x + 8, 1 if value & RED > 0 else 0)
[ "Set pixel at position x, y to the given value. X and Y should be values\n of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW.\n " ]
Please provide a description of the function:def set_image(self, image): imwidth, imheight = image.size if imwidth != 8 or imheight != 8: raise ValueError('Image must be an 8x8 pixels in size.') # Convert image to RGB and grab all the pixels. pix = image.convert('RGB').load() # Loop through each pixel and write the display buffer pixel. for x in [0, 1, 2, 3, 4, 5, 6, 7]: for y in [0, 1, 2, 3, 4, 5, 6, 7]: color = pix[(x, y)] # Handle the color of the pixel. if color == (255, 0, 0): self.set_pixel(x, y, RED) elif color == (0, 255, 0): self.set_pixel(x, y, GREEN) elif color == (255, 255, 0): self.set_pixel(x, y, YELLOW) else: # Unknown color, default to LED off. self.set_pixel(x, y, OFF)
[ "Set display buffer to Python Image Library image. Red pixels (r=255,\n g=0, b=0) will map to red LEDs, green pixels (r=0, g=255, b=0) will map to\n green LEDs, and yellow pixels (r=255, g=255, b=0) will map to yellow LEDs.\n All other pixel values will map to an unlit LED value.\n " ]
Please provide a description of the function:def set_bar(self, bar, value): if bar < 0 or bar > 23: # Ignore out of bounds bars. return # Compute cathode and anode value. c = (bar if bar < 12 else bar - 12) // 4 a = bar % 4 if bar >= 12: a += 4 # Set green LED based on 1st bit in value. self.set_led(c*16+a+8, 1 if value & GREEN > 0 else 0) # Set red LED based on 2nd bit in value. self.set_led(c*16+a, 1 if value & RED > 0 else 0)
[ "Set bar to desired color. Bar should be a value of 0 to 23, and value\n should be OFF, GREEN, RED, or YELLOW.\n " ]
Please provide a description of the function:def animate(self, images, delay=.25): for image in images: # Draw the image on the display buffer. self.set_image(image) # Draw the buffer to the display hardware. self.write_display() time.sleep(delay)
[ "Displays each of the input images in order, pausing for \"delay\"\n seconds after each image.\n\n Keyword arguments:\n image -- An iterable collection of Image objects.\n delay -- How many seconds to wait after displaying an image before\n displaying the next one. (Default = .25)\n " ]
Please provide a description of the function:def set_pixel(self, x, y, value): if x < 0 or x > 7 or y < 0 or y > 15: # Ignore out of bounds pixels. return self.set_led((7 - x) * 16 + y, value)
[ "Set pixel at position x, y to the given value. X and Y should be values\n of 0 to 7 and 0 to 15, resp. Value should be 0 for off and non-zero for on.\n " ]
Please provide a description of the function:def set_image(self, image): imwidth, imheight = image.size if imwidth != 8 or imheight != 16: raise ValueError('Image must be an 8x16 pixels in size.') # Convert image to 1 bit color and grab all the pixels. pix = image.convert('1').load() # Loop through each pixel and write the display buffer pixel. for x in xrange(8): for y in xrange(16): color = pix[(x, y)] # Handle the color of the pixel, off or on. if color == 0: self.set_pixel(x, y, 0) else: self.set_pixel(x, y, 1)
[ "Set display buffer to Python Image Library image. Image will be converted\n to 1 bit color and non-zero color values will light the LEDs.\n " ]
Please provide a description of the function:def horizontal_scroll(self, image, padding=True): image_list = list() width = image.size[0] # Scroll into the blank image. if padding: for x in range(8): section = image.crop((0, 0, x, 16)) display_section = self.create_blank_image() display_section.paste(section, (8 - x, 0, 8, 16)) image_list.append(display_section) #Scroll across the input image. for x in range(8, width + 1): section = image.crop((x - 8, 0, x, 16)) display_section = self.create_blank_image() display_section.paste(section, (0, 0, 8, 16)) image_list.append(display_section) #Scroll out, leaving the blank image. if padding: for x in range(width - 7, width + 1): section = image.crop((x, 0, width, 16)) display_section = self.create_blank_image() display_section.paste(section, (0, 0, 7 - (x - (width - 7)), 16)) image_list.append(display_section) #Return the list of images created return image_list
[ "Returns a list of images which appear to scroll from left to right\n across the input image when displayed on the LED matrix in order.\n\n The input image is not limited to being 8x16. If the input image is\n larger than this, then all columns will be scrolled through but only\n the top 16 rows of pixels will be displayed.\n\n Keyword arguments:\n image -- The image to scroll across.\n padding -- If True, the animation will begin with a blank screen and the\n input image will scroll into the blank screen one pixel column at a\n time. Similarly, after scrolling across the whole input image, the\n end of the image will scroll out of a blank screen one column at a\n time. If this is not True, then only the input image will be scroll\n across without beginning or ending with \"whitespace.\"\n (Default = True)\n " ]
Please provide a description of the function:def vertical_scroll(self, image, padding=True): image_list = list() height = image.size[1] # Scroll into the blank image. if padding: for y in range(16): section = image.crop((0, 0, 8, y)) display_section = self.create_blank_image() display_section.paste(section, (0, 8 - y, 8, 16)) image_list.append(display_section) #Scroll across the input image. for y in range(16, height + 1): section = image.crop((0, y - 16, 8, y)) display_section = self.create_blank_image() display_section.paste(section, (0, 0, 8, 16)) image_list.append(display_section) #Scroll out, leaving the blank image. if padding: for y in range(height - 15, height + 1): section = image.crop((0, y, 8, height)) display_section = self.create_blank_image() display_section.paste(section, (0, 0, 8, 7 - (y - (height - 15)))) image_list.append(display_section) #Return the list of images created return image_list
[ "Returns a list of images which appear to scroll from top to bottom\n down the input image when displayed on the LED matrix in order.\n\n The input image is not limited to being 8x16. If the input image is\n largerthan this, then all rows will be scrolled through but only the\n left-most 8 columns of pixels will be displayed.\n\n Keyword arguments:\n image -- The image to scroll down.\n padding -- If True, the animation will begin with a blank screen and the\n input image will scroll into the blank screen one pixel row at a\n time. Similarly, after scrolling down the whole input image, the end\n of the image will scroll out of a blank screen one row at a time.\n If this is not True, then only the input image will be scroll down\n without beginning or ending with \"whitespace.\" (Default = True)\n " ]
Please provide a description of the function:def set_digit_raw(self, pos, bitmask): if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Set the digit bitmask value at the appropriate position. # Also set bit 7 (decimal point) if decimal is True. self.buffer[pos*2] = bitmask & 0xFF self.buffer[pos*2+1] = (bitmask >> 8) & 0xFF
[ "Set digit at position to raw bitmask value. Position should be a value\n of 0 to 3 with 0 being the left most digit on the display." ]
Please provide a description of the function:def set_decimal(self, pos, decimal): if pos < 0 or pos > 3: # Ignore out of bounds digits. return # Set bit 14 (decimal point) based on provided value. if decimal: self.buffer[pos*2+1] |= (1 << 6) else: self.buffer[pos*2+1] &= ~(1 << 6)
[ "Turn decimal point on or off at provided position. Position should be\n a value 0 to 3 with 0 being the left most digit on the display. Decimal\n should be True to turn on the decimal point and False to turn it off.\n " ]
Please provide a description of the function:def set_digit(self, pos, digit, decimal=False): self.set_digit_raw(pos, DIGIT_VALUES.get(str(digit), 0x00)) if decimal: self.set_decimal(pos, True)
[ "Set digit at position to provided value. Position should be a value\n of 0 to 3 with 0 being the left most digit on the display. Digit should\n be any ASCII value 32-127 (printable ASCII).\n " ]
Please provide a description of the function:def print_str(self, value, justify_right=True): # Calculcate starting position of digits based on justification. pos = (4-len(value)) if justify_right else 0 # Go through each character and print it on the display. for i, ch in enumerate(value): self.set_digit(i+pos, ch)
[ "Print a 4 character long string of values to the display. Characters\n in the string should be any ASCII value 32 to 127 (printable ASCII).\n " ]
Please provide a description of the function:def print_number_str(self, value, justify_right=True): # Calculate length of value without decimals. length = len(value.translate(None, '.')) # Error if value without decimals is longer than 4 characters. if length > 4: self.print_str('----') return # Calculcate starting position of digits based on justification. pos = (4-length) if justify_right else 0 # Go through each character and print it on the display. for i, ch in enumerate(value): if ch == '.': # Print decimal points on the previous digit. self.set_decimal(pos-1, True) else: self.set_digit(pos, ch) pos += 1
[ "Print a 4 character long string of numeric values to the display. This\n function is similar to print_str but will interpret periods not as\n characters but as decimal points associated with the previous character.\n " ]