content stringlengths 42 6.51k |
|---|
def temp_to_str(temp):
"""
converts temperature from format 0.1 to format 0.100 by adding three places after decimal
"""
temp=str(temp)
while len(temp)<5:
temp='{}0'.format(temp)
return temp |
def central_differences(f, h, x):
"""
Forward Finite Differences.
Approximating the derivative using the Central
Finite Method.
Parameters:
f : function to be used
h : Step size to be used
x : Given point
Returns: Approximation
"""
return (f(x + h) - f(x - h)) / (2 * h) |
def end_iter(foo):
"""Iterate to the end of foo."""
try:
next(foo)
return False
except StopIteration:
return True |
def device_loc_to_type(loc):
"""Get the fixed, hardcoded device type for a device location."""
if loc in [461, 501]:
return "ETC"
elif loc in [541, 542]:
return "GIF"
elif loc in [11, 75, 150, 239, 321, 439, 482, 496, 517, 534]:
return "FIF"
elif loc in [
38,
331,
438,
460,
478,
479,
480,
481,
497,
498,
499,
500,
513,
514,
515,
516,
527,
528,
529,
530,
531,
535,
536,
537,
538,
539,
540,
]:
return "NON"
else:
return "POS" |
def make_row(unique_row_id, row_values_dict):
"""row_values_dict is a dictionary of column name and column value.
"""
return {'insertId': unique_row_id, 'json': row_values_dict} |
def render_comment_list(comment_list, user, comment_list_css="main-thread"):
"""
Inclusion tag for rendering a comment list.
Context::
Comment List
Template::
comment_list.html
"""
return dict(comment_list=comment_list, comment_list_css=comment_list_css, user=user) |
def format_param_dict_for_logger(params_dict):
"""
"""
maxchars = max([len(key) for key in params_dict.keys()])
return "\n".join([f"{key.rjust(maxchars)} : {val}" for key, val in params_dict.items()]) |
def outline_style(keyword):
"""``outline-style`` properties validation."""
return keyword in ('none', 'dotted', 'dashed', 'double', 'inset',
'outset', 'groove', 'ridge', 'solid') |
def pe31(target=200):
"""
>>> pe31()
73682
"""
coins = [1, 2, 5, 10, 20, 50, 100, 200]
ways = [1] + [0] * target
for coin in coins:
for i in range(coin, target + 1):
ways[i] += ways[i - coin]
return ways[target] |
def prep_keyword(keyword):
"""
prepares keywords used for search.
:param keyword: raw text.
:return: formatted text.
"""
operator = '%'
_term = '%(op)s%(kw)s%(op)s'
term = _term % dict(op=operator, kw=keyword)
return term |
def stripnl(s):
"""Remove newlines from a string (and remove extra whitespace)"""
s = str(s).replace("\n", " ")
return ' '.join(s.split()) |
def get_message(name, value):
"""Provides the message for a standard Python exception"""
if hasattr(value, "msg"):
return f"{name}: {value.msg}\n"
return f"{name}: {value}\n" |
def reconcile_positions(pos_dict_1, pos_dict_2):
""" Reconciles two position dictionaries into a new dictionary.
I had run through a number of implementations of this function before
settling on this one. See the repository history for further details.
Parameters:
pos_dict_1 (dict): Position data post-transactions
pos_dict_2 (dict): Position data reported by "bank"
Returns:
res (dict): Differences in reported values for each symbol (incl. cash)
from each passed-in position data.
"""
res = {}
all_keys = set(list(pos_dict_1.keys()) + list(pos_dict_2.keys()))
for symbol in all_keys:
if symbol not in pos_dict_2: # "left" keys
symbol_diff = pos_dict_1[symbol] * -1
elif symbol not in pos_dict_1: # "right" keys
symbol_diff = pos_dict_2[symbol]
else: # "middle" keys
symbol_diff = pos_dict_2[symbol] - pos_dict_1[symbol]
if symbol_diff != 0:
res[symbol] = symbol_diff
return res |
def cover_points(points):
"""
Find the minimum number of steps to cover a sequence of points in the
order they need to be covered.
The points are in an infinite 2D grid and one can move in any of the
8 directions.
points = [(0,0, (2,2), (0,5)]
0 1 2
0 *
1 \
2 *
3 /
4 |
5 *
"""
moves = 0
for prev_point, point in zip(points, points[1:]):
prev_x, prev_y = prev_point
x, y = point
x_dist = abs(x - prev_x)
y_dist = abs(y - prev_y)
moves += max(x_dist, y_dist)
return moves |
def repr_as_obj(d: dict) -> str:
"""Returns pretty representation of dict.
>>> repr_as_obj({'a': 1, 'b': 2})
'a=1, b=2'
"""
return ', '.join(f'{key}={value!r}' for key, value in d.items()) |
def esAnoBisiesto(ano):
"""Verifica si es un ano bisiesto"""
if (ano % 4 == 0 and ano % 100 != 0) or ano % 400 == 0:
return True
return False |
def getZoneLocFromGrid(gridCol, gridRow):
"""
Create a string location (eg 'A10') from zero based grid refs (col=0,
row=11)
"""
locX = chr(ord('A') + gridCol)
locY = str(gridRow + 1)
return locX + locY |
def _getObjectScope(objectid):
"""Intended for private use within wsadminlib only.
Pick out the part of the config object ID between the '('
and the '|' -- we're going to use it in createObjectCache to identify the scope
of the object"""
return objectid.split("(")[1].split("|")[0] |
def get_rate(value:str):
"""
v:values:'tensorflow_theano:325317.28125-tensorflow_cntk:325317.28125-tensorflow_mxnet:325317.28125-theano_cntk:0.07708668-theano_mxnet:0.09217975-cntk_mxnet:0.0887682'
rate: max_Rl
"""
if 'inf' in value:
return 'inf'
else:
try:
value_splits = value.split("|")
value_list = [abs(float(val.split(":")[1])) for val in value_splits]
except ValueError as e:
print(value)
raise e
max_rl,min_rl = max(value_list),min(value_list)
return max_rl / (min_rl + 1e-10) |
def get_largest_logo(logos):
"""
Given a list of logos, this one finds the largest in terms of perimeter
:param logos: List of logos
:return: Largest logo or None
"""
if len(logos) >= 1:
logo = max(logos, key=lambda x: int(x.get('height', 0)) + int(x.get('width', 0))).get('value')
return logo |
def get_aic(lnL, Nf):
"""
Provides the Akaike Information Criterion (Akaike, 1973), i.e. AIC.
Parameters
----------
lnL : float
Minus the log-likelihood.
Nf : int
Number of free parameters.
Returns
-------
AIC : float
AIC indicator.
"""
AIC = 2 * (lnL + Nf)
return AIC |
def _get_package_status(package):
"""Get the status for a package."""
status = package['status_str'] or 'Unknown'
stage = package['stage_str'] or 'Unknown'
if stage == 'Fully Synchronised':
return status
return '%(status)s / %(stage)s' % {
'status': status,
'stage': stage
} |
def range_overlap(a, b):
"""
>>> range_overlap(("1", 30, 45), ("1", 45, 55))
True
>>> range_overlap(("1", 30, 45), ("1", 57, 68))
False
>>> range_overlap(("1", 30, 45), ("2", 42, 55))
False
"""
a_chr, a_min, a_max = a
b_chr, b_min, b_max = b
# must be on the same chromosome
if a_chr!=b_chr: return False
return (a_min <= b_max) and (b_min <= a_max) |
def overlay_file_name(p):
"""
generate overlay file name from ljpeg file name
"""
return '.'.join(p.split('.')[:-1]) + '.OVERLAY' |
def caption_time_to_milliseconds(caption_time):
"""
Converts caption time with HH:MM:SS.MS format to milliseconds.
Args:
caption_time (str): string to convert
Returns:
int
"""
ms = caption_time.split('.')[1]
h, m, s = caption_time.split('.')[0].split(':')
return (int(h) * 3600 + int(m) * 60 + int(s)) * 1000 + int(ms) |
def tf_b(tf, _):
"""Boolean term frequency."""
return 1.0 if tf > 0.0 else 0.0 |
def log2(n):
"""
Smallest integer greater than or equal to log_2(n).
"""
i = 1
log = 0
while n > i:
log += 1
i *= 2
return log |
def remove_ansi(s : str) -> str:
"""
Remove ANSI escape characters from a string.
"""
import re
return re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])').sub('', s) |
def html_mark_warning(text):
""" Simple mark warning using html and css. """
return u"<div style='color:orange;'>%s</div>" % text |
def rem(number=2304811, divisor=47):
"""
task 0.5.2
"""
return number - (
(number // divisor) * divisor
) |
def get_version_number(data):
"""Gets the table version from the given section data
Parses the given array of section data bytes and returns the version number of the section.
"""
vn = data[5] & int('00111110', 2)
vn = vn >> 1
return vn |
def solver_problem1(input_list):
"""walk through the binaries and calculate the most/least common bit"""
common_bit = [0] * len(input_list[0])
for _, bin_list in enumerate(input_list):
for j, bin_num in enumerate(bin_list):
if bin_num == 1:
common_bit[j] += 1
else:
common_bit[j] -= 1
gamma_rate = []
epsilon_rate = []
for _, bit_num in enumerate(common_bit):
if bit_num > 0:
gamma_rate.append(1)
epsilon_rate.append(0)
else:
gamma_rate.append(0)
epsilon_rate.append(1)
gamma_strs = [str(integer) for integer in gamma_rate]
gamma_ints = int("".join(gamma_strs), 2)
epsilon_strs = [str(integer) for integer in epsilon_rate]
epsilon_ints = int("".join(epsilon_strs), 2)
return gamma_ints * epsilon_ints |
def effective_area(subidx, subncol, cellsize, r_ratio=0.5):
"""Returns True if highress cell <subidx> is inside the effective area."""
R = cellsize * r_ratio
offset = cellsize / 2.0 - 0.5 # lowres center
ri = abs((subidx // subncol) % cellsize - offset)
ci = abs((subidx % subncol) % cellsize - offset)
# describes effective area
ea = (ri ** 0.5 + ci ** 0.5) <= R ** 0.5 or ri <= 0.5 or ci <= 0.5
return ea |
def linOriginRegression(points):
"""
computes a linear regression starting at zero
"""
j = sum([ i[0] for i in points ])
k = sum([ i[1] for i in points ])
if j != 0:
return k/j, j, k
return 1, j, k |
def from_ymd(y, m=None, d=None):
"""take a year y, a month m or a d (all integers, or strings represeting integers) and return a stirng in the form "YYYY-MM-DD"
"""
if y and m and d:
return '%s-%s-%s' % (str(y).zfill(4), str(m).zfill(2), str(d).zfill(2))
elif y and m:
return '%s-%s' % (str(y).zfill(4), str(m).zfill(2))
elif y:
return '%s' % (str(y).zfill(4)) |
def is_dict_of(d: dict, expected_type: type) -> bool:
"""Check whether it is a dict of some type."""
if not isinstance(expected_type, type):
raise TypeError(f"`expected_type` must be a valid type. But got: {expected_type}.")
return all(isinstance(v, expected_type) for k, v in d.items()) |
def first_line_of(step):
"""
Return the first line of a step
"""
return step.strip().splitlines()[0] |
def n2s(counts):
"""convert a counts vector to corresponding samples"""
samples = ()
for (value, count) in enumerate(counts):
samples = samples + (value,)*count
return samples |
def get_transceiver_description(sfp_type, if_alias):
"""
:param sfp_type: SFP type of transceiver
:param if_alias: Port alias name
:return: Transceiver decsription
"""
if not if_alias:
description = "{}".format(sfp_type)
else:
description = "{} for {}".format(sfp_type, if_alias)
return description |
def focus_index(average_pages_visited_in_section, total_pages_in_section):
"""Return the focus index for a section of a website.
Args:
average_pages_visited_in_section (float): Average number of pages visited in this section of the website.
total_pages_in_section (int): Total number of pages in this section of the website.
Returns:
Focus index as average_pages_visited_in_section / total_pages_in_section
"""
return (average_pages_visited_in_section / total_pages_in_section) * 100 |
def escape_string(s: str) -> str:
"""escape special characters"""
s = repr(s)
if not s.startswith(('"', "'")):
# u'hello\r\nworld' -> hello\\r\\nworld
s = s[2:-1]
else:
# 'hello\r\nworld' -> hello\\r\\nworld
s = s[1:-1]
s = s.replace("\\'", "'") # repr() may escape "'" in some edge cases, remove
s = s.replace('"', '\\"') # repr() does not escape '"', add
return s |
def get_pending_registration_ip_set(
ip_from_dns_set, ip_from_target_group_set
):
"""
# Get a set of IPs that are pending for registration:
# Pending registration IPs that meet all the following conditions:
# 1. IPs that are currently in the DNS
# 2. Those IPs must have not been registered yet
:param ip_from_target_group_set: a set of IPs that are currently registered with a target group
:param ip_from_dns_set: a set of IPs that are in the DNS
"""
pending_registration_ip_set = ip_from_dns_set - ip_from_target_group_set
return pending_registration_ip_set |
def delete_trailing_zeros(strValue):
""" Remove all the trailing zeros"""
newStr = strValue
if '.' in strValue:
lStr = strValue.split('.')[0]
rStr = strValue.split('.')[1].rstrip('0')
newStr = lStr + '.' + rStr
if rStr == '':
newStr = lStr
return newStr |
def character_arena_progress(pvp_data):
"""Accepts a JSON object containing pvp data
and returns the players current arena/bg progression. """
brackets = pvp_data["pvp"]["brackets"]
two_v_two = brackets["ARENA_BRACKET_2v2"]["rating"]
two_v_two_skirmish = brackets["ARENA_BRACKET_2v2_SKIRMISH"]["rating"]
three_v_three = brackets["ARENA_BRACKET_3v3"]["rating"]
rated_bg = brackets["ARENA_BRACKET_RBG"]["rating"]
honorable_kills = pvp_data["totalHonorableKills"]
pvp_data = {
"2v2": two_v_two,
"2v2s": two_v_two_skirmish,
"3v3": three_v_three,
"rbg": rated_bg,
"kills": honorable_kills,
}
return pvp_data |
def get_class_attr(obj, name, default=None):
"""Specifically get an attribute of an object's class."""
return getattr(obj.__class__, name, default) |
def eppley_1979(pprod):
"""Export production from satellite derived properties
Parameters
----------
pprod: array_like
Primary Production (mg C m-3)
Returns
-------
eprod : ndarray or scalar
Export production (mg C m-3)
Ref
---
"""
eprod = 0.0025 * pprod**2 #\; (PP \leq 200)
eprod = 0.5 * pprod # (PP > 200)
return eprod |
def is_date_time(file_type, path):
"""
Return True if path is an object that needs to be converted to date/time string.
"""
date_time_objects = {}
date_time_objects["Gzip"] = ("mod_time",)
date_time_objects["PE"] = ("pe.coff_hdr.time_date_stamp",)
date_time_objects["Windows shortcut"] = ("header.time_creation", "header.time_access", "header.time_write", "last_mod_time")
date_time_objects["ZIP"] = ("body.last_mod_time", "body.last_access_time", "body.creation_time")
if file_type in date_time_objects.keys():
for p in date_time_objects[file_type]:
if p in path:
return True
return False
else:
return False |
def partition(alist, size):
"""
Returns a partition value of a list
Always parts of size
Ex.: ['1985', 1, '1990', 1]
Returns: [['1985', 1], ['1990', 1]]
"""
return [alist[i : i + size] for i in range(0, len(alist), size)] |
def converge(converging, branches, args):
"""Accepts a converging function and a list of branching functions and returns
a new function. When invoked, this new function is applied to some
arguments, each branching function is applied to those same arguments. The
results of each branching function are passed as arguments to the converging
function to produce the return value"""
return converging(*[f(args) for f in branches]) |
def vars_in_env(type_env, keys=False):
"""Where `type_env` is a mapping to types, return all type varaibles found
in the mapping. If `keys` is true, collect all keys."""
unsafe = set()
for k in type_env:
if keys:
unsafe |= {k}
unsafe |= type_env[k].bound_type_vars()
return unsafe |
def _rangelen(begin, end):
"""Returns length of the range specified by begin and end.
As this is typically used to calculate the length of a buffer, it
always returns a result >= 0.
See functions like `_safeDoubleArray` and `safeLongArray`.
"""
# We allow arguments like begin=0, end=-1 on purpose. This represents
# an empty range; the callable library should do nothing in this case
# (see RTC-31484).
result = end - begin + 1
if result < 0:
return 0
return result |
def is_empty(iterable):
"""
This filter checks whether the given iterable is empty.
:param iterable: The requested iterable
:type iterable: ~collections.abc.Iterable
:return: Whether or not the given iterable is empty
:rtype: bool
"""
return not bool(iterable) |
def scalar_in_sequence(x, y):
"""Determine whether the scalar in the sequence."""
if x is None:
raise ValueError("Judge scalar in tuple or list require scalar and sequence should be constant, "
"but the scalar is not.")
if y is None:
raise ValueError("Judge scalar in tuple or list require scalar and sequence should be constant, "
"but the sequence is not.")
return x in y |
def find_allowed_size(nx_size):
"""
Finds the next largest "allowed size" for the Fried Phase Screen method
Parameters:
nx_size (int): Requested size
Returns:
int: Next allowed size
"""
n = 0
while (2 ** n + 1) < nx_size:
n += 1
nx_size = 2 ** n + 1
return nx_size |
def from_hex(hexstring) -> bytearray:
# converts hex to bytearray
"""
converts hex to bytearray
Converts the hex string received from databse to bytes for decryption
:param hexstring: hex string recieved from database
:type hexstring: hex
:return: bytes from hex string
:rtype: bytearray
"""
return bytearray.fromhex(hexstring) |
def parse_processing_parents(processings, parent_keys):
"""Return a dictionary relating each processing identifier to its parent.
Parameters
----------
processings : dict
A dictionary of processing data, whose keys are processing identifiers
and values are dictionaries containing corresponding processing data.
This sort of dictionary is generated by reading the JSON file containing
processing/artifact metadata derived from the processing network/tree on
Qiita.
parent_keys : ordered iterable of str
An ordered collection of strings that are keys that will be
sequentially used to find parent processing identifiers in the
processing data of the `processings` argument.
Returns
-------
dict
Dictionary whose keys are processing identifiers and values are the
identifiers of a parent processing.
"""
processing_parents = {}
for proc_id, proc_data in processings.items():
for key in parent_keys:
try:
parent_id = proc_data[key]
except KeyError:
# Processings can also have no parents, in which case the for
# loop will simply exhaust all keys.
pass
else:
processing_parents[proc_id] = parent_id
break
return processing_parents |
def pil_rect(rect_tup):
""" x, y, w, h -> x, y, x, y
"""
x, y, w, h = [float(f) for f in rect_tup]
return (x, y), (x + w, y + h) |
def flip_case(phrase, to_swap):
"""Flip [to_swap] case each time it appears in phrase.
>>> flip_case('Aaaahhh', 'a')
'aAAAhhh'
>>> flip_case('Aaaahhh', 'A')
'aAAAhhh'
>>> flip_case('Aaaahhh', 'h')
'AaaaHHH'
"""
to_swap = to_swap.lower()
out = ""
for ltr in phrase:
if ltr.lower() == to_swap:
ltr = ltr.swapcase()
out += ltr
return out |
def is_prime(n: int) -> bool:
"""Return True if *n* is a prime number
"""
n = abs(n)
if n == 0:
return False
return all((n % i != 0 for i in range(2, int(n**.5)+1))) |
def inv_map(dictionary: dict):
"""
creates a inverse mapped dictionary of the provided dict
:param dictionary: dictionary to be reverse mapped
:return: inverse mapped dict
"""
return {v: k for k, v in dictionary.items()} |
def split_number(number, multiplier):
"""Decodes a number into two. The number = high * multiplier + low, and
This method returns the tuple (high, low).
"""
low = int(number % multiplier)
high = int(number / multiplier)
return (high, low) |
def parse_schema(raw: dict) -> dict:
"""Parse a field, adapter, or config schema into a more user friendly format.
Args:
raw: original schema
"""
parsed = {}
if raw:
schemas = raw["items"]
required = raw["required"]
for schema in schemas:
name = schema["name"]
schema["required"] = name in required
parsed[name] = schema
return parsed |
def remove_param_from_pytest_node_str_id(test_id, param_id_str):
"""
Returns a new test id where the step parameter is not present anymore.
:param test_id:
:param param_id_str:
:return:
"""
# from math import isnan
# if isnan(step_id):
# return test_id
new_id = test_id.replace('-' + param_id_str + '-', '-', 1)
# only continue if previous replacement was not successful to avoid cases where the step id is identical to
# another parameter
if len(new_id) == len(test_id):
new_id = test_id.replace('[' + param_id_str + '-', '[', 1)
if len(new_id) == len(test_id):
new_id = test_id.replace('-' + param_id_str + ']', ']', 1)
return new_id |
def flip(func, a, b):
"""Call the function call with the arguments flipped.
This function is curried.
>>> def div(a, b):
... return a / b
...
>>> flip(div, 2, 1)
0.5
>>> div_by_two = flip(div, 2)
>>> div_by_two(4)
2.0
This is particularly useful for built in functions and functions defined
in C extensions that accept positional only arguments. For example:
isinstance, issubclass.
>>> data = [1, 'a', 'b', 2, 1.5, object(), 3]
>>> only_ints = list(filter(flip(isinstance, int), data))
>>> only_ints
[1, 2, 3]
"""
return func(b, a) |
def get_last_package_name(name):
"""
Returns module name.
From `a.b.c` it returns `c`.
:param str name: Full module name
:return: Last package name / module name.
:rtype: str
"""
return name.split(".")[-1] |
def thumb_url_form(url):
"""Takes the SLWA photo url and returns the thumbnail url. Note this
function is heavily influenced by the format of the catalogue and could be
easily broken if the Library switches to a different url structure.
"""
if url[-4:] != '.png' and url[-4:] != '.jpg':
url = url + '.png'
return url |
def get_target_value_list(data_set):
"""Get the list that contains the value of quality."""
target_value_list = []
for line in data_set:
target_value_list.append(line[-1])
return target_value_list |
def remove_duplicates(jobs):
"""
Removee test duplicates which may come from JOBSARCHIVED4 and JOBSARCHIVED
:return:
"""
jobs_new = []
pandaids = {}
for job in jobs:
if job['pandaid'] not in pandaids:
pandaids[job['pandaid']] = []
pandaids[job['pandaid']].append(job)
for pid, plist in pandaids.items():
if len(plist) == 1:
jobs_new.append(plist[0])
elif len(plist) > 1:
# find one that has bigger attemptmark
jobs_new.append(sorted(plist, key=lambda d: d['attemptmark'], reverse=True)[0])
return jobs_new |
def get_dot_indices(face_index_from_1):
"""Get indices (from 0 through 20) corresponding to dots on the given face (from 1 through 6)."""
if face_index_from_1 == 1:
return [0]
elif face_index_from_1 == 2:
return [1,2]
elif face_index_from_1 == 3:
return [3,4,5]
elif face_index_from_1 == 4:
return [6,7,8,9]
elif face_index_from_1 == 5:
return [10,11,12,13,14]
elif face_index_from_1 == 6:
return [15,16,17,18,19,20]
else:
return [] |
def divided_by(base, dvdby):
"""Implementation of / or //"""
if isinstance(dvdby, int):
return base // dvdby
return base / dvdby |
def spotinst_tags_to_dict(tags):
""" Converts a list of Spotinst tag dicts to a single dict with corresponding keys and values """
return {tag.get('tagKey'): tag.get('tagValue') for tag in tags or {}} |
def make_kwargs_for_wallet(data):
"""
:param data: dict type
"""
fee_dict = {}
channel_config = data.get("Channel")
if channel_config:
for key in channel_config:
fee_dict[key] = channel_config[key].get("Fee")
return {
"ip": data.get("Ip"),
"public_key": data.get("Publickey"),
"name": data.get("alias"),
# "deposit": data.get("CommitMinDeposit"),
"fee": fee_dict,
"balance": data.get("Balance")
} |
def decode_int(string):
"""
Decodes integer from byte string
"""
result = 0
for n, c in enumerate(string):
if isinstance(c, str):
c = ord(c)
result |= c << (8 * n)
return result |
def eval_add(lst):
"""Evaluate an addition expression. For addition rules, the parser will return
[number, [[op, number], [op, number], ...]]
To evaluate that, we start with the first element of the list as result value,
and then we iterate over the pairs that make up the rest of the list, adding
or subtracting depending on the operator.
"""
first = lst[0]
result = first
for n in lst[1]:
if n[0] == '+':
result += n[1]
else:
result -= n[1]
return result |
def transpose(lines):
"""
Transpose the lines
"""
lines = lines.split("\n")
if not lines:
return ""
max_length = max(map(len, lines))
result = []
for index in range(max_length):
col, spaces = "", ""
for line in lines:
try:
col += spaces + line[index]
spaces = ""
except IndexError:
spaces += " "
result.append(col)
for line in result:
print("\"" + line + "\"")
return "\n".join(result) |
def _is_items(lst):
"""Is ``lst`` an items list?
"""
try:
return [(a, b) for a, b in lst]
except ValueError:
return False |
def reverse_complement(nuc_sequence):
"""
Returns the reverse complement of a nucleotide sequence.
>>> reverse_complement('ACGT')
'ACGT'
>>> reverse_complement('ATCGTGCTGCTGTCGTCAAGAC')
'GTCTTGACGACAGCAGCACGAT'
>>> reverse_complement('TGCTAGCATCGAGTCGATCGATATATTTAGCATCAGCATT')
'AATGCTGATGCTAAATATATCGATCGACTCGATGCTAGCA'
"""
complements = {
"A": "T",
"C": "G",
"G": "C",
"T": "A"
}
rev_seq = "".join([complements[s] for s in nuc_sequence[::-1]])
return rev_seq |
def number(spelling):
"""
Number construction helper.
This helper tries to cast the number as an integer. If that is not possible
it switches over to float representation as a last resort.
"""
try:
return int(spelling)
except ValueError as e:
try:
v = float(spelling)
if v == int(v):
return int(v)
return v
except ValueError as f:
raise f from e |
def validate_server_port(port):
"""
Returns Whether or not gicen port is a valid server port.
"""
try:
int(port)
return True
except:
return False |
def extract_edge_type(edge_address):
"""Given a graph edge address, returns the edge type.
:param edge_address: The edge address
:return: The label
"""
edge_type = edge_address[2]
if edge_type == "REACTS":
return "REACTS" + edge_address[3]
else:
return edge_type |
def get_result_from_file(file_name):
"""
load dependency result from file
:param file_name: name of the file that stores functional dependency
:return: a sequence of each stripped line string
"""
try:
with open(file_name, 'r') as f:
raw_data = f.read()
except IOError as e:
print(e)
return []
lines = raw_data.strip().split('\n')
return [x.strip() for x in lines] |
def return_code(text):
"""
Make return code for slack
:param text(string): slack return text
:return (string): json format for slack
"""
payload={'text': text}
return payload |
def indent(t, indent=0, sep='\n'):
"""Indent text."""
return sep.join(' ' * indent + p for p in t.split(sep)) |
def karatsuba(x, y):
"""Function to multiply 2 numbers in a more efficient manner than the grade school algorithm"""
if len(str(x)) == 1 or len(str(y)) == 1:
return x*y
else:
n = max(len(str(x)), len(str(y)))
nby2 = n / 2
a = x / 10**(nby2)
b = x % 10**(nby2)
c = y / 10**(nby2)
d = y % 10**(nby2)
ac = karatsuba(a, c)
bd = karatsuba(b, d)
ad_plus_bc = karatsuba(a+b, c+d) - ac - bd
# this little trick, writing n as 2*nby2 takes care of both even and odd n
prod = ac * 10**(2*nby2) + (ad_plus_bc * 10**nby2) + bd
return prod |
def remove_unwanted_files(workdir, files):
"""
Remove files from the list that are to be ignored by the looping job algorithm.
:param workdir: working directory (string). Needed in case the find command includes the workdir in the list of
recently touched files.
:param files: list of recently touched files (file names).
:return: filtered files list.
"""
_files = []
for _file in files:
if not (workdir == _file or
"pilotlog" in _file or
".lib.tgz" in _file or
".py" in _file or
"pandaJob" in _file):
_files.append(_file)
return _files |
def get_id_from_airlabname(name):
"""
Directly get the clonenames from raulnames
:param name:
:return:
"""
newname = name.split('_')[-1]
newname = newname.split('(')[0]
if newname == '':
newname = name
return newname |
def get_parameter_kwargs(args):
"""Get parameter name-value mappings from the raw arg list
An example: ['-g', 'RG', '--name=NAME'] ==> {'-g': 'RG', '--name': 'NAME'}
:param args: The raw arg list of a command
:type args: list
:return: The parameter name-value mappings
:type: dict
"""
parameter_kwargs = dict()
for index, parameter in enumerate(args):
if parameter.startswith('-'):
param_name, param_val = parameter, None
if '=' in parameter:
pieces = parameter.split('=')
param_name, param_val = pieces[0], pieces[1]
elif index + 1 < len(args) and not args[index + 1].startswith('-'):
param_val = args[index + 1]
if param_val is not None and ' ' in param_val:
param_val = '"{}"'.format(param_val)
parameter_kwargs[param_name] = param_val
return parameter_kwargs |
def set_flag_state(flags: int, flag: int, state: bool = True) -> int:
"""Set/clear binary `flag` in data `flags`.
Args:
flags: data value
flag: flag to set/clear
state: ``True`` for setting, ``False`` for clearing
"""
if state:
flags = flags | flag
else:
flags = flags & ~flag
return flags |
def sentence_preprocessing(sentence):
"""Prepossing the sentence for SQL query.
Prepocessing the sentence for query:
- Delete redundant space
- Convert into lower case
Args:
sentence (str): the str to be processed
Returns:
str: the str after processing
"""
while ' ' in sentence:
sentence = sentence.replace(' ', ' ')
if sentence[0] == ' ':
sentence = sentence[1:]
if sentence[-1] == ' ':
sentence = sentence[:-1]
sentence = sentence.lower()
return sentence |
def next_power_of_2(n):
"""
Return next power of 2 greater than or equal to n
"""
return 2**(n-1).bit_length() |
def decode(string):
"""
Decode the string
"""
result, index, count = "", 0, ""
while index < len(string):
if string[index].isdigit():
count += string[index]
else:
if not count:
result += string[index]
else:
result += int(count) * string[index]
count = ""
index += 1
return result |
def update_all_dict_values(my_dict, value):
"""
All the values of the given dictionary are updated to a single given value.
Args:
my_dict (dict): Given dictionary.
value: Can be any data structure. list, dict, tuple, set, int or string.
Returns:
dict: Updated dict with the performed changes.
"""
my_dict = my_dict.copy()
for k in my_dict.keys():
my_dict[k] = value
return my_dict |
def apply_profile(fgraph, node, profile):
"""Return apply profiling informaton."""
if not profile or profile.fct_call_time == 0:
return None
time = profile.apply_time.get((fgraph, node), 0)
call_time = profile.fct_call_time
return [time, call_time] |
def fibonacci(n):
"""Get all terms of the Fibonacci sequence until the first term has a
length of N digits."""
a, b = 1, 1
f = [a, b]
while len(str(b)) < n:
a, b = b, a + b
f.append(b)
return f |
def main(dog_name):
"""
This function takes in dog name and returns info about it.
:param dog_name: string
:return: string
"""
print("This is the best!")
print(dog_name)
return "My dog is named" + dog_name |
def asId(v, default=0):
"""The *asId* method transforms the *value* attribute either to an instance
of @ int@ or to @None@, so it can be used as *id* field in a @Record@
instance. If the value cannot be converted, then the optional *default*
(default value is @0 @) is answered.
>>> asId(123) == 123
True
>>> asId('abcd', 'ABCD')
'ABCD'
"""
try:
v = int(v)
if v <= 0:
return default
return v
except (ValueError, TypeError):
return default |
def DGS3600(v):
"""
DGS-3600-series
:param v:
:return:
"""
return (
"DGS-3610" not in v["platform"]
and "DGS-3620" not in v["platform"]
and v["platform"].startswith("DGS-36")
) |
def parser(response):
"""Parses the json response from CourtListener /opinions endpoint."""
results = response.get("results")
if not results:
return []
ids = []
for result in results:
_id = result.get("id", None)
if _id is not None:
ids.append(_id)
return ids |
def iround(val, lower):
"""Round value to lower or upper integer in case of the equally good fit.
Equas to math.round for lower = False.
val: float - the value to be rounded
lower: bool - direction of the rounding resolution in case of the equally good fit
return v: int - rounded value
>>> iround(2.5, True)
2
>>> iround(2.5, False)
3
>>> iround(2.2, True)
2
>>> iround(2.2, False)
2
>>> iround(2.7, True)
3
>>> iround(2.7, False)
3
"""
q, r = divmod(val, 1)
res = int(q if lower and r <= 0.5 or not lower and r < 0.5 else q + 1)
# print('>> val: {:.3f}, q: {:.0f}, r: {:.3f}, res: {:.0f}'.format(val, q, r-0.5, res), file=sys.stderr)
return res |
def teddy(do_print = True):
"""
Returns and optionally prints a teddy bear ASCII art.
Arguments
---------
do_print : bool
Whether to print the teddy bear.
Returns
-------
str :
Reeturns a teddy bear ASCII art.
Examples
--------
teddy()
"""
# Art by Joan G. Stark
# https://www.asciiart.eu/toys/teddy-bears
teddy_str = """
___ .--.
.--.-" "-' .- |
/ .-,` .'
\ ` \\
'. ! \\
| ! .--. |
\ '--' /.____
/`-. \__,'.' `\\
__/ \`-.____.-' `\ /
| `---`'-'._/-` \----' _
|,-'` / | _.-' `\\
.' / |--'` / |
/ /\ ` | |
| .\/ \ .--. __ \ |
'-' '._ / `\ /
jgs `\ ' |------'`
\ | |
\ /
'._ _.'
``"""
if (do_print):
print(teddy_str)
return teddy_str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.