content stringlengths 42 6.51k |
|---|
def Any(cls):
"""Used to call assert_called_with with any argument.
Usage: Any(list) => allows any list to pass as input
"""
class Any(cls):
def __eq__(self, other):
return isinstance(other, cls)
return Any() |
def move_j(joints, accel, vel):
"""
Function that returns UR script for linear movement in joint space.
Args:
joints: A list of 6 joint angles (double).
accel: tool accel in m/s^2
accel: tool accel in m/s^2
vel: tool speed in m/s
Returns:
script: UR script
"""
# Check acceleration and velocity are non-negative and below a set limit
_j_fmt = "[" + ("%.2f,"*6)[:-1]+"]"
_j_fmt = _j_fmt%tuple(joints)
script = "movej(%s, a = %.2f, v = %.2f)\n"%(_j_fmt,accel,vel)
return script |
def clean(line):
"""
Clean a given line so it has only the output required.
Split by `:` once and then take the second half and remove the \n
"""
return line.split(':', 1)[1].strip() |
def split_conf_str(conf_str):
"""Split multiline strings into a list or return an empty list"""
if conf_str is None:
return []
else:
return conf_str.strip().splitlines() |
def bytes2human(n):
"""
>>> bytes2human(10000)
'9K'
>>> bytes2human(100001221)
'95M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = int(float(n) / prefix[s])
return '%s%s' % (value, s)
return "%sB" % n |
def sum(total,temp):
"""
:param total: the total amount of previously input temperatures
:param temp: the temperature that the user input
:return: total plus temp
"""
sum = total + temp
return sum |
def common_start(stra, strb):
""" returns the longest common substring from the beginning of stra and strb """
def _iter():
for a, b in zip(stra, strb):
if a == b:
yield a
else:
return ""
return ''.join(_iter()) |
def imul(a, b):
"""Same as a *= b."""
a *= b
return a |
def get_word_dist(idx1, idx2):
"""
get distance between two index tuples. Each index tuple contains (starting index, ending index)
"""
dist = None
for k in idx1:
for j in idx2:
curdist = abs(k - j)
if dist is None:
dist = curdist
else:
dist = min(dist, curdist)
return dist |
def format_num(num, digit=4):
"""Formatting the float values as string."""
rounding = f".{digit}g"
num_str = f"{num:{rounding}}".replace("+0", "+").replace("-0", "-")
num = str(num)
return num_str if len(num_str) < len(num) else num |
def formatString(para, pageWidth):
"""Format a string to have line lengths < pageWidth"""
para = " ".join(para.split("\n")).lstrip()
outStr = []
outLine = ""
for word in para.split():
if outLine and len(outLine) + len(word) + 1 > pageWidth:
outStr.append(outLine)
outLine = ""
if outLine:
outLine += " "
outLine += word
if outLine:
outStr.append(outLine)
return "\n".join(outStr) |
def right_pair(k1, k2, triplets):
"""
We have right word and searching for left
(variants..., <our_words>)
"""
lefts = [(l, v)
for (l, m, r), v in triplets.items()
if m == k1 and r == k2]
total = sum([v for (_, v) in lefts])
return sorted([(r, v/total) for (r, v) in lefts], key=lambda x: -x[1]) |
def get_correct_answer_dict(label_segments):
"""
Function that returns dictionary with the input as keys
Input: array of tuples; (start index of answer, length of answer)
Output: dict with string versions of tuples as keys
"""
label_dict = {}
for a in label_segments:
key = str(a[0]) + ' ' + str(a[1])
label_dict[key] = None
return label_dict |
def get_ansi_color(color):
"""
Returns an ANSI-escape code for a given color.
"""
colors = {
# attributes
'reset': '\033[0m',
'bold': '\033[1m',
'underline': '\033[4m',
# foregrounds
'grey': '\033[30m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'magenta': '\033[35m',
'cyan': '\033[36m',
'white': '\033[37m',
# backgrounds
'ongrey': '\033[40m',
'onred': '\033[41m',
'ongreen': '\033[42m',
'onyellow': '\033[43m',
'onblue': '\033[44m',
'onmagenta': '\033[45m',
'oncyan': '\033[46m',
'onwhite': '\033[47m',
}
return colors.get(color.lower()) |
def flatten_json_recursive(entry, cumulated_key=''):
"""
Recursively loop through the json dictionary and flatten it out in a column structure.
For every value in the tree, we use the path to the value as a key. This method returns
2 lists, 1 with keys and 1 with values, which later can be accumulated to form colums
"""
csv_keys = []
csv_values = []
for key in entry:
value = entry[key]
key_name = cumulated_key + key
if 'key' in entry and 'value' in entry: # In case there is literally a dictionary with key and values
item_key = entry['key']
item_value = entry['value']
return [item_key], [item_value]
# If we encounter a value, add it to the list, as well as the path to the value
elif type(value) == int or type(value) == bool or type(value) == float or type(value) == str:
csv_keys.append(key_name)
csv_values.append(value)
# If we encounter another dictionary we also have to flatten it out.
# therefore we have to call the recursive method again.
elif type(value) == dict:
result_keys, result_values = flatten_json_recursive(value, key_name + "_")
csv_keys += result_keys
csv_values += result_values
# if we encounter a list it could be that we find duplicate values, therefore we ha
elif type(value) == list:
i = 0
for list_item in value:
try:
result_keys, result_values = flatten_json_recursive(list_item, key_name + "_" + str(i) + "_")
csv_keys += result_keys
csv_values += result_values
i += 1
except TypeError:
pass
return csv_keys, csv_values |
def get_bool_from_text_value(value):
""" to be deprecated
It has issues, as accepting into the registry whatever=value, as False, without
complaining
"""
return (value == "1" or value.lower() == "yes" or value.lower() == "y" or
value.lower() == "true") if value else True |
def get_output(job_output):
"""
Return all outputs name
Return value can be used for WPS.execute method.
:return: output names
:rtype:list
"""
the_output = []
for key in job_output.keys():
the_output.append((key, job_output[key]['asReference']))
return the_output |
def to_futurenow_level(level):
"""Convert the given Home Assistant light level (0-255) to FutureNow (0-100)."""
return int((level * 100) / 255) |
def getFansInZone(zone_num, profiles, fan_data):
"""
Parses the fan definition YAML files to find the fans
that match both the zone passed in and one of the
cooling profiles.
"""
fans = []
for f in fan_data['fans']:
if zone_num != f['cooling_zone']:
continue
# 'cooling_profile' is optional (use 'all' instead)
if f.get('cooling_profile') is None:
profile = "all"
else:
profile = f['cooling_profile']
if profile not in profiles:
continue
fan = {}
fan['name'] = f['inventory']
fan['sensors'] = f['sensors']
fans.append(fan)
return fans |
def _test_rgb(h):
"""SGI image library"""
if h.startswith(b'\001\332'):
return 'rgb' |
def linear_interp(x, in_min, in_max, out_min, out_max):
""" linear interpolation function
maps `x` between `in_min` -> `in_max`
into `out_min` -> `out_max`
"""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def is_int(n):
""" checks if a number is float. 2.0 is True while 0.3 is False"""
return round(n) == n |
def _get_dropbox_path_from_dictionary(info_dict, account_type):
"""
Returns the 'path' value under the account_type dictionary within the main dictionary
"""
return info_dict[account_type]['path'] |
def packSplittedBytes(pSplitted):
"""
Unsplit splitted array of bytes.
Output: byterarray
"""
packed = bytearray()
for elt in pSplitted:
packed += elt
return packed |
def form(time):
"""Checks if the input parameter is a time played.
parameters:
- time: A string that is checked to have the time played format
returns:
- ret: A boolean represeting the conformaty of the input parameter
time
raises:
"""
ret = -1
temp = []
try:
temp = time.split(" ")
except AttributeError:
ret = False
if(len([i[-1] for i in temp]) > 4 and ret == -1):
ret = False
elif(len(list(set([i[-1] for i in temp]))) != len(temp) and ret == -1):
ret = False
elif ret == -1:
for x in temp:
# the implementation is casefold here makes the check non case
# sensitive
if(x[-1].casefold() not in ["d", "h", "m", "s"]):
ret = False
break
else:
try:
int(x[:-1])
ret = True
except ValueError:
ret = False
break
return ret |
def M_TO_N_ONLY(m, n, e):
"""
:param:
- `m`: the minimum required number of matches
- `n`: the maximum number of matches
- `e`: the expression t match
"""
return r"\b{e}{{{m},{n}}}\b".format(m=m, n=n, e=e) |
def format_button(recipient_id, button_text, buttons):
""" Ref: https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template """
return {
"recipient": {"id": recipient_id},
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": button_text,
"buttons": buttons,
}
}
}
} |
def complement(s):
"""
>>> complement('01100')
'10011'
"""
t = {"0": "1", "1": "0"}
return "".join(t[c] for c in s) |
def get_line_number(node):
"""Try to get the line number for `node`.
If no line number is available, this returns "<UNKNOWN>".
"""
if hasattr(node, 'lineno'):
return node.lineno
return '<UNKNOWN>' |
def find_island_id(phospho_islands, phospho_site):
""" Find the phospho island containing the specified phospho site.
:returns: the phospho island ID of the matching phospho island
"""
matching_island_id = None
for island_id, island in phospho_islands.items():
if phospho_site <= island['hi'] and phospho_site >= island['lo']:
matching_island_id = island_id
break
return matching_island_id |
def prepare_windowed_executions_colors(executions, center_commit_hash):
"""
This function will mark all the commit executions to be from other branch except for the passed commit.
This is because we want to emphatize the centered commit.
"""
for item in executions:
for execution in item['data']:
if center_commit_hash.startswith(execution['benchmark_execution_hash']):
execution['bar_type'] = 'current_branch'
else:
execution['bar_type'] = 'other_branch'
return executions |
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*',\
'*41532*', '*2*1***'])
True
>>> check_uniqueness_in_rows(['***21**', '452453*', '423145*', '*543215', '*35214*',\
'*41532*', '*2*1***'])
False
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*553215', '*35214*',\
'*41532*', '*2*1***'])
False
"""
for row in range(1, len(board[:-1])):
row_num_entry = set()
for elem in board[row][1:-1]:
if elem in row_num_entry:
return False
else:
row_num_entry.add(elem)
return True |
def get_label(timestamp, commercials):
"""Given a timestamp and the commercials list, return if
this frame is a commercial or not. If not, return label."""
for com in commercials['commercials']:
if com['start'] <= timestamp <= com['end']:
return 'ad'
return commercials['class'] |
def bin_str(tok):
"""Returns a binary string equivalent to the input value.
Given a string that represents a binary number (with or without a '0b') or
a hex value with a '0x' in front, converts the value to a string of 1s and
0s. If a hex value is specified, each hex digit specifies four bits.
"""
if tok.startswith('0x'): # Specified as hex
# Calculate the length of the binary string if each hex digit
# specifies 4 binary digits
bin_strlen = 4 * (len(tok) - 2)
# Convert hex value to binary
intval = int(tok[2:], 16) # Convert hex value to integer
binstr = bin(intval) # Convert integer value to binary string with '0b'
bitstr = binstr[2:] # Get rid of the '0b'
bits = bitstr.zfill(bin_strlen) # Left-pad string with the zeros
elif tok.startswith('0b'): # Specified as binary
bits = tok[2:]
else: # Base not specified - assume binary literal
bits = tok
return bits |
def get_bcs_x(shift=0, stimulus='reyes_puerta', seed=170, middle=False):
"""
restored variability
:param dt:
:return:
"""
shift_string = ''
shift_string_2 = ''
if stimulus == 'exp_25' or shift > 0:
shift_string = '_shift'
shift_string_2 = 'shift%d/' % shift
middle_string = ''
base_string = 'spontaneous/base_seeds_abcd'
if middle:
middle_string = '_middle'
base_string = 'evoked/base_seeds_exp_25'
bc_0 = '/gpfs/bbp.cscs.ch/project/proj9/simulations/nolte/variability/' + base_string + '/seed%d/BlueConfig' % seed
bc_1 = '/gpfs/bbp.cscs.ch/project/proj9/simulations/nolte/variability/evoked/continue_change_' + stimulus + middle_string + shift_string + '_abcd/' + shift_string_2 + ('seed%d/BlueConfig' % seed)
bc_2 = '/gpfs/bbp.cscs.ch/project/proj9/simulations/nolte/variability/evoked/continue_change_' + stimulus + middle_string + shift_string + '_x/' + shift_string_2 + ('seed%d/BlueConfig' % seed)
return bc_0, bc_1, bc_2 |
def _validate_version(version: int) -> bool:
"""Validate all supported protocol versions."""
return version in [4] |
def mapper2(lines):
"""Mapper mapping to 2D Matrix"""
mapped_matrix = []
for word in lines.split():
mapped_matrix.append((word.strip(",")))
return mapped_matrix |
def _inject_mutations_3D(phi, dt, xx, yy, zz, theta0, frozen1, frozen2, frozen3):
"""
Inject novel mutations for a timestep.
"""
# Population 1
# Normalization based on the multi-dimensional trapezoid rule is
# implemented ************** here ***************
if not frozen1:
phi[1,0,0] += dt/xx[1] * theta0/2 * 8/((xx[2] - xx[0]) * yy[1] * zz[1])
# Population 2
if not frozen2:
phi[0,1,0] += dt/yy[1] * theta0/2 * 8/((yy[2] - yy[0]) * xx[1] * zz[1])
# Population 3
if not frozen3:
phi[0,0,1] += dt/zz[1] * theta0/2 * 8/((zz[2] - zz[0]) * xx[1] * yy[1])
return phi |
def _trim_zeros(str_floats, na_rep='NaN'):
"""
Trims zeros, leaving just one before the decimal points if need be.
"""
trimmed = str_floats
def _cond(values):
non_na = [x for x in values if x != na_rep]
return (len(non_na) > 0 and all([x.endswith('0') for x in non_na]) and
not (any([('e' in x) or ('E' in x) for x in non_na])))
while _cond(trimmed):
trimmed = [x[:-1] if x != na_rep else x for x in trimmed]
# leave one 0 after the decimal points if need be.
return [x + "0" if x.endswith('.') and x != na_rep else x for x in trimmed] |
def format_fold_run(fold=None, run=None, mode='concise'):
"""Construct a string to display the fold, and run currently being executed
Parameters
----------
fold: Int, or None, default=None
The fold number currently being executed
run: Int, or None, default=None
The run number currently being executed
mode: Str in ['concise', 'verbose'], default='concise'
If 'concise', the result will contain abbreviations for fold/run
Returns
-------
content: Str
A clean display of the current fold/run"""
content = ''
valid_fold, valid_run = isinstance(fold, int), isinstance(run, int)
if mode == 'verbose':
content += format('Fold' if valid_fold else '')
content += format('/' if valid_fold and valid_run else '')
content += format('Run' if valid_run else '')
content += format(': ' if valid_fold or valid_run else '')
content += format(fold if valid_fold else '')
content += format('/' if valid_fold and valid_run else '')
content += format(run if valid_run else '')
elif mode == 'concise':
content += format('F' if valid_fold else '')
content += format(fold if valid_fold else '')
content += format('/' if valid_fold and valid_run else '')
content += format('R' if valid_run else '')
content += format(run if valid_run else '')
else:
raise ValueError('Received invalid mode value: "{}". Expected mode string'.format(mode))
return content |
def _one_contains_other(s1, s2):
"""
Whether one set contains the other
"""
return min(len(s1), len(s2)) == len(s1 & s2) |
def _varint_final_byte(char):
"""Return True iff the char is the last of current varint"""
return not ord(char) & 0x80 |
def _all(itr):
"""Similar to Python's all, but returns the first value that doesn't match."""
any_iterations = False
val = None
for val in itr:
any_iterations = True
if not val:
return val
return val if any_iterations else True |
def replace_dict_value(d, bad_val, good_val):
"""
IN PLACE replacement of bad_val to good_val ues
"""
for key, val in d.items():
if bad_val == val:
d[key] = good_val
print(d)
return d |
def convert_readable(size_to_convert):
"""
This function will convert size to human readable string
:param size_to_convert: size in bytes
:return: human-readable string with size
"""
i = 0
size_to_convert = int(size_to_convert)
units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB']
for i in range(6):
size_to_convert /= 1024
if size_to_convert < 1:
break
size_to_convert *= 1024
if i == 0:
return f"{size_to_convert}B"
return f"{round(size_to_convert, 2)}{units[i]}" |
def _block_format_index(index):
"""
Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``.
"""
idx_str = "".join("[{}]".format(i) for i in index if i is not None)
return "arrays" + idx_str |
def render_build_args(options, ns):
"""Get docker build args dict, rendering any templated args.
Args:
options (dict):
The dictionary for a given image from chartpress.yaml.
Fields in `options['buildArgs']` will be rendered and returned,
if defined.
ns (dict): the namespace used when rendering templated arguments
"""
build_args = options.get("buildArgs", {})
for key, value in build_args.items():
build_args[key] = value.format(**ns)
return build_args |
def format_model_type(mt):
"""
Converts the model type identifier into a human-readable string.
e.g. "random_forest" -> "random forest"
:param mt: string: the model type ID
:return: a human-readable version with underscores stripped and capitalised words
"""
components = mt.split('_')
formatted_components = list(map(lambda word: word.capitalize(), components))
return ' '.join(formatted_components) |
def head(list, n):
"""Return the firsts n elements of a list """
return list[:n] |
def process_template(template: str, arg1: str) -> str:
"""Replaces placeholder in a template with argument"""
if "<1>" in template and arg1 == "":
raise Exception(
f'Template string "{template}" includes a placeholder, but no argument was provided'
)
return template.replace("<1>", arg1) |
def remove_none(obj):
"""
Remove empty values recursively from an iterable dictionary.
:param obj:
:return:
"""
if isinstance(obj, (list, tuple, set)):
return type(obj)(remove_none(x) for x in obj if x is not None)
elif isinstance(obj, dict):
return type(obj)(
(remove_none(k), remove_none(v))
for k, v in obj.items()
if k is not None and v is not None
)
else:
return obj |
def getRecurringLen(n):
""" Returns the length of the recurring part of the fraction 1/n """
index = {}
rem, curIndex = 1, 0
while rem > 0 and rem not in index:
index[rem] = curIndex
rem = rem * 10
ext = 0
while rem < n:
rem = rem * 10
ext += 1
curIndex += 1 + ext
rem = rem % n
if rem == 0:
return 0
return curIndex - index[rem%n] |
def targetFeatureSplit( data ):
"""
given a numpy array like the one returned from
featureFormat, separate out the first feature
and put it into its own list (this should be the
quantity you want to predict)
return targets and features as separate lists
(sklearn can generally handle both lists and numpy arrays as
input formats when training/predicting)
"""
target = []
features = []
for item in data:
target.append( item[0] )
features.append( item[1:] )
return target, features |
def _catmull_rom_weighting_function(x: float) -> float:
"""Catmull-Rom filter's weighting function.
For more information about the Catmull-Rom filter, see
`Cubic Filters <https://legacy.imagemagick.org/Usage/filter/#cubics>`_.
Args:
x (float): distance to source pixel.
Returns:
float: weight on the source pixel.
"""
if x <= 1:
return (3*x**3 - 5*x**2 + 2) / 2
elif x <= 2:
return (-x**3 + 5*x**2 - 8*x + 4) / 2
else:
return 0 |
def normalize(x: float, x_min: float, x_max: float) -> float:
"""
Rescaling data to have values between 0 and 1
"""
return (x - x_min) / (x_max - x_min) |
def lerp_np(x, y, w):
"""Helper function."""
fin_out = (y - x) * w + x
return fin_out |
def has_palindrome ( i, start, length ):
"""Checks if the string representation of i has a palindrome.
i: integer
start: where in the string to start
length: length of the palindrome to check for
"""
s = str(i)[start: length]
return s == s[::-1] |
def check_true(option):
"""Check if option is true.
Account for user inputting "yes", "Yes", "True", "Y" ...
"""
option = option.lower()
if 'y' in option or 't' in option:
return True
else:
return False |
def build_oai_url(handle: str,
prefix: str,
base_url: str = "https://air.uniud.it/oai/request?") -> str:
"""build the url for an oai request of a single record (in the case of
institutional repository, one record corresponds to a publication)
Parameters
----------
handle
entire handle of the publication (e.g. "http://hdl.handle.net/11390/693468")
prefix
prefix for the oai request.
Accepted values:
- "oai"
- "ore"
base_url : optional
url of the oai repository, by default "https://air.uniud.it/oai/request?"
Returns
-------
str
url of the publication
"""
pub_id = handle.split("/")
oai_url = base_url + "verb=GetRecord&" \
+ "metadataPrefix=" + prefix \
+ "&identifier=oai:air.uniud.it:" \
+ pub_id[-2] + "/" + pub_id[-1]
return oai_url |
def sort_and_prioritize(lst, to_prioritize):
"""Usage:
>>> sort_and_prioritize(["B", "C", "D", "A", "F", "E"], ["C", "D"])
>>> ['C', 'D', 'A', 'B', 'E', 'F']
"""
queue = [lst.pop(lst.index(item)) for item in to_prioritize]
lst = sorted(lst)
for item in sorted(queue, reverse=True):
lst.insert(0, item)
return lst |
def sort_top_editors_per_country(editors, editcount_index, top_n):
"""
Takes a list of lists of editors with editcounts
and a top editor cutoff int, returns a sorted top list.
"""
editors.sort(key=lambda x: int(x[2]), reverse=True)
if len(editors) > top_n:
editors = editors[:top_n]
return editors |
def ext_euclid_alg (m, n):
""" Extended Euclidean algorithm for gcd.
Finds the greatest common divisor of
two integers a and bm and solves for integer
x, y such that ax + by = 1. From Knuth, TAOCP
vol. I, p. 14.
Variables --
q, r -- quotient and remainder
a, b -- am + bn = gcd
apme, bpme -- a prime and b prime
t -- temporary
"""
m, n = abs(m), abs(n)
q, r = m // n, m % n
apme = b = 1
a = bpme = 0
while r != 0:
m, n = n, r
t = apme
apme = a
a = t - q * a
t = bpme
bpme = b
b = t - q * b
""" reset q and r """
q, r = m // n, m % n
return (n, a, b) |
def count_stars(chars):
"""
Count the number of trailing '#' (~== '#+$')
>>> count_stars("http://example.org/p?q#fragment####")
<<< 4
"""
count = 0
for c in chars[::-1]:
if c != '#':
break
count += 1
return count |
def extract_data_from_dict(d1, keys, mandatory_keys=()):
"""
Given a dictionary keeps only data defined by the keys param
Args:
d1: dictionary to extract the data from
keys: keys to extract
mandatory_keys: if any of this keys isn't in the d1, exception will be risen
Returns:
dictionary containing data from d1 defined by keys param
"""
for k in mandatory_keys:
if k not in d1:
raise ValueError('Not all mandatory keys are in the given dictionary')
d2 = {k: d1[k] for k in keys if k in d1}
return d2 |
def mel2hz(mel):
"""Convert a value in Hertz to Mels
Parameters
----------
hz : number of array
value in Hz, can be an array
Returns:
--------
_ : number of array
value in Mels, same type as the input.
"""
return 700 * (10 ** (mel / 2595.0) - 1) |
def A006577(n: int) -> int:
"""Give the number of halving and tripling steps to reach 1 in '3x+1' problem."""
if n == 1:
return 0
x = 0
while True:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
x += 1
if n < 2:
break
return x |
def parse_frontmatter(raw_text: str) -> dict:
"""
Parser for markdown file front matter. This parser has the following features:
* Simple key-value pairings (`key: value`)
* Comma-separated lists between brackets (`list: ['value1', 'value2']`)
* Keys are case insensitive
Args:
raw_text (str): String containing frontmatter (excluding fences)
Returns:
dict: A dictionary containing all the frontmatter key:value pairs
"""
front_matter = {}
lines = raw_text.split("\n")
for line in lines:
if ":" in line:
key, value = (item.strip() for item in line.split(": "))
if value.startswith("[") and value.endswith("]"):
value = [item.strip().strip("'\"") for item in value[1:-1].split(",")]
front_matter[key.lower()] = value
else:
continue
return front_matter |
def get_license_tag_issue_type(issue_category):
"""
Classifies the license detection issue into one of ISSUE_TYPES_BY_CLASSIFICATION,
where it is a license tag.
"""
if issue_category == "false-positive":
return "tag-false-positive"
else:
return "tag-tag-coverage" |
def normalize_control_field_name(name):
"""
Return a case-normalized field name string.
Normalization of control file field names is not really needed when reading
as we lowercase everything and replace dash to underscore internally, but it
can help to compare the parsing results to the original file while testing.
According to the Debian Policy Manual field names are not case-sensitive,
however a conventional capitalization is most common and not using it may
break hings.
http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-controlsyntax
"""
special_cases = dict(md5sum='MD5sum', sha1='SHA1', sha256='SHA256')
return '-'.join(special_cases.get(
w.lower(), w.capitalize()) for w in name.split('-')) |
def hexval2val(hexval):
"""Unconvert a decimal digit equivalent hex byte to int."""
ret = 10*(hexval>>4) # tens 0x97 -> 90
ret += hexval&0x0f # ones 0x97 -> 7
return ret |
def get_string(fh):
"""fh is the file handle """
mystr = b''
byte = fh
if fh != '':
mystr = bytearray(fh, 'ascii')
else:
mystr = bytes(1)
return mystr |
def count_elements(seq) -> dict:
"""Tally elements from `seq`."""
hist = {}
for i in seq:
hist[i] = hist.get(i, 0) + 1
return hist |
def _get_full_text(tweet):
"""Parses a tweet json to retrieve the full text.
:param tweet: a Tweet either from the streaming or search API
:type tweet: a nested dictionary
:returns: full_text field hidden in the Tweet
:rtype: str
"""
if isinstance(tweet, dict):
if "extended_tweet" in tweet and "full_text" in tweet["extended_tweet"]:
return tweet["extended_tweet"]["full_text"]
elif "full_text" in tweet:
tweet["full_text"]
else:
return tweet.get("text")
else:
dtype = type(tweet)
raise ValueError("Input needs to be key-value pair! Input is {}".format(dtype)) |
def is_plenary_agenda_item(assignment):
"""Is this agenda item a regular session item?
A regular item appears as a sub-entry in a timeslot within the agenda
>>> from collections import namedtuple # use to build mock objects
>>> mock_timeslot = namedtuple('t2', ['slug'])
>>> mock_assignment = namedtuple('t1', ['slot_type']) # slot_type must be a callable
>>> factory = lambda t: mock_assignment(slot_type=lambda: mock_timeslot(slug=t))
>>> is_plenary_agenda_item(factory('plenary'))
True
>>> any(is_plenary_agenda_item(factory(t)) for t in ['regular', 'break', 'reg', 'other', 'officehours'])
False
>>> is_plenary_agenda_item(None)
False
"""
return assignment is not None and assignment.slot_type().slug == 'plenary' |
def celsius_to_fahrenheit(deg_C):
"""Convert degrees Celsius to Fahrenheit."""
return (9 / 5) * deg_C + 32 |
def from_time(year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None):
"""Convenience wrapper to take a series of date/time elements and return a WMI time
of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or
omitted altogether. If omitted, they will be replaced in the output string
by a series of stars of the appropriate length.
:param year: The year element of the date/time
:param month: The month element of the date/time
:param day: The day element of the date/time
:param hours: The hours element of the date/time
:param minutes: The minutes element of the date/time
:param seconds: The seconds element of the date/time
:param microseconds: The microseconds element of the date/time
:param timezone: The timeezone element of the date/time
:returns: A WMI datetime string of the form: `yyyymmddHHMMSS.mmmmmm+UUU`
"""
def str_or_stars(i, length):
if i is None:
return "*" * length
else:
return str(i).rjust(length, "0")
wmi_time = ""
wmi_time += str_or_stars(year, 4)
wmi_time += str_or_stars(month, 2)
wmi_time += str_or_stars(day, 2)
wmi_time += str_or_stars(hours, 2)
wmi_time += str_or_stars(minutes, 2)
wmi_time += str_or_stars(seconds, 2)
wmi_time += "."
wmi_time += str_or_stars(microseconds, 6)
if timezone is None:
wmi_time += "+"
else:
try:
int(timezone)
except ValueError:
wmi_time += "+"
else:
if timezone >= 0:
wmi_time += "+"
else:
wmi_time += "-"
timezone = abs(timezone)
wmi_time += str_or_stars(timezone, 3)
return wmi_time |
def escape(text):
"""Escape some Markdown text"""
for char in '*_`[]':
text = text.replace(char, '\\'+char)
return text |
def time_in_range(start: int, end: int, current_time: int) -> bool:
""" Return true if current_time is in the range [start, end] """
if start <= end:
return start <= current_time < end
else:
return start <= current_time or current_time <= end |
def read_varint(readfn):
"""
Reads a variable-length encoded integer.
:param readfn: a callable that reads a given number of bytes,
like file.read().
"""
b = ord(readfn(1))
i = b & 0x7F
shift = 7
while b & 0x80 != 0:
b = ord(readfn(1))
i |= (b & 0x7F) << shift
shift += 7
return i |
def reverseSentence(s):
"""i am a student. -> student. a am i"""
s = s[::-1]
sNums = s.split(' ')
for i in range(len(sNums)):
sNums[i] = sNums[i][::-1]
return " ".join(sNums) |
def is_float(v):
"""
Check for valid float
>>> is_float(10)
True
>>> is_float(10.2)
True
>>> is_float("10.2")
True
>>> is_float("Ten")
False
>>> is_float(None)
False
"""
try:
v = float(v)
except ValueError:
return False
except TypeError:
return False
return True |
def pythoncross(v1, v2):
"""Take the cross product between v1 and v2, slightly faster than np.cross"""
c = [v1[1]*v2[2] - v1[2]*v2[1],
v1[2]*v2[0] - v1[0]*v2[2],
v1[0]*v2[1] - v1[1]*v2[0]]
return c |
def separate_substructures(tokenized_commands):
"""Returns a list of SVG substructures."""
# every moveTo command starts a new substructure
# an SVG substructure is a subpath that closes on itself
# such as the outter and the inner edge of the character `o`
substructures = []
curr = []
for cmd in tokenized_commands:
if cmd[0] in 'mM' and len(curr) > 0:
substructures.append(curr)
curr = []
curr.append(cmd)
if len(curr) > 0:
substructures.append(curr)
return substructures |
def get_object_type(object_id):
"""
Obtain object type
Parameters
----------
object_id : int
object identifier
Returns
-------
object_type : str
type of object
"""
# https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/naif_ids.html
if object_id < -100000:
# artificial satellite (earth orbitting spacecraft)
return "ASAT"
elif object_id < 0:
# spacecraft or instrument
return "SPACECRAFT"
elif object_id < 10:
# Required size for System barycenter
return "BARYCENTER"
elif object_id == 10:
# sun
return "SUN"
elif object_id < 100:
# invalid (11...99)
return "INVALID"
elif (object_id % 100) == 99:
# planet (199, 299, ...)
return "PLANET"
elif (object_id % 100) == 0:
# invalid (100, 200, ...)
return "INVALID"
elif object_id < 100000:
# satellite (PXX, PNXXX, 1<=P<=9, N=0,5)
return "SATELLITE"
else:
# comets, asteroids or other objects
return "SMALL_BODY" |
def M(metric_name):
"""Make a full metric name from a short metric name.
This is just intended to help keep the lines shorter in test
cases.
"""
return "django_model_%s" % metric_name |
def unifom_distr_moment(d,sigma):
""" computes the moments E[X] for X uniformly (-sigma,sigma) distributed """
if 1==d%2:
return 0
else:
return sigma**d/(d+1.) |
def comment_lines(lines, prefix):
"""Return commented lines"""
if not prefix:
return lines
return [prefix + ' ' + line if line else prefix for line in lines] |
def common_elements(left, right) -> int:
""" Returns the number of elements that are common between `left` and `right`"""
common = set(left) & set(right)
return len(common) |
def csort(objs, key=lambda x: x):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) |
def turn(orient_index, direction):
"""
change the current orientation according to
the new directions
Args:
orient_index (int): index in the orient list for the
current orientations
direction (str): R or L
Returns:
int
"""
if direction == 'R':
orient_index += 1
if orient_index == 4:
orient_index = 0
else:
orient_index -= 1
if orient_index == -1:
orient_index = 3
return orient_index |
def remove_nulls(input_dict):
"""Remove keys with no value from a dictionary."""
output = {}
for k, v in input_dict.items():
if v is not None:
output[k] = v
return output |
def get_sci_val(decimal_val):
"""
returns the scientific notation for a decimal value
:param decimal_val: the decimal value to be converted
:return: the scientific notation of the decimal value
"""
sci_val = ''
if decimal_val is not None:
if decimal_val == 0:
sci_val = '0'
else:
sci_val = '{0: E}'.format(decimal_val)
sci_val = sci_val.split('E')[0].rstrip('0').rstrip('.').lstrip() + 'E' + sci_val.split('E')[1]
return sci_val |
def row_sum_odd_numbers3(n):
"""
Time complexity: O(n).
Space complexity: O(n).
"""
start_odd = n * (n - 1) + 1
row = []
for i in range(1, n + 1):
row.append(start_odd + (i - 1) * 2)
return sum(row) |
def calc_triangle_area(base, height):
"""
Calculates the area of the triangle
:param base:
:param height:
:return: area
"""
return (base * height) / 2 |
def twoNumberSum(array, targetSum):
"""
This works completely on pointers, here we are having two pointers
One is left pointer and another being right pointer
idea here is to have left+right=sum, this can have three outcomes
1. First outcome
targetsum = sum
2. Second outcome
targetsum > sum
reduce the value of right which intially is at length of array -1 , but now it
is going to be lenght of array -2
3. Third outcome
targetsum < sum
increase the value of left whose intiall value was at 0. Now it will be at 1
"""
array.sort()
left = 0
right = len(array)-1
while (left < right):
currentSum = array[left]+array[right]
if currentSum == targetSum:
return [array[left], array[right]]
elif currentSum < targetSum:
left+=1
elif currentSum > targetSum:
right-=1
return [] |
def ratio(value, count):
"""compute ratio but ignore count=0"""
if count == 0:
return 0.0
else:
return value / count |
def create_category_index(categories):
"""Creates dictionary of COCO compatible categories keyed by category id.
Args:
categories: a list of dicts, each of which has the following keys:
'id': (required) an integer id uniquely identifying this category.
'name': (required) string representing category name
e.g., 'cat', 'dog', 'pizza'.
Returns:
category_index: a dict containing the same entries as categories, but keyed
by the 'id' field of each category.
"""
category_index = {}
for cat in categories:
category_index[cat["id"]] = cat
return category_index |
def _repr_pen_commands(commands):
"""
>>> print(_repr_pen_commands([
... ('moveTo', tuple(), {}),
... ('lineTo', ((1.0, 0.1),), {}),
... ('curveTo', ((1.0, 0.1), (2.0, 0.2), (3.0, 0.3)), {})
... ]))
pen.moveTo()
pen.lineTo((1, 0.1))
pen.curveTo((1, 0.1), (2, 0.2), (3, 0.3))
>>> print(_repr_pen_commands([
... ('beginPath', tuple(), {}),
... ('addPoint', ((1.0, 0.1),),
... {"segmentType":"line", "smooth":True, "name":"test", "z":1}),
... ]))
pen.beginPath()
pen.addPoint((1, 0.1), name='test', segmentType='line', smooth=True, z=1)
>>> print(_repr_pen_commands([
... ('addComponent', ('A', (1, 0, 0, 1, 0, 0)), {})
... ]))
pen.addComponent('A', (1, 0, 0, 1, 0, 0))
"""
s = []
for cmd, args, kwargs in commands:
if args:
if isinstance(args[0], tuple):
# cast float to int if there're no digits after decimal point
args = [tuple((int(v) if int(v) == v else v) for v in pt)
for pt in args]
args = ", ".join(repr(a) for a in args)
if kwargs:
kwargs = ", ".join("%s=%r" % (k, v)
for k, v in sorted(kwargs.items()))
if args and kwargs:
s.append("pen.%s(%s, %s)" % (cmd, args, kwargs))
elif args:
s.append("pen.%s(%s)" % (cmd, args))
elif kwargs:
s.append("pen.%s(%s)" % (cmd, kwargs))
else:
s.append("pen.%s()" % cmd)
return "\n".join(s) |
def solution(A): # O(N)
"""
Given a variable length array of integers, partition them such that the even
integers precede the odd integers in the array. Your must operate on the array
in-place, with a constant amount of extra space. The answer should scale
linearly in time with respect to the size of the array.
>>> solution([7, 7, 4, 0, 9, 8, 2, 4, 1, 9])
[4, 2, 4, 0, 8, 9, 7, 7, 1, 9]
"""
i = 0 # O(1)
j = len(A) - 1 # O(1)
while i < j: # O(<N)
if A[i] % 2 == 0: # O(1)
i += 1 # O(1)
if A[j] % 2 == 1: # O(1)
j -= 1 # O(1)
if A[i] % 2 == 1 and A[j] % 2 == 0: # O(1)
A[i], A[j] = A[j], A[i] # O(1)
i += 1 # O(1)
j -= 1 # O(1)
return A # O(1) |
def time_sep(t1: int, t2: int, time_max: int):
""" Calculate the separation amount and direction of two time slices"""
if not (isinstance(t1, int) and isinstance(t1, int)):
raise TypeError(f"t1={t1} and t2={t2} must be ints")
i = (t1 - t2) % time_max
j = (t2 - t1) % time_max
if j > i:
return -i
return j |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.