content
stringlengths 42
6.51k
|
---|
def _unquote(string: str) -> str:
"""Removes the double quotes surrounding a string."""
return string[1:-1]
|
def list_to_svm_line(original_list):
"""
Concatenates list elements in consecutive element pairs.
Parameters
----------
original_list : list
The elements to be joined
Returns
-------
String
Returns a string, resulting from concatenation of list elements in consecutive element pairs, separeted by " ".
Example
-------
>>> from pymove import conversions
>>> a = [1, 2, 3, 4, 5]
>>> conversions.list_to_svm_line(a)
'1 1:2 2:3 3:4 4:5'
"""
list_size = len(original_list)
svm_line = "%s " % original_list[0]
for i in range(1, list_size):
svm_line += "{}:{} ".format(i, original_list[i])
return svm_line.rstrip()
|
def random_ints(count=20, min=1, max=50):
"""Return a list of `count` integers sampled uniformly at random from
given range [`min`...`max`] with replacement (duplicates are allowed)."""
import random
return [random.randint(min, max) for _ in range(count)]
|
def divide_lists(ls, by):
"""
Divide lists by 'by'.
"""
return [x / float(by) for x in ls]
|
def GenerateAnnulusNodeToRZPhi(nRCoords, nZCoords, phiPoints):
"""
Generate the map from node IDs to r, z phi IDs for a structured 3D linear
tet annulus mesh
"""
nodeToRzphi = []
index = 0
index = 0
for i in range(nRCoords):
for j in range(nZCoords):
for k in range(phiPoints):
nodeToRzphi.append((i, j, k))
return nodeToRzphi
|
def restructure_opentarget_response(json_doc):
"""
Restructure the API output from opentarget API.
:param: json_doc: json output from opentarget API
"""
if not json_doc.get("data"):
return json_doc
for _doc in json_doc['data']:
if "drug" in _doc:
if "CHEMBL" in _doc['drug']['id']:
_doc['drug']['id'] = _doc['drug']['id'].split('/')[-1]
return json_doc
|
def calculate(name_list):
"""Returns the sum of the alphabetical value for each name
in the list multiplied by its position in the list"""
return sum(
(i + 1) * (ord(c) - ord("A") + 1)
for i, name in enumerate(sorted(name_list))
for c in name.strip('"')
)
|
def triangle_n(n):
"""Returns the nth triangle number"""
return int(n * (n + 1) / 2)
|
def version_1_39_12(model_dict):
"""Implement changes in a Model dict to make it compatible with version 1.39.12."""
removed_equip = 'PSZ-AC district chilled water with baseboard district hot water'
replaced_equip = 'PSZ-AC district chilled water with district hot water'
if 'energy' in model_dict['properties']:
if 'hvacs' in model_dict['properties']['energy']:
for hvac in model_dict['properties']['energy']['hvacs']:
if hvac['type'] != 'IdealAirSystemAbridged' and \
hvac['equipment_type'] == removed_equip:
hvac['equipment_type'] = replaced_equip
return model_dict
|
def remove_common_molecules(reactants, products):
"""
Removes common species between two lists leaving only reacting species.
Parameters
----------
reactants, products : list of str
List containing strings all molecular species.
Returns
-------
tuple of str
Reduced lists for both reactants and products such that only species
that participate in the reaction remain.
"""
reduced_react = reactants.copy()
reduced_prod = products.copy()
reduced_react.sort()
reduced_prod.sort()
if reduced_react == reduced_prod:
raise Exception("Reactants and products are the same.")
else:
pass
for mol in reactants:
if mol in reduced_prod:
reduced_prod.remove(mol)
reduced_react.remove(mol)
return (reduced_react, reduced_prod)
|
def project_sorted(row, sorted_cols):
"""Extract the values in the ORDER BY columns from a row.
"""
return [ row[col] for col in sorted_cols ]
|
def get_kth_inorder_record(root, k):
"""
Question 10.7
"""
current_num = 0
cur = root
prev = None
while cur:
next_node = None
if cur.parent == prev:
if cur.left:
next_node = cur.left
else:
current_num += 1
if current_num == k:
return cur.val
next_node = cur.right if cur.right else cur.parent
elif cur.left == prev:
current_num += 1
if current_num == k:
return cur.val
next_node = cur.right if cur.right else cur.parent
else:
next_node = cur.parent
prev = cur
cur = next_node
return None
|
def binary_search(given_array, key, starting_index, ending_index):
""" Using binary search method to find the accurate(inplace) place for 'key'
to reduce the complexity for comparisons of insertion sort"""
if starting_index == ending_index:
if given_array[starting_index] > key:
return starting_index
else:
return starting_index + 1
if starting_index > ending_index:
return starting_index
# Binary Search process starts from here.
mid = (starting_index + ending_index) // 2
if given_array[mid] < key:
return binary_search(given_array, key, mid + 1, ending_index)
elif given_array[mid] > key:
return binary_search(given_array, key, starting_index, mid)
elif given_array[mid] == key:
return mid
|
def _create_default_branch_id(repo_url, default_branch_ref_id):
"""
Return a unique node id for a repo's defaultBranchId using the given repo_url and default_branch_ref_id.
This ensures that default branches for each GitHub repo are unique nodes in the graph.
"""
return f"{repo_url}:{default_branch_ref_id}"
|
def i_sort_rec(seq, i=None):
""" perform insertion sort recursively"""
# if the sequence is empty return it
if not seq:
return seq
if i is None:
i=len(seq)
if i==1:
return
i_sort_rec(seq, i-1)
val = seq[i-1]
del seq[i-1]
seq.insert(0, val)
i2 = 0
while i2 < i-1 and seq[i2+1]<seq[i2]:
seq[i2], seq[i2+1] = seq[i2+1], seq[i2]
i2+=1
|
def two_opt_swap(r: list, i: int, k: int) -> list:
"""Reverses items `i`:`k` in the list `r`
https://en.wikipedia.org/wiki/2-opt."""
out = r.copy()
out[i:k + 1] = out[k:i - 1:-1]
return out
|
def get_resource_group_name_by_resource_id(resource_id):
"""Returns the resource group name from parsing the resource id.
:param str resource_id: The resource id
"""
resource_id = resource_id.lower()
resource_group_keyword = '/resourcegroups/'
return resource_id[resource_id.index(resource_group_keyword) + len(
resource_group_keyword): resource_id.index('/providers/')]
|
def DIVIDE(x, y):
"""
Divides one number by another and returns the result.
See https://docs.mongodb.com/manual/reference/operator/aggregation/divide/
for more details
:param x: The number or field of number (is the dividend)
:param y: The number or field of number (is the divisor)
:return: Aggregation operator
"""
return {'$divide': [x, y]}
|
def _rule_compare(rule1, rule2):
"""
Compare the common keys between security group rules against eachother
"""
commonkeys = set(rule1.keys()).intersection(rule2.keys())
for key in commonkeys:
if rule1[key] != rule2[key]:
return False
return True
|
def normalize(c: str) -> str:
"""Returns the given char if alphanumeric, or normalizes/elides it"""
if c.isalnum():
return c
elif c == '-':
return '_'
else:
return ''
|
def oneHotEncode_4_evtypes(x, r_vals=None):
"""
This function one hot encodes the input for the event types
cascade, tracks, doubel-bang, starting tracks
"""
cascade = [1., 0., 0., 0.]
track = [0., 1., 0., 0.]
doublebang = [0., 0., 1., 0.]
s_track = [0., 0., 0., 1.]
# map x to possible classes
mapping = {0: cascade, 1: cascade, 2: track, 3: s_track, 4: track,
5: doublebang, 6: doublebang, 7: cascade, 8: track, 9: cascade}
return mapping[int(x)]
|
def duration_hm(time_delta):
"""time_delta -> 1:01"""
minutes, s = divmod(time_delta, 60)
h, minutes = divmod(minutes, 60)
return "%d:%02d" % (h, minutes)
|
def get_object_value(value) -> str:
"""Get value from object or enum."""
while hasattr(value, "value"):
value = value.value
return value
|
def get_ticker_name(s: str) -> str:
"""Gets ticker name from file name."""
x = s.find('_')
name = s[:x]
return name
|
def hk_obc_enabled(bits: list) -> bytes:
"""
First bit should be on the left, bitfield is read from left to right
"""
enabled_bits = 0
bits.reverse()
for i in range(len(bits)):
enabled_bits |= bits[i] << i
return enabled_bits.to_bytes(4, byteorder='big')
|
def num_docs(a):
""" Return a dict with all the documents returned in all
queries """
full_prediction_set = {}
for item in a:
for doc in a[item]:
if doc not in full_prediction_set:
full_prediction_set[doc] = 0
full_prediction_set[doc] += 1
return full_prediction_set
|
def dequantize(Q, cp, cn):
"""
Dequanitze from the given 1-bit quantization and the reconstruction values.
Parameters:
Q : input quantized values (+/- 1)
cp: center of the quantization bins for positive values
cn: center of the quantization bins for negative values
"""
Qn = 1 - Q
Wh = cp * Q + cn * Qn
return Wh
|
def hinge_loss(predicted_value: float, real_label: float) -> float:
"""
Computes hinge loss for given predicted value, given the real label.
:param predicted_value: inner product of data sample and coefficient
vector, possibly corrected by intercept
:param real_label: Real label
:return: Hinge loss of datapoint
"""
return max(0, 1 - real_label * predicted_value)
|
def parameterize(ref):
"""Rewrites attributes to match the kwarg naming convention in client.
>>> paramterize({'project_id': 0})
{'project': 0}
"""
params = ref.copy()
for key in ref:
if key[-3:] == '_id':
params.setdefault(key[:-3], params.pop(key))
return params
|
def _join_smt2(seq, conn):
"""Produces a SMT-LIB 2.0 formula containing all elements of the sequence merged by a provided connective."""
if len(seq) == 0:
return ''
elif len(seq) == 1:
return seq[0]
else:
return '({0} {1})'.format(conn, ' '.join(seq))
|
def count_pattern(pattern, lst):
"""
count_pattern() returns the count of the number of times that the pattern occurs in the lst
"""
count = 0
if type(pattern) != type(lst):
raise TypeError("count_pattern() : arguments must be of the same type")
elif not pattern or not lst:
return count
else:
# size of the pattern and the lst
patternlength = len(pattern)
lstlength = len(lst)
# if the pattern is longer than the lst, quit out
if patternlength > lstlength:
return count
# otherwise look for matches
else:
# for the maximum total possible matches
for ii in range(lstlength - patternlength + 1):
# step the pattern through the lst
candidatematch = lst[ii:(ii + patternlength)]
# if it's a match, increment the count of the matches
if pattern == candidatematch:
count += 1
return count
|
def indent_string(the_string, indent_level):
"""Indents the given string by a given number of spaces
Args:
the_string: str
indent_level: int
Returns a new string that is the same as the_string, except that
each line is indented by 'indent_level' spaces.
In python3, this can be done with textwrap.indent.
"""
lines = the_string.splitlines(True)
padding = ' ' * indent_level
lines_indented = [padding + line for line in lines]
return ''.join(lines_indented)
|
def get_readout_time(dicom_img, dcm_info, dwell_time):
""" Get read out time from a dicom image.
Parameters
----------
dicom_img: dicom.dataset.FileDataset object
one of the dicom image loaded by pydicom.
dcm_info: dict
array containing dicom data.
dwell_time: float
Effective echo spacing in s.
Returns
-------
readout_time: float
read-out time in seconds.
For philips scanner
~~~~~~~~~~~~~~~~~~~
Formula to compute read out time:
echo spacing (seconds) * (epi - 1) where
epi = nb of phase encoding steps/ acceleration factor.
For Siemens and GE scanners
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Readout time is written by dcm2niix in json summary dcm_info.
"""
manufacturer = dcm_info["Manufacturer"]
if manufacturer.upper() in ["SIEMENS", "GE MEDICAL SYSTEMS", "GE"]:
readout_time = dcm_info["TotalReadoutTime"]
elif manufacturer.upper() in ["PHILIPS MEDICAL SYSTEMS", "PHILIPS"]:
acceleration_factor = dicom_img[int("2005", 16),
int("140f", 16)][0][24, 36969].value
etl = float(dicom_img[0x0018, 0x0089].value)
readout_time = dwell_time * (etl - 1)
else:
raise ValueError("Unknown manufacturer : {0}".format(manufacturer))
return readout_time
|
def without_http_prefix(url):
"""
Returns a URL without the http:// or https:// prefixes
"""
if url.startswith('http://'):
return url[7:]
elif url.startswith('https://'):
return url[8:]
return url
|
def subset_with_values(target, lst):
"""Determines whether or not it is possible to create the target sum using
values in the list. Values in the list can be positive, negative, or zero.
The function returns a tuple of exactly two items. The first is a boolean,
that indicates true if the sum is possible and false if it is not. The second
element in the tuple is a list of all values that add up to make the target sum."""
if target == 0:
return(True, [])
if lst == []:
return(False, [])
use_it = subset_with_values(target - lst[0], lst[1:])
if use_it[0]:
return(True, [lst[0]] + use_it[1])
return subset_with_values(target, lst[1:])
|
def gabfr_nbrs(gabfr):
"""
gabfr_nbrs(gabfr)
Returns the numbers corresponding to the Gabor frame letters
(A, B, C, D/U, G).
Required args:
- gabfr (str or list): gabor frame letter(s)
Returns:
- gab_nbr (int or list): gabor frame number(s)
"""
if not isinstance(gabfr, list):
gabfr_list = False
gabfr = [gabfr]
else:
gabfr_list = True
all_gabfr = ["A", "B", "C", "D", "U", "D/U", "G"]
all_gabnbr = [0, 1, 2, 3, 3, 3, 4]
gabfr = [
all_gabfr[all_gabnbr.index(fr)]
if fr in all_gabnbr else fr
for fr in gabfr
]
if sum([g not in all_gabfr for g in gabfr]):
raise ValueError("Gabor frames letters include A, B, C, D, U and G only.")
if gabfr_list:
gab_nbr = [all_gabnbr[all_gabfr.index(g)] for g in gabfr]
else:
gab_nbr = all_gabnbr[all_gabfr.index(gabfr[0])]
return gab_nbr
|
def rpower(n, k):
"""Recursive divide and conquer"""
if k == 0: return 1
p = rpower(n, k >> 1)
if k & 1: return n * p * p
return p * p
|
def is_alphanumeric(word: str, valid_punctuation_marks: str = '-') -> bool:
"""
Check if a word contains only alpha-numeric
characters and valid punctuation marks.
Parameters
----------
word: `str`
The given word
valid_punctuation_marks: `str`
Punctuation marks that are valid, defaults to `'-'`.
Returns
-------
result: `bool`
The result
"""
for punctuation_mark in valid_punctuation_marks.split():
word = word.replace(punctuation_mark, '')
return word.isalnum()
|
def reverse(string):
"""Native reverse of a string looks a little bit cryptic,
just a readable wrapper"""
return string[::-1]
|
def dec_indent(indent, count=1):
"""
decrease indent, e.g.
if indent = " ", and count = 1, return " ",
if indent = " ", and count = 2, return "",
"""
if indent.endswith('\t'):
indent = indent[:len(indent) - 1 * count]
elif indent.endswith(' '):
indent = indent[:len(indent) - 4 * count]
return indent
|
def cut(string, characters=2, trailing="normal"):
"""
Split a string into a list of N characters each.
.. code:: python
reusables.cut("abcdefghi")
# ['ab', 'cd', 'ef', 'gh', 'i']
trailing gives you the following options:
* normal: leaves remaining characters in their own last position
* remove: return the list without the remainder characters
* combine: add the remainder characters to the previous set
* error: raise an IndexError if there are remaining characters
.. code:: python
reusables.cut("abcdefghi", 2, "error")
# Traceback (most recent call last):
# ...
# IndexError: String of length 9 not divisible by 2 to splice
reusables.cut("abcdefghi", 2, "remove")
# ['ab', 'cd', 'ef', 'gh']
reusables.cut("abcdefghi", 2, "combine")
# ['ab', 'cd', 'ef', 'ghi']
:param string: string to modify
:param characters: how many characters to split it into
:param trailing: "normal", "remove", "combine", or "error"
:return: list of the cut string
"""
split_str = [string[i : i + characters] for i in range(0, len(string), characters)]
if trailing != "normal" and len(split_str[-1]) != characters:
if trailing.lower() == "remove":
return split_str[:-1]
if trailing.lower() == "combine" and len(split_str) >= 2:
return split_str[:-2] + [split_str[-2] + split_str[-1]]
if trailing.lower() == "error":
raise IndexError("String of length {0} not divisible by {1} to" " cut".format(len(string), characters))
return split_str
|
def isFormedBy(part, symbol_set):
"""
>>> from production import Production
>>> p = Production(['A'], ['A', 'b', 'C'])
>>> isFormedBy(p.right, ['A', 'b', 'C', 'd'])
True
>>> isFormedBy(p.right, ['A', 'B', 'C', 'd'])
False
"""
for option in part:
for symbol in option:
if symbol not in symbol_set:
return False
return True
|
def flatten(xs):
"""Recursively flattens a list of lists of lists (arbitrarily,
non-uniformly deep) into a single big list.
"""
res = []
def loop(ys):
for i in ys:
if isinstance(i, list):
loop(i)
elif i is None:
pass
else:
res.append(i)
loop(xs)
return res
|
def bytesto(bytes, to, bsize=1024):
"""convert bytes to megabytes.
bytes to mb: bytesto(bytes, 'm')
bytes to gb: bytesto(bytes, 'g' etc.
From https://gist.github.com/shawnbutts/3906915
"""
levels = {"k": 1, "m": 2, "g": 3, "t": 4, "p": 5, "e": 6}
answer = float(bytes)
for _ in range(levels[to]):
answer = answer / bsize
return answer
|
def merge_dict(a, b, path=None):
"""merge b into a. The values in b will override values in a.
Args:
a (dict): dict to merge to.
b (dict): dict to merge from.
Returns: dict1 with values merged from b.
"""
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dict(a[key], b[key], path + [str(key)])
else:
a[key] = b[key]
else:
a[key] = b[key]
return a
|
def username_first(twitter_data, a, b):
""" (Twitterverse dictionary, str, str) -> int
Return 1 if user a has a username that comes after user b's username
alphabetically, -1 if user a's username comes before user b's username,
and 0 if a tie, based on the data in twitter_data.
>>> twitter_data = {\
'a':{'name':'', 'location':'', 'web':'', 'bio':'', 'following':['b']}, \
'b':{'name':'', 'location':'', 'web':'', 'bio':'', 'following':[]}, \
'c':{'name':'', 'location':'', 'web':'', 'bio':'', 'following':[]}}
>>> username_first(twitter_data, 'c', 'b')
1
>>> username_first(twitter_data, 'a', 'b')
-1
"""
if a < b:
return -1
if a > b:
return 1
return 0
|
def split_epiweek(epiweek):
""" return a (year, week) pair from this epiweek """
return (epiweek // 100, epiweek % 100)
|
def dup_factions(factions, num_winners):
"""Expand a list of factions by a factor of num_winners into a list of candidates
>>> dup_factions(['A', 'B'], 3)
['A1', 'A2', 'A3', 'B1', 'B2', 'B3']
"""
return [f'{f}{n}' for f in factions for n in range(1, num_winners+1)]
|
def _merge_entities(e1, e2, primary_property, other_properties=None):
"""
Merge dict objects e1 and e2 so that the resulting dict has the data from both.
Entities are in-particular dicts which may contain an "identifier" field, such as
used by projects and authors.
The primary_property names the field in the dict which can be used to confirm that
e1 and e2 reference the same entity, in the event that no matching identifiers are present.
If no identifier is present, and the primary_property values do not match, then this merge
will not proceed.
The other_properties is an explicit list of the properties that should be merged to form
the final output (no need to list the primary_property)
:param e1: first entity object
:param e2: second entity object
:param primary_property: primary way to assert two entities refer to the same thing
:param other_properties: explicit list of properties to merge
:return: True if the merge was successfully carried out (with e1 as the decisive object), False if not
"""
if other_properties is None:
other_properties = []
# 1. If both entities have identifiers and one matches, they are equivalent and missing properties/identifiers should be added
if e2.get("identifier") is not None and e1.get("identifier") is not None:
for maid in e2.get("identifier"):
for raid in e1.get("identifier"):
if maid.get("type") == raid.get("type") and maid.get("id") == raid.get("id"):
# at this point we know that e1 is the same entity as e2
if e1.get(primary_property) is None and e2.get(primary_property) is not None:
e1[primary_property] = e2[primary_property]
for op in other_properties:
if e1.get(op) is None and e2.get(op) is not None:
e1[op] = e2[op]
for maid2 in e2.get("identifier"):
match = False
for raid2 in e1.get("identifier"):
if maid2.get("type") == raid2.get("type") and maid2.get("id") == raid2.get("id"):
match = True
break
if not match:
e1["identifier"].append(maid2)
return True
# 2. If one does not have identifiers, match by primary property.
# 3. If primary property matches, add any missing other properties/identifiers
elif e2.get(primary_property) == e1.get(primary_property):
for op in other_properties:
if e1.get(op) is None and e2.get(op) is not None:
e1[op] = e2[op]
for maid2 in e2.get("identifier", []):
match = False
for raid2 in e1.get("identifier", []):
if maid2.get("type") == raid2.get("type") and maid2.get("id") == raid2.get("id"):
match = True
break
if not match:
if "identifier" not in e1:
e1["identifier"] = []
e1["identifier"].append(maid2)
return True
return False
|
def httpResponse(text, status, start_response):
"""
httpResponse
"""
text = "%s" % str(text)
response_headers = [('Content-type', 'text/html'), ('Content-Length', str(len(text)))]
if start_response:
start_response(status, response_headers)
return [text.encode('utf-8')]
|
def first_non_empty(items):
"""
Return first non empty item from the list. If nothing is found, we just
pick the first item. If there is no item, we return the whole form
(defaulting to []).
"""
if items:
for it in items:
if it:
return it
return items[0]
else:
return items
|
def get_first_object_or_none(queryset):
"""
A shortcut to obtain the first object of a queryset if it exists or None
otherwise.
"""
try:
return queryset[:1][0]
except IndexError:
return None
|
def incsum(prevsum, prevmean, mean, x):
"""Caclulate incremental sum of square deviations"""
newsum = prevsum + abs((x - prevmean) * (x - mean))
return newsum
|
def getNewDimensions(width , height , block_size=8):
""" Since block width = height we can use only one variable to compare"""
if height % block_size !=0 :
new_ht = height + (block_size - (height%block_size))
else:
new_ht = height
if width % block_size !=0:
new_wt = width + (block_size - (width%block_size))
else:
new_wt = width
return new_wt , new_ht
|
def replace_vars(arg, i=0):
"""
Doc String
"""
if isinstance(arg, tuple):
ret = []
for elem in arg:
replaced, i = replace_vars(elem, i)
ret.append(replaced)
return tuple(ret), i
elif isinstance(arg, str) and len(arg) > 0 and arg[0] == '?':
return '?foa%s' % (str(i)), i+1
else:
return arg, i
|
def extract_target_box(proc: str):
"""
Extracts target box as a tuple of 4 integers (x1, y1, x2, y2) from
a string that ends with four integers, in parentheses, separated
by a comma.
"""
a = proc.strip(")").split("(")
assert len(a) == 2
b = a[1].split(",")
assert len(b) == 4
return (int(b[0]), int(b[1]), int(b[2]), int(b[3]))
|
def PathArgument(context, path):
"""Resolve path from context variable is possible.
"""
try:
# Path argument was context variable name.
return context[path]
except KeyError:
# Path argument was a string value.
return path
|
def instrument_port_prevent_reset(pwr_status, n_intervals, text, placeholder):
"""prevents the input box's value to be reset by dcc.Interval"""
if pwr_status:
return text
else:
return placeholder
|
def prepend_speechreps_for_dict_encoding(speechreps, prepend_str="HUB",
mask_symbol="<mask>",
eos_symbol="</s>"):
"""
take list of hubert codes (int from 0 to K-1 where K is number of k-means clusters)
return a string version suitable for dictionary encoding
"""
new_speechreps = []
for symbol in speechreps:
if symbol in [eos_symbol, mask_symbol]:
new_speechreps.append(symbol)
else:
# speech reps code
new_speechreps.append(f"{prepend_str}{symbol}")
return new_speechreps
|
def sumorients(in_: list):
"""
Sums the four orientations into one image, computes sum of 4 elements of a list.
"""
out = in_[0] + in_[1] + in_[2] + in_[3]
return out
|
def batch_data(data, batch_size):
"""Given a list, batch that list into chunks of size batch_size
Args:
data (List): list to be batched
batch_size (int): size of each batch
Returns:
batches (List[List]): a list of lists, each inner list of size batch_size except possibly
the last one.
"""
batches = [data[i : i + batch_size] for i in range(0, len(data), batch_size)]
return batches
|
def _escape_dq(s):
"""Lightweight escaping function used in writing curl calls...
"""
if not isinstance(s, str):
if isinstance(s, bool):
return 'true' if s else 'false'
return s
if '"' in s:
ss = s.split('"')
return '"{}"'.format('\\"'.join(ss))
return '"{}"'.format(s)
|
def search( top, aName ):
"""Search down through the copybook structure."""
for aDDE in top:
if aDDE.name == aName:
return aDDE
|
def gen_param_help(hyper_parameters):
"""
Generates help for hyper parameters section.
"""
type_map = {"FLOAT": float, "INTEGER": int, "BOOLEAN": bool}
help_keys = ("header", "type", "default_value", "max_value", "min_value")
def _gen_param_help(prefix, cur_params):
cur_help = {}
for k, val in cur_params.items():
if isinstance(val, dict) and "default_value" not in val.keys():
if "visible_in_ui" in val and val["visible_in_ui"]:
x = _gen_param_help(prefix + f"{k}.", val)
cur_help.update(x)
elif isinstance(val, dict) and "default_value" in val.keys():
assert isinstance(val["default_value"], (int, float, str))
help_str = "\n".join(
[f"{kk}: {val[kk]}" for kk in help_keys if kk in val.keys()]
)
assert "." not in k
if val["type"] == "SELECTABLE":
continue
cur_help.update(
{
prefix
+ f"{k}": {
"default": val["default_value"],
"help": help_str,
"type": type_map[val["type"]],
"affects_outcome_of": val["affects_outcome_of"],
}
}
)
return cur_help
return _gen_param_help("", hyper_parameters)
|
def say_hello(
greeting: str = "Hello", name: str = "World", print_message: bool = True
):
"""
A simple function to say hello
:param greeting: the greeting to use
:param name: the person to greet
:param print_message: flag to indicate whether to print to the commandline
"""
hello_str = f"{greeting}, {name}"
if print_message:
print(hello_str)
return hello_str
|
def limit_throughput_sinr(throughput):
"""Function to limit throughput for SINR!
Args:
throughput: (limit) User throughput in bps!
Returns:
_: (list) Limited User throughput in bps!
"""
_ = list(filter(lambda x: x < 5 * 10 ** 6, throughput))
return _
|
def clean_empty_keyvalues_from_dict(d):
"""
Cleans all key value pairs from the object that have empty values, like [], {} and ''.
Arguments:
d {object} -- The object to be sent to metax. (might have empty values)
Returns:
object -- Object without the empty values.
"""
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [v for v in (clean_empty_keyvalues_from_dict(v) for v in d) if v]
return {k: v for k, v in ((k, clean_empty_keyvalues_from_dict(v)) for k, v in d.items()) if v}
|
def starts_with(match, ignore_case = True):
"""
Starts with a prefix
Parameters
----------
match : str
String to match columns
ignore_case : bool
If TRUE, the default, ignores case when matching names.
Examples
--------
>>> df = tp.Tibble({'a': range(3), 'add': range(3), 'sub': ['a', 'a', 'b']})
>>> df.select(starts_with('a'))
"""
if ignore_case == True:
out = f"^(?i){match}.*$"
else:
out = f"^{match}.*$"
return out
|
def convert(flippy):
""" Convert to Martin's format. """
for char in ('[ ]'):
flippy = str(flippy).replace(char, '')
flippy = flippy.replace('0', '-').replace('1', '#')
return flippy
|
def equal_chunks(list, chunk_size):
"""return successive n-sized chunks from l."""
chunks = []
for i in range(0, len(list), chunk_size):
chunks.append(list[i:i + chunk_size])
return chunks
|
def date_str(year, month, day, hour=0, minute=0, second=0., microsecond=None):
"""
Creates an ISO 8601 string.
"""
# Get microsecond if not provided
if microsecond is None:
if type(second) is float:
microsecond = int((second - int(second)) * 1000000)
else:
microsecond = 0
# Convert types
year = int(year)
month = int(month)
day = int(day)
hour = int(hour)
minute = int(minute)
second = int(second)
microsecond = int(microsecond)
# ISO 8601 template
tmp = '{year}-{month:0>2d}-{day:0>2d}T{hour:0>2d}:{minute:0>2d}:{second}.{microsecond}'
return tmp.format(year = year, month = month, day = day,
hour = hour, minute = minute, second = second, microsecond = microsecond)
|
def convert_frequency(value):
"""! @brief Applies scale suffix to frequency value string."""
value = value.strip()
suffix = value[-1].lower()
if suffix in ('k', 'm'):
value = int(value[:-1])
if suffix == 'k':
value *= 1000
elif suffix == 'm':
value *= 1000000
return value
else:
return int(value)
|
def lsst_sky_brightness(bands=''):
"""
Sample from the LSST sky brightness distribution
"""
dist = {'u': 22.99, 'g': 22.26, 'r': 21.2, 'i': 20.48, 'z': 19.6, 'Y': 18.61}
return [dist[b] for b in bands.split(',')]
|
def replaceRefund(e):
"""Redistribute compensation type values."""
e['compensation_type'] = 'partial_refund' if e['compensation_amount']<55.0 else 'full_refund'
return e
|
def flatten(l, ltypes=(list, tuple)):
"""flatten an array or list"""
ltype = type(l)
l = list(l)
i = 0
while i < len(l):
while isinstance(l[i], ltypes):
if not l[i]:
l.pop(i)
i -= 1
break
else:
l[i:i + 1] = l[i]
i += 1
return ltype(l)
|
def denorm(data, mean, std):
"""stream am model need to denorm
"""
return data * std + mean
|
def check_bbox(bb):
"""check bounding box"""
bbox = []
bbox.append(bb['coordinate_x'])
bbox.append(bb['coordinate_y'])
bbox.append(bb['width'])
bbox.append(bb['height'])
return bbox
|
def clean(some_string, uppercase=False):
"""
helper to clean up an input string
"""
if uppercase:
return some_string.strip().upper()
else:
return some_string.strip().lower()
|
def compute_max_len(example):
"""Compute the max length of the sequence, before the padding tokens"""
if '[PAD]' not in example['tokens']:
return len(example['tokens'])
return example['tokens'].index('[PAD]')
|
def _GetFailedStepsForEachCL(analysis):
"""Gets suspected CLs and their corresponding failed steps."""
suspected_cl_steps = {}
if (analysis is None or analysis.result is None or
not analysis.result['failures']):
return suspected_cl_steps
for failure in analysis.result['failures']:
for suspected_cl in failure['suspected_cls']:
cl_key = suspected_cl['repo_name'] + ',' + suspected_cl['revision']
if not suspected_cl_steps.get(cl_key):
suspected_cl_steps[cl_key] = [failure['step_name']]
else:
suspected_cl_steps[cl_key].append(failure['step_name'])
return suspected_cl_steps
|
def get_digit_at_pos(num, base, pos):
"""
Gets the integer at the given position of the number in a specific base
@param num The number we wish to find the converted digit in
@param base The base in which the digit is calculated
@param pos The position of the digit to be found
@return The integer at that digit
@complexity O(1)
"""
return (num // base ** pos) % base
|
def getFaceData( data ):
"""Extracts vertex, normal and uv indices for a face definition.
data consists of strings: i, i/i, i//i, or i/i/i.
All strings in the data should be of the same format. Format determines what
indices are defined"""
dataLists = [[], [], []]
for s in data:
indices = s.split('/')
for i in range(len(indices)):
try:
index = int( indices[i] )
if ( i == 0 and index in dataLists[i] ):
raise IOError
dataLists[i].append( int( indices[i] ) )
except ValueError:
pass
# validate the data -- i.e. lengths should equal all be equal, unless length = 0
if ( ( len(dataLists[0]) != len(dataLists[1] ) and len(dataLists[1]) != 0 ) or
( len(dataLists[0] ) != len( dataLists[2] ) and len(dataLists[2]) != 0 ) ):
raise IOError
return dataLists
|
def get_xpath_for_date_of_available_time_element(day_index: int) -> str:
"""
The element showing date of the available time is found in the div having the xpath:
'/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[N]/span'
^
where N is the day of the week from 2 to 8.
"""
return f'/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[{day_index}]/span'
|
def inc_patch_no(v = "0.0.0"):
"""inc_patch_no takes a symvar and increments the right most value in the dot touple"""
suffix = ''
if "-" in v:
(v, suffix) = v.split("-")
parts = v.split(".")
if len(parts) == 3:
#major_no = parts[0]
#minor_no = parts[1]
patch_no = int(parts[2])
patch_no += 1
parts[2] = str(patch_no)
v = ".".join(parts)
if suffix != '':
return f'{v}-{suffix}'
return v
|
def find_final_position(obs: dict) -> int:
"""Find final player position."""
if len(obs["geese"][0]) == 0:
pos = 4 - sum([1 if len(i) == 0 else 0 for i in obs["geese"][1:]])
else:
geese = [0, 1, 2, 3]
length = [len(i) for i in obs["geese"]]
order = list(zip(*sorted(zip(length, geese))))[1]
pos = 4 - order.index(0)
return pos
|
def _docstring(docstring):
"""Return summary of docstring"""
return " ".join(docstring.split("\n")[4:5]) if docstring else ""
|
def float_to_uint(x, x_min, x_max, bits):
"""
Converts float to unsigned int
"""
span = float(x_max - x_min)
offset = float(x_min)
return int((x - offset) * float(((1 << bits) - 1) / span))
|
def _kernel(kernel_spec):
"""Expands the kernel spec into a length 2 list.
Args:
kernel_spec: An integer or a length 1 or 2 sequence that is expanded to a
list.
Returns:
A length 2 list.
"""
if isinstance(kernel_spec, int):
return [kernel_spec, kernel_spec]
elif len(kernel_spec) == 1:
return [kernel_spec[0], kernel_spec[0]]
else:
assert len(kernel_spec) == 2
return kernel_spec
|
def remove(thing, l):
"""
REMOVE thing list
outputs a copy of ``list`` with every member equal to ``thing``
removed.
"""
l = l[:]
l.remove(thing)
return l
|
def chieffPH(m1, m2, s1, s2):
"""
Computes the effective spin from PhenomB/C
input: m1, m2, s1z, s2z
output: chi effective
"""
return (m1*s1 + m2*s2) / (m1 + m2)
|
def isiterable(obj):
"""
Return whether an object is iterable
"""
# see https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable
try:
iter(obj)
return True
except:
return False
|
def mouv(m_):
"""
Converts SINGLE movement from human comprehensive to boolean and str
Parameters
----------
m_ : str
The movement <F B L R U D> [' 2]
Returns
-------
f : str
The face to move <F B L R U D>
cw : boolean
True = rotates clockwise
r180 : boolean
True = rotates twice
"""
# Creating returned vals
f, cw, r180 = "", True, False
mli = list(m_)
# check if len m is valid
if len(mli) > 2 or len(mli) == 0:
return None
# add face except if invalid
if mli[0] in "FBLRUD":
f = mli[0]
else:
return None
# modify r180 and cw except if invalid
if len(mli) == 2:
cw = False
if mli[1] == "'":
r180 = False
elif mli [1] == "2":
r180 = True
else:
return None
return (f, cw, r180)
|
def get_service(vm, port):
"""Return the service for a given port."""
for service in vm.get('suppliedServices', []):
if service['portRange'] == port:
return service
|
def formatCurVal(val):
"""
Helper function for formatting current values to 3 significant digits, but
avoiding the use of scientific notation for display. Also, integers are
shown at full precision.
"""
if val is None:
return ''
elif val == int(val):
return '{:,}'.format(int(val))
elif abs(val) >= 1000.0:
return '{:,}'.format( int(float('%.4g' % val)))
else:
return '%.4g' % val
|
def condensed_coords(i, j, n):
"""Transform square distance matrix coordinates to the corresponding
index into a condensed, 1D form of the matrix.
Parameters
----------
i : int
Row index.
j : int
Column index.
n : int
Size of the square matrix (length of first or second dimension).
Returns
-------
ix : int
"""
# guard conditions
if i == j or i >= n or j >= n or i < 0 or j < 0:
raise ValueError('invalid coordinates: %s, %s' % (i, j))
# normalise order
i, j = sorted([i, j])
# calculate number of items in rows before this one (sum of arithmetic
# progression)
x = i * ((2 * n) - i - 1) / 2
# add on previous items in current row
ix = x + j - i - 1
return int(ix)
|
def chunk_list(items, size):
"""
Return a list of chunks
:param items: List
:param size: int The number of items per chunk
:return: List
"""
size = max(1, size)
return [items[i:i + size] for i in range(0, len(items), size)]
|
def create_intersection(whole_dict, sub_dict):
"""
Reduces a dictionary to have the same keys as an another dict.
:param whole_dict: dict, the dictionary to be reduced.
:param sub_dict: dict, the dictionary with the required keys.
:return: dict, the reduced dict.
"""
reduced_dict = {}
for parameter in sub_dict.keys():
if whole_dict.get(parameter, None) is None:
return {}
reduced_dict[parameter] = whole_dict[parameter]
return reduced_dict
|
def gv_get_event_code(event):
"""get the event code"""
#if event == '+RESP:GTFRI': return '5' #programated report
#elif event == '+RESP:GTSOS': return '1' #panic report
#elif event == '+RESP:GTSPD': return '2' #speed alarm
#elif event == '+RESP:GTIGN': return '6' #ignition on report
#elif event == '+RESP:GTIGF': return '7' #ignition off report
#elif event == '+RESP:GTMPN': return '8' #connecting main power supply
#elif event == '+RESP:GTMPF': return '9' #disconnecting main power supply
if event[6:] == 'GTFRI': return '5' #programated report
elif event[6:] == 'GTSOS': return '1' #panic report
elif event[6:] == 'GTSPD': return '2' #speed alarm
elif event[6:] == 'GTIGN': return '6' #ignition on report
elif event[6:] == 'GTIGF': return '7' #ignition off report
elif event[6:] == 'GTMPN': return '8' #connecting main power supply
elif event[6:] == 'GTMPF': return '9' #disconnecting main power supply
else: return None
|
def update(rules):
"""Adjust the rules to contain loops"""
rules["8"] = "42 | 42 8"
rules["11"] = "42 31 | 42 11 31"
return rules
|
def get_network(properties):
""" Get the configuration that connects the instance to an existing network
and assigns to it an ephemeral public IP.
"""
network_name = properties.get('network')
return {
'network': 'global/networks/{}'.format(network_name),
'accessConfigs': [
{
'name': 'External NAT',
'type': 'ONE_TO_ONE_NAT'
}
]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.