content
stringlengths 42
6.51k
|
|---|
def maybe_ansi(text: str, level: int, use_ansi: bool = True):
"""
Adds an ANSI highlight corresponding to the level, if enabled
"""
return f"\u001b[{(level % 6) + 31}m{text}\u001b[0m" if use_ansi else text
|
def clean_path(path):
"""
Add ws:///@user/ prefix if necessary
"""
if path[0:3] != "ws:":
while path and path[0] == "/":
path = path[1:]
path = "ws:///@user/" + path
return path
|
def default_flist_reader(root, flist):
"""
flist format: impath label\nimpath label\n ...(same to caffe's filelist)
"""
imlist = []
with open(flist, 'r') as rf:
for line in rf.readlines():
splitted = line.strip().split()
if len(splitted) == 2:
impath, imlabel = splitted
elif len(splitted) == 1:
impath, imlabel = splitted[0], None
else:
raise ValueError('weird length ?')
impath = impath.strip('../')
imlist.append((impath, imlabel))
return imlist
|
def _coco_category_name_id_dict_from_list(category_list):
"""Extract ``{category_name: category_id}`` from a list."""
# check if this is a full annotation json or just the categories
category_dict = {category['name']: category['id']
for category in category_list}
return category_dict
|
def station_name(f):
"""
From the file name (f), extract the station name. Gets the data
from the file name directly and assumes the file
name is formatted as Data/Station_info.csv.
"""
return f.split('/')[1].split('_')[0]
|
def _format_key(key):
"""Format table key `key` to a string."""
schema, table = key
table = table or "(FACT)"
if schema:
return "{}.{}".format(schema, table)
else:
return table
|
def set_verbose(amount=1):
"""
Set the current global verbosity level
Parameters:
amount (int): the new level
Returns:
int: the new level
"""
global VERBOSE
VERBOSE = amount
return VERBOSE
|
def matrix_get(main: list, pos: int):
"""
Get a subset of a matrix.
"""
n = len(main)
if n % 2 != 0:
print("ERROR: Cannot split matrix with odd num of cols/rows. Stop.")
return None
mid = n // 2
sub = []
if pos == 0:
for col in range(mid):
column = []
for row in range(mid):
column.append(main[col][row])
sub.append(column)
return sub
elif pos == 1:
for col in range(mid):
column = []
for row in range(mid):
column.append(main[mid + col][row])
sub.append(column)
return sub
elif pos == 2:
for col in range(mid):
column = []
for row in range(mid):
column.append(main[col][mid + row])
sub.append(column)
return sub
elif pos == 3:
for col in range(mid):
column = []
for row in range(mid):
column.append(main[mid + col][mid + row])
sub.append(column)
return sub
|
def get_domain_concept_id(domain_table):
"""
A helper function to create the domain_concept_id field
:param domain_table: the cdm domain table
:return: the domain_concept_id
"""
return domain_table.split('_')[0] + '_concept_id'
|
def handle_arg(arg_index, arg_key, arg_value, args, kwargs):
"""
Replace an argument with a specified value if it does not
appear in :samp:`{args}` or :samp:`{kwargs}` argument list.
:type arg_index: :obj:`int`
:param arg_index: Index of argument in :samp:`{args}`
:type arg_key: :obj:`str`
:param arg_index: String key of argument in :samp:`{kwargs}`
:type arg_value: :obj:`object`
:param arg_value: Value for argument if it does not appear in argument
lists or has :samp:`None` value in argument lists.
:type args: :obj:`list`
:param args: List of arguments.
:type kwargs: :obj:`dict`
:param kwargs: Dictionary of key-word arguments.
"""
a = None
if len(args) > arg_index:
a = args[arg_index]
if arg_key in kwargs.keys():
a = kwargs[arg_key]
if a is None:
a = arg_value
if len(args) > arg_index:
args[arg_index] = a
if arg_key in kwargs.keys():
kwargs[arg_key] = a
if (len(args) <= arg_index) and (arg_key not in kwargs.keys()):
kwargs[arg_key] = a
return a
|
def tidy_gene(tcr_gene):
"""
:param tcr_gene: The named TCR gene as read in the data file
:return: A properly IMGT-recognised TCR gene name
"""
# Remove leading zeroes and inappropriate 'C' in 'TRXY'
tcr_gene = tcr_gene.replace('TCR', 'TR').replace('V0', 'V').replace('J0', 'J').replace('D0', 'D').replace('-0', '-')
# Correct orphon names
tcr_gene = tcr_gene.replace('-or09_02', '/OR9-2')
# Remove inappropriate sub-family naming in TRAJ and TRBD genes
if 'TRAJ' in tcr_gene or 'TRBD' in tcr_gene:
tcr_gene = tcr_gene.replace('-1', '')
return tcr_gene
|
def getForecastRun(cycle, times):
"""
Get the latest forecast run (list of objects) from all
all cycles and times returned from DataAccessLayer "grid"
response.
Args:
cycle: Forecast cycle reference time
times: All available times/cycles
Returns:
DataTime array for a single forecast run
"""
fcstRun = []
for t in times:
if str(t)[:19] == str(cycle):
fcstRun.append(t)
return fcstRun
|
def remove_point(vector, element):
"""
Returns a copy of vector without the given element
"""
vector.pop(vector.index(element))
return vector
|
def get_otpauth_url(user, domain, secret_key):
"""Generate otpauth url from secret key.
Arguments:
.. csv-table::
:header: "argument", "type", "value"
:widths: 7, 7, 40
"*user*", "string", "User."
"*domain*", "string", "Domain."
"*secret_key*", "string", "Base 32 secret key."
Returns:
Otpauth url.
Usage::
import googauth
secret_key = googauth.generate_secret_key()
print googauth.get_otpauth_url('user', 'domain.com', secret_key)
"""
return ('otpauth://totp/' + user + '@' + domain +
'?secret=' + secret_key)
|
def init_defaults(*sections):
"""
Returns a standard dictionary object to use for application defaults.
If sections are given, it will create a nested dict for each section name.
This is sometimes more useful, or cleaner than creating an entire dict set
(often used in testing).
Args:
sections: Section keys to create nested dictionaries for.
Returns:
dict: Dictionary of nested dictionaries (sections)
Example:
.. code-block:: python
from cement import App, init_defaults
defaults = init_defaults('myapp', 'section2', 'section3')
defaults['myapp']['debug'] = False
defaults['section2']['foo'] = 'bar
defaults['section3']['foo2'] = 'bar2'
app = App('myapp', config_defaults=defaults)
"""
defaults = dict()
for section in sections:
defaults[section] = dict()
return defaults
|
def bgr_to_rgb(ims):
"""Convert a list of images from BGR format to RGB format."""
out = []
for im in ims:
out.append(im[:,:,::-1])
return out
|
def neg(effect):
"""
Makes the given effect a negative (delete) effect, like 'not' in PDDL.
"""
return (-1, effect)
|
def cmyk2rgb(c, m, y, k):
"""
Convert cmyk color to rbg color.
"""
r = 1.0 - min(1.0, c + k)
g = 1.0 - min(1.0, m + k)
b = 1.0 - min(1.0, y + k)
return r, g, b
|
def approx_second_derivative(f,x,h):
"""
Numerical differentiation by finite differences. Uses central point formula
to approximate second derivative of function.
Args:
f (function): function definition.
x (float): point where second derivative will be approximated
h (float): step size for central differences. Tipically less than 1
Returns:
ddf (float): approximation to second_derivative.
"""
ddf =(f(x+h) - 2.0*f(x) + f(x-h))/h**2
return ddf
|
def longestCommonSubsequence(text1: str, text2: str) -> int:
"""
Time: O(mn)
Space: O(mn)
"""
dp = [[0 for _ in range(len(text2) + 1)] for _ in range(len(text1) + 1)]
for i in range(len(text1)):
for j in range(len(text2)):
if text1[i] == text2[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
return dp[-1][-1]
|
def ascii_to_string(s):
""" Convert the array s of ascii values into the corresponding string. """
return ''.join(chr(i) for i in s)
|
def str2int(s):
"""
Returns integer representation of product state.
Parameters
----------
s : str
"""
return int(s, 2)
|
def color_prob(prob):
"""Generates a purple shade which is darker for higher probs"""
return (f"rgb({240 - 120*prob:0.0f}, {240 - 130*prob:0.0f}, "
f"{240 - 70*prob:0.0f})")
|
def get_urls(doc_names: list) -> list:
"""
:param doc_names: list of wiki url (the key word)
:return:
"""
urls = []
for doc_name in doc_names:
url = "https://en.wikipedia.org/wiki/" + doc_name
urls.append(url)
return urls
|
def to_seconds(hours, minutes, seconds):
"""Return the amount of seconds in the given hours, minutes, seconds."""
return hours * 3600 + minutes * 60 + seconds
|
def series_char(series,header):
"""Uses interquartile range to estimate amplitude of a time series."""
series=[float(s) for s in series[1:] if s!="NA"]
head = [header[i] for i,s in enumerate(series) if s!="NA"]
if series!=[]:
mmax = max(series)
mmaxloc = head[series.index(mmax)]
mmin = min(series)
mminloc = head[series.index(mmin)]
diff=mmax-mmin
else:
mmax = "NA"
mmaxloc = "NA"
mmin = "NA"
mminloc = "NA"
diff = "NA"
return mmax,mmaxloc,mmin,mminloc,diff
|
def rgbsplit(image):
""" Converts an RGB image to a 3-element list of grayscale images, one for each color channel"""
return [[[pixel[i] for pixel in row] for row in image] for i in (0,1,2)]
|
def check_command_format(command):
"""Check command format
"""
if len(command[0].split(' ')) != 2:
return True
for twocell in command[1].split(';'):
if len(twocell.split(' ')) != 2:
return True
for cell in twocell.split(' '):
if len(cell.split(',')) != 2:
return True
return False
|
def compute_CIs(data, alpha=0.95):
"""
compute confidence interval for a bootstrapped set of data...
"""
n = len(data)
data = sorted(data)
lower_bound, upper_bound = int(n*(1-alpha)/2), int(n*(1+alpha)/2)
return data[lower_bound], data[upper_bound]
|
def goa_criterion_1_check(x1_list, x2_list):
"""
function
Calculate the difference between the current and previous x_list
if the difference between each pair in the same index of the current and previous x_list is less than 1%:
the x_list is good enough to be returned
:param
x1_list:
previous x_list
x2_list:
current x_list
:return:
"""
criterion_flag = False
criterion_list = []
for x1, x2 in zip(x1_list, x2_list):
if abs((x2 - x1) / x1) < 0.01:
criterion_list.append(0)
else:
criterion_list.append(1)
if sum(criterion_list) == 0:
criterion_flag = True
return criterion_flag
|
def run_intcode(memory):
"""Run an Intcode program from memory and return the result"""
instr_ptr = 0
while instr_ptr < len(memory):
opcode = memory[instr_ptr]
if opcode == 99:
return memory[0]
if opcode == 1:
store = memory[instr_ptr + 3]
num1 = memory[instr_ptr + 1]
num2 = memory[instr_ptr + 2]
memory[store] = memory[num1] + memory[num2]
instr_ptr = instr_ptr + 4
elif opcode == 2:
store = memory[instr_ptr + 3]
num1 = memory[instr_ptr + 1]
num2 = memory[instr_ptr + 2]
memory[store] = memory[num1] * memory[num2]
instr_ptr = instr_ptr + 4
else:
raise Exception
raise Exception
|
def exponent(numbers):
"""Raises the 0th number to the 1..Nth numbers as powers"""
result = numbers[0]
for number in numbers[1:]:
result *= number
return result
|
def is_bool(element):
"""True if boolean else False"""
check = isinstance(element, bool)
return check
|
def generate_set_l2_general(ident,size=13):
""" return list of page numbers that collide in L2 TLB, likely
independent of addressing function """
assert ident >= 0
assert ident < 256
l=[]
k=0
for x in range(size):
k+=1
l.append(k * 2**16 + ident)
assert len(l) == size
return l
|
def centroid_points(points):
"""Compute the centroid of a set of points.
Warning
-------
Duplicate points are **NOT** removed. If there are duplicates in the
sequence, they should be there intentionally.
Parameters
----------
points : sequence
A sequence of XYZ coordinates.
Returns
-------
list
XYZ coordinates of the centroid.
Examples
--------
>>> centroid_points()
"""
p = len(points)
x, y, z = zip(*points)
return sum(x) / p, sum(y) / p, sum(z) / p
|
def get_nested_value(d, key):
"""Return a dictionary item given a dictionary `d` and a flattened key from `get_column_names`.
Example:
d = {
'a': {
'b': 2,
'c': 3,
},
}
key = 'a.b'
will return: 2
"""
if '.' not in key:
if key not in d:
return None
return d[key]
base_key, sub_key = key.split('.', 1)
if base_key not in d:
return None
sub_dict = d[base_key]
return get_nested_value(sub_dict, sub_key)
|
def sunday(text, pattern):
"""sunday string match
Args:
text, pattern
Returns:
int: match index, -1: not match
"""
# get index from right
char_right_idx_dict = dict()
for i in range(len(pattern)):
# right pos char will replace left
char_right_idx_dict[pattern[i]] = len(pattern) - i
cur_idx = 0
match_char_num = 0
while cur_idx < len(text):
if text[cur_idx] == pattern[match_char_num]:
match_char_num += 1
if match_char_num == len(pattern):
return cur_idx + 1 - len(pattern)
else:
next_char_idx = cur_idx - match_char_num + len(pattern)
if next_char_idx < len(text):
move_idx = char_right_idx_dict.get(text[next_char_idx],
len(pattern) + 1)
cur_idx += move_idx - match_char_num
match_char_num = 0
continue
cur_idx += 1
return -1
|
def percent_to_str(percent):
"""
Return a nice string given a percentage.
"""
s = ""
if percent < 0:
return "Unknown"
return str(int(percent)) + "%"
|
def coverage(seq, seq_len):
"""
Return coverage of the sequence in the alignment.
>>> coverage("AAAA----", 8)
50.0
"""
res = len(seq.replace('-', ''))
return 100.0 * res / seq_len
|
def operation(d, i, r):
"""Get operation from item.
:param d: Report definition
:type d: Dict
:param i: Item definition
:type i: Dict
:param r: Meter reading
:type r: usage.reading.Reading
:return: operation
:rtype: String
"""
return i.get('operation', '')
|
def get_string_index(strings, substrings, exact=False):
"""
Search for the first index in list of strings that contains substr string
anywhere or, if exact=True, contains an exact match.
Args:
-----
strings : List of strings to be searched
substrings : List of strings to be found in **strings**
exact : (bool, optional) Whether to perform search for exact match
Returns:
--------
tuple of integers : first index of match, or None, if not found
@author: Todd Jones and Peter Clark
"""
index_list = []
for substr in substrings:
idx = None
for i, string in enumerate(strings):
if exact:
if substr == string:
idx = i
break
else:
if substr in string:
idx = i
break
# end if (exact)
index_list.append(idx)
return tuple(index_list)
|
def sbox_inv(block):
"""Bitsliced implementation of the inverse s-box
>>> x = [1, 2, 3, 4]
>>> sbox_inv(sbox(x))
[1, 2, 3, 4]
"""
b = (block[2] & block[3]) ^ block[1]
d = (block[0] | b) ^ block[2]
a = (d & block[0]) ^ block[3]
c = (a & b) ^ block[0]
return [a, b, c, d]
|
def sum_even_fib_below(n):
"""
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
:param n:
:return: the sum of the even-valued terms
"""
ans = 0
x = 1 # Represents the current Fibonacci number being processed
y = 2 # Represents the next Fibonacci number in the sequence
while x <= n:
if x % 2 == 0:
ans += x
x, y = y, x + y
return ans
|
def get_exception_message(exception: Exception) -> str:
"""Returns the message part of an exception as string"""
return str(exception).strip()
|
def mb(x):
"""Represent as MB"""
return x / 10**6
|
def red(text):
"""
Shameless hack-up of the 'termcolor' python package
by Konstantin Lepa - <https://pypi.python.org/pypi/termcolor>
to reduce rependencies and only make red text.
"""
s = '\033[%dm%s\033[0m' % (31, text)
return s
|
def make_filename(params, run):
"""Generate a filename based on params and run.
params: (net, seed, freq, weight)"""
nets = ['net_tunedrev',
'net_nofeedbackrev',
'net_disinhibitedrev']
return (f"population_vectors_{nets[int(params[0])]}"
f".TunedNetwork_{params[1]}_{str(run).zfill(3)}"
f"_{params[2]}_{params[3]}.npz")
|
def moyenne(liste):
""" calculer la moyenne """
print ( locals())
print ( globals())
return sum(liste)/len(liste)
|
def clean_output_string(s):
"""Cleans up an output string for comparison"""
return s.replace("\r\n", "\n").strip()
|
def foo1(x):
"""
Returns x+1
Parameter x: The number to add to
Precondition: x is a number (int or float)
"""
assert type(x) in [int,float], repr(x)+' is not a number'
return x+1
|
def id_ee(value):
"""generate id"""
return f"execution_environment={value}"
|
def collect_defaults(config_spec):
"""Extract the default values from config_spec as a dict of param_name:value.
Inputs:
config_spec: list of tuples of format (param_name, conversion_function, default),
where default = None means no default.
Outputs:
defaults: dict of param_name:default_value, only where a default was specified.
"""
defaults = {}
for config_tup in filter(lambda t: t[2] is not None, config_spec):
defaults[config_tup[0]] = config_tup[2]
return defaults
|
def _map_mdast(node):
"""
Walk a MDAST and return a "map" that includes just the hierarchy and types
of nodes, but none of the inner content of those nodes. Can be used to
easily compare, for example, two trees which represent the same basic
content in two different languages, and verify that they produce the same
basic HTML structure.
See https://github.com/syntax-tree/mdast for MDAST specification
"""
result = {
"type": node["type"]
}
if "children" in node:
result["children"] = [_map_mdast(child) for child in node["children"]]
return result
|
def truediv_operator():
"""/: Division operator."""
class _Operand:
def __truediv__(self, other):
return "hipster R&B"
return _Operand() / 0
|
def applyConstraint(data, constraint_func):
"""Return a subset of data that satisfies constraint_function
If constraint_func is None, return back entire data
Args:
data:
constraint_func:
Returns:
"""
if constraint_func is None:
return data
else:
outdata = {}
for key, val in data.items():
if constraint_func(val):
outdata[key] = val
return outdata
|
def size (N):
"""size(N:long) : int
Returns the size of the number N in bits.
"""
bits = 0
while N >> bits:
bits += 1
return bits
|
def partition(arr, left, right, pivot):
"""Partition function inplace
Args:
arr ([type]): [description]
left ([type]): [description]
right ([type]): [description]
pivot ([type]): [description]
"""
sorted_i = left
# Move pivot to the end
pivot_value = arr[pivot]
arr[pivot], arr[right] = arr[right], arr[pivot]
for i in range(left, right):
if arr[i] < pivot_value:
arr[i], arr[sorted_i] = arr[sorted_i], arr[i]
sorted_i += 1
arr[sorted_i], arr[right] = arr[right], arr[sorted_i]
# print(arr)
return sorted_i
|
def associate(keys, values, multiValues=False, allowDuplicates=False, shift=0, logger=None, verbose=True, sortKeys=True, sortValues=True):
"""
This function associate keys to values.
If you set multiValues as True, multiple values can ba associated to each key,
so the structure will be a dictionary of keys -> list of values.
If you set allowDuplicates to True (when multiValues is False), you will allow to associate
several time a value to keys, so each key will be used.
"""
if not multiValues and len(values) > len(keys):
if verbose:
message = "Cannot associate values of size " + str(len(values)) + " to keys of size " + str(len(keys)) + ". You can set multiValues to True."
if logger is None:
print(message)
else:
logger.log(message)
if multiValues and allowDuplicates:
raise Exception("You cannot set multiValues as True and allowDuplicates as True")
if not isinstance(keys, set):
newKeys = set(keys)
assert len(keys) == len(newKeys)
keys = newKeys
if sortKeys:
keys = sorted(list(keys))
else:
keys = list(keys)
if sortValues:
values = sorted(list(values))
else:
values = list(values)
if shift < 0:
shift = len(values) - shift
if shift > 0:
shift = shift % len(values)
values = values[shift:] + values[:shift]
assoc = dict()
if not multiValues:
i = 0
for key in keys:
if allowDuplicates:
assoc[key] = values[i]
i += 1
if i == len(values):
i = 0
else:
assoc[key] = values.pop(0)
if len(values) == 0:
break
else:
while len(values) > 0:
for key in keys:
if key not in assoc:
assoc[key] = []
assoc[key].append(values.pop(0))
if len(values) == 0:
break
return assoc
|
def substitute(expr, d):
"""
Using a dictionary of substitutions ``d`` try and explicitly evaluate as much of ``expr`` as
possible.
:param Expression expr: The expression whose parameters are substituted.
:param Dict[Parameter,Union[int,float]] d: Numerical substitutions for parameters.
:return: A partially simplified Expression or a number.
:rtype: Union[Expression,int,float]
"""
try:
return expr._substitute(d)
except AttributeError:
return expr
|
def calculate_derivative(x_value, c0, c1, c2, c3):
"""Get the first derivative value according to x_value and curve analysis formula
y = c3 * x**3 + c2 * x**2 + c1 * x + c0
Args:
x_value: value of x
c3: curvature_derivative
c2: curvature
c1: heading_angle
c0: position
Returns:
the first derivative value when x equal to x_value
"""
return 3 * c3 * x_value ** 2 + 2 * c2 + c1
|
def sane_fname(mbox):
""" sanitise the mailbox name for notification """
ret = str(mbox)
if "." in ret:
ret = ret.split(".")[-1]
return ret
|
def getFormat( self ) :
"""Checks if self has a getFormat method. If it does not, then None is returned. If it does then:
1) if getFormat returns a string or None then it is returned else getFormat must return an
integer, n1. If n1 is 12 (default for legacy ENDL) then None is returned else returns string
'%n1.n2e' where n2 = n1 - 7."""
try :
format = self.getFormat( )
if( ( format is None ) or ( type( format ) == type( '' ) ) ) : return( format )
if( format == 12 ) :
format = None
else :
format = '%%%d.%de' % ( format, format - 7 )
except :
format = None
return( format )
|
def _GetBinnedHotlistViews(visible_hotlist_views, involved_users):
"""Bins into (logged-in user's, issue-involved users', others') hotlists"""
user_issue_hotlist_views = []
involved_users_issue_hotlist_views = []
remaining_issue_hotlist_views = []
for view in visible_hotlist_views:
if view.role_name in ('owner', 'editor'):
user_issue_hotlist_views.append(view)
elif view.owner_ids[0] in involved_users:
involved_users_issue_hotlist_views.append(view)
else:
remaining_issue_hotlist_views.append(view)
return (user_issue_hotlist_views, involved_users_issue_hotlist_views,
remaining_issue_hotlist_views)
|
def getgwinfo(alist):
"""Picks off the basic information from an input dictionary list
(such as that returned by readGridworld) and returns it"""
height = alist.get('height')
width = alist.get('width')
startsquare = alist.get('startsquare')
goalsquare = alist.get('goalsquare')
barrierp = alist.get('barrierp')
wallp = alist.get('wallp')
return width, height, startsquare, goalsquare, barrierp, wallp
|
def fixture_real_base_context(real_spring_api, real_cram_api) -> dict:
"""context to use in cli"""
return {
"spring_api": real_spring_api,
"cram_api": real_cram_api,
}
|
def cowsay(msg: str) -> str:
"""
Generate ASCII picture of a cow saying something provided by the user.
Refers to the true and original: https://en.wikipedia.org/wiki/Cowsay
"""
speech_bubble_border = len(msg) * '#'
cow_speech_bubble = (
f'\n'
f'##{speech_bubble_border}##\n'
f'# {msg} #\n'
f'##{speech_bubble_border}##\n'
)
cow_img = '\n'.join((
r' \ ',
r' \ ^__^ ',
r' \ (oo)\_______ ',
r' (__)\ )\/\ ',
r' ||----w | ',
r' || || ',
))
return cow_speech_bubble + cow_img
|
def dfs(graph, source, path=None, explored=None):
"""Depth-First Search Recursive"""
if not path:
path = []
if not explored:
explored = set()
explored.add(source)
path.append(source)
for node in graph[source]:
if node not in explored:
dfs(graph, node, path, explored)
return path
|
def list_of_str(seq):
"""
Converting sequence of integers to list of strings.
:param seq: any sequence
:return: list of string
"""
return [str(el) for el in seq]
|
def str_list(input_Str):
"""convert string to list"""
temp=input_Str.split(' ') #define temp list to save the result
for i in range(len(temp)):
temp[i]=float(temp[i])
return temp
|
def get_first_duplicate_freq(changes: list):
"""Find the first duplicate frequency.
Args:
changes: frequency changes
Returns:
first duplicate frequency
"""
cur_freq = 0
visited_freqs = set()
while True:
for change in changes:
if cur_freq in visited_freqs:
return cur_freq
visited_freqs.add(cur_freq)
cur_freq += change
|
def _apply_colon_set(snode):
"""helper method for parse_patran_syntax"""
ssnode = snode.split(':')
if len(ssnode) == 2:
nmin = int(ssnode[0])
nmax = int(ssnode[1])
new_set = list(range(nmin, nmax + 1))
elif len(ssnode) == 3:
nmin = int(ssnode[0])
nmax = int(ssnode[1])
delta = int(ssnode[2])
nmin, nmax = min([nmin, nmax]), max([nmin, nmax])
if delta > 0:
new_set = list(range(nmin, nmax + 1, delta))
else:
new_set = list(range(nmin, nmax + 1, -delta))
else:
raise NotImplementedError(snode)
return new_set
|
def reverse(dafsa):
"""Generates a new DAFSA that is reversed, so that the old sink node becomes
the new source node.
"""
sink = []
nodemap = {}
def dfs(node, parent):
"""Creates reverse nodes.
A new reverse node will be created for each old node. The new node will
get a reversed label and the parents of the old node as children.
"""
if not node:
sink.append(parent)
elif id(node) not in nodemap:
nodemap[id(node)] = (node[0][::-1], [parent])
for child in node[1]:
dfs(child, nodemap[id(node)])
else:
nodemap[id(node)][1].append(parent)
for node in dafsa:
dfs(node, None)
return sink
|
def leastCommonMuliply(m:int, n:int) ->int:
"""
Return a least common multiply of a given two numbers
param: int, int
return LCM
"""
large = max(m,n)
small = min(m,n)
# if large is divisible by small returns large
if large % small == 0: return large
lcm = large
while lcm % small != 0:
lcm += large
return lcm
|
def remove_none_tags(xml_string: str) -> str:
"""
Function for removing tags with None values.
"""
xml_string_splitted = xml_string.split("\n")
xml_string_cleaned = []
for line in xml_string_splitted:
if not line.strip() or ">None</" in line:
continue
xml_string_cleaned.append(line.strip())
return "\n".join(xml_string_cleaned)
|
def get_ratios(L1, L2):
"""
Assume L1 and L2 as lists of equal lengths
Return list of containing L1[i]/L2[i]
"""
ratios = []
for i in range(len(L1)):
try:
ratios.append(L1[i]/float(L2[i]))
except ZeroDivisionError:
ratios.append(float('NaN')) # Appends nan i.e. not a number
except:
raise ValueError('get_ratios called with bad arguments')
return ratios
|
def label_filter(label_key, label_value):
"""Return a valid label filter for operations.list()."""
return 'labels."{}" = "{}"'.format(label_key, label_value)
|
def min_path(path):
"""
this function recives a path of a file and will find lightest
path from point the upper left corner to the bottom right corner
:param path: Sting a path that contains the Matrix
:return: the weight of the minimum path
"""
# parses the file into a matrix
matrix_lines = path.split('\n')
matrix_lines = matrix_lines[:-1]
val_matrix = [x.split() for x in matrix_lines]
# creates a matrix of the same size just with zeros in it
dynamic_sizes = []
for i in range(len(val_matrix)):
x = []
for j in range(len(val_matrix[0])):
x.append(0)
dynamic_sizes.append(x)
row_amount = len(dynamic_sizes)
col_amount = len(dynamic_sizes[0])
# go through the rows and columns
for i in range(row_amount):
for j in range(col_amount):
# if we are in the first row
if i == 0:
# if we are in the first col and first row just use the
# original table
if j == 0:
dynamic_sizes[i][j] = int(val_matrix[i][j])
# just use from the number from the left side and add our number
else:
dynamic_sizes[i][j] = dynamic_sizes[i][j - 1]+ \
int(val_matrix[i][j])
# if we are in the col we need the value from below us
elif j == 0:
dynamic_sizes[i][j] =\
dynamic_sizes[i-1][j] + int(val_matrix[i][j])
else:
# gets the min between coming from the
# left or coming from the bottom
dynamic_sizes[i][j] = min(
(dynamic_sizes[i-1][j] + int(val_matrix[i][j])),
(dynamic_sizes[i][j-1] + int(val_matrix[i][j])))
# returns what is in the bottom right corner
return dynamic_sizes[len(dynamic_sizes)-1][len(dynamic_sizes[0]) - 1]
|
def get_valid_extension(extension_string):
"""
Convert an extension string into a tuple that can be used on an
hdulist.
Transform an extension string obtained from the command line into
a valid extension that can be used on an hdulist. If the extension
string is just the extension version, convert that to an int.
If the extension string is 'extname,extver', split the string, store
in a tuple the extname in uppercase and the extver as an int.
Parameters
----------
extension_string : str
An extension string obtained from the command line. In such a
string, the extension version needs to be separated and converted
to an int.
Returns
-------
int or tuple
If the input is just the extension version, returns it as an int.
Otherwise, returns a two elements in the tuple with the first element
containing the extension name as an upper case str and the second
containing the extension version as an int.
Examples
--------
>>> get_valid_extension('sci,1')
('SCI',1)
>>> get_valid_extension('1')
1
"""
ext = extension_string.split(',')
if ext[0].isdigit():
valid_extension = int(ext[0])
else:
valid_extension = (ext[0].upper(), int(ext[1]))
return valid_extension
|
def f(stack, k):
"""
Fake tail recursive function
"""
if k == 1:
return stack
stack = 0.5 * (stack + 2/stack)
return f(stack, k-1)
|
def sqrt(a, m):
"""Compute two possible square roots of a mod m."""
assert m & 0b11 == 0b11
t = pow(a, (m + 1) >> 2, m)
if t % 2 == 0:
return t, m - t
else:
return m - t, t
|
def intlist(tensor):
"""
A slow and stupid way to turn a tensor into an iterable over ints
:param tensor:
:return:
"""
if type(tensor) is list:
return tensor
tensor = tensor.squeeze()
assert len(tensor.size()) == 1
s = tensor.size()[0]
l = [None] * s
for i in range(s):
l[i] = int(tensor[i])
return l
|
def decrypt_letter(letter):
""" (str) -> str
Precondition: len(letter) == 1 and letter.isupper()
Return letter decrypted by shifting 3 places to the left.
>>> decrypt_letter('Y')
'V'
"""
# Translate to a number.
ord_diff = ord(letter) - ord('A')
# Apply the left shift.
new_char_ord = (ord_diff - 3) % 26
# Convert back to a letter.
return chr(new_char_ord + ord('A'))
|
def is_float3(items):
"""Verify that the sequence contains 3 :obj:`float`.
Parameters
----------
items : iterable
The sequence of items.
Returns
-------
bool
"""
return len(items) == 3 and all(isinstance(item, float) for item in items)
|
def invert_mapping(kvp):
"""Inverts the mapping given by a dictionary.
:param kvp: mapping to be inverted
:returns: inverted mapping
:rtype: dictionary
"""
return {v: k for k, v in list(kvp.items())}
|
def user_model(role):
"""Return a user model"""
return {
"email": "user@email.com",
"id": 99,
"name": "User Name",
"profile": {
"institution": "User Institute",
"occupation": "User occupation"
},
"roles": [
f"jupyter:{role}"
]
}
|
def la_tamgiac(a,b,c):
"""Cho biet tam giac gi"""
if a+b <= c or b+c <= a or c+a <= b:
return 'Khong phai tam giac'
else:
if a == b or b == c or a == b:
if a == b and b == c:
return 'Tam giac deu'
elif a*a+b*b==c*c or b*b+c*c==a*a or c*c+a*a==b*b:
return 'Tam giac vuong can'
else:
return 'Tam giac can'
elif a*a+b*b==c*c or b*b+c*c==a*a or c*c+a*a==b*b:
return 'Tam giac vuong'
else:
return 'Tam giac thuong'
|
def is_string_environment_variable(string):
"""Determines if string being sent in without the $ is a valid environmnet variable"""
if len(string) == 0:
return False
return string[0].isalpha()
|
def cga_signature(b):
"""+-(...+)"""
return 1 if b == 0 else (-1 if b == 1 else 1)
|
def sizes(ranges):
"""Get a list with the size of the ranges"""
sizes = []
for r in ranges:
sizes.append(r[1] - r[0]) # 1: end, 0: start
return sizes
|
def argument(*name_or_flags, **kwargs):
"""Convenience function to properly format arguments to pass to the
subcommand decorator.
"""
return list(name_or_flags), kwargs
|
def select_first(*args):
"""Return the first argument that's not None."""
for arg in args:
if arg is not None:
return arg
return None
|
def create_error_message(message='Error was happened.'):
"""Create a error message dict for JSON
:param message: error message
:return: dict contain a error message
"""
return {'error': message}
|
def filter_null(item, keep_null=False, null_vals=None):
"""Function that returns or doesn't return the inputted item if its first
value is either a False value or is in the inputted null_vals list.
This function first determines if the item's first value is equivalent to
False using bool(), with one exception; 0 is considered as "True". If the
first value is in null_vals, the first value is automatically considered a
"null value" and is therefore considered to be False. If the value is False,
then None is returned; if the value is True, then the original item is
returned. The keep_null value reverses this, so True values return None,
and False values return the item.
Args:
item: Tuple whose first value determines whether it is returned or not.
Should always be a two-value tuple, with the first value being the class
value and the second value being all examples that belong to that class.
keep_null: Determines whether we keep False/"null" values or True/not
"null" values.
null_vals: List containing values that should be considered as False/"null".
Returns:
None or the inputted item, depending on if the item is False/in null_vals,
and then depending on the value of keep_null.
"""
if item[0] == 0:
keep = True
else:
keep = bool(item[0])
if null_vals and str(item[0]) in null_vals and keep:
keep = False
keep ^= keep_null
return item if keep else None
|
def read_binary(filepath):
"""return bytes read from filepath"""
with open(filepath, "rb") as file:
return file.read()
|
def mem_profile(func):
"""Profile memory usage of `func`.
"""
import tracemalloc
tracemalloc.start()
success = func()
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics('lineno')
print("[ Top 20 ]")
for stat in top_stats[:20]:
print(stat)
return success
|
def robot_move(current, direction):
"""Moves robot one square, depending on current direction it is facing. Returns new current."""
if direction == 0:
current = (current[0] - 1, current[1])
elif direction == 1:
current = (current[0], current[1] + 1)
elif direction == 2:
current = (current[0] + 1, current[1])
elif direction == 3:
current = (current[0], current[1] - 1)
else:
print("And I oop...robot_move")
return current
|
def pad_right(string, chars, filler="0"):
"""
Should be called to pad string to expected length
"""
numchars = chars - len(string)
tail = ""
if numchars > 0:
tail = filler * numchars
return string + tail
|
def dict_count_to_freq(d):
"""Turns dictionary of counts to dictionary of frequencies"""
tot_d = sum(d.values())
for val in d:
d[val] /= float(tot_d)
return d
|
def pa_test(a, b, c, d, e = None, f = None):
""" ============ DOCTEST FOOD ============
>>> pa_test(1, 2, 3, 4, 5)
(1, 2, 3, 4, 5, None)
>>> pa = pa_test(_1, 2, 3, 4, 5)
>>> pa(1)
(1, 2, 3, 4, 5, None)
"""
return (a, b, c, d, e, f)
|
def annualYield(r, c):
"""Annual yield
Returns: Simple interest rate necessary to yield the same amount
of dollars yielded by the annual rate r compounded c times for one
year
Input values:
r : interest rate
c : number of compounding periods in a year
"""
y = ((1 + (r / c)) ** c) - 1
return y
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.