INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Wait a little and then open a web browser page for the control panel.
def raw_opener(ip_address, port, delay=1): """ Wait a little and then open a web browser page for the control panel. """ def target(): time.sleep(delay) url = 'http://%s:%d' % (ip_address, port) webbrowser.open(url, new=0, autoraise=True) threading.Thread(target=target, daem...
Creates and starts the project.
def start(self, threaded): """Creates and starts the project.""" self.stop() self.__class__._INSTANCE = weakref.ref(self) self.is_running = True if threaded: self.thread = runnable.LoopThread() self.thread.run_once = self._target self.thread.s...
Stop the Runner if it s running. Called as a classmethod stop the running instance if any.
def stop(self): """ Stop the Runner if it's running. Called as a classmethod, stop the running instance if any. """ if self.is_running: log.info('Stopping') self.is_running = False self.__class__._INSTANCE = None try: ...
Display an image on a matrix.
def show_image(setter, width, height, image_path='', image_obj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on a matrix.""" bgcolor = color_scale(bgcolor, brightness) img = image_obj if image_path and not img: from PIL import Image ...
Display an image on the matrix
def showImage(layout, imagePath="", imageObj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on the matrix""" if not isinstance(layout, Matrix): raise RuntimeError("Must use Matrix with showImage!") layout.all_off() return show_image(layout.set, layo...
Display an image on the matrix
def loadImage(layout, imagePath="", imageObj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on the matrix""" if not isinstance(layout, Matrix): raise RuntimeError("Must use Matrix with loadImage!") texture = [[COLORS.Off for x in range(layout.width)] ...
Every other row is indexed in reverse.
def serpentine_x(x, y, matrix): """Every other row is indexed in reverse.""" if y % 2: return matrix.columns - 1 - x, y return x, y
Every other column is indexed in reverse.
def serpentine_y(x, y, matrix): """Every other column is indexed in reverse.""" if x % 2: return x, matrix.rows - 1 - y return x, y
Coerce a list into a list of triplets.
def to_triplets(colors): """ Coerce a list into a list of triplets. If `colors` is a list of lists or strings, return it as is. Otherwise, divide it into tuplets of length three, silently discarding any extra elements beyond a multiple of three. """ try: colors[0][0] return...
Return a Palette but don t take into account Pallete Names.
def colors_no_palette(colors=None, **kwds): """Return a Palette but don't take into account Pallete Names.""" if isinstance(colors, str): colors = _split_colors(colors) else: colors = to_triplets(colors or ()) colors = (color(c) for c in colors or ()) return palette.Palette(colors, ...
: param dict master: a multilevel dictionary: return: a flattened dictionary: rtype: dict
def flatten(master): """ :param dict master: a multilevel dictionary :return: a flattened dictionary :rtype: dict Flattens a multilevel dictionary into a single-level one so that:: {'foo': {'bar': { 'a': 1, 'b': True, ...
: param dict master: a multilevel dictionary: return: a unflattened dictionary: rtype: dict
def unflatten(master): """ :param dict master: a multilevel dictionary :return: a unflattened dictionary :rtype: dict Unflattens a single-level dictionary a multilevel into one so that:: {'foo.bar.a': 1, 'foo.bar.b': True, 'foo.bar.a': 1, } would become:: ...
Receives a message and either sets it immediately or puts it on the edit queue if there is one.
def receive(self, msg): """ Receives a message, and either sets it immediately, or puts it on the edit queue if there is one. """ if self.edit_queue: self.edit_queue.put_edit(self._set, msg) else: self._set(msg)
Helper method to generate X Y coordinate maps for strips
def make_matrix_coord_map( dx, dy, serpentine=True, offset=0, rotation=0, y_flip=False): """Helper method to generate X,Y coordinate maps for strips""" result = [] for y in range(dy): if not serpentine or y % 2 == 0: result.append([(dx * y) + x + offset for x in range(dx)]) ...
Make an object from a symbol.
def make_object(*args, typename=None, python_path=None, datatype=None, **kwds): """Make an object from a symbol.""" datatype = datatype or import_symbol(typename, python_path) field_types = getattr(datatype, 'FIELD_TYPES', fields.FIELD_TYPES) return datatype(*args, **fields.component(kwds, field_types))
For the duration of this context manager put the PID for this process into pid_filename and then remove the file at the end.
def pid_context(pid_filename=None): """ For the duration of this context manager, put the PID for this process into `pid_filename`, and then remove the file at the end. """ pid_filename = pid_filename or DEFAULT_PID_FILENAME if os.path.exists(pid_filename): contents = open(pid_filename)....
Return an integer index or None
def index(self, i, length=None): """Return an integer index or None""" if self.begin <= i <= self.end: index = i - self.BEGIN - self.offset if length is None: length = self.full_range() else: length = min(length, self.full_range()) ...
Returns a generator with the elements data taken by offset restricted by self. begin and self. end and padded on either end by pad to get back to the original length of data
def read_from(self, data, pad=0): """ Returns a generator with the elements "data" taken by offset, restricted by self.begin and self.end, and padded on either end by `pad` to get back to the original length of `data` """ for i in range(self.BEGIN, self.END + 1): ...
Cleans up all sorts of special cases that humans want when entering an animation from a yaml file.
def _clean_animation(desc, parent): """ Cleans up all sorts of special cases that humans want when entering an animation from a yaml file. 1. Loading it from a file 2. Using just a typename instead of a dict 3. A single dict representing an animation, with a run: section. 4. (Legacy) Having...
Given a list of animations some of which might have duplicate names rename the first one to be <duplicate > _0 the second <duplicate > _1 <duplicate > _2 etc.
def _make_names_unique(animations): """ Given a list of animations, some of which might have duplicate names, rename the first one to be <duplicate>_0, the second <duplicate>_1, <duplicate>_2, etc.""" counts = {} for a in animations: c = counts.get(a['name'], 0) + 1 counts[a['nam...
Give each animation a unique mutable layout so they can run independently.
def detach(self, overlay): """ Give each animation a unique, mutable layout so they can run independently. """ # See #868 for i, a in enumerate(self.animations): a.layout = a.layout.clone() if overlay and i: a.preclear = False
If a project has a Curses driver the section main in the section run must be bibliopixel. drivers. curses. Curses. main.
def main(): """ If a project has a Curses driver, the section "main" in the section "run" must be "bibliopixel.drivers.curses.Curses.main". """ if not _curses: # https://stackoverflow.com/a/1325587/43839 if os.name == 'nt': raise ValueErro...
Merge zero or more dictionaries representing projects with the default project dictionary and return the result
def merge(*projects): """ Merge zero or more dictionaries representing projects with the default project dictionary and return the result """ result = {} for project in projects: for name, section in (project or {}).items(): if name not in PROJECT_SECTIONS: ra...
Copy the instance and make sure not to use a reference
def copy(self): """ Copy the instance and make sure not to use a reference """ return self.__class__( amount=self["amount"], asset=self["asset"].copy(), blockchain_instance=self.blockchain, )
Returns the asset as instance of: class:. asset. Asset
def asset(self): """ Returns the asset as instance of :class:`.asset.Asset` """ if not self["asset"]: self["asset"] = self.asset_class( self["symbol"], blockchain_instance=self.blockchain ) return self["asset"]
Refresh/ Obtain an account s data from the API server
def refresh(self): """ Refresh/Obtain an account's data from the API server """ import re if re.match(r"^1\.2\.[0-9]*$", self.identifier): account = self.blockchain.rpc.get_objects([self.identifier])[0] else: account = self.blockchain.rpc.lookup_account_n...
List balances of an account. This call returns instances of: class: amount. Amount.
def balances(self): """ List balances of an account. This call returns instances of :class:`amount.Amount`. """ balances = self.blockchain.rpc.get_account_balances(self["id"], []) return [ self.amount_class(b, blockchain_instance=self.blockchain) for b...
Obtain the balance of a specific Asset. This call returns instances of: class: amount. Amount.
def balance(self, symbol): """ Obtain the balance of a specific Asset. This call returns instances of :class:`amount.Amount`. """ if isinstance(symbol, dict) and "symbol" in symbol: symbol = symbol["symbol"] balances = self.balances for b in balances: ...
Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a for loop.
def history(self, first=0, last=0, limit=-1, only_ops=[], exclude_ops=[]): """ Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a ``for`` loop. :param int first: sequence number of the first ...
Upgrade account to life time member
def upgrade(self): # pragma: no cover """ Upgrade account to life time member """ assert callable(self.blockchain.upgrade_account) return self.blockchain.upgrade_account(account=self)
Add an other account to the whitelist of this account
def whitelist(self, account): # pragma: no cover """ Add an other account to the whitelist of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=["white"], account=self)
Add an other account to the blacklist of this account
def blacklist(self, account): # pragma: no cover """ Add an other account to the blacklist of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=["black"], account=self)
Remove an other account from any list of this account
def nolist(self, account): # pragma: no cover """ Remove an other account from any list of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=[], account=self)
In oder to obtain the actual: class: account. Account from this class you can use the account attribute.
def account(self): """ In oder to obtain the actual :class:`account.Account` from this class, you can use the ``account`` attribute. """ account = self.account_class(self["owner"], blockchain_instance=self.blockchain) # account.refresh() return account
Recover the public key from the the signature
def recover_public_key(digest, signature, i, message=None): """ Recover the public key from the the signature """ # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily curve = ecdsa.SECP256k1.curve G = ecdsa.SECP256k1.generator order = ecdsa.SECP256k1.order yp = i ...
Use to derive a number that allows to easily recover the public key from the signature
def recoverPubkeyParameter(message, digest, signature, pubkey): """ Use to derive a number that allows to easily recover the public key from the signature """ if not isinstance(message, bytes): message = bytes(message, "utf-8") # pragma: no cover for i in range(0, 4): if SECP256...
Sign a digest with a wif key
def sign_message(message, wif, hashfn=hashlib.sha256): """ Sign a digest with a wif key :param str wif: Private key in """ if not isinstance(message, bytes): message = bytes(message, "utf-8") digest = hashfn(message).digest() priv_key = PrivateKey(wif) p = bytes(priv_key) ...
Auxiliary method to obtain ref_block_num and ref_block_prefix. Requires a websocket connection to a witness node!
def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = stru...
Properly Format Time that is x seconds in the future
def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() ...
Returns a datetime of the block with the given block number.
def block_time(self, block_num): """ Returns a datetime of the block with the given block number. :param int block_num: Block number """ return self.block_class(block_num, blockchain_instance=self.blockchain).time()
Returns the timestamp of the block with the given block number.
def block_timestamp(self, block_num): """ Returns the timestamp of the block with the given block number. :param int block_num: Block number """ return int( self.block_class(block_num, blockchain_instance=self.blockchain) .time() .time...
Yields blocks starting from start.
def blocks(self, start=None, stop=None): """ Yields blocks starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "head" (the last block) and "irreversible" (the block that i...
Get the desired block from the chain if the current head block is smaller ( for both head and irreversible ) then we wait but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before failure.
def wait_for_and_get_block(self, block_number, blocks_waiting_for=None): """ Get the desired block from the chain, if the current head block is smaller (for both head and irreversible) then we wait, but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before ...
Yields all operations ( excluding virtual operations ) starting from start.
def ops(self, start=None, stop=None, **kwargs): """ Yields all operations (excluding virtual operations) starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "h...
Yield specific operations ( e. g. comments ) only
def stream(self, opNames=[], *args, **kwargs): """ Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the ch...
Returns the transaction as seen by the blockchain after being included into a block
def awaitTxConfirmation(self, transaction, limit=10): """ Returns the transaction as seen by the blockchain after being included into a block .. note:: If you want instant confirmation, you need to instantiate class:`.blockchain.Blockchain` with ...
Yields account names between start and stop.
def get_all_accounts(self, start="", stop="", steps=1e3, **kwargs): """ Yields account names between start and stop. :param str start: Start at this account name :param str stop: Stop at this account name :param int steps: Obtain ``steps`` ret with a single call from RPC ...
Refresh the data from the API server
def refresh(self): """ Refresh the data from the API server """ asset = self.blockchain.rpc.get_asset(self.identifier) if not asset: raise AssetDoesNotExistsException(self.identifier) super(Asset, self).__init__(asset, blockchain_instance=self.blockchain) if s...
Update the Core Exchange Rate ( CER ) of an asset
def update_cer(self, cer, account=None, **kwargs): """ Update the Core Exchange Rate (CER) of an asset """ assert callable(self.blockchain.update_cer) return self.blockchain.update_cer( self["symbol"], cer, account=account, **kwargs )
Manual execute a command on API ( internally used )
def rpcexec(self, payload): """ Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises Unauthoriz...
Properly Format Time for permlinks
def formatTime(t): """ Properly Format Time for permlinks """ if isinstance(t, float): return datetime.utcfromtimestamp(t).strftime(timeFormat) if isinstance(t, datetime): return t.strftime(timeFormat)
Properly Format Time that is x seconds in the future
def formatTimeFromNow(secs=None): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return d...
Take a string representation of time from the blockchain and parse it into datetime object.
def parse_time(block_time): """Take a string representation of time from the blockchain, and parse it into datetime object. """ return datetime.strptime(block_time, timeFormat).replace(tzinfo=timezone.utc)
Convert an operation id into the corresponding string
def getOperationNameForId(i: int): """ Convert an operation id into the corresponding string """ assert isinstance(i, (int)), "This method expects an integer argument" for key in operations: if int(operations[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" ...
Is the store unlocked so that I can decrypt the content?
def unlocked(self): """ Is the store unlocked so that I can decrypt the content? """ if self.password is not None: return bool(self.password) else: if ( "UNLOCK" in os.environ and os.environ["UNLOCK"] and self.config...
The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database one must use BIP38 decrypt the masterpassword from the configuration store with the user password and use the decrypted masterpassword to decrypt the BIP38 encrypted private keys from the keys storage!
def unlock(self, password): """ The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database, one must use BIP38, decrypt the masterpassword from the configuration store with the user password, and use the decrypted masterpa...
Decrypt the encrypted masterkey
def _decrypt_masterpassword(self): """ Decrypt the encrypted masterkey """ aes = AESCipher(self.password) checksum, encrypted_master = self.config[self.config_key].split("$") try: decrypted_master = aes.decrypt(encrypted_master) except Exception: s...
Generate a new random masterkey encrypt it with the password and store it in the store.
def _new_masterpassword(self, password): """ Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption """ # make sure to not overwrite an existing key if self.config_key in s...
Derive the checksum
def _derive_checksum(self, s): """ Derive the checksum :param str s: Random string for which to derive the checksum """ checksum = hashlib.sha256(bytes(s, "ascii")).hexdigest() return checksum[:4]
Obtain the encrypted masterkey
def _get_encrypted_masterpassword(self): """ Obtain the encrypted masterkey .. note:: The encrypted masterkey is checksummed, so that we can figure out that a provided password is correct or not. The checksum is only 4 bytes long! """ if not self.unlo...
Change the password that allows to decrypt the master key
def change_password(self, newpassword): """ Change the password that allows to decrypt the master key """ if not self.unlocked(): raise WalletLocked self.password = newpassword self._save_encrypted_masterpassword()
Decrypt the content according to BIP38
def decrypt(self, wif): """ Decrypt the content according to BIP38 :param str wif: Encrypted key """ if not self.unlocked(): raise WalletLocked return format(bip38.decrypt(wif, self.masterkey), "wif")
Encrypt the content according to BIP38
def encrypt(self, wif): """ Encrypt the content according to BIP38 :param str wif: Unencrypted key """ if not self.unlocked(): raise WalletLocked return format(bip38.encrypt(str(wif), self.masterkey), "encwif")
Derive private key from the brain key and the current sequence number
def get_private(self): """ Derive private key from the brain key and the current sequence number """ encoded = "%s %d" % (self.brainkey, self.sequence) a = _bytes(encoded) s = hashlib.sha256(hashlib.sha512(a).digest()).digest() return PrivateKey(hexlify(s).dec...
Derive private key from the brain key ( and no sequence number )
def get_blind_private(self): """ Derive private key from the brain key (and no sequence number) """ a = _bytes(self.brainkey) return PrivateKey(hashlib.sha256(a).hexdigest(), prefix=self.prefix)
Suggest a new random brain key. Randomness is provided by the operating system using os. urandom ().
def suggest(): """ Suggest a new random brain key. Randomness is provided by the operating system using ``os.urandom()``. """ word_count = 16 brainkey = [None] * word_count dict_lines = BrainKeyDictionary.split(",") assert len(dict_lines) == 49744 for ...
Load an address provided the public key.
def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None): """ Load an address provided the public key. Version: 56 => PTS """ # Ensure this is a public key pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix) if compressed: pubkey_plai...
Derive address using RIPEMD160 ( SHA512 ( x ))
def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix) if compressed: pubkey_plain = pubkey.compressed() else: pubkey_plain = pubkey.uncompressed() "...
Derive y point from x point
def _derive_y_from_x(self, x, is_even): """ Derive y point from x point """ curve = ecdsa.SECP256k1.curve # The curve equation over F_p is: # y^2 = x^3 + ax + b a, b, p = curve.a(), curve.b(), curve.p() alpha = (pow(x, 3, p) + a * x + b) % p beta = ecdsa.numbert...
Return the point for the public key
def point(self): """ Return the point for the public key """ string = unhexlify(self.unCompressed()) return ecdsa.VerifyingKey.from_string( string[1:], curve=ecdsa.SECP256k1 ).pubkey.point
Derive new public key from this key and a sha256 offset
def child(self, offset256): """ Derive new public key from this key and a sha256 "offset" """ a = bytes(self) + offset256 s = hashlib.sha256(a).digest() return self.add(s)
Derive uncompressed public key
def from_privkey(cls, privkey, prefix=None): """ Derive uncompressed public key """ privkey = PrivateKey(privkey, prefix=prefix or Prefix.prefix) secret = unhexlify(repr(privkey)) order = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1 ).curve.generator.or...
Derive new private key from this private key and an arbitrary sequence number
def derive_private_key(self, sequence): """ Derive new private key from this private key and an arbitrary sequence number """ encoded = "%s %d" % (str(self), sequence) a = bytes(encoded, "ascii") s = hashlib.sha256(hashlib.sha512(a).digest()).digest() return P...
Derive new private key from this key and a sha256 offset
def child(self, offset256): """ Derive new private key from this key and a sha256 "offset" """ a = bytes(self.pubkey) + offset256 s = hashlib.sha256(a).digest() return self.derive_from_seed(s)
Derive private key using generate_from_seed method. Here the key itself serves as a seed and offset is expected to be a sha256 digest.
def derive_from_seed(self, offset): """ Derive private key using "generate_from_seed" method. Here, the key itself serves as a `seed`, and `offset` is expected to be a sha256 digest. """ seed = int(hexlify(bytes(self)).decode("ascii"), 16) z = int(hexlify(offset)....
Derive address using RIPEMD160 ( SHA256 ( x ))
def from_pubkey(cls, pubkey, compressed=False, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey) if compressed: pubkey = pubkey.compressed() else: pubkey = pubkey.uncompressed() """ Derive address using ``RIPEMD160(SHA256(...
Execute a call by sending the payload
def rpcexec(self, payload): """ Execute a call by sending the payload :param json payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises HttpInvalidStatusCode: if the server returns a status code...
Varint encoding
def varint(n): """ Varint encoding """ data = b"" while n >= 0x80: data += bytes([(n & 0x7F) | 0x80]) n >>= 7 data += bytes([n]) return data
Varint decoding
def varintdecode(data): # pragma: no cover """ Varint decoding """ shift = 0 result = 0 for b in bytes(data): result |= (b & 0x7F) << shift if not (b & 0x80): break shift += 7 return result
Claim a balance from the genesis block
def claim(self, account=None, **kwargs): """ Claim a balance from the genesis block :param str balance_id: The identifier that identifies the balance to claim (1.15.x) :param str account: (optional) the account that owns the bet (defaults to ``default_acc...
This method returns the default ** key ** store that uses an SQLite database internally.
def get_default_key_store(*args, config, **kwargs): """ This method returns the default **key** store that uses an SQLite database internally. :params str appname: The appname that is used internally to distinguish different SQLite files """ kwargs["appname"] = kwargs.get("appna...
Convert an operation id into the corresponding string
def getOperationNameForId(self, i): """ Convert an operation id into the corresponding string """ for key in self.ops: if int(self.ops[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" % i)
This method will initialize SharedInstance. instance and return it. The purpose of this method is to have offer single default instance that can be reused by multiple classes.
def shared_blockchain_instance(self): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default instance that can be reused by multiple classes. """ if not self._sharedInstance.instance: ...
This allows to set a config that will be used when calling shared_blockchain_instance and allows to define the configuration without requiring to actually create an instance
def set_shared_config(cls, config): """ This allows to set a config that will be used when calling ``shared_blockchain_instance`` and allows to define the configuration without requiring to actually create an instance """ assert isinstance(config, dict) cls._share...
Find the next url in the list
def find_next(self): """ Find the next url in the list """ if int(self.num_retries) < 0: # pragma: no cover self._cnt_retries += 1 sleeptime = (self._cnt_retries - 1) * 2 if self._cnt_retries < 10 else 10 if sleeptime: log.warning( ...
reset the failed connection counters
def reset_counter(self): """ reset the failed connection counters """ self._cnt_retries = 0 for i in self._url_counter: self._url_counter[i] = 0
Even though blocks never change you freshly obtain its contents from an API with this method
def refresh(self): """ Even though blocks never change, you freshly obtain its contents from an API with this method """ block = self.blockchain.rpc.get_block(self.identifier) if not block: raise BlockDoesNotExistsException super(Block, self).__init__( ...
Even though blocks never change you freshly obtain its contents from an API with this method
def refresh(self): """ Even though blocks never change, you freshly obtain its contents from an API with this method """ block = self.blockchain.rpc.get_block_header(self.identifier) if not block: raise BlockDoesNotExistsException super(BlockHeader, self)....
Is the key key available?
def _haveKey(self, key): """ Is the key `key` available? """ query = ( "SELECT {} FROM {} WHERE {}=?".format( self.__value__, self.__tablename__, self.__key__ ), (key,), ) connection = sqlite3.connect(self.sqlite_file) c...
returns all items off the store as tuples
def items(self): """ returns all items off the store as tuples """ query = "SELECT {}, {} from {}".format( self.__key__, self.__value__, self.__tablename__ ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(que...
Return the key if exists or a default value
def get(self, key, default=None): """ Return the key if exists or a default value :param str value: Value :param str default: Default value if key not present """ if key in self: return self.__getitem__(key) else: return default
Delete a key from the store
def delete(self, key): """ Delete a key from the store :param str value: Value """ query = ( "DELETE FROM {} WHERE {}=?".format(self.__tablename__, self.__key__), (key,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connec...
Wipe the store
def wipe(self): """ Wipe the store """ query = "DELETE FROM {}".format(self.__tablename__) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(query) connection.commit()
Check if the database table exists
def exists(self): """ Check if the database table exists """ query = ( "SELECT name FROM sqlite_master " + "WHERE type='table' AND name=?", (self.__tablename__,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() ...
Create the new table in the SQLite database
def create(self): # pragma: no cover """ Create the new table in the SQLite database """ query = ( """ CREATE TABLE {} ( id INTEGER PRIMARY KEY AUTOINCREMENT, {} STRING(256), {} STRING(256) )""" ).format...
Append op ( s ) to the transaction builder
def appendOps(self, ops, append_to=None): """ Append op(s) to the transaction builder :param list ops: One or a list of operations """ if isinstance(ops, list): self.ops.extend(ops) else: self.ops.append(ops) parent = self.parent if pa...
Returns an instance of base Operations for further processing
def get_raw(self): """ Returns an instance of base "Operations" for further processing """ if not self.ops: return ops = [self.operations.Op_wrapper(op=o) for o in list(self.ops)] proposer = self.account_class( self.proposer, blockchain_instance=self.block...
Show the transaction as plain json
def json(self): """ Show the transaction as plain json """ if not self._is_constructed() or self._is_require_reconstruction(): self.constructTx() return dict(self)
Try to obtain the wif key from the wallet by telling which account and permission is supposed to sign the transaction
def appendSigner(self, accounts, permission): """ Try to obtain the wif key from the wallet by telling which account and permission is supposed to sign the transaction """ assert permission in self.permission_types, "Invalid permission" if self.blockchain.wallet.locked(): ...
Add a wif that should be used for signing of the transaction.
def appendWif(self, wif): """ Add a wif that should be used for signing of the transaction. """ if wif: try: self.privatekey_class(wif) self.wifs.add(wif) except Exception: raise InvalidWifError