content
stringlengths 42
6.51k
|
---|
def handles_url(url):
"""
Does this driver handle this kind of URL?
"""
return url.startswith("dht+udp://")
|
def sign(x):
"""Retuns 1 if x > 0 else -1. > instead of >= so that sign(False) returns -1"""
return 1 if x > 0 else -1
|
def remainder(val: str) -> str:
""" Return unpaired chars, else empty string """
expected = {')': '(', '}': '{', ']': '[', '>': '<'}
opened = []
for char in list(val):
if char in '({[<':
opened.append(char)
elif char in ')}]>':
if opened and opened[-1] == expected[char]:
opened.pop(-1)
else:
return ''
else:
return ''
return ''.join(reversed(opened))
|
def parseMalformedBamHeader(headerDict):
"""
Parses the (probably) intended values out of the specified
BAM header dictionary, which is incompletely parsed by pysam.
This is caused by some tools incorrectly using spaces instead
of tabs as a seperator.
"""
headerString = " ".join(
"{}:{}".format(k, v) for k, v in headerDict.items() if k != 'CL')
ret = {}
for item in headerString.split():
key, value = item.split(":", 1)
# build up dict, casting everything back to original type
ret[key] = type(headerDict.get(key, ""))(value)
if 'CL' in headerDict:
ret['CL'] = headerDict['CL']
return ret
|
def __check_rule(s_index, part_size, part_index):
"""
CV.
"""
return s_index / part_size == part_index
|
def _remove_anonymous_asset_paths(layer, path, identifiers):
"""Remove any anonymous identifier that is/will be merged into a USD stage."""
if path in identifiers:
# If `path` is one of the anonymous layers, setting to an empty
# string will force USD to treat the Asset Path as if it were
# pointing to a namespace located in the current USD layer.
#
return ""
return path
|
def decrypt(ciphertext, key):
"""Dccrypt a ciphertext using key.
This method will return the plaintext as a list of bytes.
"""
plaintext = []
key_length = len(key)
for i in range(len(ciphertext)):
p = ciphertext[i]
k = ord(key[i % key_length])
c = (p - k) % 256
plaintext.append(c)
return bytes(plaintext)
|
def is_prime(number: int) -> bool:
"""Return whether the specified number is a prime number."""
if number <= 1:
return False
for num in range(1, number):
if number % num == 0 and number != num and num != 1:
return False
return True
|
def compress_name(champion_name):
"""To ensure champion names can be searched for and compared,
the names need to be reduced.
The process is to remove any characters not in the alphabet
(apostrophe, space, etc) and then convert everything to lowercase.
Note that reversing this is non-trivial, there are inconsistencies
in the naming scheme used.
Examples:
Jhin -> jhin
GALIO -> galio
Aurelion Sol -> aurelionsol
Dr. Mundo -> drmundo
kha'zix -> khazix
"""
compressed_name = "".join(c for c in champion_name if c.isalpha())
return compressed_name.lower()
|
def is_valid_position(password: str) -> bool:
"""
Check if given password is valid.
Example: '1-3 b: cdefg' is invalid: neither position 1 nor position 3 contains b.
:type password: str
:rtype: bool
"""
import re
first_index, second_index, letter, pwd = re.split(': |-| ',password)
return (pwd[int(first_index)-1] == letter) ^ (pwd[int(second_index)-1] == letter)
|
def serialize_key(key: str) -> bytes:
"""Serializes a key for use as BigTable row key."""
return key.encode("utf-8")
|
def append_dict(dic_a:dict, dic_b:dict):
"""On the fly add/change a key of a dict and return a new dict, without changing the original dict
Requires Python 3.5 or higher.
In Python 3.9 that can be substituted by
dic_a | dic_b
Args:
dic_a (dict): [description]
dic_b (dict): [description]
Returns:
[type]: [description]
"""
return {**dic_a, **dic_b}
|
def collect_named_entities(tokens):
"""
Creates a list of Entity named-tuples, storing the entity type and the start and end
offsets of the entity.
:param tokens: a list of tags
:return: a list of Entity named-tuples
"""
named_entities = []
start_offset = None
end_offset = None
ent_type = None
for offset, token_tag in enumerate(tokens):
if token_tag == 'O':
if ent_type is not None and start_offset is not None:
end_offset = offset - 1
named_entities.append((ent_type, start_offset, end_offset))
start_offset = None
end_offset = None
ent_type = None
elif ent_type is None:
ent_type = token_tag[2:]
start_offset = offset
elif ent_type != token_tag[2:] or (ent_type == token_tag[2:] and token_tag[:1] == 'B'):
end_offset = offset - 1
named_entities.append((ent_type, start_offset, end_offset))
# start of a new entity
ent_type = token_tag[2:]
start_offset = offset
end_offset = None
# catches an entity that goes up until the last token
if ent_type is not None and start_offset is not None and end_offset is None:
named_entities.append((ent_type, start_offset, len(tokens) - 1))
return named_entities
|
def with_tau_m(tau_m, prms):
""" convert back from dimnesionless units """
p = dict(prms)
p["tau_m"] = tau_m
p["rin_e"] = prms["rin_e"] / tau_m
p["tr"] = prms["tr"] * tau_m
p["df"] = prms["df"] / tau_m
p["dt"] = prms["dt"] * tau_m
p["f_c"] = prms["f_c"] / tau_m
p["f_max"] = prms["f_max"] / tau_m
#p["f_sig"] = prms["f_sig"] / tau_m
p["r_sample"] = prms["r_sample"] / tau_m
return p
|
def accumulator_value(rules):
"""Accumulate value until infinite loop starts."""
counter = 0
pos = 0
visited_pos = []
while pos not in visited_pos:
rule = rules[pos]
visited_pos.append(pos)
if rule[0] == 'acc':
counter += rule[1]
pos += 1
elif rule[0] == 'jmp':
pos += rule[1]
else:
pos += 1
return counter
|
def valid_version(version):
"""Return true if the **version** has the format 'x.x.x' with integers `x`"""
try:
numbers = [int(part) for part in version.split('.')]
except ValueError:
return False
if len(numbers) == 3:
return True
else:
return False
|
def freqs2probs(freqs):
"""Converts the given frequencies (list of numeric values) into probabilities.
This just normalizes them to have sum = 1"""
freqs = list(freqs)
total = float(sum(freqs))
return [f/total for f in freqs]
|
def format_decimal(num: float, decimal_places: int):
"""Formats float as a string with number of decimal places."""
return format(num, '.' + str(decimal_places) + 'f')
|
def get_minidump_keys(crash_info):
"""Get minidump_keys."""
# This is a new crash, so add its minidump to blobstore first and get the
# blob key information.
if crash_info:
return crash_info.store_minidump()
return ''
|
def appname_basename(appname):
"""Returns the base name of the app instance without instance id."""
basename, _taskid = appname.split('#')
return basename
|
def type_aware_equals(expected, actual):
"""
Use the type of expected to convert actual before comparing.
"""
if type(expected) == int:
try:
return expected == int(actual)
except:
return False
elif type(expected) == float:
try:
return expected == float(actual)
except:
return False
elif type(expected) == bool:
try:
return expected == bool(actual)
except:
return False
else:
return '{}'.format(expected) == '{}'.format(actual)
|
def exp_lr_scheduler(optimizer, epoch, lr_decay=0.1, lr_decay_epoch=7):
"""Decay learning rate by a factor of lr_decay every lr_decay_epoch epochs"""
if epoch % lr_decay_epoch:
return optimizer
for param_group in optimizer.param_groups:
param_group['lr'] *= lr_decay
return optimizer
|
def downloadable_version(url):
"""Strip the version out of the git manual download url."""
# example: https://github.com/.../v2.14.1.windows.1/Git-2.14.1-64-bit.exe
return url.split('/')[-2][1:]
|
def _complete(states):
"""Returns as per Task.complete depending on whether ALL elements of the given list are at least that state
Priority is "none", "skipped", "revealed", "complete"; this returns the lowest priority complete value that any
list entry has.
"""
toReturn = "complete"
for state in states:
if state == "none": return "none"
if state == "skipped": toReturn = "skipped"
if state == "revealed" and toReturn != "skipped": toReturn = "revealed"
return toReturn
|
def get_protein_score(average_coverage, coverage):
"""Returns relative coverage
Args:
average_coverage (float): average read coverage in the sample
coverage (float): read coverage of contig
"""
try:
result = coverage / average_coverage
except ZeroDivisionError:
result = coverage
return result
|
def sma_calc(candle_list, period_qty):
"""
Calculate the SMA 20 period.
"""
period_sum = 0.0
for candle in candle_list:
period_sum += candle["close"]
result = period_sum / period_qty
return result
|
def permutations(l):
""" Generate the permutations of l using recursion. """
if not l:
return [[]]
result = []
for i in range(len(l)):
item = l.pop(i)
temp_result = permutations(l)
l.insert(i,item)
for res in temp_result:
res.append(item)
result.extend(temp_result)
return result
|
def _test_categories(line):
"""Returns a tuple indicating whether the line contained categories, the
value of category 1, and the value of category 2."""
if line.lower().startswith('categories : '):
category1 = line[16:48].strip()
category2 = line[48:].strip()
return True, category1, category2
elif line.startswith(' '):
category1 = line[16:48].strip()
category2 = line[48:].strip()
if category1:
return True, category1, category2
else:
return False, '', ''
else:
return False, '', ''
|
def subtract_params(param_list_left: list, param_list_right: list):
"""Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
return [x - y for x, y in zip(param_list_left, param_list_right)]
|
def get_scop_labels_from_string(scop_label):
"""
In [23]: label
Out[23]: 'a.1.1.1'
In [24]: get_scop_labels_from_string(label)
Out[24]: ('a', 'a.1', 'a.1.1', 'a.1.1.1')
"""
class_, fold, superfam, fam = scop_label.split('.')
fold = '.'.join([class_, fold])
superfam = '.'.join([fold, superfam])
fam = '.'.join([superfam, fam])
return class_, fold, superfam, fam
|
def str_to_int(text):
"""Convert strnig with unit to int. e.g. "30 GB" --> 30."""
return int(''.join(c for c in text if c.isdigit()))
|
def get_tuples(l, n=2):
"""Yield successive n-sized chunks from l."""
return [l[i:i + n] for i in range(0, len(l), n)]
|
def arglist_to_dict(arglist):
"""Convert a list of arguments like ['arg1=val1', 'arg2=val2', ...] to a
dict
"""
return dict(x.split('=', 1) for x in arglist)
|
def get2dgridsize(sz, tpb = (8, 8)):
"""Return CUDA grid size for 2d arrays.
:param sz: input array size
:param tpb: (optional) threads per block
"""
bpg0 = (sz[0] + (tpb[0] - 1)) // tpb[0]
bpg1 = (sz[1] + (tpb[1] - 1)) // tpb[1]
return (bpg0, bpg1), tpb
|
def human_readable_list(elements, separator=', ', last_separator=' y ', cap_style='title'):
"""
:param elements: list of elements to be stringyfied
:param separator: join string between two list elements
:param last_separator: join string between the two last list elements
:param type: title (all words first cap), upper (all in caps), lower (all in lowercase), capitalize (first word)
:return: string with all elements joined
"""
if cap_style == 'title':
hrl = last_separator.join(separator.join(elements).rsplit(separator, 1)).title()
elif cap_style == 'upper':
hrl = last_separator.join(separator.join(elements).rsplit(separator, 1)).upper()
elif cap_style == 'lower':
hrl = last_separator.join(separator.join(elements).rsplit(separator, 1)).lower()
else:
hrl = last_separator.join(separator.join(elements).rsplit(separator, 1)).capitalize()
words_to_be_replaced = [' De ', ' Y ', ' E ', ' Al ', ' O ', ' Del ']
for w in words_to_be_replaced:
hrl = hrl.replace(w, w.lower())
return hrl
|
def tags_fromlist(python_list: list) -> str:
"""Format python list into a set of tags in HTML
Args:
python_list (list): python list to format
Returns:
str: Tag formatted list in HTML
"""
strr = ''
for tag in python_list:
strr += f"<button type='button' class='btn btn-outline-info mr-2 mb-1'>{tag}</button>"
return strr
|
def doubleLetter(word, dictionaryTree):
"""Cut the words in the dictionaryTree(stored in a BST) down to only entries with the same double letter"""
splitWord = str.split(word)
letterList = []
double = ""
# Check if the word has a double letter
for letter in splitWord:
if letter in letterList:
double == letter
else:
letterList.append(letter)
# If word does contain a double letter, then cut the dictionaryTree to only words with that double letter.
if double != "":
for words in dictionaryTree.items_pre_order:
letter_count = 0
# If the double letter is present in the word
if double in word:
# Search the word for two or more instances of letter. If there is, append word to dictionaryTree
for letter in str.split(word):
if letter == double:
letter_count += 1
# Checks if the double letter is really present twice or more
if letter_count >= 2:
dictionaryTree.insert(word)
return dictionaryTree
|
def get_digit_c(number, digit):
""" Given a number, returns the digit in the specified position, does not accept out of range digits """
return int(str(number)[-digit])
|
def is_perfect_class(confusion_matrix, k):
"""Check if class k is perfectly predicted."""
errors = sum(confusion_matrix[k]) - confusion_matrix[k][k]
for i in range(len(confusion_matrix)):
if i == k:
continue
errors += confusion_matrix[i][k]
return errors == 0
|
def count_symbol_frequency( text ):
""" Count the frequency of symbol occurances in a body of text.
"""
frequencies = dict()
for ch in text:
if ch in frequencies:
frequencies[ch] += 1
else:
frequencies[ch] = 1
return frequencies
|
def groupOptPanelPlugins(mainControl, typeDict, guiParent=None):
"""
Returns dictionary {pluginTypeName: (pluginObject, pluginTypeName,
humanReadableName, addOptPanel)}
addOptPanel: additional options GUI panel and is always None if
guiParent is None
typeDict -- dictionary {pluginTypeName: (class, pluginTypeName,
humanReadableName)}
"""
preResult = []
classIdToInstanceDict = {}
# First create an object of each exporter class and create list of
# objects with the respective exportType (and human readable export type)
for ctt in typeDict.values():
ob = classIdToInstanceDict.get(id(ctt[0]))
if ob is None:
ob = ctt[0](mainControl)
classIdToInstanceDict[id(ctt[0])] = ob
preResult.append((ob, ctt[1], ctt[2]))
result = {}
if guiParent is None:
# No GUI, just convert to appropriate dictionary
result = {}
for ob, expType, expTypeHr in preResult:
result[expType] = (ob, expType, expTypeHr, None)
return result
else:
# With GUI
# First collect desired exporter types we want from each exporter object
# Each object should only be asked once for the panel list
# with the complete set of exporter types we want from it
objIdToObjExporterTypes = {}
for ob, expType, expTypeHr in preResult:
objIdToObjExporterTypes.setdefault(id(ob), [ob, set()])[1].add(expType)
# Now actually ask for panels from each object and create dictionary from
# export type to panel
# If we would ask the same object multiple times we may get multiple
# equal panels where only one panel is necessary
exportTypeToPanelDict = {}
for ob, expTypeSet in objIdToObjExporterTypes.values():
expTypePanels = ob.getAddOptPanelsForTypes(guiParent, expTypeSet)
for expType, panel in expTypePanels:
if expType in expTypeSet:
exportTypeToPanelDict[expType] = panel
expTypeSet.remove(expType)
# Possibly remaining types not returned by getAddOptPanelsForTypes
# get a None as panel
for expType in expTypeSet:
exportTypeToPanelDict[expType] = None
# Finally create result dictionary
result = {}
for ob, expType, expTypeHr in preResult:
result[expType] = (ob, expType, expTypeHr,
exportTypeToPanelDict[expType])
return result
|
def _container_config(container):
"""Get container configuration"""
config = {}
if container:
for port_map in container.ports.values():
for port in port_map:
config["host"] = port["HostIp"]
config["port"] = port["HostPort"]
return config
|
def generate_uri(host, port, path):
"""
Generates URI string for connection.
Arguments
---------
host: Host string
port: Port string/number
path: Path string without a starting '/'
Returns
-------
A valid URI string.
"""
return "ws://{host}:{port}/{path}".format(
host=host,
port=port,
path=path,
)
|
def get_machine_value(sensitive_machines, address):
"""
Get the value of machine at given address
"""
for m in sensitive_machines:
if m[0] == address[0] and m[1] == address[1]:
return float(m[2])
return 0.0
|
def path_does_not_exist(row):
"""
Check whether any paths exist between the source and target. We know there
isn't a path if the row has a zero path count, or has a zero dwpc if the path
count isn't present in the row
"""
if "path_count" in row:
return row["path_count"] == 0
return row["dwpc"] == 0
|
def ip_diff(ip1, ip2):
"""Return ip2 - ip1
ip1/ip2 should like [*,*,*,*]"""
diff = 0
for i in range(4):
diff = 256 * diff + ip2[i] - ip1[i]
return diff
|
def _get_exec_name(cfg):
"""Helper function to process_function. """
filename = cfg['xcpp']['filename']
root = cfg['xcpp']['root']
libdir = cfg['python']['lib']
if libdir[0] == '/':
base = libdir
else:
base = '%s/%s' % (root, libdir)
out_fname = '%s/%s_pylib.so' % (base, filename)
return out_fname
|
def get_lock_key(object_id):
"""Determines the key to use for locking the ``TimeSlot``"""
return 'locked-%s' % object_id
|
def stats(r):
"""returns the median, average, standard deviation, min and max of a sequence"""
tot = sum(r)
avg = tot/len(r)
sdsq = sum([(i-avg)**2 for i in r])
s = list(r)
s.sort()
return s[len(s)//2], avg, (sdsq/(len(r)-1 or 1))**.5, min(r), max(r)
|
def format_value(value):
"""
When scraping indexable content from the search API, we joined
organisation and topic titles with pipes. Since we are combining
all the columns together here we need to make sure these get treated as
separate words.
"""
return value.replace('|', ' ')
|
def time_format_converter(time_str):
"""Accepts 12-hour format time string and converts it into 24-hour strings"""
if time_str[-2:] == "AM" or time_str[-2:] == "PM":
if time_str[1] == ":":
time_str = "0" + time_str
if time_str[0:2] == "12" and time_str[-2:] == "AM":
return "00:00"
elif time_str[0:2] == "12" and time_str[-2:] == "PM":
return "12:00"
else:
if time_str[-2:] == "PM":
return str(int(time_str[0:2]) + 12) + ":00"
elif time_str[-2:] == "AM":
return time_str[0:2] + ":00"
else:
if time_str[1] == ":":
time_str = "0" + time_str
if time_str[0:2] == "12" and time_str[-4:] == "a.m.":
return "00:00"
elif time_str[0:2] == "12" and time_str[-4:] == "p.m.":
return "12:00"
else:
if time_str[-4:] == "p.m.":
return str(int(time_str[0:2]) + 12) + ":00"
elif time_str[-4:] == "a.m.":
return time_str[0:2] + ":00"
|
def repr_type_and_name(thing):
"""Print thing's type [and name]"""
s = "<" + type(thing).__name__ + '>'
if hasattr(thing,'name'):
s += ': ' + thing.name
return s
|
def imageurl(value): # Only one argument.
"""Converts a string into all lowercase"""
value.split(" ")
return value.lower()
|
def get_json(nifti_path):
"""
Get associated JSON of input file
"""
return nifti_path.replace(".nii.gz", ".json").replace(".nii", ".json")
|
def display(computer, name, value):
"""Compute the ``display`` property.
See http://www.w3.org/TR/CSS21/visuren.html#dis-pos-flo
"""
float_ = computer['specified']['float']
position = computer['specified']['position']
if position in ('absolute', 'fixed') or float_ != 'none' or \
computer['is_root_element']:
if value == 'inline-table':
return'table'
elif value in ('inline', 'table-row-group', 'table-column',
'table-column-group', 'table-header-group',
'table-footer-group', 'table-row', 'table-cell',
'table-caption', 'inline-block'):
return 'block'
return value
|
def value_for_dsd_ref(kind, args, kwargs):
"""Maybe replace a string 'value_for' in *kwargs* with a DSD reference."""
try:
dsd = kwargs.pop("dsd")
descriptor = getattr(dsd, kind + "s")
kwargs["value_for"] = descriptor.get(kwargs["value_for"])
except KeyError:
pass
return args, kwargs
|
def coord_for(n, a=0, b=1):
"""Function that takes 3 parameters or arguments, listed above, and returns a list of the interval division coordinates."""
a=float(a)
b=float(b)
coords = []
inc = (b-a)/ n
for x in range(n+1):
coords.append(a+inc*x)
return coords
|
def dot(a, b):
"""Dot product of vectors a and b."""
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
|
def tokensMatch(expectedTokens, receivedTokens, ignoreErrorOrder):
"""Test whether the test has passed or failed
If the ignoreErrorOrder flag is set to true we don't test the relative
positions of parse errors and non parse errors
"""
if not ignoreErrorOrder:
return expectedTokens == receivedTokens
else:
#Sort the tokens into two groups; non-parse errors and parse errors
tokens = {"expected":[[],[]], "received":[[],[]]}
for tokenType, tokenList in zip(tokens.keys(),
(expectedTokens, receivedTokens)):
for token in tokenList:
if token != "ParseError":
tokens[tokenType][0].append(token)
else:
tokens[tokenType][1].append(token)
return tokens["expected"] == tokens["received"]
|
def make_wget(urls):
"""Download multiple URLs with `wget`
Parameters
----------
urls : list
A list of URLs to download from
"""
return 'wget -c {}'.format(' '.join(urls))
|
def xmltodict_ensure_list(value, key):
"""Make sure response is a list
xmltodict doesn't know schema's so doesn't know
something should be a list or not.
"""
if value is None:
return []
value = value[key]
if isinstance(value, list):
return value
return [value]
|
def exact_value_scoring(values_list1, values_list2, values1, values2):
"""
pass this two lists of values from a pair of facets and it will
give a score for exact value matches
"""
if len(values_list1) > 0 and len(values_list2) > 0:
total_attributes = len(values_list1) + len(values_list2)
matching_attributes = len(set(values_list1) & set(values_list2))
match_freq = 0
# print(values_list1)
# print(values_list2)
for k in values_list1:
if k in values_list2:
freq = values1.get(k) + values2.get(k)
match_freq = match_freq + freq
total_freq = sum(values1.values()) + sum(values2.values())
score = ((matching_attributes * 2) / (total_attributes)) * (match_freq / total_freq)
return score
else:
score = 0
return score
|
def log_compress(env_image):
"""
Log compression of envelope detected US image
:param env_image: numpy array of envelope detected
US data
:return: numpy array of log compressed US image
"""
import sys
import numpy as np
import logging
img_type = type(env_image).__module__
if img_type != np.__name__:
msg = 'ERROR [log_compress] input is not numpy array. ' \
'Exiting script...'
print(msg)
logging.error(msg)
sys.exit()
scaled_image = env_image/env_image.max()
log_image = 20*np.log10(scaled_image)
msg = '[log_compress] Log compression finished.'
print(msg)
logging.debug(msg)
return log_image
|
def validateLabel(value):
"""
Validate label for spatial database.
"""
if 0 == len(value):
raise ValueError("Descriptive label for spatial database not specified.")
return value
|
def bug11569(debugger, args, result, dict):
"""
http://llvm.org/bugs/show_bug.cgi?id=11569
LLDBSwigPythonCallCommand crashes when a command script returns an object.
"""
return ["return", "a", "non-string", "should", "not", "crash", "LLDB"]
|
def xy_to_id(x: int, y: int, nelx: int, nely: int, order: str = "F") -> int:
"""
Map from 2D indices of a node to the flattened 1D index.
The number of elements is (nelx x nely), and the number of nodes is
(nelx + 1) x (nely + 1).
Parameters
----------
x:
The x-coordinate of the node's positions.
y:
The y-coordinate of the node's positions.
nelx:
The number of elements in the x-direction.
nely:
The number of elements in the y-direction.
order:
The order of indecies. "F" for Fortran/column-major order and "C" for
C/row-major order.
Returns
-------
The index of the node in the flattened version.
"""
if order == "C":
return (y * (nelx + 1)) + x
else:
return (x * (nely + 1)) + y
|
def match_nodes(nodes1, nodes2, excluded=[]):
"""
:param nodes1: A list of Nodes from the DMRS to be matched, sorted by span_pred_key.
:param nodes2: A list of Nodes from the DMRS against which we match, sorted by span_pred_key.
:param excluded: A list of nodeids which should not be used for matching.
:return: A list of lists of nodeid pairs. The first element in the pair is from small DMRS, the second from the
larger one. The pairs are listed in reverse span_pred_key order of the corresponding nodes. Returns [] if no
match found.
"""
if not nodes1 or not nodes2:
return []
matches = []
earliest = len(nodes1)
longest = 0
for i, node2 in enumerate(nodes2):
if len(nodes2) - i < longest: # Not enough nodes left to beat the current longest match.
break
if excluded and node2.nodeid in excluded:
continue
for j, node1 in enumerate(nodes1):
if j > earliest: # To avoid repetition.
break
if node1 == node2:
best_matches = match_nodes(nodes1[j + 1:], nodes2[i + 1:], excluded=excluded)
if best_matches:
for match in best_matches:
match.append((node1.nodeid, node2.nodeid))
else:
best_matches = [[(node1.nodeid, node2.nodeid)]]
earliest = j
longest = max(longest, len(best_matches[0]))
matches.extend(best_matches)
if matches:
max_len = len(max(matches, key=len))
return [m for m in matches if len(m) == max_len]
else:
return []
|
def getPointOnLine(x1, y1, x2, y2, n):
"""Returns the (x, y) tuple of the point that has progressed a proportion
n along the line defined by the two x, y coordinates.
Args:
x1 (int, float): The x coordinate of the line's start point.
y1 (int, float): The y coordinate of the line's start point.
x2 (int, float): The x coordinate of the line's end point.
y2 (int, float): The y coordiante of the line's end point.
n (float): Progress along the line. 0.0 is the start point, 1.0 is the end point. 0.5 is the midpoint. This value can be less than 0.0 or greater than 1.0.
Returns:
Tuple of floats for the x, y coordinate of the point.
Example:
>>> getPointOnLine(0, 0, 6, 6, 0)
(0, 0)
>>> getPointOnLine(0, 0, 6, 6, 1)
(6, 6)
>>> getPointOnLine(0, 0, 6, 6, 0.5)
(3.0, 3.0)
>>> getPointOnLine(0, 0, 6, 6, 0.75)
(4.5, 4.5)
>>> getPointOnLine(3, 3, -3, -3, 0.5)
(0.0, 0.0)
>>> getPointOnLine(3, 3, -3, -3, 0.25)
(1.5, 1.5)
>>> getPointOnLine(3, 3, -3, -3, 0.75)
(-1.5, -1.5)
"""
x = ((x2 - x1) * n) + x1
y = ((y2 - y1) * n) + y1
return (x, y)
|
def maf_bubble(lst):
""" Sorts a list using a bubblesort algorithm """
for p in range(len(lst)-1, 0, -1):
for i in range(p):
if lst[i] > lst[i + 1]:
t = lst[i]
lst[i] = lst[i + 1]
lst[i + 1] = t
return lst
|
def dequote(name):
""" dequote if need be """
if name[0] == '"' and name[-1] == '"':
return name[1:-1]
return name
|
def parse_bucket_id(bucket_id):
"""Returns a (project_id, bucket_name) tuple."""
parts = bucket_id.split('/', 1)
assert len(parts) == 2
return tuple(parts)
|
def flatten(lis: list) -> list:
"""
Given a list, possibly nested to any level, return it flattened.
From: http://code.activestate.com/recipes/578948-flattening-an-arbitrarily-nested-list-in-python/
"""
new_lis = []
for item in lis:
if isinstance(item, list):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis
|
def force_unicode(text) -> str:
""" Encodes a string as UTF-8 if it isn't already """
try: return str(text, 'utf-8')
except TypeError: return text
|
def sign(num):
""":yaql:sign
Returns 1 if num > 0; 0 if num = 0; -1 if num < 0.
:signature: sign(num)
:arg num: input value
:argType num: number
:returnType: integer (-1, 0 or 1)
.. code::
yaql> sign(2)
1
"""
if num > 0:
return 1
elif num < 0:
return -1
return 0
|
def binary_array_to_number(arr):
"""Returns decimal from the contactanation of the given binary list"""
return int(''.join([str(x) for x in arr]),2)
|
def matches(open_symbol: str, close_symbol: str) -> bool:
"""Checks if the opening and closing sybols match"""
symbol_close_map = {"(": ")", "[": "]", "{": "}"}
return close_symbol == symbol_close_map.get(open_symbol)
|
def FilterEmptyLinesAndComments(text):
"""Filters empty lines and comments from a line-based string.
Whitespace is also removed from the beginning and end of all lines.
@type text: string
@param text: Input string
@rtype: list
"""
return [line for line in map(lambda s: s.strip(), text.splitlines())
# Ignore empty lines and comments
if line and not line.startswith("#")]
|
def ksf_cast(value, arg):
"""
Checks to see if the value is a simple cast of the arg
and vice-versa
"""
# untaint will simplify the casting... not in pypyt!
v = value
a = arg
a_type = type(a)
v_type = type(v)
if v_type == a_type:
return v == a
try:
casted_v = a_type(v)
if casted_v == a:
return True
except TypeError:
pass
except ValueError:
pass
try:
casted_a = v_type(a)
if casted_a == v:
return True
except TypeError:
pass
except ValueError:
pass
return False
|
def _pattern_has_uppercase(pattern):
""" Check whether the given regex pattern has uppercase letters to match
"""
# Somewhat rough - check for uppercase chars not following an escape
# char (which may mean valid regex flags like \A or \B)
skipnext = False
for c in pattern:
if skipnext:
skipnext = False
continue
elif c == '\\':
skipnext = True
else:
if c >= 'A' and c <= 'Z':
return True
return False
|
def is_lookup_in_users_path(lookup_file_path):
"""
Determine if the lookup is within the user's path as opposed to being within the apps path.
"""
if "etc/users/" in lookup_file_path:
return True
else:
return False
|
def asciidec(val):
"""
Convert an integer to ascii, i.e. a list of integers in base 256.
Examples:
- asciidec(434591) = 6 * 256**2 + 161 * 256**1 + 159 * 256**0
- asciidec(797373) = 12 * 256**2 + 42 * 256**1 + 189 * 256**0
"""
word = []
while val > 0:
word.append(val % 256)
val = val // 256
return word[-1::-1]
|
def shape_to_HW(shape):
""" Convert from WH => HW
"""
if len(shape) != 2:
return shape # Not WH, return as is
return [shape[1], 1, 1, shape[0]]
|
def get_account_ids_from_match(*matches: dict):
"""From an initial list of matches, find all account ids."""
account_ids = []
for match in matches:
for participant in match['participantIdentities']:
account_ids.append(participant['player']['accountId'])
return list(set(account_ids))
|
def long2ip(ip):
"""Converts an integer representation of an IP address to string."""
from socket import inet_ntoa
from struct import pack
return inet_ntoa(pack('!L', ip))
|
def filter_even(input):
"""
[5, 6, 7] -> [6]
:return:
"""
return list(filter(
lambda i: i % 2 == 0,
input
))
|
def is_comment(line):
"""
Check if a line consists only of whitespace and
(optionally) a comment.
"""
line = line.strip()
return line == '' or line.startswith('#')
|
def readFile(path):
"""Read data from a file.
@param path: The path of the file to read.
@type path: string
@return: The data read from the file.
@rtype: string
"""
f = open(path, "rb")
try:
return f.read()
finally:
f.close()
|
def day_spent(records):
"""Return the total time spent for given day"""
return sum([int(record['time']) for record in records])
|
def _extract_path(srcs):
"""Takes the first label in srcs and returns its target name.
Args:
srcs: a collection of build labels of the form "//package/name:target"
Returns:
The first element's target (i.e.- the part after the ":"), else None if empty.
"""
for s in srcs:
toks = s.split(":")
if len(toks) == 2:
return toks[1]
return None
|
def expand_data_indicies(label_indices, data_per_label=1):
"""
when data_per_label > 1, gives the corresponding data indicies for the data
indicies
"""
import numpy as np
expanded_indicies = [
label_indices * data_per_label + count for count in range(data_per_label)
]
data_indices = np.vstack(expanded_indicies).T.flatten()
return data_indices
|
def compute_f1score(precision, recall):
""" Function to compute F1 Score"""
if precision * recall == 0:
return 0
return float(2 * precision * recall) / float(precision + recall)
|
def validate_tls_security_policy(tls_security_policy):
"""
Validate TLS Security Policy for ElasticsearchDomain
Property: DomainEndpointOptions.TLSSecurityPolicy
"""
VALID_TLS_SECURITY_POLICIES = (
"Policy-Min-TLS-1-0-2019-07",
"Policy-Min-TLS-1-2-2019-07",
)
if tls_security_policy not in VALID_TLS_SECURITY_POLICIES:
raise ValueError(
"Minimum TLS Security Policy must be one of: %s"
% ", ".join(VALID_TLS_SECURITY_POLICIES)
)
return tls_security_policy
|
def generate_permulations(param_list):
"""
param_list is a list(types of parameter) of list(possible parameter values)
returns a list(all permulation) of list(parameter value) in same order
as in param_list
"""
permu = []
def recurse(param_type_index, current_param_value, param_list):
if param_type_index == len(param_list):
permu.append(current_param_value)
else:
for val in param_list[param_type_index]:
temp = current_param_value.copy()
temp.append(val)
recurse(param_type_index+1, temp, param_list)
recurse(0, [], param_list)
return permu
|
def product(factors):
"""Return the product of all numbers in the given list."""
prod = 1
for f in factors:
prod *= f
return prod
|
def non_negative(start, idx1, idx2, symbol):
"""
Returns SMT constrains about constants being non-negative
"""
result = ""
for i in range(start, idx1):
for j in range(idx2):
const_name = symbol + str(i) + "_" + str(j)
result += "(>= " + const_name + " 0)\n"
return result
|
def get_good_dim(dim):
"""
This function calculates the dimension supported by opencl library (i.e. is multiplier of 2, 3, or 5) and is closest to the given starting dimension.
If the dimension is not supported the function adds 1 and verifies the new dimension. It iterates until it finds supported value.
Parameters
----------
dim : int
initial dimension
Returns
-------
new_dim : int
a dimension that is supported by the opencl library, and closest to the original dimension
"""
def is_correct(x):
sub = x
if sub % 3 == 0:
sub = sub / 3
if sub % 3 == 0:
sub = sub / 3
if sub % 5 == 0:
sub = sub / 5
while sub % 2 == 0:
sub = sub / 2
return sub == 1
new_dim = dim
if new_dim % 2 == 1:
new_dim += 1
while not is_correct(new_dim):
new_dim += 2
return new_dim
|
def retrieve_captions(data_list):
"""
Reads the captions from a list and returns them
Args:
data_list (list<dict>): List of image metadata
Returns:
merged_captions (list<str>): List of captions from the dataset
"""
caption_list = []
for data in data_list:
for article in data['articles']:
caption_list.append(article['caption'])
return caption_list
|
def _min_or_none(itr):
"""
Return the lowest value in itr, or None if itr is empty.
In python 3, this is just min(itr, default=None)
"""
try:
return min(itr)
except ValueError:
return None
|
def node_dict(node):
"""Convert a node object to a result dict"""
if node:
return {
'node_id': node.id,
'workers': ", ".join(node.workers),
'disks': ", ".join(node.disks),
'ram': node.memory,
'load_average' : node.load_average,
}
else:
return {}
|
def parse_tab_list_view(lines, key='Name', sep=":"):
"""
:param lines:
:param key:
:return: list of dictionaries
"""
res = list()
temp = dict()
if isinstance(lines, str):
lines = lines.splitlines()
for line in lines:
if not line:
continue
sep_pos = line.find(sep)
if sep_pos == -1:
raise Exception("separator is not found on the output line")
k = line[:sep_pos]
v = line[sep_pos+1:]
k = k.strip()
v = v.strip()
if line.startswith(key):
if temp:
res.append(temp)
temp = dict()
temp[k] = v
res.append(temp)
return res
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.