code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# Based on https://stackoverflow.com/a/45091961
if not isinstance(lst, (list, tuple)):
raise TypeError('lst must be a list or a tuple')
for num in lst:
if not isinstance(num, (int, str, float, complex)):
raise TypeError('lst can only be comprised of int, str, float, '
... | def entropy_bits(
lst: Union[
List[Union[int, str, float, complex]],
Tuple[Union[int, str, float, complex]]
]
) -> float | Calculate the number of entropy bits in a list or tuple of elements. | 2.98659 | 2.887028 | 1.034486 |
# Shannon:
# d = fabs(maximum - minimum)
# ent = -(1/d) * log(1/d, 2) * d
# Aprox form: log10(digits) * log2(10)
if not isinstance(minimum, (int, float)):
raise TypeError('minimum can only be int or float')
if not isinstance(maximum, (int, float)):
raise TypeError('maximum c... | def entropy_bits_nrange(
minimum: Union[int, float], maximum: Union[int, float]
) -> float | Calculate the number of entropy bits in a range of numbers. | 3.278912 | 3.141016 | 1.043902 |
if not isinstance(entropybits, (int, float)):
raise TypeError('entropybits can only be int or float')
if entropybits < 0:
raise ValueError('entropybits should be greater than 0')
if not isinstance(chars, str):
raise TypeError('chars can only be string')
if not chars:
... | def password_length_needed(entropybits: Union[int, float], chars: str) -> int | Calculate the length of a password for a given entropy and chars. | 3.740392 | 3.447525 | 1.08495 |
# Thanks to @julianor for this tip to calculate default amount of
# entropy: minbitlen/log2(len(wordlist)).
# I set the minimum entropy bits and calculate the amount of words
# needed, cosidering the entropy of the wordlist.
# Then: entropy_w * amount_w + entropy_n * amount_n >= ENTROPY_BITS_MI... | def words_amount_needed(entropybits: Union[int, float],
entropy_w: Union[int, float],
entropy_n: Union[int, float],
amount_n: int) -> int | Calculate words needed for a passphrase based on entropy. | 2.963369 | 2.917867 | 1.015594 |
if not isinstance(length, int):
raise TypeError('length can only be int')
if length < 0:
raise ValueError('length should be greater than 0')
if not isinstance(chars, str):
raise TypeError('chars can only be string')
if not chars:
raise ValueError("chars can't be null... | def password_entropy(length: int, chars: str) -> float | Calculate the entropy of a password with given length and chars. | 2.877481 | 2.628489 | 1.094728 |
if not isinstance(amount_w, int):
raise TypeError('amount_w can only be int')
if not isinstance(entropy_w, (int, float)):
raise TypeError('entropy_w can only be int or float')
if not isinstance(entropy_n, (int, float)):
raise TypeError('entropy_n can only be int or float')
i... | def passphrase_entropy(amount_w: int,
entropy_w: Union[int, float],
entropy_n: Union[int, float],
amount_n: int) -> float | Calculate the entropy of a passphrase with given words and numbers. | 1.405847 | 1.3601 | 1.033635 |
if not isinstance(lst, (tuple, list)):
raise TypeError('lst must be a list or a tuple')
size = len(lst)
if (
size == 2
and isinstance(lst[0], (int, float))
and isinstance(lst[1], (int, float))
):
return cal... | def entropy_bits(
lst: Union[
List[Union[int, str, float, complex]],
Tuple[Union[int, str, float, complex]]
]
) -> float | Calculate the entropy of a wordlist or a numerical range.
Keyword arguments:
lst -- A wordlist as list or tuple, or a numerical range as a list:
(minimum, maximum) | 2.775858 | 2.753253 | 1.00821 |
if not Aux.isfile_notempty(inputfile):
raise FileNotFoundError('Input file does not exists, is not valid '
'or is empty: {}'.format(inputfile))
self._wordlist_entropy_bits = None
if is_diceware:
self._wordlist = self._read_wor... | def import_words_from_file(self,
inputfile: str,
is_diceware: bool) -> None | Import words for the wordlist from a given file.
The file can have a single column with words or be diceware-like
(two columns).
Keyword arguments:
inputfile -- A string with the path to the wordlist file to load, or
the value 'internal' to load the internal one.
is_dic... | 4.342821 | 4.512818 | 0.96233 |
characters = self._get_password_characters()
if (
self.entropy_bits_req is None
or not characters
):
raise ValueError("Can't calculate the password length needed: "
"entropy_bits_req isn't set or the character "
... | def password_length_needed(self) -> int | Calculate the needed password length to satisfy the entropy number.
This is for the given character set. | 5.513143 | 4.846826 | 1.137475 |
if (
self.entropy_bits_req is None
or self.amount_n is None
or not self.wordlist
):
raise ValueError("Can't calculate the words amount needed: "
"wordlist is empty or entropy_bits_req or "
... | def words_amount_needed(self) -> int | Calculate the needed amount of words to satisfy the entropy number.
This is for the given wordlist. | 7.455226 | 7.123553 | 1.04656 |
characters = self._get_password_characters()
if (
self.passwordlen is None
or not characters
):
raise ValueError("Can't calculate the password entropy: character"
" set is empty or passwordlen isn't set")
... | def generated_password_entropy(self) -> float | Calculate the entropy of a password that would be generated. | 5.939548 | 5.433605 | 1.093114 |
if (
self.amount_w is None
or self.amount_n is None
or not self.wordlist
):
raise ValueError("Can't calculate the passphrase entropy: "
"wordlist is empty or amount_n or "
"amou... | def generated_passphrase_entropy(self) -> float | Calculate the entropy of a passphrase that would be generated. | 4.661321 | 4.579097 | 1.017956 |
if (
self.amount_n is None
or self.amount_w is None
or not self.wordlist
):
raise ValueError("Can't generate passphrase: "
"wordlist is empty or amount_n or "
"amount_w isn't se... | def generate(self, uppercase: int = None) -> list | Generate a list of words randomly chosen from a wordlist.
Keyword arguments:
uppercase -- An integer number indicating how many uppercase
characters are wanted: bigger than zero means that many characters and
lower than zero means all uppercase except that many. Use 0 to make
th... | 4.028912 | 3.855241 | 1.045048 |
characterset = self._get_password_characters()
if (
self.passwordlen is None
or not characterset
):
raise ValueError("Can't generate password: character set is "
"empty or passwordlen isn't set")
password ... | def generate_password(self) -> list | Generate a list of random characters. | 5.340353 | 4.910109 | 1.087624 |
# uuid4: 8-4-4-4-12: xxxxxxxx-xxxx-4xxx-{8,9,a,b}xxx-xxxxxxxxxxxx
# instead of requesting small amounts of bytes, it's better to do it
# for the full amount of them.
hexstr = randhex(30)
uuid4 = [
hexstr[:8],
hexstr[8:12],
'4' + hexst... | def generate_uuid4(self) -> list | Generate a list of parts of a UUID version 4 string.
Usually, these parts are concatenated together using dashes. | 6.007264 | 5.820076 | 1.032162 |
''' keystone assembler '''
ks_archs = {
'x16': (KS_ARCH_X86, KS_MODE_16),
'x86': (KS_ARCH_X86, KS_MODE_32),
'x64': (KS_ARCH_X86, KS_MODE_64),
'arm': (KS_ARCH_ARM, KS_MODE_ARM),
'arm_t': (KS_ARCH_ARM, KS_MOD... | def get_ks_archs(self) | keystone assembler | 1.569813 | 1.52162 | 1.031672 |
''' if no other commands was invoked '''
try:
encoding, count = self._ks.asm(line)
machine_code = ""
for opcode in encoding:
machine_code += "\\x" + hexlify(pack("B", opcode)).decode()
print("\"" + machine_code + "\"")
except KsErro... | def default(self, line) | if no other commands was invoked | 8.008586 | 6.623608 | 1.209097 |
ivalue = int(value)
if ivalue < 0:
raise ArgumentTypeError(
'{} should be bigger than 0'.format(ivalue)
)
return ivalue | def _bigger_than_zero(value: str) -> int | Type evaluator for argparse. | 4.368035 | 3.528007 | 1.238103 |
class NewPopupCreateView(PopupCreateView, cls.parent_class):
model = cls.model
form_class = cls.form_class
popup_name = cls.get_class_verbose_name()
template_name = cls.get_template_name_create()
permission_required = cls.get_permission_requi... | def create(cls) | Returns the create view that can be specified as the second argument
to url() in urls.py. | 3.175289 | 3.070535 | 1.034116 |
class NewPopupUpdateView(PopupUpdateView, cls.parent_class):
model = cls.model
form_class = cls.form_class
popup_name = cls.get_class_verbose_name()
template_name = cls.get_template_name_update()
permission_required = cls.get_permission_requi... | def update(cls) | Returns the update view that can be specified as the second argument
to url() in urls.py. | 3.241215 | 3.14002 | 1.032228 |
class PopupDeleteViewView(PopupDeleteView, cls.parent_class):
model = cls.model
form_class = cls.form_class
permission_required = cls.get_permission_required('delete')
return PopupDeleteViewView | def delete(cls) | Returns the delete view that can be specified as the second argument
to url() in urls.py. | 6.068975 | 5.413651 | 1.12105 |
class_name = cls.get_class_name()
if django.VERSION >= (2, 0):
return path('{}/'.format(class_name), include([
path('popup/', cls.create().as_view(), name='{}_popup_create'.format(class_name)),
path('popup/<int:pk>/', cls.update().as_view(), name='{}_... | def urls(cls) | generate url and url_name for create、update and delete view
default url_name is classname_name | 1.628907 | 1.565832 | 1.040282 |
kwargs['popup_name'] = cls.get_class_verbose_name()
kwargs['permissions_required'] = cls.permissions_required
if cls.template_name_fk is not None:
kwargs['template_name'] = cls.template_name_fk
return ForeignKeyWidget('{}_popup_create'.format(cls.get_class_name()), *... | def get_fk_popup_field(cls, *args, **kwargs) | generate fk field related to class wait popup crud | 4.154147 | 3.857033 | 1.077032 |
kwargs['popup_name'] = cls.get_class_verbose_name()
kwargs['permissions_required'] = cls.permissions_required
if cls.template_name_m2m is not None:
kwargs['template_name'] = cls.template_name_m2m
return ManyToManyWidget('{}_popup_create'.format(cls.get_class_name()),... | def get_m2m_popup_field(cls, *args, **kwargs) | generate m2m field related to class wait popup crud | 4.228741 | 3.931555 | 1.07559 |
return ''.join([c if c.islower() else '' for c in str(string)]) | def lowercase_chars(string: any) -> str | Return all (and only) the lowercase chars in the given string. | 5.205045 | 3.430898 | 1.517109 |
return ''.join([c if c.isupper() else '' for c in str(string)]) | def uppercase_chars(string: any) -> str | Return all (and only) the uppercase chars in the given string. | 5.273594 | 3.3297 | 1.583805 |
return ''.join([c if c.isalpha() else '' for c in str(string)]) | def chars(string: any) -> str | Return all (and only) the chars in the given string. | 5.38225 | 3.896321 | 1.381367 |
if not isinstance(lst, (list, tuple, str, set)):
raise TypeError('lst must be a list, a tuple, a set or a string')
if isinstance(lst, str):
return lst.upper()
arr = list(lst)
# enumerate is 70% slower than range
# for i in range(len(lst)):
... | def make_all_uppercase(
lst: Union[list, tuple, str, set]
) -> Union[list, tuple, str, set] | Make all characters uppercase.
It supports characters in a (mix of) list, tuple, set or string.
The return value is of the same type of the input value. | 2.286096 | 2.255358 | 1.013629 |
if not isinstance(string, str):
raise TypeError('string must be a string')
if Aux.lowercase_count(string) > 0:
while True:
cindex = randbelow(len(string))
if string[cindex].islower():
aux = list(string)
... | def _make_one_char_uppercase(string: str) -> str | Make a single char from the string uppercase. | 3.831022 | 3.324231 | 1.152454 |
if not isinstance(lst, (list, tuple, str, set)):
raise TypeError('lst must be a list, a tuple, a set or a string')
if not isinstance(uppercase, int):
raise TypeError('uppercase must be an integer')
if uppercase < 0:
raise ValueError('uppercase must be... | def make_chars_uppercase(
lst: Union[list, tuple, str, set],
uppercase: int
) -> Union[list, tuple, str, set] | Make uppercase some randomly selected characters.
The characters can be in a (mix of) string, list, tuple or set.
Keyword arguments:
lst -- the object to make all chars uppercase, which can be a (mix of)
list, tuple, string or set.
uppercase -- Number of characters to be set as... | 2.904591 | 2.923396 | 0.993567 |
try:
return isfile(inputfile) and getsize(inputfile) > 0
except TypeError:
raise TypeError('inputfile is not a valid type') | def isfile_notempty(inputfile: str) -> bool | Check if the input filename with path is a file and is not empty. | 4.617228 | 3.610932 | 1.278681 |
arg = ['cat', '/proc/sys/kernel/random/entropy_avail']
proc = Popen(arg, stdout=PIPE, stderr=DEVNULL)
response = proc.communicate()[0]
return int(response) if response else -1 | def system_entropy() | Return the system's entropy bit count, or -1 if unknown. | 4.204085 | 3.421923 | 1.228574 |
inputs, total_amount = self._collect_uncolored_outputs(
issuance_spec.unspent_outputs, 2 * self._dust_amount + fees)
return bitcoin.core.CTransaction(
vin=[bitcoin.core.CTxIn(item.out_point, item.output.script) for item in inputs],
vout=[
sel... | def issue(self, issuance_spec, metadata, fees) | Creates a transaction for issuing an asset.
:param TransferParameters issuance_spec: The parameters of the issuance.
:param bytes metadata: The metadata to be embedded in the transaction.
:param int fees: The fees to include in the transaction.
:return: An unsigned transaction for issui... | 4.916887 | 5.07696 | 0.968471 |
inputs = []
outputs = []
asset_quantities = []
for asset_id, transfer_spec in asset_transfer_specs:
colored_outputs, collected_amount = self._collect_colored_outputs(
transfer_spec.unspent_outputs, asset_id, transfer_spec.amount)
inputs.ex... | def transfer(self, asset_transfer_specs, btc_transfer_spec, fees) | Creates a transaction for sending assets and bitcoins.
:param list[(bytes, TransferParameters)] asset_transfer_specs: A list of tuples. In each tuple:
- The first element is the ID of an asset.
- The second element is the parameters of the transfer.
:param TransferParameters btc... | 2.546211 | 2.48616 | 1.024154 |
return self.transfer(
[(asset_id, transfer_spec)],
TransferParameters(transfer_spec.unspent_outputs, None, btc_change_script, 0),
fees) | def transfer_assets(self, asset_id, transfer_spec, btc_change_script, fees) | Creates a transaction for sending an asset.
:param bytes asset_id: The ID of the asset being sent.
:param TransferParameters transfer_spec: The parameters of the asset being transferred.
:param bytes btc_change_script: The script where to send bitcoin change, if any.
:param int fees: Th... | 6.331794 | 6.243726 | 1.014105 |
return self.transfer([(asset_id, asset_transfer_spec)], btc_transfer_spec, fees) | def btc_asset_swap(self, btc_transfer_spec, asset_id, asset_transfer_spec, fees) | Creates a transaction for swapping assets for bitcoins.
:param TransferParameters btc_transfer_spec: The parameters of the bitcoins being transferred.
:param bytes asset_id: The ID of the asset being sent.
:param TransferParameters asset_transfer_spec: The parameters of the asset being transfer... | 4.777326 | 7.7391 | 0.617297 |
btc_transfer_spec = TransferParameters(
asset1_transfer_spec.unspent_outputs, asset1_transfer_spec.to_script, asset1_transfer_spec.change_script, 0)
return self.transfer(
[(asset1_id, asset1_transfer_spec), (asset2_id, asset2_transfer_spec)], btc_transfer_spec, fees) | def asset_asset_swap(
self, asset1_id, asset1_transfer_spec, asset2_id, asset2_transfer_spec, fees) | Creates a transaction for swapping an asset for another asset.
:param bytes asset1_id: The ID of the first asset.
:param TransferParameters asset1_transfer_spec: The parameters of the first asset being transferred.
It is also used for paying fees and/or receiving change if any.
:par... | 3.969683 | 3.777203 | 1.050958 |
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id is None:
result.append(output)
total_amount += output.output.value
if total_amount >= amount:
return result, total_amount
... | def _collect_uncolored_outputs(unspent_outputs, amount) | Returns a list of uncolored outputs for the specified amount.
:param list[SpendableOutput] unspent_outputs: The list of available outputs.
:param int amount: The amount to collect.
:return: A list of outputs, and the total amount collected.
:rtype: (list[SpendableOutput], int) | 3.046755 | 2.846837 | 1.070225 |
total_amount = 0
result = []
for output in unspent_outputs:
if output.output.asset_id == asset_id:
result.append(output)
total_amount += output.output.asset_quantity
if total_amount >= asset_quantity:
return result... | def _collect_colored_outputs(unspent_outputs, asset_id, asset_quantity) | Returns a list of colored outputs for the specified quantity.
:param list[SpendableOutput] unspent_outputs: The list of available outputs.
:param bytes asset_id: The ID of the asset to collect.
:param int asset_quantity: The asset quantity to collect.
:return: A list of outputs, and the... | 2.800601 | 2.649385 | 1.057076 |
if value < self._dust_amount:
raise DustOutputError
return bitcoin.core.CTxOut(value, bitcoin.core.CScript(script)) | def _get_uncolored_output(self, script, value) | Creates an uncolored output.
:param bytes script: The output script.
:param int value: The satoshi value of the output.
:return: An object representing the uncolored output.
:rtype: TransactionOutput | 13.814804 | 8.416681 | 1.64136 |
return bitcoin.core.CTxOut(self._dust_amount, bitcoin.core.CScript(script)) | def _get_colored_output(self, script) | Creates a colored output.
:param bytes script: The output script.
:return: An object representing the colored output.
:rtype: TransactionOutput | 12.723192 | 11.438985 | 1.112266 |
payload = openassets.protocol.MarkerOutput(asset_quantities, metadata).serialize_payload()
script = openassets.protocol.MarkerOutput.build_script(payload)
return bitcoin.core.CTxOut(0, script) | def _get_marker_output(self, asset_quantities, metadata) | Creates a marker output.
:param list[int] asset_quantities: The asset quantity list.
:param bytes metadata: The metadata contained in the output.
:return: An object representing the marker output.
:rtype: TransactionOutput | 8.265475 | 7.240698 | 1.14153 |
app.add_url_rule(self.request_token_url, view_func=self.request_token,
methods=[u'POST'])
app.add_url_rule(self.access_token_url, view_func=self.access_token,
methods=[u'POST'])
app.add_url_rule(self.register_url, view_func=self.register... | def init_app(self, app) | Setup the 4 default routes. | 1.657782 | 1.578782 | 1.050038 |
verifier = generate_token(length=self.verifier_length[1])
self.save_verifier(request_token, verifier)
response = [
(u'oauth_token', request_token),
(u'oauth_verifier', verifier)
]
callback = self.get_callback(request_token)
return redirect... | def authorized(self, request_token) | Create a verifier for an user authorized client | 3.975831 | 3.460546 | 1.148903 |
client_key = request.oauth.client_key
realm = request.oauth.realm
# TODO: fallback on default realm?
callback = request.oauth.callback_uri
request_token = generate_token(length=self.request_token_length[1])
token_secret = generate_token(length=self.secret_length)... | def request_token(self) | Create an OAuth request token for a valid client request.
Defaults to /request_token. Invoked by client applications. | 3.577744 | 3.368348 | 1.062166 |
access_token = generate_token(length=self.access_token_length[1])
token_secret = generate_token(self.secret_length)
client_key = request.oauth.client_key
self.save_access_token(client_key, access_token,
request.oauth.resource_owner_key, secret=token_secret)
r... | def access_token(self) | Create an OAuth access token for an authorized client.
Defaults to /access_token. Invoked by client applications. | 4.025078 | 3.801943 | 1.05869 |
def decorator(f):
@wraps(f)
def verify_request(*args, **kwargs):
try:
if request.form:
body = request.form.to_dict()
else:
body = request.data.decode("utf-8"... | def require_oauth(self, realm=None, require_resource_owner=True,
require_verifier=False, require_realm=False) | Mark the view function f as a protected resource | 4.375029 | 4.41165 | 0.991699 |
class OAuthParameters(object):
pass
# Collect parameters
query = urlparse(request.url.decode("utf-8")).query
content_type = request.headers.get('Content-Type', '')
if request.form:
body = request.form.to_dict()
elif content_... | def collect_request_parameters(self, request) | Collect parameters in an object for convenient access | 2.62306 | 2.556548 | 1.026016 |
crc32 = binascii.crc32(name.encode())
if crc32 in self.crc32_map:
return self.crc32_map[crc32]
if name in self.name_map:
return self.name_map[name]
return 0 | def get_size(self, name: str) -> int | Get a resource size from the RSTB. | 2.932334 | 2.513747 | 1.166519 |
if self._needs_to_be_in_name_map(name):
if len(name) >= 128:
raise ValueError("Name is too long")
self.name_map[name] = size
else:
crc32 = binascii.crc32(name.encode())
self.crc32_map[crc32] = size | def set_size(self, name: str, size: int) | Set the size of a resource in the RSTB. | 4.072768 | 3.786696 | 1.075546 |
stream.write(b'RSTB')
stream.write(_to_u32(len(self.crc32_map), be))
stream.write(_to_u32(len(self.name_map), be))
# The CRC32 hashmap *must* be sorted because the game performs a binary search.
for crc32, size in sorted(self.crc32_map.items()):
stream.write... | def write(self, stream: typing.BinaryIO, be: bool) -> None | Write the RSTB to the specified stream. | 3.305374 | 2.974645 | 1.111183 |
r
if not isinstance(nbytes, int):
raise TypeError('number of bytes shoud be an integer')
if nbytes <= 0:
raise ValueError('number of bytes must be greater than zero')
return _urandom(nbytes) | def randbytes(nbytes: int) -> bytes | r"""Return a random byte string containing *nbytes* bytes.
Raises ValueError if nbytes <= 0, and TypeError if it's not an integer.
>>> randbytes(16) #doctest:+SKIP
b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b' | 4.168032 | 4.435972 | 0.939598 |
if not isinstance(nbits, int):
raise TypeError('number of bits should be an integer')
if nbits <= 0:
raise ValueError('number of bits must be greater than zero')
# https://github.com/python/cpython/blob/3.6/Lib/random.py#L676
nbytes = (nbits + 7) // 8 # bits /... | def randint(nbits: int) -> int | Generate an int with nbits random bits.
Raises ValueError if nbits <= 0, and TypeError if it's not an integer.
>>> randint(16) #doctest:+SKIP
1871 | 2.714029 | 2.826812 | 0.960103 |
if not isinstance(seq, (str, list, tuple, dict, set)):
raise TypeError('seq must be str, list, tuple, dict or set')
if len(seq) <= 0:
raise IndexError('seq must have at least one element')
if isinstance(seq, set):
values = list(seq)
return randchoice(values)
elif is... | def randchoice(seq: Union[str, list, tuple, dict, set]) -> any | Return a randomly chosen element from the given sequence.
Raises TypeError if *seq* is not str, list, tuple, dict, set and an
IndexError if it is empty.
>>> randchoice((1, 2, 'a', 'b')) #doctest:+SKIP
'a' | 2.360066 | 2.430674 | 0.970951 |
if not isinstance(num, int):
raise TypeError('number must be an integer')
if num <= 0:
raise ValueError('number must be greater than zero')
if num == 1:
return 0
# https://github.com/python/cpython/blob/3.6/Lib/random.py#L223
nbits = num.bit_length() # don't use (n-1... | def randbelow(num: int) -> int | Return a random int in the range [0,num).
Raises ValueError if num <= 0, and TypeError if it's not an integer.
>>> randbelow(16) #doctest:+SKIP
13 | 2.840461 | 2.908553 | 0.976589 |
if not isinstance(lower, int) or not isinstance(upper, int):
raise TypeError('lower and upper must be integers')
if lower < 0 or upper <= 0:
raise ValueError('lower and upper must be greater than zero')
return randbelow(upper - lower + 1) + lower | def randbetween(lower: int, upper: int) -> int | Return a random int in the range [lower, upper].
Raises ValueError if any is lower than 0, and TypeError if any is not an
integer. | 2.321871 | 2.214787 | 1.04835 |
if not isinstance(ndigits, int):
raise TypeError('number of digits must be an integer')
if ndigits <= 0:
raise ValueError('number of digits must be greater than zero')
nbytes = ceil(ndigits / 2)
rbytes = random_randbytes(nbytes)
hexstr = rbytes.hex()[:ndigits]
return hexst... | def randhex(ndigits: int) -> str | Return a random text string of hexadecimal characters.
The string has *ndigits* random digits.
Raises ValueError if ndigits <= 0, and TypeError if it's not an integer.
>>> randhex(16) #doctest:+SKIP
'56054d728fc56f63' | 2.681811 | 2.780298 | 0.964577 |
''' capstone disassembler '''
cs_archs = {
'x16': (CS_ARCH_X86, CS_MODE_16),
'x86': (CS_ARCH_X86, CS_MODE_32),
'x64': (CS_ARCH_X86, CS_MODE_64),
'arm': (CS_ARCH_ARM, CS_MODE_ARM),
'arm_t': (CS_ARCH_ARM, CS_... | def get_cs_archs(self) | capstone disassembler | 1.765425 | 1.706611 | 1.034463 |
''' if no other command was invoked '''
try:
for i in self._cs.disasm(unhexlify(self.cleanup(user_input)), self.base_address):
print("0x%08x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))
except CsError as e:
print("Error: %s" %e) | def default(self, user_input) | if no other command was invoked | 4.543686 | 3.791651 | 1.19834 |
self._setProperty('_NET_ACTIVE_WINDOW', [1, X.CurrentTime, win.id],
win) | def setActiveWindow(self, win) | Set the given window active (property _NET_ACTIVE_WINDOW)
:param win: the window object | 25.792185 | 17.945114 | 1.437282 |
self._setProperty('_NET_CLOSE_WINDOW',
[int(time.mktime(time.localtime())), 1], win) | def setCloseWindow(self, win) | Close the given window (property _NET_CLOSE_WINDOW)
:param win: the window object | 15.376503 | 10.214655 | 1.505337 |
# indicate source (application)
gravity_flags = gravity | 0b0000100000000000
if x is None:
x = 0
else:
gravity_flags = gravity_flags | 0b0000010000000000
if y is None:
y = 0
else:
gravity_flags = gravity_flags | 0b0... | def setMoveResizeWindow(self, win, gravity=0, x=None, y=None, w=None,
h=None) | Set the property _NET_MOVERESIZE_WINDOW to move or resize the given
window. Flags are automatically calculated if x, y, w or h are defined.
:param win: the window object
:param gravity: gravity (one of the Xlib.X.*Gravity constant or 0)
:param x: int or None
:param y: int or Non... | 1.948997 | 1.801164 | 1.082076 |
if type(state) != int:
state = self.display.get_atom(state, 1)
if type(state2) != int:
state2 = self.display.get_atom(state2, 1)
self._setProperty('_NET_WM_STATE', [action, state, state2, 1], win) | def setWmState(self, win, action, state, state2=0) | Set/unset one or two state(s) for the given window (property
_NET_WM_STATE).
:param win: the window object
:param action: 0 to remove, 1 to add or 2 to toggle state(s)
:param state: a state
:type state: int or str (see :attr:`NET_WM_STATES`)
:param state2: a state or 0
... | 3.803548 | 3.54536 | 1.072824 |
types = self._getProperty('_NET_WM_WINDOW_TYPE', win) or []
if not str:
return types
return [self._getAtomName(t) for t in types] | def getWmWindowType(self, win, str=False) | Get the list of window types of the given window (property
_NET_WM_WINDOW_TYPE).
:param win: the window object
:param str: True to get a list of string types instead of int
:return: list of (int|str) | 5.922925 | 5.242715 | 1.129744 |
states = self._getProperty('_NET_WM_STATE', win) or []
if not str:
return states
return [self._getAtomName(s) for s in states] | def getWmState(self, win, str=False) | Get the list of states of the given window (property _NET_WM_STATE).
:param win: the window object
:param str: True to get a list of string states instead of int
:return: list of (int|str) | 6.084919 | 5.986925 | 1.016368 |
wAllowedActions = (
self._getProperty('_NET_WM_ALLOWED_ACTIONS', win) or [])
if not str:
return wAllowedActions
return [self._getAtomName(a) for a in wAllowedActions] | def getWmAllowedActions(self, win, str=False) | Get the list of allowed actions for the given window (property
_NET_WM_ALLOWED_ACTIONS).
:param win: the window object
:param str: True to get a list of string allowed actions instead of int
:return: list of (int|str) | 6.410966 | 6.302667 | 1.017183 |
if not win:
win = self.root
if type(data) is str:
dataSize = 8
else:
data = (data+[0]*(5-len(data)))[:5]
dataSize = 32
ev = protocol.event.ClientMessage(
window=win,
client_type=self.display.get_atom(_type)... | def _setProperty(self, _type, data, win=None, mask=None) | Send a ClientMessage event to the root window | 4.987819 | 4.261375 | 1.170472 |
f = self.__getAttrs.get(prop)
if not f:
raise KeyError('Unknown readable property: %s' % prop)
return f(self, *args, **kwargs) | def getProperty(self, prop, *args, **kwargs) | Get the value of a property. See the corresponding method for the
required arguments. For example, for the property _NET_WM_STATE, look
for :meth:`getWmState` | 4.642535 | 5.251456 | 0.884047 |
f = self.__setAttrs.get(prop)
if not f:
raise KeyError('Unknown writable property: %s' % prop)
f(self, *args, **kwargs) | def setProperty(self, prop, *args, **kwargs) | Set the value of a property by sending an event on the root window.
See the corresponding method for the required arguments. For example,
for the property _NET_WM_STATE, look for :meth:`setWmState` | 4.842626 | 5.251925 | 0.922067 |
# adapted from NumPy's percentile function
a = np.asarray(a)
if limit:
a = a[(limit[0] <= a) & (a <= limit[1])]
if per == 0:
return a.min(axis=axis)
elif per == 100:
return a.max(axis=axis)
sorted = np.sort(a, axis=axis)
if axis is None:
axis = 0
... | def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
axis=None) | Calculate the score at a given percentile of the input sequence.
For example, the score at `per=50` is the median. If the desired quantile
lies between two data points, we interpolate between them, according to
the value of `interpolation`. If the parameter `limit` is provided, it
should be a tuple (lo... | 2.474658 | 3.679717 | 0.672513 |
IDX_LENGTH = 3
merged = self.segs.copy()
current_start = 0
j = 0
seg = self.segs.iloc[0]
for i in range(1, self.num_segments):
seg = self.segs.iloc[i]
last = self.segs.iloc[i - 1]
if seg.speaker == last.speaker:
... | def merge_equal_neighbors(self) | Merge neighbors with same speaker. | 3.381955 | 3.025178 | 1.117936 |
if not path.startswith('~'):
return path
if os.name == 'posix':
user = pwd.getpwuid(os.geteuid())
return path.replace('~', user.pw_dir, 1)
else:
return os.path.expanduser(path) | def expand_user(path) | Expands ~/path to /home/<current_user>/path
On POSIX systems does it by getting the home directory for the
current effective user from the passwd database. On other systems
do it by using :func:`os.path.expanduser`
Args:
path (str): A path to expand to a user's home folder
Returns:
... | 2.199794 | 2.448673 | 0.898362 |
positional_args = []
kwargs = {}
split_key = None
for arg in args:
if arg.startswith('--'):
arg = arg[2:]
if '=' in arg:
key, value = arg.split('=', 1)
kwargs[key.replace('-', '_')] = value
else:
split_key... | def format_arguments(*args) | Converts a list of arguments from the command line into a list of
positional arguments and a dictionary of keyword arguments.
Handled formats for keyword arguments are:
* --argument=value
* --argument value
Args:
*args (list): a list of arguments
Returns:
([positional_args], {kwar... | 2.17189 | 1.983068 | 1.095217 |
if isinstance(settings_paths, basestring):
settings_paths = (settings_paths,)
config_file = next((path for path in settings_paths if is_file_readable(path)), None)
if config_file:
config_file = expand_user(config_file)
return Settings(prefix=section, section=section, filename=conf... | def get_settings(section='gocd', settings_paths=('~/.gocd/gocd-cli.cfg', '/etc/go/gocd-cli.cfg')) | Returns a `gocd_cli.settings.Settings` configured for settings file
The settings will be read from environment variables first, then
it'll be read from the first config file found (if any).
Environment variables are expected to be in UPPERCASE and to be prefixed
with `GOCD_`.
Args:
section:... | 3.025526 | 3.46764 | 0.872503 |
if not settings:
settings = get_settings()
return gocd.Server(
settings.get('server'),
user=settings.get('user'),
password=settings.get('password'),
) | def get_go_server(settings=None) | Returns a `gocd.Server` configured by the `settings`
object.
Args:
settings: a `gocd_cli.settings.Settings` object.
Default: if falsey calls `get_settings`.
Returns:
gocd.Server: a configured gocd.Server instance | 3.641253 | 3.723722 | 0.977853 |
'''
get the standard tab completions.
These are the options which could complete the full_text.
'''
final_matches = [o for o in options if o.startswith(full_text)]
return final_matches | def _get_standard_tc_matches(text, full_text, options) | get the standard tab completions.
These are the options which could complete the full_text. | 8.232615 | 3.360317 | 2.449952 |
'''
Get the options that match the full text, then from each option
return only the individual words which have not yet been matched
which also match the text being tab-completed.
'''
print("text: {}, full: {}, options: {}".format(text, full_text, options))
# get the options which match the ... | def _get_fuzzy_tc_matches(text, full_text, options) | Get the options that match the full text, then from each option
return only the individual words which have not yet been matched
which also match the text being tab-completed. | 3.970964 | 3.17106 | 1.252251 |
'''Create and use a tab-completer object'''
# using some sort of nested-scope construct is
# required because readline doesn't pass the necessary args to
# its callback functions
def _get_matches(text, state):
'''
Get a valid match, given:
text - the portion of text curre... | def _tab_complete_init(items, post_prompt, insensitive, fuzzy, stream) | Create and use a tab-completer object | 4.513482 | 4.499358 | 1.003139 |
'''
Prompt once.
If you want the default displayed, put a format {} into the
post_prompt string (like 'select one [{}]: ')
'''
# try to sub in the default if provided
if default is not None:
if '{}' in pre_prompt:
pre_prompt = pre_prompt.format(default)
if '{}' in... | def _prompt(pre_prompt, items, post_prompt, default, indexed, stream) | Prompt once.
If you want the default displayed, put a format {} into the
post_prompt string (like 'select one [{}]: ') | 3.471785 | 2.616397 | 1.326933 |
'''return True if response fuzzily matches candidate'''
r_words = response.split()
c_words = candidate.split()
# match whole words first
for word in r_words:
if word in c_words:
r_words.remove(word)
c_words.remove(word)
# match partial words, fewest matches first
... | def _fuzzily_matches(response, candidate) | return True if response fuzzily matches candidate | 3.96995 | 3.937457 | 1.008252 |
'''
Return True if the response matches fuzzily exactly.
Insensitivity is taken into account.
'''
if insensitive:
response = response.lower()
match = match.lower()
r_words = response.split()
m_words = match.split()
# match whole words first
for word in r_words:
... | def _exact_fuzzy_match(response, match, insensitive) | Return True if the response matches fuzzily exactly.
Insensitivity is taken into account. | 3.464704 | 2.706067 | 1.280347 |
'''
returns an exact match, if it exists, given parameters
for the match
'''
for match in matches:
if response == match:
return match
elif insensitive and response.lower() == match.lower():
return match
elif fuzzy and _exact_fuzzy_match(response, match... | def _exact_match(response, matches, insensitive, fuzzy) | returns an exact match, if it exists, given parameters
for the match | 3.84782 | 2.217608 | 1.735122 |
'''Check the response against the items'''
# Set selection
selection = None
# if indexed, check for index
if indexed:
if response.isdigit():
index_response = int(response)
if index_response < len(items):
selection = items[index_response]
# if not m... | def _check_response(response, items, default, indexed, stream, insensitive, fuzzy) | Check the response against the items | 3.329434 | 3.319149 | 1.003099 |
'''Check that the prompts are strings'''
if not isinstance(pre_prompt, str):
raise TypeError("The pre_prompt was not a string!")
if post_prompt is not _NO_ARG and not isinstance(post_prompt, str):
raise TypeError("The post_prompt was given and was not a string!") | def _check_prompts(pre_prompt, post_prompt) | Check that the prompts are strings | 3.589092 | 3.30174 | 1.08703 |
'''
Check:
- that the list of items is iterable and finite.
- that the list is not empty
'''
num_items = 0
# Check that the list is iterable and finite
try:
num_items = len(items)
except:
raise TypeError("The item list ({}) is not a finite iterable (has no length)".... | def _check_items(items) | Check:
- that the list of items is iterable and finite.
- that the list is not empty | 4.33444 | 2.975351 | 1.456783 |
'''Check that the default is in the list, and not empty'''
num_items = len(items)
if default_index is not None and not isinstance(default_index, int):
raise TypeError("The default index ({}) is not an integer".format(default_index))
if default_index is not None and default_index >= num_items:
... | def _check_default_index(items, default_index) | Check that the default is in the list, and not empty | 2.00771 | 1.818367 | 1.104128 |
'''Check that the stream is a file'''
if not isinstance(stream, type(_sys.stderr)):
raise TypeError("The stream given ({}) is not a file object.".format(stream)) | def _check_stream(stream) | Check that the stream is a file | 6.814489 | 6.256354 | 1.089211 |
'''CLI interface'''
parser = _argparse.ArgumentParser(
description='''
Present the user with a simple CLI menu, and return the option chosen.
The menu is presented via stderr.
The output is printed to stdout for piping.
'''.format(_VERSION),
epilog... | def _cli() | CLI interface | 4.169658 | 4.187834 | 0.99566 |
'''
Deduplicate an item list, and preserve order.
For case-insensitive lists, drop items if they case-insensitively match
a prior item.
'''
deduped = []
if insensitive:
i_deduped = []
for item in items:
lowered = item.lower()
if lowered not in i_dedup... | def _dedup(items, insensitive) | Deduplicate an item list, and preserve order.
For case-insensitive lists, drop items if they case-insensitively match
a prior item. | 2.831837 | 1.73978 | 1.627698 |
@wraps(f)
def decorator(*args, **kwargs):
if g.user is None:
next_url = url_for("login") + "?next=" + request.url
return redirect(next_url)
else:
return f(*args, **kwargs)
return decorator | def require_openid(f) | Require user to be logged in. | 2.178308 | 2.134917 | 1.020324 |
# if we are already logged in, go back to were we came from
if g.user is not None:
return redirect(oid.get_next_url())
if request.method == 'POST':
openid = request.form.get('openid')
if openid:
return oid.try_login(openid, ask_for=['email', 'fullname',
... | def login() | Does the login via OpenID. Has to call into `oid.try_login`
to start the OpenID machinery. | 3.13786 | 2.794546 | 1.122851 |
session['openid'] = resp.identity_url
user = User.query.filter_by(openid=resp.identity_url).first()
if user is not None:
flash(u'Successfully signed in')
g.user = user
return redirect(oid.get_next_url())
return redirect(url_for('create_profile', next=oid.get_next_url(),
... | def create_or_login(resp) | This is called when login with OpenID succeeded and it's not
necessary to figure out if this is the users's first login or not.
This function has to redirect otherwise the user will be presented
with a terrible URL which we certainly don't want. | 3.136752 | 2.937825 | 1.067712 |
if g.user is None:
abort(401)
form = dict(name=g.user.name, email=g.user.email)
if request.method == 'POST':
if 'delete' in request.form:
db_session.delete(g.user)
db_session.commit()
session['openid'] = None
flash(u'Profile deleted')
... | def edit_profile() | Updates a profile | 1.84031 | 1.852043 | 0.993665 |
cached_output = yield from self._cache.get(transaction_hash, output_index)
if cached_output is not None:
return cached_output
transaction = yield from self._transaction_provider(transaction_hash)
if transaction is None:
raise ValueError('Transaction {0... | def get_output(self, transaction_hash, output_index) | Gets an output and information about its asset ID and asset quantity.
:param bytes transaction_hash: The hash of the transaction containing the output.
:param int output_index: The index of the output.
:return: An object containing the output as well as its asset ID and asset quantity.
... | 2.849774 | 3.044322 | 0.936095 |
# If the transaction is a coinbase transaction, the marker output is always invalid
if not transaction.is_coinbase():
for i, output in enumerate(transaction.vout):
# Parse the OP_RETURN script
marker_output_payload = MarkerOutput.parse_script(output.s... | def color_transaction(self, transaction) | Computes the asset ID and asset quantity of every output in the transaction.
:param CTransaction transaction: The transaction to color.
:return: A list containing all the colored outputs of the transaction.
:rtype: Future[list[TransactionOutput]] | 4.30295 | 3.844538 | 1.119237 |
# If there are more items in the asset quantities list than outputs in the transaction (excluding the
# marker output), the marker output is deemed invalid
if len(asset_quantities) > len(outputs) - 1:
return None
# If there is no input in the transaction, the marker... | def _compute_asset_ids(cls, inputs, marker_output_index, outputs, asset_quantities) | Computes the asset IDs of every output in a transaction.
:param list[TransactionOutput] inputs: The outputs referenced by the inputs of the transaction.
:param int marker_output_index: The position of the marker output in the transaction.
:param list[CTxOut] outputs: The outputs of the transact... | 2.615473 | 2.528807 | 1.034272 |
sha256 = hashlib.sha256()
ripemd = hashlib.new('ripemd160')
sha256.update(data)
ripemd.update(sha256.digest())
return ripemd.digest() | def hash_script(data) | Hashes a script into an asset ID using SHA256 followed by RIPEMD160.
:param bytes data: The data to hash. | 2.002727 | 1.772641 | 1.129798 |
with io.BytesIO(payload) as stream:
# The OAP marker and protocol version
oa_version = stream.read(4)
if oa_version != cls.OPEN_ASSETS_TAG:
return None
try:
# Deserialize the expected number of items in the asset quantity... | def deserialize_payload(cls, payload) | Deserializes the marker output payload.
:param bytes payload: A buffer containing the marker output payload.
:return: The marker output object.
:rtype: MarkerOutput | 4.382794 | 4.254927 | 1.030052 |
with io.BytesIO() as stream:
stream.write(self.OPEN_ASSETS_TAG)
bitcoin.core.VarIntSerializer.stream_serialize(len(self.asset_quantities), stream)
for asset_quantity in self.asset_quantities:
stream.write(self.leb128_encode(asset_quantity))
... | def serialize_payload(self) | Serializes the marker output data into a payload buffer.
:return: The serialized payload.
:rtype: bytes | 3.732198 | 4.19417 | 0.889854 |
script_iterator = output_script.raw_iter()
try:
first_opcode, _, _ = next(script_iterator, (None, None, None))
_, data, _ = next(script_iterator, (None, None, None))
remainder = next(script_iterator, None)
except bitcoin.core.script.CScriptTruncatedP... | def parse_script(output_script) | Parses an output and returns the payload if the output matches the right pattern for a marker output,
or None otherwise.
:param CScript output_script: The output script to be parsed.
:return: The marker output payload if the output fits the pattern, None otherwise.
:rtype: bytes | 3.748747 | 3.750064 | 0.999649 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.