_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q256400 | toggle | validation | def toggle(s):
"""
Toggle back and forth between a name and a tuple representation.
:param str s: a string which is either a text name, or a tuple-string:
a string with three numbers separated by commas
:returns: if the string was a text name, return a tuple. If it's a
tuple-string and it corresponds to a text name, | python | {
"resource": ""
} |
q256401 | to_color | validation | def to_color(c):
"""Try to coerce the argument into a color - a 3-tuple of numbers-"""
if isinstance(c, numbers.Number):
return c, c, c
if not c:
raise ValueError('Cannot create color from empty "%s"' % c)
if isinstance(c, str):
return name_to_color(c)
if isinstance(c, list):
| python | {
"resource": ""
} |
q256402 | Animation.construct | validation | def construct(cls, project, *, run=None, name=None, data=None, **desc):
"""
Construct an animation, set the runner, and add in the two
"reserved fields" `name` and `data`.
"""
from . failed import Failed
exception = desc.pop('_exception', None)
if exception:
a = Failed(project.layout, desc, exception)
else:
try:
a = cls(project.layout, **desc)
| python | {
"resource": ""
} |
q256403 | convert_mode | validation | def convert_mode(image, mode='RGB'):
"""Return an image in the given mode."""
deprecated.deprecated('util.gif.convert_model')
| python | {
"resource": ""
} |
q256404 | image_to_colorlist | validation | def image_to_colorlist(image, container=list):
"""Given a PIL.Image, returns a ColorList | python | {
"resource": ""
} |
q256405 | animated_gif_to_colorlists | validation | def animated_gif_to_colorlists(image, container=list):
"""
Given an animated GIF, return a list with a colorlist for each frame.
"""
deprecated.deprecated('util.gif.animated_gif_to_colorlists')
from PIL import | python | {
"resource": ""
} |
q256406 | parse | validation | def parse(s):
"""
Parse a string representing a time interval or duration into seconds,
or raise an exception
:param str s: a string representation of a time interval
:raises ValueError: if ``s`` can't be interpreted as a duration
"""
parts = s.replace(',', ' ').split()
if not parts:
raise ValueError('Cannot parse empty string')
pieces = []
for part in parts:
m = PART_MATCH(part)
pieces.extend(m.groups() if m else [part])
if len(pieces) == 1:
pieces.append('s')
if len(pieces) % 2:
| python | {
"resource": ""
} |
q256407 | Runner.stop | validation | 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')
| python | {
"resource": ""
} |
q256408 | show_image | validation | 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
img = Image.open(image_path)
elif not img:
raise ValueError('Must provide either image_path or image_obj')
w = min(width - offset[0], img.size[0])
h = min(height - offset[1], img.size[1])
ox = offset[0]
oy = offset[1]
for x in range(ox, w + ox):
for y in range(oy, h + oy):
r, g, b, a = (0, 0, 0, 255)
rgba = img.getpixel((x - ox, y - oy))
if isinstance(rgba, int):
raise ValueError('Image must be in RGB or RGBA format!')
if len(rgba) == 3:
| python | {
"resource": ""
} |
q256409 | serpentine_x | validation | def serpentine_x(x, y, matrix):
"""Every other row is indexed in reverse."""
if y % 2:
| python | {
"resource": ""
} |
q256410 | serpentine_y | validation | def serpentine_y(x, y, matrix):
"""Every other column is indexed in reverse."""
if x % 2:
| python | {
"resource": ""
} |
q256411 | to_triplets | validation | 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]
| python | {
"resource": ""
} |
q256412 | colors_no_palette | validation | 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:
| python | {
"resource": ""
} |
q256413 | Editor.receive | validation | 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:
| python | {
"resource": ""
} |
q256414 | make_matrix_coord_map | validation | 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 + | python | {
"resource": ""
} |
q256415 | make_object | validation | 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)
| python | {
"resource": ""
} |
q256416 | pid_context | validation | 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).read(16)
| python | {
"resource": ""
} |
q256417 | OffsetRange.index | validation | 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 = | python | {
"resource": ""
} |
q256418 | OffsetRange.read_from | validation | 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`
"""
| python | {
"resource": ""
} |
q256419 | _clean_animation | validation | 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 a dict with parallel elements run: and animation:
5. (Legacy) A tuple or list: (animation, run )
"""
desc = load.load_if_filename(desc) or desc
if isinstance(desc, str):
animation = {'typename': desc}
elif not isinstance(desc, dict):
raise TypeError('Unexpected type %s in collection' % type(desc))
elif 'typename' in desc or 'animation' not in desc:
animation = desc
else:
animation = desc.pop('animation', {})
if isinstance(animation, str):
animation = {'typename': animation}
animation['run'] = desc.pop('run', {})
if desc:
| python | {
"resource": ""
} |
q256420 | Collection.detach | validation | 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):
| python | {
"resource": ""
} |
q256421 | Curses.main | validation | 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 ValueError('curses is not | python | {
"resource": ""
} |
q256422 | merge | validation | 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:
raise ValueError(UNKNOWN_SECTION_ERROR % name)
if section is None:
result[name] = type(result[name])()
continue
if name in NOT_MERGEABLE + SPECIAL_CASE:
result[name] = section
continue
if section and not isinstance(section, (dict, str)):
cname = section.__class__.__name__
raise ValueError(SECTION_ISNT_DICT_ERROR % (name, cname))
if name == 'animation':
# Useful hack to allow you to load projects as animations.
adesc = load.load_if_filename(section)
| python | {
"resource": ""
} |
q256423 | Amount.copy | validation | def copy(self):
""" Copy the instance and make sure not to use a reference
"""
return self.__class__(
amount=self["amount"],
| python | {
"resource": ""
} |
q256424 | Account.history | validation | 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
transaction to return (*optional*)
:param int last: sequence number of the last
transaction to return (*optional*)
:param int limit: limit number of transactions to
return (*optional*)
:param array only_ops: Limit generator by these
operations (*optional*)
:param array exclude_ops: Exclude these operations from
generator (*optional*).
... note::
only_ops and exclude_ops takes an array of strings:
The full list of operation ID's can be found in
operationids.py.
Example: ['transfer', 'fill_order']
"""
_limit = 100
cnt = 0
if first < 0:
first = 0
while True:
# RPC call
txs = self.blockchain.rpc.get_account_history(
self["id"],
"1.11.{}".format(last),
_limit,
"1.11.{}".format(first - 1),
api="history",
)
for i in txs:
if (
| python | {
"resource": ""
} |
q256425 | Account.upgrade | validation | def upgrade(self): # pragma: no cover
""" Upgrade account to life time member
"""
assert | python | {
"resource": ""
} |
q256426 | Account.whitelist | validation | def whitelist(self, account): # pragma: no cover
""" Add an other account to the whitelist of this account
"""
assert | python | {
"resource": ""
} |
q256427 | Account.blacklist | validation | def blacklist(self, account): # pragma: no cover
""" Add an other account to the blacklist of this account
"""
assert | python | {
"resource": ""
} |
q256428 | Account.nolist | validation | def nolist(self, account): # pragma: no cover
""" Remove an other account from any list of this account
"""
assert | python | {
"resource": ""
} |
q256429 | recover_public_key | validation | 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 % 2
r, s = ecdsa.util.sigdecode_string(signature, order)
# 1.1
x = r + (i // 2) * order
# 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified.
# This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve.
alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p()
beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p())
y = beta if (beta - yp) % 2 == 0 else curve.p() - beta
# 1.4 Constructor of Point is supposed to check if nR is at infinity.
R = ecdsa.ellipticcurve.Point(curve, x, y, order)
# 1.5 Compute e
e = ecdsa.util.string_to_number(digest)
# 1.6 Compute Q = r^-1(sR - eG)
Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G)
if SECP256K1_MODULE == "cryptography" and message is not None:
if not isinstance(message, bytes):
message = bytes(message, "utf-8") # pragma: no cover
sigder = encode_dss_signature(r, s)
| python | {
"resource": ""
} |
q256430 | recoverPubkeyParameter | validation | 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 SECP256K1_MODULE == "secp256k1": # pragma: no cover
sig = pubkey.ecdsa_recoverable_deserialize(signature, i)
p = secp256k1.PublicKey(pubkey.ecdsa_recover(message, sig))
if p.serialize() == pubkey.serialize():
return i
| python | {
"resource": ""
} |
q256431 | Blockchain.block_time | validation | def block_time(self, block_num):
""" Returns a datetime of the block with the given block
number.
:param int block_num: Block number
"""
| python | {
"resource": ""
} |
q256432 | Blockchain.block_timestamp | validation | 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(
| python | {
"resource": ""
} |
q256433 | Blockchain.blocks | validation | 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 is
confirmed by 2/3 of all block producers and is thus irreversible)
"""
# Let's find out how often blocks are generated!
self.block_interval = self.get_block_interval()
if not start:
start = self.get_current_block_num()
# We are going to loop indefinitely
while True:
# Get chain properies to identify the
if stop:
head_block = stop
else:
head_block = self.get_current_block_num()
# Blocks from start until head block | python | {
"resource": ""
} |
q256434 | Blockchain.awaitTxConfirmation | validation | 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
``mode="head"``, otherwise, the call will wait until
confirmed in an irreversible block.
.. note:: This method returns once the blockchain has included a
transaction with the **same signature**. Even though the
signature is not usually used to identify a transaction,
it still cannot be forfeited and is derived from the
transaction contented and thus identifies a transaction
| python | {
"resource": ""
} |
q256435 | Blockchain.get_all_accounts | validation | 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
"""
lastname = start
while True:
ret = self.blockchain.rpc.lookup_accounts(lastname, steps)
for account in ret:
| python | {
"resource": ""
} |
q256436 | Asset.refresh | validation | 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 self.full:
if "bitasset_data_id" in asset:
| python | {
"resource": ""
} |
q256437 | formatTime | validation | def formatTime(t):
""" Properly Format Time for permlinks
"""
if isinstance(t, float):
return | python | {
"resource": ""
} |
q256438 | parse_time | validation | def parse_time(block_time):
"""Take a string representation of time from the blockchain, and parse it
into datetime object.
""" | python | {
"resource": ""
} |
q256439 | MasterPassword.unlocked | validation | 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_key in self.config
and self.config[self.config_key]
):
| python | {
"resource": ""
} |
q256440 | MasterPassword.unlock | validation | 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
masterpassword to decrypt the BIP38 encrypted private keys
from the keys storage!
:param str password: Password to use for en-/de-cryption
"""
| python | {
"resource": ""
} |
q256441 | MasterPassword._decrypt_masterpassword | validation | 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:
| python | {
"resource": ""
} |
q256442 | MasterPassword._new_masterpassword | validation | 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 self.config and self.config[self.config_key]:
raise Exception("Storage already has a masterpassword!") | python | {
"resource": ""
} |
q256443 | MasterPassword._derive_checksum | validation | def _derive_checksum(self, s):
""" Derive the checksum
:param str s: Random string for which to derive the checksum
"""
| python | {
"resource": ""
} |
q256444 | MasterPassword._get_encrypted_masterpassword | validation | 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. | python | {
"resource": ""
} |
q256445 | MasterPassword.change_password | validation | def change_password(self, newpassword):
""" Change the password that allows to decrypt the master key
"""
if not self.unlocked():
raise WalletLocked
| python | {
"resource": ""
} |
q256446 | MasterPassword.decrypt | validation | def decrypt(self, wif):
""" Decrypt the content according to BIP38
:param str wif: Encrypted key | python | {
"resource": ""
} |
q256447 | MasterPassword.encrypt | validation | def encrypt(self, wif):
""" Encrypt the content according to BIP38
:param str wif: Unencrypted key
| python | {
"resource": ""
} |
q256448 | BrainKey.get_private | validation | 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)
| python | {
"resource": ""
} |
q256449 | Address.from_pubkey | validation | 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_plain = pubkey.compressed()
else:
| python | {
"resource": ""
} |
q256450 | PublicKey._derive_y_from_x | validation | 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) + | python | {
"resource": ""
} |
q256451 | PublicKey.point | validation | def point(self):
""" Return the point for the public key """
string = unhexlify(self.unCompressed())
return | python | {
"resource": ""
} |
q256452 | PublicKey.child | validation | def child(self, offset256):
""" Derive new public key from this key and a sha256 "offset" """
a = bytes(self) + offset256
| python | {
"resource": ""
} |
q256453 | PublicKey.from_privkey | validation | 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.order()
p = ecdsa.SigningKey.from_string(
secret, curve=ecdsa.SECP256k1
).verifying_key.pubkey.point
x_str = ecdsa.util.number_to_string(p.x(), order) | python | {
"resource": ""
} |
q256454 | PrivateKey.derive_private_key | validation | 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 | python | {
"resource": ""
} |
q256455 | PrivateKey.child | validation | def child(self, offset256):
""" Derive new private key from this key and a sha256 "offset"
"""
a | python | {
"resource": ""
} |
q256456 | PrivateKey.derive_from_seed | validation | 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).decode("ascii"), 16)
order = ecdsa.SECP256k1.order
secexp = (seed + | python | {
"resource": ""
} |
q256457 | GenesisBalance.claim | validation | 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_account``)
"""
if not account:
if "default_account" in self.blockchain.config:
account = self.blockchain.config["default_account"]
if not account:
raise ValueError("You need to provide an account")
account = self.account_class(account, blockchain_instance=self.blockchain)
pubkeys = self.blockchain.wallet.getPublicKeys()
addresses = dict()
for p in pubkeys:
if p[: len(self.blockchain.prefix)] != self.blockchain.prefix:
continue
pubkey = self.publickey_class(p, prefix=self.blockchain.prefix)
addresses[
str(
self.address_class.from_pubkey(
pubkey,
compressed=False,
version=0,
prefix=self.blockchain.prefix,
)
)
] = pubkey
addresses[
str(
self.address_class.from_pubkey(
pubkey,
compressed=True,
version=0,
prefix=self.blockchain.prefix,
)
)
] = pubkey
addresses[
str(
self.address_class.from_pubkey(
pubkey,
compressed=False,
version=56,
prefix=self.blockchain.prefix,
)
)
] = pubkey
addresses[
str(
self.address_class.from_pubkey(
pubkey,
compressed=True,
| python | {
"resource": ""
} |
q256458 | AbstractBlockchainInstanceProvider.shared_blockchain_instance | validation | 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.
"""
| python | {
"resource": ""
} |
q256459 | AbstractBlockchainInstanceProvider.set_shared_config | validation | 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)
| python | {
"resource": ""
} |
q256460 | Api.find_next | validation | 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(
"Lost connection to node during rpcexec(): %s (%d/%d) "
% (self.url, self._cnt_retries, self.num_retries)
+ "Retrying in %d seconds" % sleeptime
)
sleep(sleeptime)
return next(self.urls)
urls = [
k
for k, v in self._url_counter.items()
if (
# Only provide URLS if num_retries is bigger equal 0,
# i.e. we want to do reconnects at all
| python | {
"resource": ""
} |
q256461 | Api.reset_counter | validation | def reset_counter(self):
""" reset the failed connection counters
"""
self._cnt_retries = 0 | python | {
"resource": ""
} |
q256462 | SQLiteStore._haveKey | validation | def _haveKey(self, key):
""" Is the key `key` available?
"""
query = (
"SELECT {} FROM {} WHERE {}=?".format(
self.__value__, self.__tablename__, self.__key__
),
(key,),
| python | {
"resource": ""
} |
q256463 | SQLiteStore.items | validation | 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()
| python | {
"resource": ""
} |
q256464 | SQLiteStore.get | validation | 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
"""
| python | {
"resource": ""
} |
q256465 | SQLiteStore.delete | validation | def delete(self, key):
""" Delete a key from the store
:param str value: Value
"""
query = (
"DELETE FROM {} WHERE {}=?".format(self.__tablename__, | python | {
"resource": ""
} |
q256466 | SQLiteStore.exists | validation | 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)
| python | {
"resource": ""
} |
q256467 | SQLiteStore.create | validation | def create(self): # pragma: no cover
""" Create the new table in the SQLite database
"""
query = (
"""
CREATE TABLE {} (
id INTEGER PRIMARY KEY AUTOINCREMENT,
{} STRING(256),
{} | python | {
"resource": ""
} |
q256468 | ProposalBuilder.get_raw | validation | 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.blockchain
)
data = {
"fee": {"amount": 0, "asset_id": "1.3.0"},
"fee_paying_account": proposer["id"],
"expiration_time": formatTimeFromNow(self.proposal_expiration),
"proposed_ops": | python | {
"resource": ""
} |
q256469 | TransactionBuilder.json | validation | def json(self):
""" Show the transaction as plain json
"""
if not self._is_constructed() or | python | {
"resource": ""
} |
q256470 | TransactionBuilder.appendSigner | validation | 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():
raise WalletLocked()
if not isinstance(accounts, (list, tuple, set)):
accounts = [accounts]
for account in accounts:
# Now let's actually deal with the accounts
if account not in self.signing_accounts:
# is the account an instance of public key?
if isinstance(account, self.publickey_class):
self.appendWif(
self.blockchain.wallet.getPrivateKeyForPublicKey(str(account))
)
# ... or should we rather obtain the keys from an account name
else:
accountObj = self.account_class(
account, blockchain_instance=self.blockchain
| python | {
"resource": ""
} |
q256471 | TransactionBuilder.appendWif | validation | def appendWif(self, wif):
""" Add a wif that should be used for signing of the transaction.
"""
if wif:
try:
self.privatekey_class(wif)
| python | {
"resource": ""
} |
q256472 | TransactionBuilder.set_fee_asset | validation | def set_fee_asset(self, fee_asset):
""" Set asset to fee
"""
if isinstance(fee_asset, self.amount_class):
self.fee_asset_id = fee_asset["id"]
elif isinstance(fee_asset, self.asset_class):
| python | {
"resource": ""
} |
q256473 | TransactionBuilder.add_required_fees | validation | def add_required_fees(self, ops, asset_id="1.3.0"):
""" Auxiliary method to obtain the required fees for a set of
operations. Requires a websocket connection to a witness node!
"""
ws = self.blockchain.rpc
fees = ws.get_required_fees([i.json() for i in ops], asset_id)
for i, d in enumerate(ops):
if isinstance(fees[i], list):
# Operation is a proposal
ops[i].op.data["fee"] = Asset(
amount=fees[i][0]["amount"], asset_id=fees[i][0]["asset_id"]
)
for j, _ in enumerate(ops[i].op.data["proposed_ops"].data):
ops[i].op.data["proposed_ops"].data[j].data["op"].op.data[
"fee"
] = Asset(
| python | {
"resource": ""
} |
q256474 | TransactionBuilder.constructTx | validation | def constructTx(self):
""" Construct the actual transaction and store it in the class's dict
store
"""
ops = list()
for op in self.ops:
if isinstance(op, ProposalBuilder):
# This operation is a proposal an needs to be deal with
# differently
proposal = op.get_raw()
if proposal:
ops.append(proposal)
elif isinstance(op, self.operation_class):
ops.extend([op])
| python | {
"resource": ""
} |
q256475 | TransactionBuilder.verify_authority | validation | def verify_authority(self):
""" Verify the authority of the signed transaction
"""
try:
if not self.blockchain.rpc.verify_authority(self.json()):
| python | {
"resource": ""
} |
q256476 | TransactionBuilder.broadcast | validation | def broadcast(self):
""" Broadcast a transaction to the blockchain network
:param tx tx: Signed transaction to broadcast
"""
# Sign if not signed
if not self._is_signed():
self.sign()
# Cannot broadcast an empty transaction
if "operations" not in self or not self["operations"]:
log.warning("No operations in transaction! Returning")
return
# Obtain JS
ret = self.json()
# Debugging mode does not broadcast
if self.blockchain.nobroadcast:
log.warning("Not broadcasting anything!")
self.clear()
return | python | {
"resource": ""
} |
q256477 | TransactionBuilder.clear | validation | def clear(self):
""" Clear the transaction builder and start from scratch
"""
self.ops = []
self.wifs = set()
self.signing_accounts = []
| python | {
"resource": ""
} |
q256478 | Price.as_base | validation | def as_base(self, base):
""" Returns the price instance so that the base asset is ``base``.
Note: This makes a copy of the object!
"""
if base == self["base"]["symbol"]:
return self.copy()
| python | {
"resource": ""
} |
q256479 | Price.as_quote | validation | def as_quote(self, quote):
""" Returns the price instance so that the quote asset is ``quote``.
Note: This makes a copy of the object!
"""
if quote == self["quote"]["symbol"]:
return self.copy()
| python | {
"resource": ""
} |
q256480 | AbstractGrapheneChain.finalizeOp | validation | def finalizeOp(self, ops, account, permission, **kwargs):
""" This method obtains the required private keys if present in
the wallet, finalizes the transaction, signs it and
broadacasts it
:param operation ops: The operation (or list of operaions) to
broadcast
:param operation account: The account that authorizes the
operation
:param string permission: The required permission for
signing (active, owner, posting)
:param object append_to: This allows to provide an instance of
ProposalsBuilder (see :func:`new_proposal`) or
TransactionBuilder (see :func:`new_tx()`) to specify
where to put a specific operation.
... note:: ``append_to`` is exposed to every method used in the
this class
... note::
If ``ops`` is a list of operation, they all need to be
signable by the same key! Thus, you cannot combine ops
that require active permission with ops that require
posting permission. Neither can you use different
accounts for different operations!
... note:: This uses ``txbuffer`` as instance of
:class:`transactionbuilder.TransactionBuilder`.
You may want to use your own txbuffer
"""
if "append_to" in kwargs and kwargs["append_to"]:
if self.proposer:
log.warning(
"You may not use append_to and self.proposer at "
"the same time. Append new_proposal(..) instead"
)
# Append to the append_to and return
append_to = kwargs["append_to"]
parent = append_to.get_parent()
assert isinstance(
append_to, (self.transactionbuilder_class, self.proposalbuilder_class)
)
append_to.appendOps(ops)
# Add the signer to the buffer so we sign the tx properly
if isinstance(append_to, self.proposalbuilder_class):
parent.appendSigner(append_to.proposer, permission)
else:
parent.appendSigner(account, permission)
# This returns as we used append_to, it does NOT broadcast, or sign
| python | {
"resource": ""
} |
q256481 | AbstractGrapheneChain.broadcast | validation | def broadcast(self, tx=None):
""" Broadcast a transaction to the Blockchain
:param tx tx: Signed transaction to broadcast
"""
if tx:
# If tx is provided, we broadcast the tx
| python | {
"resource": ""
} |
q256482 | AbstractGrapheneChain.proposal | validation | def proposal(self, proposer=None, proposal_expiration=None, proposal_review=None):
""" Return the default proposal buffer
... note:: If any parameter is set, the default proposal
parameters will be changed!
"""
if not self._propbuffer:
return self.new_proposal(
self.tx(), proposer, proposal_expiration, proposal_review
)
if proposer:
self._propbuffer[0].set_proposer(proposer)
| python | {
"resource": ""
} |
q256483 | AbstractGrapheneChain.new_tx | validation | def new_tx(self, *args, **kwargs):
""" Let's obtain a new txbuffer
:returns int txid: id of the new txbuffer
| python | {
"resource": ""
} |
q256484 | AccountOptions.detail | validation | def detail(self, *args, **kwargs):
prefix = kwargs.pop("prefix", default_prefix)
# remove dublicates
kwargs["votes"] = list(set(kwargs["votes"]))
""" This is an example how to sort votes prior to using them in the
Object
"""
# # Sort votes
# kwargs["votes"] = sorted(
# kwargs["votes"],
# key=lambda x: float(x.split(":")[1]),
# )
return OrderedDict(
[
("memo_key", PublicKey(kwargs["memo_key"], prefix=prefix)),
| python | {
"resource": ""
} |
q256485 | Signed_Transaction.id | validation | def id(self):
""" The transaction id of this transaction
"""
# Store signatures temporarily since they are not part of
# transaction id
sigs = self.data["signatures"]
self.data.pop("signatures", None)
# Generage Hash of the seriliazed version
h = | python | {
"resource": ""
} |
q256486 | Signed_Transaction.sign | validation | def sign(self, wifkeys, chain=None):
""" Sign the transaction with the provided private keys.
:param array wifkeys: Array of wif keys
:param str chain: identifier for the chain
"""
if not chain:
chain = self.get_default_prefix()
self.deriveDigest(chain)
# Get Unique private keys
self.privkeys = []
for item in wifkeys:
if item not in self.privkeys:
self.privkeys.append(item)
| python | {
"resource": ""
} |
q256487 | Object.refresh | validation | def refresh(self):
""" This is the refresh method that overloads the prototype in
BlockchainObject.
"""
dict.__init__(
self,
| python | {
"resource": ""
} |
q256488 | encrypt | validation | def encrypt(privkey, passphrase):
""" BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.
:param privkey: Private key
:type privkey: Base58
:param str passphrase: UTF-8 encoded passphrase for encryption
:return: BIP0038 non-ec-multiply encrypted wif key
:rtype: Base58
"""
if isinstance(privkey, str):
privkey = PrivateKey(privkey)
else:
privkey = PrivateKey(repr(privkey))
privkeyhex = repr(privkey) # hex
addr = format(privkey.bitcoin.address, "BTC")
a = _bytes(addr)
salt = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
if SCRYPT_MODULE == "scrypt": # pragma: no cover
key = scrypt.hash(passphrase, salt, 16384, 8, 8)
elif SCRYPT_MODULE == "pylibscrypt": # pragma: no cover
key = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
else: # pragma: no cover
raise ValueError("No scrypt | python | {
"resource": ""
} |
q256489 | decrypt | validation | def decrypt(encrypted_privkey, passphrase):
"""BIP0038 non-ec-multiply decryption. Returns WIF privkey.
:param Base58 encrypted_privkey: Private key
:param str passphrase: UTF-8 encoded passphrase for decryption
:return: BIP0038 non-ec-multiply decrypted key
:rtype: Base58
:raises SaltException: if checksum verification failed (e.g. wrong
password)
"""
d = unhexlify(base58decode(encrypted_privkey))
d = d[2:] # remove trailing 0x01 and 0x42
flagbyte = d[0:1] # get flag byte
d = d[1:] # get payload
assert flagbyte == b"\xc0", "Flagbyte has to be 0xc0"
salt = d[0:4]
d = d[4:-4]
if SCRYPT_MODULE == "scrypt": # pragma: no cover
key = scrypt.hash(passphrase, salt, 16384, 8, 8)
elif SCRYPT_MODULE == "pylibscrypt": # pragma: no cover
key = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
else:
raise ValueError("No scrypt module loaded") # pragma: no cover
derivedhalf1 = | python | {
"resource": ""
} |
q256490 | Wallet.setKeys | validation | def setKeys(self, loadkeys):
""" This method is strictly only for in memory keys that are
passed to Wallet with the ``keys`` argument
"""
log.debug("Force setting of private keys. Not using the wallet database!")
if isinstance(loadkeys, dict):
loadkeys = list(loadkeys.values())
| python | {
"resource": ""
} |
q256491 | Wallet.unlock | validation | def unlock(self, pwd):
""" Unlock the wallet database
"""
if | python | {
"resource": ""
} |
q256492 | Wallet.newWallet | validation | def newWallet(self, pwd):
""" Create a new wallet database
"""
if self.created():
| python | {
"resource": ""
} |
q256493 | Wallet.addPrivateKey | validation | def addPrivateKey(self, wif):
""" Add a private key to the wallet database
"""
try:
pub = self.publickey_from_wif(wif)
except Exception:
raise InvalidWifError("Invalid Key format!")
if str(pub) in | python | {
"resource": ""
} |
q256494 | Wallet.getPrivateKeyForPublicKey | validation | def getPrivateKeyForPublicKey(self, pub):
""" Obtain the private key for a given public key
:param str | python | {
"resource": ""
} |
q256495 | Wallet.removeAccount | validation | def removeAccount(self, account):
""" Remove all keys associated with a given account
"""
| python | {
"resource": ""
} |
q256496 | Wallet.getOwnerKeyForAccount | validation | def getOwnerKeyForAccount(self, name):
""" Obtain owner Private Key for an account from the wallet database
"""
account = self.rpc.get_account(name)
for authority in account["owner"]["key_auths"]:
| python | {
"resource": ""
} |
q256497 | Wallet.getMemoKeyForAccount | validation | def getMemoKeyForAccount(self, name):
""" Obtain owner Memo Key for an account from the wallet database
"""
account = self.rpc.get_account(name)
| python | {
"resource": ""
} |
q256498 | Wallet.getActiveKeyForAccount | validation | def getActiveKeyForAccount(self, name):
""" Obtain owner Active Key for an account from the wallet database
"""
account = self.rpc.get_account(name)
for authority in account["active"]["key_auths"]:
try:
| python | {
"resource": ""
} |
q256499 | Wallet.getAccountFromPrivateKey | validation | def getAccountFromPrivateKey(self, wif):
""" Obtain account name from private key
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.