content stringlengths 42 6.51k |
|---|
def getNextPort(ports, num):
"""Given a list of open ports, get the next open one from a starting location."""
while True:
if any(str(num) in p for p in ports):
num += 1
else:
return num |
def dot(a,b):
"""
Dot product between two dictionaries.
"""
keys = set(a.keys()).intersection(set(b.keys()))
sum = 0
for i in keys:
try:
sum += a[i] * b[i];
except KeyError:
pass
return sum |
def check_api_connection(post_data, response) -> list:
""" checks connection with api by verifying error codes and number of tasks between
post_data/requests and response
parameters:
post_data: dictionary with requests
response: json response form server
Returns list of tasks id to be downloaded
"""
# check status code
if response['status_code'] != 20000:
raise ConnectionError(f"Status code is not ok: {response['status_message']}")
# check
id_list = []
for a, b in zip(post_data.values(), response['tasks']):
if a['keyword'] != b['data']['keyword']:
raise ConnectionError("task is missing")
else:
id_list.append(b['id'])
return id_list |
def parse_command_num(command_str, end, start = 1):
"""
start: Starting value of valid integer commands
end: Ending value of valid integer commands
"""
command_int = int(command_str.strip())
if command_int >= start and command_int <= end:
return command_int
else:
raise ValueError |
def get_coords(geojson):
"""."""
if geojson.get('features') is not None:
return geojson.get('features')[0].get('geometry').get('coordinates')
elif geojson.get('geometry') is not None:
return geojson.get('geometry').get('coordinates')
else:
return geojson.get('coordinates') |
def _members_to_exclude(arg):
"""Return a set of members to exclude given a comma-delim list them.
Exclude none if none are passed. This differs from autodocs' behavior,
which excludes all. That seemed useless to me.
"""
return set(a.strip() for a in (arg or '').split(',')) |
def _get_pattern_strings(compiled_list):
"""Returns regex pattern strings from a list of compiled regex pattern objects.
Args:
compiled_list (list): of regular expression patterns to extract strings
from
Returns:
list: A list of regex pattern strings extracted from compiled list of
regex pattern objects.
"""
return [pattern.pattern for pattern in compiled_list] |
def bold(string: str) -> str:
"""Add bold colour codes to string
Args:
string (str): Input string
Returns:
str: Bold string
"""
return "\033[1m" + string + "\033[0m" |
def _compose_gpindices(parent_gpindices, child_gpindices):
"""
Maps `child_gpindices`, which index `parent_gpindices` into a new slice
or array of indices that is the subset of parent indices.
Essentially:
`return parent_gpindices[child_gpindices]`
"""
if parent_gpindices is None or child_gpindices is None: return None
if isinstance(child_gpindices, slice) and child_gpindices == slice(0, 0, None):
return slice(0, 0, None) # "null slice" ==> "null slice" convention
if isinstance(parent_gpindices, slice):
start = parent_gpindices.start
assert(parent_gpindices.step is None), "No support for nontrivial step size yet"
if isinstance(child_gpindices, slice):
return _slct.shift(child_gpindices, start)
else: # child_gpindices is an index array
return child_gpindices + start # numpy "shift"
else: # parent_gpindices is an index array, so index with child_gpindices
return parent_gpindices[child_gpindices] |
def testSuite(debug: bool = False):
"""
Function Type: Method
Run all test for the class.
"""
print(debug)
# testObj = RegressionUnitTestsCases(debug=debug)
# testObj.run()
return True |
def popCount(v):
"""Return number of 1 bits (population count) of an integer.
If the integer is negative, the number of 1 bits in the
twos-complement representation of the integer is returned. i.e.
``popCount(-30) == 28`` because -30 is::
1111 1111 1111 1111 1111 1111 1110 0010
Uses the algorithm from `HAKMEM item 169 <https://www.inwap.com/pdp10/hbaker/hakmem/hacks.html#item169>`_.
Args:
v (int): Value to count.
Returns:
Number of 1 bits in the binary representation of ``v``.
"""
if v > 0xFFFFFFFF:
return popCount(v >> 32) + popCount(v & 0xFFFFFFFF)
# HACKMEM 169
y = (v >> 1) & 0xDB6DB6DB
y = v - y - ((y >> 1) & 0xDB6DB6DB)
return (((y + (y >> 3)) & 0xC71C71C7) % 0x3F) |
def sum_func(n):
"""
Given an integer, create a function
which returns the sum of all the
individual digits in that integer.
For example: if n = 4321, return 4+3+2+1
"""
if n < 10:
return n
else:
return n%10 + sum_func(n//10) |
def cb_layer(ctx, param, value):
"""Let --layer be a name or index."""
if value is None or not value.isdigit():
return value
else:
return int(value) |
def pad(traces, fill=0, end=None):
"""Pads all the traces signals have the same duration.
If ``end`` parameter is not provided the traces are padded to have
the same duration as the longest given trace.
Parameters
----------
traces : list[list[int]]
2D list of numbers representing the trace signal.
fill : int, optional
Padding value to insert after the end of traces.
end : int, optional
New count of samples of the traces.
Must be greater than the length of the longest trace.
Returns
-------
list[list[int]]
Padded traces.
"""
samples = list(map(len, traces))
m = max(samples)
m = max(end or m, m)
return [trace + [fill] * (m - read) for trace, read in zip(traces, samples)] |
def is_palindrome(x):
""" returns True if x is palindrome """
return x == int(str(x)[::-1]) |
def first_line(doc):
"""Extract first non-blank line from text, to extract docstring title."""
if doc is not None:
for line in doc.splitlines():
striped = line.strip()
if striped:
return striped
return '' |
def split_group(group):
"""
Converts a list of objects splitted by "|" into a list. The complication
comes from the fact that we do not want to use other group's "|" to split
this one. Meaning (a|(b|c)|e) should be splitted into ['a', '(b|c)', 'e'].
Warning, this function supposes that there is no parenthesis around the
given group (it must be under the form "a|(b|c)|e").
"""
# suppose no parenthesis around group
parenthesis_level = 0
last_split_index = 0
result = []
for index, char in enumerate(group):
if char == "(":
parenthesis_level += 1
elif char == ")":
parenthesis_level -= 1
elif char == "|" and parenthesis_level == 0:
result.append(group[last_split_index:index])
last_split_index = index + 1
result.append(group[last_split_index:])
return result |
def attr_bool(s):
"""Converts an attribute in to a boolean
A True value is returned if the string matches 'y', 'yes' or 'true'.
The comparison is case-insensitive and whitespace is stripped.
All other values are considered False. If None is passed in, then None will be returned.
"""
if s is None or isinstance(s, bool):
return s
return s.strip().lower() in ("yes", "true") |
def calc_power(cell, serial):
"""Calculate the power for a single cell
"""
rack_id = cell[0] + 10
power_level = rack_id * cell[1]
power_level += serial
power_level *= rack_id
hundereds = power_level // 100
if hundereds > 10:
hundereds = hundereds % 10
power_level = hundereds - 5
return power_level |
def repos_dict(repos):
"""Returns {"repo1": "branch", "repo2": "pull"}."""
return {r: b or p for (r, (b, p)) in repos.items()} |
def add_article(name):
""" Returns a string containing the correct indefinite article ('a' or 'an')
prefixed to the specified string.
"""
if name[:1].lower() in "aeiou":
return "an " + name
return "a " + name |
def insertIntoPath(original, insertion='rest'):
""" Insert a string after the first block in a path, for example
/my/original/path,insertion
/my/INSERTION/original/path
"""
slashIndex = original.index('/',1)
newString = '%s/%s%s' % (original[0:slashIndex], insertion, original[slashIndex:len(original)])
return newString |
def linear_with_memory(A):
"""
Find single number using
hash set using a linear time
and linear amount of memory.
"""
if not A:
return None
if len(A) == 1:
return A[0]
seen = dict()
for num in A:
if num in seen:
seen[num] += 1
else:
seen[num] = 1
for (key, value) in seen.items():
if value == 1: return key |
def align16(address):
"""
Return the next 16 byte aligned address.
"""
return (address + 0x10) & 0xFFFFFFF0 |
def interpretValue(value,*args,**kwargs):
"""Interprets a passed value. In this order:
- If it's callable, call it with the parameters provided
- If it's a tuple/list/dict and we have a single, non-kwarg parameter, look up that parameter within the tuple/list/dict
- Else, just return it
"""
if callable(value): return value(*args,**kwargs)
if isinstance(value,tuple) or isinstance(value,list) or isinstance(value,dict):
if len(args)==1 and kwargs=={}:
return value[args[0]]
return value |
def next_char(string, idx):
"""
Get the next character in a string if it exists otherwise return
an empty string
Arguments:
string (str):
idx (idx): Index of the current position in the string
Returns:
(str): Next character in the string
"""
if idx >= len(string) - 1:
return ''
return string[idx + 1] |
def is_prime(num : int) -> bool:
"""
Checks if a number is prime or not.
Parameters:
num: the number to be checked
Returns:
True if number is prime, otherwise False
"""
flag : bool = True
if num <= 0:
raise ValueError("Input argument should be a natural number")
elif num == 1:
flag = False
else:
# check for factors
for i in range(2, num):
if (num % i) == 0:
flag = False
break
return flag |
def unique_list_order_preserved(seq):
"""Returns a unique list of items from the sequence
while preserving original ordering.
The first occurrence of an item is returned in the new sequence:
any subsequent occurrences of the same item are ignored.
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] |
def _remove_proper_feature(human_readable: str) -> str:
"""Removes proper feature from human-readable analysis."""
human_readable = human_readable.replace("+[Proper=False]", "")
human_readable = human_readable.replace("+[Proper=True]", "")
return human_readable |
def remove_item(inventory, item):
"""
:param inventory: dict - inventory dictionary.
:param item: str - item to remove from the inventory.
:return: dict - updated inventory dictionary with item removed.
"""
# inventory.pop(item, None)
if item in inventory:
del inventory[item]
return inventory |
def getThrusterFiringIntervalBefore(tfIndices, minDuration = 10):
"""Returns range of points between last two thruster firings in input
See getThrusterFiringIntervalAfter() for more details. This
function does the same job, but returns the last two indices
in the array meeting the criteria.
"""
nTfi = len(tfIndices)
if nTfi == 0:
return None, None
if nTfi == 1:
return 0, tfIndices[0]
i = len(tfIndices)-1
while i > 1:
if tfIndices[i-1] + minDuration < tfIndices[i]:
return tfIndices[i-1], tfIndices[i]
i -= 1
return None, None |
def flipBit(int_type, offset):
"""Flips the bit at position offset in the integer int_type."""
mask = 1 << offset
return(int_type ^ mask) |
def getFeaturePerm(feature):
"""
Return a list of assets permission of a feature
params:
feature -> a feature
"""
return feature["_permissions"] |
def is_valid(bo, num, pos):
"""Returns bollean expresion whether inserting some number
in an empty space is valid or not"""
#Check whether the number is already in the current row
for i in range(len(bo[0])):
if bo[pos[0]][i] == num and pos[1] != i:
return False
#Check whether the number is already in the current column
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
#Check whether the number is already in the current box
box_X_coo = pos[1] // 3 #Will be an integer from 0-2
box_Y_coo = pos[0] // 3
for i in range(box_Y_coo * 3, box_Y_coo * 3 + 3):
for j in range(box_X_coo * 3, box_X_coo * 3 + 3):
if bo[i][j] == num and (i, j) != pos:
return False
return True |
def areoverlapping(left, right):
"""Test if the chains represented by left and right are overlapping."""
return right[0] <= left[-1] |
def prettyBytes (b):
"""
Pretty-print bytes
"""
prefixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB']
while b >= 1024 and len (prefixes) > 1:
b /= 1024
prefixes.pop (0)
return f'{b:.1f} {prefixes[0]}' |
def parse_wallet_data_import(wallet_data):
"""Parses wallet JSON for import, takes JSON in a supported format
and returns a tuple of wallet name, wallet descriptor, and cosigners types (if known, electrum only for now)
Supported formats: Specter, Electrum, Account Map (Fully Noded, Gordian, Sparrow etc.)
"""
cosigners_types = []
# specter format
if "recv_descriptor" in wallet_data:
wallet_name = wallet_data.get("name", "Imported Wallet")
recv_descriptor = wallet_data.get("recv_descriptor", None)
# Electrum multisig
elif "x1/" in wallet_data:
i = 1
xpubs = ""
while "x{}/".format(i) in wallet_data:
d = wallet_data["x{}/".format(i)]
xpubs += "[{}]{}/0/*,".format(
d["derivation"].replace("m", d["root_fingerprint"]), d["xpub"]
)
cosigners_types.append(d["hw_type"])
i += 1
xpubs = xpubs.rstrip(",")
if wallet_data["addresses"]["receiving"][0].startswith("bc") or wallet_data[
"addresses"
]["receiving"][0].startswith("tb"):
wallet_type = "wsh"
else:
wallet_type = "sh-wsh"
required_sigs = int(wallet_data.get("wallet_type").split("of")[0])
recv_descriptor = "{}(sortedmulti({}, {}))".format(
wallet_type, required_sigs, xpubs
)
wallet_name = "Electrum {} of {}".format(required_sigs, i - 1)
# Electrum singlesig
elif "keystore" in wallet_data:
wallet_name = wallet_data["keystore"]["label"]
if wallet_data["addresses"]["receiving"][0].startswith("bc") or wallet_data[
"addresses"
]["receiving"][0].startswith("tb"):
wallet_type = "wpkh"
else:
wallet_type = "sh-wpkh"
recv_descriptor = "{}({})".format(
wallet_type,
"[{}]{}/0/*,".format(
wallet_data["keystore"]["derivation"].replace(
"m", wallet_data["keystore"]["root_fingerprint"]
),
wallet_data["keystore"]["xpub"],
),
)
cosigners_types = [wallet_data["keystore"]["hw_type"]]
else:
wallet_name = wallet_data.get("label", "Imported Wallet")
recv_descriptor = wallet_data.get("descriptor", None)
return (wallet_name, recv_descriptor, cosigners_types) |
def empty_line(line):
"""Check if line is emtpy."""
return not bool(line.strip()) |
def upload_file(body):
"""accepts file uploads"""
# <body> is a simple dictionary of {filename: b'content'}
print('body: ', body)
return {'filename': list(body.keys()).pop(), 'filesize': len(list(body.values()).pop())} |
def stats(ps):
"""Averages of conflicts at different q rates
Parameter
---------
ps: list of pairs of rates and conflicts
Returns
-------
statistics """
s = {}
c = {}
for p in ps:
i,t = p
c[i] = c.get(i,0) + 1
s[i] = s.get(i,0) + t
r = {}
for i in c:
r[i] = s[i]/c[i]
return r |
def _format_integer_field(field_name, status_information):
"""Format an integer field.
:param field_name: The name of the field
:type field_name: str
:param status_information: The various fields information
:type status_information: :class:`collections.defaultdict`
:returns: The updated status informations
:rtype: :class:`collections.defaultdict`
"""
try:
status_information[field_name] = int(''.join(status_information[field_name]))
except ValueError:
status_information.pop(field_name, None)
return status_information |
def get_sidebar_app_legend(title):
"""Return sidebar link legend HTML"""
return '<br />'.join(title.split(' ')) |
def navigate(obj, attr_path):
"""get the final attribute, will raise AttributeError when attr not exists
>>> navigate(dict(), '__class__.__name__')
'dict'
"""
attrs = attr_path.split('.')
target = obj
for attr in attrs:
target = getattr(target, attr)
return target |
def listDiff(lstA, lstB):
"""
Return a logical of size lstA
For each element in lstA, return true if it is not in lstB
Therefore, its like lstA-lstB
It returns the elements of lstA that are not in lstB
"""
lstDiffBool = [] # logical
for a in lstA:
lstDiffBool.append(not a in lstB)
lstDiff = [k for i, k in enumerate(lstA) if lstDiffBool[i]]
return lstDiff, lstDiffBool |
def escape_command(cmd: str, needs_enter: bool = True) -> str:
"""
Escapes a given command for use in tmux shell commands
If there is a "C-m" at the end of the command, assume this is already quoted
Parameters
----------
cmd : string
The command to escape
needs_enter : bool
Whether the command needs an "enter" keystroke at the end of it
Returns
-------
string
The command, formatted for use in tmux
"""
command = ""
if not cmd or len(cmd.strip()) == 0:
pass
elif cmd.endswith('"C-m"'):
command = cmd
else:
command = '"' + cmd.replace('"', '\\"') + '"'
command += ' "C-m"' if needs_enter else ""
return command |
def is_scalar(value):
"""Returns whether the given value is a scalar."""
return isinstance(value, (str, int)) |
def btc_to_satoshi(btc):
"""
Converts a value in BTC to satoshi
outputs => <int>
btc: <Decimal> or <Float>
"""
value = btc * 100000000
return int(value) |
def ravel_multi_index(I, J, shape):
"""Create an array of flat indices from coordinate arrays.
shape is (rows, cols)
"""
r, c = shape
return I * c + J |
def get_host_context_for_host_finding(resp_host):
"""
Prepare host context data as per the Demisto standard.
:param resp_host: response from host command.
:return: Dictionary representing the Demisto standard host context.
"""
return {
'ID': resp_host.get('hostId', ''),
'Hostname': resp_host.get('hostName', ''),
'IP': resp_host.get('ipAddress', ''),
} |
def jaccard(a, b):
"""
Jaccard index
"""
a, b = set(a), set(b)
return 1.*len(a.intersection(b))/len(a.union(b)) |
def make_human_readable_stations(res):
"""Makes text representation of a search result that is suitable for
showing to a user. Returns a string"""
ret = []
if not res:
ret.append( u"""No stations found""")
else:
format = u"%%(id)%ds %%(name)s (%%(district)s)" % \
max([ len(e["id"]) for e in res ])
for dep in res:
ret.append(format % dep)
return "\n".join(ret) |
def decode_cp1252(str):
"""
CSV files look to be in CP-1252 encoding (Western Europe)
Decoding to ASCII is normally fine, except when it gets an O umlaut, for example
In this case, values must be decoded from cp1252 in order to be added as unicode
to the final XML output.
This function helps do that in selected places, like on author surnames
"""
try:
# See if it is not safe to encode to ascii first
junk = str.encode('ascii')
except (UnicodeEncodeError, UnicodeDecodeError):
# Wrap the decode in another exception to make sure this never fails
try:
str = str.decode('cp1252')
except:
pass
return str |
def ascii_encode(non_compatible_string):
"""Primarily used for ensuring terminal display compatibility"""
if non_compatible_string:
return non_compatible_string.encode("ascii", errors="ignore").decode("ascii")
else:
return "" |
def ListJoiner(list):
""" Takes in a nested list, returns a list of strings """
temp_list = []
for item in list:
i = " ".join(item)
temp_list.append(i)
return temp_list |
def flatten_json_with_key(data, json_key):
"""
Return a list of tokens from a list of json obj.
"""
to_return = []
for obj in data:
to_return.append(obj[json_key])
return to_return |
def get_by_path(root, path):
"""Access a nested object in root by path sequence."""
for k in path if isinstance(path, list) else path.split("."):
root = root[int(k)] if k.isdigit() else root.get(k, "")
return root |
def jointerms(terms):
"""String that joins lists of lists of terms as the sum of products."""
return "+".join(["*".join(map(str, t)) for t in terms]) |
def ReplaceVariables(text, variables):
"""Returns the |text| with variables replaced with their values.
Args:
text: A string to be replaced.
variables: A list in the form of [(prefix, var_name, values), ...].
Returns:
A replaced string.
"""
for unused_prefix, var_name, value in variables:
text = text.replace('@%s@' % var_name.upper(), str(value))
return text |
def isUniqueSeq(objlist):
"""Check that list contains items only once"""
for obj in objlist:
if objlist.count(obj) != 1:
return False
return True |
def xor(a, b):
"""
Compute the xor between two bytes sequences.
"""
return [x ^ y for x, y in zip(a, b)] |
def _nbcols(data):
""" retrieve the number of columns of an object
Example
-------
>>> df = pd.DataFrame({"a":np.arange(10),"b":["aa","bb","cc"]*3+["dd"]})
>>> assert _nbcols(df) == 2
>>> assert _nbcols(df.values) == 2
>>> assert _nbcols(df["a"]) == 1
>>> assert _nbcols(df["a"].values) == 1
"""
s = getattr(data, "shape", None)
if s is None:
return 1
else:
if len(s) == 1:
return 1
else:
return s[1] |
def is_palindrome(x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x < 10:
return True
# arr = [n for n in str(x)]
# while len(arr) > 1:
# a = arr.pop(0)
# b = arr.pop()
# if a != b:
# return False
new = 0
while x > new:
new = new * 10 + x % 10
x /= 10
print(x)
print(new)
return x == new or x == new / 10 |
def __style_function__(feature):
"""
Function to define the layer highlight style
"""
return {"color": "#1167B1", "fillColor": "#476930", "weight": 2, "dashArray": "1, 1"} |
def remove_char(string,
iterable):
"""
Return str without given elements from the iterable. More convenient than
chaining the built-in replace methods.
Parameters
-------
string: str
String from which the characters from the iterable are removed.
iterable: str, list, tuple, set
Iterable with characters that are removed from the string.
Returns
-------
str
Without elements from the iterable.
"""
for i in iterable:
string = string.replace(i, "")
return string |
def uri_to_uuid(uri_uuid: str) -> str:
"""
Standardize a device UUID (MAC address) from URI format (xx_xx_xx_xx_xx_xx) to conventional
format (XX:XX:XX:XX:XX:XX)
"""
return uri_uuid.upper().replace('_', ':') |
def extract_counts_double(sentence, pos=False):
"""Extract the two-edge properties with the same head from a treebank sentence.
Args:
`Sentence`: A sentence object.
pos (boolean): True iff the properties should be PoS-specific.
Returns:
dict of str:(list of int): Explanation by example:
"D#case-det" : [0, 0, 2, -> "Rows" indicate the order of the edge labels; "columns" indicate the position of the head.
0, 1, 0] -> Two times case-det-HEAD; one time det-HEAD-case.
The list is only of length 3 iff the edge labels are identical.
"""
heads = {}
for token in sentence:
if token.deprel is None:
continue
dep_label = token.deprel.split(":")[0]
if dep_label != "_":
if token.head not in heads.keys():
heads[token.head] = []
if pos:
dep_label += "+" + token.upos
heads[token.head].append((token.id, dep_label))
counts = {}
for head in heads.keys():
if len(heads[head]) >= 2:
for i, dep1 in enumerate(heads[head]):
for j, dep2 in enumerate(heads[head]):
if int(dep1[0]) < int(dep2[0]):
concat = "-".join(sorted([dep1[1], dep2[1]]))
order = 0
if concat != "-".join([dep1[1], dep2[1]]):
order += 1
hpos = 0
if int(dep1[0]) < int(head):
hpos += 1
if int(dep2[0]) < int(head):
hpos += 1
label = "D#" + concat
if pos:
pos0 = "ROOT"
if head != "0":
pos0 = sentence[head].upos
label = "DPOS" + label[1:] + "_" + pos0
if label not in counts.keys():
if dep1[1] == dep2[1]:
counts[label] = [0, 0, 0]
else:
counts[label] = [0, 0, 0, 0, 0, 0]
counts[label][order*3+hpos] += 1
return counts |
def quicksort_equal_elements(s):
"""Quicksort from finxter modified to add all elements equal to the pivot
directly after the pivot, so that quicksort performs faster for cases
where there are many identical elements in the array to be sorted (e.g.
there are only 2 values for all elements, or 1 unique value in a large
array, etc.)"""
if len(s) < 2:
return s
else:
# upgraded to work for sets with multiple identical numbers!
return (
quicksort_equal_elements([x for x in s[1:] if x < s[0]])
+ [s[0]]
+ [x for x in s[1:] if x == s[0]]
+ quicksort_equal_elements([x for x in s[1:] if x > s[0]])
) |
def NB_calc(TP, FP, POP, w):
"""
Calculate Net Benefit (NB).
:param TP: true positive
:type TP: int
:param FP: false positive
:type FP: int
:param POP: population or total number of samples
:type POP: int
:param w: weight
:type w: float
:return: NB as float
"""
try:
NB = (TP - w * FP) / POP
return NB
except (ZeroDivisionError, TypeError):
return "None" |
def method_already_there(cls,
method_name, # type: str
this_class_only=False # type: bool
):
# type: (...) -> bool
"""
Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from
the one in `object`.
:param cls:
:param method_name:
:param this_class_only:
:return:
"""
if this_class_only:
return method_name in vars(cls) # or cls.__dict__
else:
method = getattr(cls, method_name, None)
return method is not None and method is not getattr(object, method_name, None) |
def func_f(x_i, base, y, p):
"""
x_(i+1) = func_f(x_i)
"""
if x_i % 3 == 2:
return (y*x_i) % p
elif x_i % 3 == 0:
return pow(x_i, 2, p)
elif x_i % 3 == 1:
return base*x_i % p
else:
print("[-] Something's wrong!")
return -1 |
def get_size(bytes):
"""
Returns size of bytes in a nice format
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P']:
if bytes < 1024:
return f"{bytes:.2f}{unit}B"
bytes /= 1024 |
def coord_to_gtp(coord, board_size):
""" From 1d coord (0 for position 0,0 on the board) to A1 """
if coord == board_size ** 2:
return "pass"
return "{}{}".format("ABCDEFGHJKLMNOPQRSTYVWYZ"[int(coord % board_size)],\
int(board_size - coord // board_size)) |
def coding_problem_22(dictionary, the_string):
"""
Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a
list. If there is more than one possible reconstruction, return any of them. If there is no possible
reconstruction, then return null.
Examples:
>>> coding_problem_22(['Riccardo', 'Brigittie', 'and', 'lollipop'], 'RiccardoandBrigittie')
['Riccardo', 'and', 'Brigittie']
>>> coding_problem_22(['quick', 'brown', 'the', 'fox'], 'thequickbrownfox')
['the', 'quick', 'brown', 'fox']
>>> coding_problem_22(['bed', 'bath', 'bedbath', 'and', 'beyond'], 'bedbathandbeyond')
['bed', 'bath', 'and', 'beyond']
"""
result = []
while the_string:
found = False
for word in dictionary:
if the_string.startswith(word):
the_string = the_string[len(word):]
result += [word]
found = True
break
if not found:
return None
return result |
def GetCaId(settings):
"""Get ca_id to be used with GetCaParameters().
Args:
settings: object with attribute level access to settings parameters.
Returns:
str like "FOO" or None (use primary parameters)
"""
return getattr(settings, 'CA_ID', None) |
def generate_assembly_id(params):
"""Generate assembly id for IBM Cloud report."""
return ":".join([str(param) for param in params if param]) |
def ComputeListDeltas(old_list, new_list):
"""Given an old and new list, return the items added and removed.
Args:
old_list: old list of values for comparison.
new_list: new list of values for comparison.
Returns:
Two lists: one with all the values added (in new_list but was not
in old_list), and one with all the values removed (not in new_list
but was in old_lit).
"""
if old_list == new_list:
return [], [] # A common case: nothing was added or removed.
added = set(new_list)
added.difference_update(old_list)
removed = set(old_list)
removed.difference_update(new_list)
return list(added), list(removed) |
def printDictionary( dictio, tabLevel = 0, tabSize = 4, prefix = '', verbose = False ):
"""
@brief Visualize dictionary contents
"""
output = ''
for k in list(dictio.keys()):
if isinstance(dictio[k], dict):
output += "%s%s%-20s:\n"%(prefix,tabLevel*tabSize*' ', k)
output += printDictionary(dictio[k], prefix = '#', tabLevel = tabLevel+1)
elif isinstance(dictio[k], float):
output += "%s%s%-20s: %12.3g\n"%(prefix,tabLevel*tabSize*' ', k, dictio[k])
elif isinstance(dictio[k], int):
output += "%s%s%-20s: %12d\n"%(prefix,tabLevel*tabSize*' ', k, dictio[k])
elif isinstance(dictio[k], list):
l = '['
for i in range(len(dictio[k])):
if i > 0: l += ' '
if isinstance(dictio[k][i], int): l += '%d'%dictio[k][i]
elif isinstance(dictio[k][i], float): l += '%g'%dictio[k][i]
else: l += ' %s'%dictio[k][i]
if i < len(dictio[k])-1: l += ','
l += ']'
output += "%s%s%-20s: %12s\n"%(prefix,tabLevel*tabSize*' ', k, l)
else:
output += "%s%s%-20s: %12s\n"%(prefix,tabLevel*tabSize*' ', k, dictio[k])
if verbose: print(output)
return output |
def remove_leading_zeros(num: str) -> str:
"""
Strips zeros while handling -, M, and empty strings
"""
if not num:
return num
if num.startswith("M"):
ret = "M" + num[1:].lstrip("0")
elif num.startswith("-"):
ret = "-" + num[1:].lstrip("0")
else:
ret = num.lstrip("0")
return "0" if ret in ("", "M", "-") else ret |
def classify_turn_direction(relative_azimuth, straight_angle=20):
"""Classify turn directions based on a relative azimuth
"""
if (relative_azimuth < straight_angle) or (relative_azimuth > (360 - straight_angle)):
return 'straight'
elif (relative_azimuth >= straight_angle) and (relative_azimuth <= (180 - straight_angle)):
return 'left'
elif (relative_azimuth > (180 - straight_angle)) and (relative_azimuth < (180 + straight_angle)):
return 'U'
elif (relative_azimuth >= (180 + straight_angle)) and (relative_azimuth <= (360 - straight_angle)):
return 'right' |
def round_price(price: float, exchange_precision: int) -> float:
"""Round prices to the nearest cent.
Args:
price (float)
exchange_precision (int): number of decimal digits for exchange price
Returns:
float: The rounded price.
"""
return round(price, exchange_precision) |
def is_device_target(hostname, device_list):
"""
Check if CV Device is part of devices listed in module inputs.
Parameters
----------
hostname : string
CV Device hostname
device_list : dict
Device list provided as module input.
Returns
-------
boolean
True if hostname is in device_list. False if not.
"""
if hostname in device_list.keys():
return True
return False |
def mirror_mag_d(distance_image,distance_object):
"""Usage: Find magnification using distance of image and distance of object"""
neg_di = (-1) * distance_image
return neg_di / distance_object |
def get_rotate_order(gimbal_data):
"""
Based on the gimbal generate the rotate order. Here we can decide whether the Gimbal will be on the twist or
on the roll
@param gimbal_data: dict which defines what axis are on the bend, roll and twist. Also defines where the
gimbal will reside
@return: The rotate order*
"""
if gimbal_data["gimbal"] == "roll":
return '{}{}{}'.format(gimbal_data["bend"], gimbal_data["roll"], gimbal_data["twist"])
elif gimbal_data["gimbal"] == "twist":
return '{}{}{}'.format(gimbal_data["bend"], gimbal_data["twist"], gimbal_data["roll"]) |
def get_tags(misp_attr: dict):
"""
Tags are attached as list of objects to MISP attributes. Returns a list of
all tag names.
@param The MISP attribute to get the tag names from
@return A list of tag names
"""
return [
t.get("name", None)
for t in misp_attr.get("Tag", [])
if t and t.get("name", None)
] |
def getlist(option, sep=',', chars=None):
"""Return a list from a ConfigParser option. By default,
split on a comma and strip whitespaces."""
return [ chunk.strip(chars) for chunk in option.split(sep) ] |
def lcs_recursive(s1, s2):
"""
Given two strings s1 and s2, find their longest common subsequence (lcs).
Basic idea of algorithm is to split on whether the first characters of
the two strings match, and use recursion.
Time complexity:
If n1 = len(s1) and n2 = len(s2), the runtime is O(2^(n1+n2)).
The depth of the recursion is at most n1+n2, by alternately
removing the first letter of s1, then s2, then s1, and so on.
One function call makes at most two subsequent recursive calls,
so the total number of calls is at most 2^(recursion depth),
or 2^(n1+n2).
This bound is also the time complexity of the brute force approach
of enumerating all 2^n1 subsequences of s1 and all 2^n2 subsequences
of s2, and comparing all (2^n1)*(2^n2) pairs.
Space complexity:
As noted above, the recursion depth is at most n1+n2, which is
achieved in the worst case of an empty lcs, so the space complexity
is Omega(n1+n2).
"""
if len(s1)==0 or len(s2) == 0:
return ""
if s1[0] == s2[0]:
#If 1st character is the same, it is part of the
#longest common subsequence.
return s1[0] + lcs_recursive(s1[1:],s2[1:])
#If 1st characters are different, need to consider two cases
seq1 = lcs_recursive(s1, s2[1:])
seq2 = lcs_recursive(s1[1:], s2)
#Return whichever sequence is longer
return seq1 if len(seq1) > len(seq2) else seq2 |
def pluralize(count, singular, plural):
"""Return singular or plural based on count"""
return singular if count == 1 else plural |
def k2e(k, E0):
"""
Convert from k-space to energy in eV
Parameters
----------
k : float
k value
E0 : float
Edge energy in eV
Returns
-------
out : float
Energy value
See Also
--------
:func:`isstools.conversions.xray.e2k`
"""
return ((1000/(16.2009 ** 2)) * (k ** 2)) + E0 |
def substitute_rpath(orig_rpath, topdir, new_root_path):
"""
Replace topdir with new_root_path RPATH list orig_rpath
"""
new_rpaths = []
for path in orig_rpath:
new_rpath = path.replace(topdir, new_root_path)
new_rpaths.append(new_rpath)
return new_rpaths |
def _lookup_option_cost(tier_dict, premium):
"""
Returns the per share option commission for a given premium.
"""
if tier_dict is None:
return 0.0
for (min_val, max_val) in tier_dict:
if min_val <= premium < max_val:
return tier_dict[(min_val, max_val)]
raise Exception('Failed to lookup tiered option cost.') |
def pad_items(items, pad_id):
"""
`items`: a list of lists (each row has different number of elements).
Return:
padded_items: a converted items where shorter rows are padded by pad_id.
lengths: lengths of rows in original items.
"""
lengths = [len(row) for row in items]
max_l = max(lengths)
for i in range(len(items)):
items[i] = items[i] + ([pad_id] * (max_l - len(items[i])))
return items, lengths |
def file_type(infile):
"""Return file type after stripping gz or bz2."""
name_parts = infile.split('.')
if name_parts[-1] == 'gz' or name_parts[-1] == 'bz2':
name_parts.pop()
return name_parts[-1] |
def should_shard_by_property_range(filters):
"""Returns whether these filters suggests sharding by property range.
Args:
filters: user supplied filters. Each filter should be a list or tuple of
format (<property_name_as_str>, <query_operator_as_str>,
<value_of_certain_type>). Value type is up to the property's type.
Returns:
True if these filters suggests sharding by property range. False
Otherwise.
"""
if not filters:
return False
for f in filters:
if f[1] != "=":
return True
return False |
def bsearch(list_,value):
"""Binary search."""
lower = 0
upper = len(list_) - 1
while lower <= upper:
if list_[lower] == value:
return lower
elif list_[upper] == value:
return upper
else:
mid = lower + (upper - lower) / 2
if list_[mid] == value:
return mid
elif list_[mid] < value:
lower = mid + 1
else:
upper = mid - 1
return None |
def vecMul(vec, sca):
"""Retruns something."""
return tuple([c * sca for c in vec]) |
def param_str(params):
"""Helper that turns a param dict in a key=value string"""
return ', '.join([f'{key}={value}' for key, value in params.items()]) |
def get_field_matches(explain, index_fields):
"""
Iterates over the toString output of the Lucene explain object to parse
out which fields generated the current hit. Returns a list containing all
fields involved in generating this hit
"""
match_fields = set()
for line in explain.split('\n'):
if line.find('fieldNorm') != -1:
field_name = line.split('field=')[1].split(',')[0]
if field_name in index_fields: match_fields.add(field_name)
return match_fields |
def workers_and_async_done(workers, async_map):
"""Returns True if the workers list and asyncore channels are all done.
@param workers list of workers (threads/processes). These must adhere
to the threading Thread or multiprocessing.Process interface.
@param async_map the threading-aware asyncore channel map to check
for live channels.
@return False if the workers list exists and has any entries in it, or
if the async_map exists and has any entries left in it; otherwise, True.
"""
if workers is not None and len(workers) > 0:
# We're not done if we still have workers left.
return False
if async_map is not None and len(async_map) > 0:
return False
# We're done.
return True |
def convert_list_to_dict(origin_list):
""" convert HAR data list to mapping
Args:
origin_list (list)
[
{"name": "v", "value": "1"},
{"name": "w", "value": "2"}
]
Returns:
dict:
{"v": "1", "w": "2"}
"""
return {item["name"]: item.get("value") for item in origin_list} |
def predict(list_items):
"""Returns the double of the items"""
return [i*2 for i in list_items] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.