content
stringlengths 42
6.51k
|
|---|
def genres_separate(genre_ids):
"""
Each genre represented by a three-digit number, and there are songs
have more than one genres. We want to separate them.
Input: column"genre_ids" of song.csv file.
Output: devided all possible categories existed for each of the song.
return a dictionary where key=distinguish genre_id,
value=number of songs belongs to that specific genre_id.
"""
genre_dictionary = {}
for genre_id in genre_ids:
if type(genre_id) != str:
continue
genre_list = genre_id.split('|')
for genre in genre_list:
if genre not in genre_dictionary:
genre_dictionary[genre] = 1
else:
genre_dictionary[genre] += 1
return genre_dictionary
|
def linearRange(start, stop, step):
"""Make a list of allowed parameter values."""
pval = start
plist = [pval]
while pval < stop:
pval = pval + step
plist.append(pval)
return plist
|
def status2str(num):
""" Return YubiHSM response status code as string. """
known = {0x80: 'YSM_STATUS_OK',
0x81: 'YSM_KEY_HANDLE_INVALID',
0x82: 'YSM_AEAD_INVALID',
0x83: 'YSM_OTP_INVALID',
0x84: 'YSM_OTP_REPLAY',
0x85: 'YSM_ID_DUPLICATE',
0x86: 'YSM_ID_NOT_FOUND',
0x87: 'YSM_DB_FULL',
0x88: 'YSM_MEMORY_ERROR',
0x89: 'YSM_FUNCTION_DISABLED',
0x8a: 'YSM_KEY_STORAGE_LOCKED',
0x8b: 'YSM_MISMATCH',
0x8c: 'YSM_INVALID_PARAMETER',
}
if num in known:
return known[num]
return "0x%02x" % (num)
|
def tiers_for_dev(dev):
"""
Returns a tuple of tiers for a given device in ascending order by
length.
:returns: tuple of tiers
"""
t1 = dev['region']
t2 = dev['zone']
t3 = "{ip}:{port}".format(ip=dev.get('ip'), port=dev.get('port'))
t4 = dev['id']
return ((t1,),
(t1, t2),
(t1, t2, t3),
(t1, t2, t3, t4))
|
def _element_to_string(x):
"""element to a string within a list."""
if x is Ellipsis:
return "..."
if isinstance(x, str):
return "'" + x + "'"
return str(x)
|
def document_uris_from_highwire_pdf(highwire_dict, claimant):
"""
Return PDF document URI dicts for the given 'highwire' document metadata.
Process a document.highwire dict that the client submitted as part of an
annotation create or update request and return document URI dicts for all
of the PDF document equivalence claims that it makes.
"""
document_uris = []
hwpdfvalues = highwire_dict.get("pdf_url", [])
for pdf in hwpdfvalues:
document_uris.append(
{
"claimant": claimant,
"uri": pdf,
"type": "highwire-pdf",
"content_type": "application/pdf",
}
)
return document_uris
|
def coords(coord_string):
"""
Match a coordinate string (eg A7) to a gv.CHESSBOARD list index.
Must check file string matches a regex in invalid input choices
"""
if len(coord_string) == 2:
file_ = ord(coord_string[0].lower()) - 97
rank = int(coord_string[1])
return file_, rank
else:
return None, None
|
def partition(test, sequence):
"""Split `sequence` into 2 lists: (positive,negative), according to the bool value of test(x), order preserved.
`test` is either a 1-arg function; or None, which is equivalent to test=bool.
`test` is called only ONCE for each element of `sequence`.
"""
pos = []
neg = []
test = test if test is not None else bool
for x in sequence:
if test(x): pos.append(x)
else: neg.append(x)
return pos, neg
|
def binary_superposition_mop(r, dic_mop, ar_1, ar_2, mop):
"""substitution for unary multioperations.
"""
rez = [0 for _ in range(r ** 2)]
for i, (x, y) in enumerate(zip(ar_1, ar_2)):
if x != 0 and y != 0:
for a in dic_mop[x]:
for b in dic_mop[y]:
rez[i] = rez[i] | mop[a * r + b]
return tuple(rez)
|
def modable(n, v):
"""If n can be modulo by v"""
if n % v:
return True
else:
return False
|
def first_values(query_parameters):
"""
Select the first values from a dictionary of query parameters
Query strings support multiple values for one key. This function takes a dictionary of lists
and returns a dictionary of strings, where the string is the first value in each list.
"""
return {key: value[0] for (key, value) in query_parameters.items()}
|
def is_same_files(files1, files2):
"""
test if two collection of files are equivalent
"""
files1_resolved = [f.resolve() for f in files1]
files2_resolved = [f.resolve() for f in files2]
return files1_resolved == files2_resolved
|
def sensitivity_adj(a,b):
"""
Tries to remove the issue that smaller complexes get biased towards high
scores by subtracting the base case where just a single member overlaps.
"""
return (len(set.intersection(a,b))-1)/len(a)
|
def get_commit_type(commit_message):
"""Return new or fix or None"""
commit_message = commit_message.lower()
if commit_message.startswith('add'):
return 'new'
elif commit_message.startswith('new '):
return 'new'
elif '[new]' in commit_message:
return 'new'
elif commit_message.startswith('fix'):
return 'fix'
elif ' fixes' in commit_message:
return 'fix'
elif ' fixed' in commit_message:
return 'fix'
elif 'bugfix' in commit_message:
return 'fix'
elif '[fix]' in commit_message:
return 'fix'
return 'new'
|
def floatToSize(val, resolution=0):
"""
string floatToSize(val, resolution=0)
formats and decorates <val>. <resolution> controls the decimal point.
"""
if not val:
return "0"
unit=""
orgVal = float(val)
val = orgVal / 1024.
if val < 2048:
unit="KiB"
else:
val /= 1024.
if val < 1500:
unit="MiB"
else:
val /= 1024.
if val < 1500:
unit="GiB"
else:
val /= 1024.
unit="TiB"
if val < 15 and orgVal >= resolution*100:
return "%0.02f %s" % (val, unit)
elif val < 150 and val >= resolution*10:
return "%0.01f %s" % (val, unit)
else:
return "%0.0f %s" % (val, unit)
|
def set_ad_blocking_enabled(enabled: bool) -> dict:
"""Enable Chrome's experimental ad filter on all sites.
Parameters
----------
enabled: bool
Whether to block ads.
**Experimental**
"""
return {"method": "Page.setAdBlockingEnabled", "params": {"enabled": enabled}}
|
def class_(obj):
"""Return a class from an object
Often in itk, the __class__ is not what the user is expecting.
class_() should do a better job
"""
import inspect
if inspect.isclass(obj):
# obj is already a class !
return obj
else:
return obj.__class__
|
def get_arguments(args, training_memory):
"""
Argument parser
:param args: dict of all the agent arguments with key and value as string
:param training_memory: memory to be used for training agent if any
:return: a dict with at least the same keys and values parsed into objects
"""
for arg_name, arg_value in args.items():
try:
arg_value = int(arg_value)
except ValueError:
pass
if arg_value == "True":
arg_value = True
elif arg_value == "False":
arg_value = False
args[arg_name] = arg_value
# if train mode is set
if "train_mode" in args:
# add a memory object
if args["train_mode"]:
args["shared_memory"] = training_memory
else:
args["shared_memory"] = None
return args
|
def get_closure_lines(lines, start_line_number):
"""
splite closure between '{' '}'
:param lines: content
:param start_line_number: should recognize begein this line
:return: Null
"""
bracket_count = 0;
for p_line in range(start_line_number, len(lines)):
line = lines[p_line]
# simplely count closure bracket count to find lines belong same closure
bracket_count = bracket_count + len(line.split('{')) - len(line.split('}'))
if bracket_count == 0:
return lines[start_line_number:p_line + 1]
|
def count(arrays, cn):
"""
Used in conjuction with `get_vals`.
Counts the proportions of all_wt, all_mut,
or mixed arrays in a given set of `data`,
up to a copy number of `cn`.
"""
all_wt, all_mut, mixed = 0, 0, 0
for array in arrays:
if len(array) != cn: continue
# homogenous WT
if all([i == 0 for i in array]): all_wt += 1
# homogenous H47R
elif all([i == 1 for i in array]): all_mut += 1
# "mixed" -- requires array to be longer than 1 copy
elif len(set(array)) > 1 and all([i in (0, 1) for i in array]):
mixed += 1
return all_wt, mixed, all_mut
|
def format_indexes_to_sql(ctypes, ColumnsIndexs):
""" in: ["Col1", "Col2"]
out: INDEX Col1, INDEX Col2
"""
sqls = []
for col in ColumnsIndexs:
ctype = ctypes[col]
if ctype == "TEXT":
key_params = "(255)"
else:
key_params = ""
sqls.append(
"INDEX ({}{})".format(
col, key_params
)
)
sql = ", \n".join(sqls)
return sql
|
def create_content_dict(file_paths):
"""Returns a dict of (txt) files, where each file contains all text in the file.
Args:
file_paths: Output of the method above
Returns:
raw_content_dict: dict of files as key. Each file contains one string containing all text in the file.
"""
raw_content_dict = {}
for filePath in file_paths:
with open(filePath, "r", errors="replace") as ifile:
file_content = ifile.read()
raw_content_dict[filePath] = file_content
return raw_content_dict
|
def ps_bad_mock(url, request):
"""
Mock for PTCRB lookup, worst case.
"""
thebody = "<table></table><table><td>CER-59665-001 - Rev2-x05-05</td><td>OS Version: 10.3.2.698 Radio Version: 10.3.2.699 SW Release Version: 10.3.2.700 OS Version: 10.3.2.698 Radio Version: 10.3.2.699 SW Release Version: 10.3.2.700</td></table>"
return {'status_code': 200, 'content': thebody}
|
def generate_ordered_sequences(waypoint_lists):
"""
Given an ordered list of lists of possible choices, generate all possible
ordered sequences.
"""
sequences = []
if len(waypoint_lists) == 0:
return []
if len(waypoint_lists) > 1:
for node in waypoint_lists[0]:
for child in generate_ordered_sequences(waypoint_lists[1:]):
if type(child) == list:
sequences.append([node] + child)
else:
sequences.append([node] + [child])
else:
sequences = waypoint_lists[0]
return sequences
|
def get_cache_key(tag_id):
"""Returns a cache key based on a tag id"""
return 'lazy_tags_{0}'.format(tag_id)
|
def bubble_sort(lst):
"""Sorts a given list using bubble sort algorithm
pre: lst is a list of elements that can be ordered
post: returns new_lst with elements of lst sorted in increasing order
"""
lst_size = len(lst)
for i in range(lst_size - 1):
for j in range(lst_size - 1 - i):
if lst[j + 1] < lst[j]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
return lst
|
def group_by(object_list, key_function):
"""
Return dictionary of objects grouped by keys returned by
`key_function` for each element in `object_list`.
`object_list` does not need to be sorted.
>>> group_by([1, 2, 3, 4, 5], lambda x: x % 2)
{0: [2, 4], 1: [1, 3, 5]}
"""
groups = dict()
for obj in object_list:
key = key_function(obj)
if key not in groups:
groups[key] = list()
groups[key].append(obj)
return groups
|
def ensemble_prediction_voting(predictions):
"""
:param predictions: a list containing the predictions of all the classifiers
:type predictions: list
:return: a value representing if a disruptive situation has been detected or not
:rtype: int
"""
count_ones = 0
count_zeros = 0
for p in predictions:
if p == 1:
count_ones += 1
else:
count_zeros += 1
if count_ones >= count_zeros:
return 1
else:
return 0
|
def find_num(s):
""" find all numbers """
if not s:
return 1
elif len(s) == 1:
return 1
else:
prefix = int(s[:2])
if prefix <= 26: # 2 char
return find_num(s[2:]) + find_num(s[1:])
else: # 1 char
return find_num(s[1:])
|
def obfuscateShortcut(shortcut):
"""
Necessary to prevent wxPython from interpreting e.g. CTRL+LEFT in a menu
item as being a shortcut. I haven't found a better way.
Unused at the moment.
"""
return u"".join([u"\u200B" + c for c in shortcut])
|
def format_us_zipcode(zipcode):
"""NiH US postcodes have wildly inconsistent formatting,
leading to geocoding errors. If the postcode if greater
than 5 chars, it should be in the format XXXXX-XXXX,
or XXXXX, even if the first 5 chars require zero-padding."""
ndigits = len(zipcode)
# Only apply the procedure to numeric postcodes like
if not zipcode.isnumeric():
return zipcode
# e.g 123456789 --> 12345-6789
# or 3456789 --> 00345-6789
if ndigits > 5:
start, end = zipcode[:-4].zfill(5), zipcode[-4:]
return f'{start}-{end}'
# e.g 12345 --> 12345
# or 345 --> 00345
else:
return zipcode.zfill(5)
|
def TrimBytes(byte_string):
"""Trim leading zero bytes."""
trimmed = byte_string.lstrip(chr(0))
if trimmed == "": # was a string of all zero byte_string
return chr(0)
else:
return trimmed
|
def ninjaenc(s):
"""
Encodes string s for use in ninja files.
"""
return s.replace('$', '$$')
|
def string_score(strang: str) -> int:
"""Sum of letter values where a==1 and z == 26
:param strang: string to be scored
:type strang: str
:returns: -> score of the string
:rtype: int
.. doctest:: python
>>> string_score('me')
18
>>> string_score('poooood')
95
>>> string_score('gregory')
95
"""
return sum((ord(character) - 96 for character in strang.lower()))
|
def _eval(lstr,locals) :
""" Evaluate parts of the string. Normal parts ("S") are not modified.
Expression parts ("E") are evaluated (using eval).
"""
l=[]
for t,s in lstr :
if t=="S" : l.append(s)
if t=="E" : l.append(str(eval(s,None,locals)))
return l
|
def pairs(itemSet, length):
"""Join a set with itself and returns the n-element itemsets"""
return set([i.union(j) for i in itemSet for j in itemSet if len(i.union(j)) == length])
|
def merge(nums1, nums2):
"""
Merge two given sorted arrays by merge sort
:param nums1: first array
:type nums1: list[int]
:param nums2: second array
:type nums2: list[int]
:return: merged array
:rtype: list[int]
"""
result = []
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
result.append(nums1[i])
i += 1
else:
result.append(nums2[j])
j += 1
while i < len(nums1):
result.append(nums1[i])
i += 1
while j < len(nums2):
result.append(nums2[j])
j += 1
return result
|
def len_route(current_route):
"""
Calculate the length of this route as when it is translated to ascii commands.
current_route: tuples with the current route.
[('L', 8),('R', 10),('L', 9) -->] will be translated to L,8,R,10,L,9 (comma's also count)
total_length = length each direction + length each number + (number of tuples * 2) - 1
"""
n_tuples = len(current_route)
if n_tuples == 0:
return 0
else:
return sum([len(direction) + len(str(n)) for direction, n in current_route]) + n_tuples * 2 - 1
|
def populate_providers_dict(provider_lst: list, read_func):
"""
Pass in lists of lists [provider,file,cost]. Reads file and populates list of channels.
Returns dictionary with provider as key and list [channel list, cost] as value
"""
dictionary = {}
for row in provider_lst:
channels = read_func(row[1])
ch_lst = []
for lst in channels:
for ch in lst:
ch_lst.append(ch)
dictionary[row[0]] = [ch_lst, row[2]]
return dictionary
|
def c_to_f(c):
"""given a temperature in C, convert to F"""
return 9/5.0*c+32
|
def tiensleutels(dict):
"""Tien sleutels van een dictionary."""
lijst = list(dict)
return(lijst[0:9])
|
def factorial(n : int) -> int:
"""
Returns the product of all the numbers in range(1,n)\n
** Uses the built in functool's module lru_cache decorator
"""
if n in (1,0):
return 1
return n * factorial(n-1)
|
def prepare_id(id_):
"""
if id_ is string uuid, return as is, if list, format as comma separated list.
"""
if isinstance(id_, list):
return ','.join(id_)
elif isinstance(id_, str):
return id_
else:
raise ValueError(f'Incorrect ID type: {type(id_)}')
|
def RGB2int(r: int, g: int, b: int
) -> int:
"""Pack byte r, g and b color value
components to an int
representation for a
specific color
Args:
r, g, b: color byte values
Returns:
int color val
"""
return b + (g << 8) + (r << 16)
|
def sequential_search_word(list1, word):
"""
Carry out a sequential search of the given sorted list for a given word
Parameters
----------
list1: input list, sorted
word: the word to be searched
Returns
-------
True/False
"""
for i in range(len(list1)):
if list1[i].lower() > word.lower():
return False
if list1[i].lower() == word.lower():
return True
return False
|
def twos_complement_8bit(b: int) -> int:
"""Interprets b like a signed 8-bit integer, possibly changing its sign.
For instance, twos_complement_8bit(204) returns -52."""
if b >= 256:
raise ValueError("b must fit inside 8 bits")
if b & (1 << 7):
# Negative number, calculate its value using two's-complement.
return b - (1 << 8)
else:
# Positive number, do not touch.
return b
|
def tweet_id_from_url(tweet_url: str) -> int:
"""Obtain tweet id from environment (from URL), e.g. .../1384130447999787017?s=20 -> 1384130447999787017."""
return int(tweet_url.split("/")[-1].split("?")[0]) if tweet_url and isinstance(tweet_url, str) else 0
|
def breaklines(s, maxcol=80, after='', before='', strip=True):
"""
Break lines in a string.
Parameters
----------
s : str
The string.
maxcol : int
The maximum number of columns per line. It is not enforced when it is
not possible to break the line. Default 80.
after : str
Characters after which it is allowed to break the line, default none.
before : str
Characters before which it is allowed to break the line, default none.
strip : bool
If True (default), remove leading and trailing whitespace from each
line.
Return
------
lines : str
The string with line breaks inserted.
"""
pieces = [c for c in s[:1]]
for i in range(1, len(s)):
if s[i - 1] in after or s[i] in before:
pieces.append('')
pieces[-1] += s[i]
lines = [p for p in pieces[:1]]
for p in pieces[1:]:
if len(lines[-1]) + len(p) <= maxcol:
lines[-1] += p
else:
lines.append(p)
if strip:
lines = [line.strip() for line in lines]
return '\n'.join(lines)
|
def histogram(letters):
"""
Creates a frequency histogram of the given letters
Input: letters -- word or scrambled letters
Output: dictionary mapping from letters to the # of occurences of that letter
"""
d = dict()
for letter in letters:
if letter in d:
d[letter] += 1
else:
d[letter] = 1
return d
|
def get_info(post: str):
"""
Get ino about year, month, day and title of the post
"""
parts = post.split("-")
return {
"year": parts[0],
"month": parts[1],
"day": parts[2],
"title": "-".join(parts[3:]),
}
|
def _unflatten_dict(flat_dict, prefixes):
"""Returns a dict of dicts if any prefixes match keys in the flat dict.
The function handles the case where the prefix may not be a dict.
Args:
flat_dict: A dict without any nesting.
prefixes: A list of strings which may have been dicts in the
original structure.
"""
original_dict = {}
for key, value in flat_dict.items():
prefix_found = False
for prefix in prefixes:
full_prefix = "__" + prefix + "_"
if key.startswith(full_prefix):
# Add a dict to the original dict with key=prefix
if prefix not in original_dict:
original_dict[prefix] = {}
original_dict[prefix][key[len(full_prefix):]] = value
prefix_found = True
break
if not prefix_found:
# No key matched a prefix in the for loop.
original_dict[key] = value
return original_dict
|
def power_eaton(v_ratio, n):
"""
Notes
-----
.. math:: \\frac{\\sigma}{{\\sigma}_{n}}=
\\left(\\frac{V}{V_{n}}\\right)^{n}
"""
return (v_ratio)**n
|
def has_updated(geo_code):
"""
Check if a muni has beein updated
"""
bad_list = ['KZN263', 'DC29', 'MP307', 'MP312', 'NC453']
if geo_code in bad_list:
return True
return False
|
def analysis_nindex(analysis):
"""
Returns a dictionary of namespace definition by name.
'nindex' stands for 'Namespace index'.
"""
return analysis.get("nindex", {})
|
def format_path(path, modules_only):
"""
Formats Rust paths.
:param path: A Rust path delimited by `::`
:param modules_only: Whether to cut off the last component of the path
:return:
"""
if modules_only:
path = path.split('::')
if len(path[-1]) == 0 or path[-1][0].isupper():
path.pop()
path = '::'.join(path)
return path
|
def hex_to_rgb(col):
"""Extracts the RGB values as integers (from 0 to 1000) from a hex color
string (#rrggbb).
"""
mul = 1000 / 255
return tuple(round(int(col.lstrip('#')[i:i + 2], 16) * mul) for i in (0, 2, 4))
|
def move_polygon(polygon_coords=None, move_coords=None, limit_x=None, limit_y=None):
"""
update coordinate pairs in a list by the specified coordinate pair that represents distance
:param polygon_coords: a list of coordinate pairs
:param move_coords: a coordinate pair that holds offset values for the x and y directions
:param limit_x: a value that represents the maximum x value
:param limit_y: a value that represents the maximum y value
:returns: Updated coordinate pair list or False
:raises TypeError: none
"""
if polygon_coords and move_coords:
new_polygon_coords = []
for polygon_coord_pair in polygon_coords:
polygon_coord_pair[0] += move_coords[0]
polygon_coord_pair[1] += move_coords[1]
if polygon_coord_pair[0] < 0:
polygon_coord_pair[0] = 0
if limit_x is not None and polygon_coord_pair[0] > limit_x:
polygon_coord_pair[0] = limit_x
if polygon_coord_pair[1] < 0:
polygon_coord_pair[1] = 0
if limit_y is not None and polygon_coord_pair[1] > limit_y:
polygon_coord_pair[1] = limit_y
new_polygon_coords.append(polygon_coord_pair)
return new_polygon_coords
else:
return False
|
def sortbyMatch(score):
"""Sort the result by number of matches in a descending order
Args:
score: A dictionary of microorganisms and match numbers obtained
by above function
Return
A sorted list of key-value pairs
"""
return sorted(score.items(), key=lambda x: x[1], reverse=True)
|
def c_measure_lag(client):
"""
Special dummyrunner command, injected in c_login. It measures
response time. Including this in the ACTION tuple will give more
dummyrunner output about just how fast commands are being processed.
The dummyrunner will treat this special and inject the
{timestamp} just before sending.
"""
return ("dummyrunner_echo_response {timestamp}",)
|
def paragraph(text):
"""Paragraph.
Args:
text (str): text to make into a paragraph.
Returns:
str: paragraph text.
"""
return text + '\r\n'
|
def curve(t):
"""
target curve for the Train during the sample fragment
:param t: time point
:return: target velocity at t point
"""
if 100 > t >= 0:
velocity = (0.8 * (t / 20) ** 2)
elif 200 > t >= 100:
velocity = 40 - 0.8 * (t / 20 - 10) ** 2
elif 400 > t >= 200:
velocity = 40
elif 500 > t >= 400:
velocity = 0.6 * (t / 20 - 20) ** 2 + 40
elif 600 > t >= 500:
velocity = 70 - 0.5 * (t / 20 - 30) ** 2
elif 1800 > t >= 600:
velocity = 70
elif 1900 > t >= 1800:
velocity = 70 - 0.6 * (t / 20 - 90) ** 2
elif 2000 > t >= 1900:
velocity = 40 + 0.6 * (t / 20 - 100) ** 2
elif 2200 > t >= 2000:
velocity = 40
elif 2300 > t >= 2200:
velocity = 40 - 0.8 * (t / 20 - 110) ** 2
elif 2400 > t >= 2300:
velocity = 0.8 * (t / 20 - 120) ** 2
else:
velocity = 0
return velocity
|
def get_dv_mission(mission):
"""Mission delta-v [units: meter second**-1]"""
if mission == 'GTO':
return 12e3 # GTO
elif mission == 'LEO':
return 9.5e3 # LEO
else:
raise ValueError()
|
def step_back_while(cur_index, condition):
"""Helper function. Decreases index from cur while condition is satisfied."""
while cur_index >= 0 and condition(cur_index):
cur_index -= 1
return cur_index
|
def gen_feat_val_list(features, values):
""" Generates feature value lists sorted in descending value.
Args:
features: A list of feature names.
values: A list of values.
Returns:
A sorted list of feature-value tuples.
"""
sorted_feat_val_list = sorted(
zip(features, values), key=lambda x: abs(x[1]), reverse=True # noqa: E731
)
return sorted_feat_val_list
|
def key_lengths(words):
"""Return a dictionary whose keys are numbers indicating word length.
Their values will be a list of all words whose length is equal to that key.
words: dictionary of words
"""
word_length = dict()
# For each word, add it to the appropriate entry (its length)
# in word_length.
for word in words:
word_length.setdefault(len(word),[]).append(word)
return word_length
|
def shift(s, n=1):
"""Rightshift string n places, with wrap around"""
return s[-n:] + s[:-n]
|
def safemin(data, default=0):
""" Return mininum of array with default value for empty array
Args:
data (array or list): data to return the maximum
default (obj): default value
Returns:
object: minimum value in the array or the default value
"""
if isinstance(data, list):
if len(data) == 0:
minimum_value = default
else:
minimum_value = min(data)
return minimum_value
if data.size == 0:
minimum_value = default
else:
minimum_value = data.min()
return minimum_value
|
def parse(string):
"""
This function parses the encoded string for the decoding phase.
This is especially userful when a character shows up
more than nine times in a row.
INPUT: An Encoded String
OUTPUT: A List of List // Parsed Encoded String
"""
if not string or len(string) == 1:
return [""]
if string[1].isdigit():
return [[int(string[:2]), string[2]]] + parse(string[3:])
else:
return [[int(string[0]), string[1]]] + parse(string[2:])
|
def convert_dict_or(obj, name, converter, default=None):
"""Just a shorthand to return default on getting smthng from dictionary."""
try:
result = converter(obj[name])
except Exception:
return default
if result <= 0:
return default
return result
|
def factorial(number):
"""
function to compute the factorial of a number
:param number: integer greater than zero
:return: factorial of the input
# DOCTEST examples
#>>> 0
1
#>>> 6
720
"""
int(number)
if number < 0:
raise ValueError("Factorial of numbers less than zero is not possible")
if 0 >= number <= 1:
return 1
# set global state
factorial_sum = 1
while number > 0:
factorial_sum = factorial_sum * number
number -= 1
print(f"{number} factorial_sum of this step = {factorial_sum:,}")
return factorial_sum
|
def one_or_more(pattern, greedy=True):
""" one or more repeats of a pattern
:param pattern: an `re` pattern
:type pattern: str
:param greedy: match as much as possible?
:type greedy: bool
:rtype: str
"""
return (r'(?:{:s})+'.format(pattern) if greedy else
r'(?:{:s})+?'.format(pattern))
|
def _get_start_stop_blocks_for_trial(
i_trial_start, i_trial_stop, input_time_length, n_preds_per_input
):
"""
Compute start stop block inds for one trial
Parameters
----------
i_trial_start: int
Index of first sample to predict(!).
i_trial_stops: 1daray/list of int
Index one past last sample to predict.
input_time_length: int
n_preds_per_input: int
Returns
-------
start_stop_blocks: list of (int, int)
A list of 2-tuples indicating start and stop index
of the inputs needed to predict entire trial.
"""
start_stop_blocks = []
i_window_stop = i_trial_start # now when we add sample preds in loop,
# first sample of trial corresponds to first prediction
while i_window_stop < i_trial_stop:
i_window_stop += n_preds_per_input
i_adjusted_stop = min(i_window_stop, i_trial_stop)
i_window_start = i_adjusted_stop - input_time_length
start_stop_blocks.append((i_window_start, i_adjusted_stop))
return start_stop_blocks
|
def uppercase_initial(string):
"""
Return a capitalized string.
:param string: Input string
:type string: str
:return: Capitalized input string
:rtype: str
>>> uppercase_initial("disableApiTermination")
"DisableApiTermination"
"""
capital = string[0].upper()
return capital + string[1:]
|
def get_indexed(data, index):
"""Index a list"""
indexed_data = {}
for element in data:
indexed_data[element[index]] = element
return indexed_data
|
def format_sec_to_dhm(sec):
"""Format seconds to days, hours, minutes.
Args:
sec: float or int
Number of seconds in a period of time.
Returns: str
Period of time represented as a string on the form ``0d\:00h\:00m``.
"""
rem_int, s_int = divmod(int(sec), 60)
rem_int, m_int, = divmod(rem_int, 60)
d_int, h_int, = divmod(rem_int, 24)
return "{}d {:02d}h {:02d}m".format(d_int, h_int, m_int)
|
def test_points(aspect_ratio, elongation, triangularity):
"""Compute the coordinates of inner and outer equatorial points and high
point based on plasma geometrical parameters.
Args:
aspect_ratio (float): minor radius / major radius
elongation (float): plasma elongation
triangularity (float): plasma triangularity
Returns:
((float, float), (float, float), (float, float)): points (x, y)
coordinates
"""
outer_equatorial_point = (1 + aspect_ratio, 0)
inner_equatorial_point = (1 - aspect_ratio, 0)
high_point = (1 - triangularity*aspect_ratio, elongation*aspect_ratio)
return outer_equatorial_point, inner_equatorial_point, high_point
|
def contiguous(_input, val):
"""
find contiguous range that sum val
"""
for idx1, n1 in enumerate(_input):
#if n1 == val:
# print('blah')
# continue
count = n1
for idx2, n2 in enumerate(_input[idx1:]):
if n1 == n2:
continue
if count == val:
new_nums = sorted(_input[idx1:idx1+idx2+1])
#pprint(new_nums)
if new_nums:
return new_nums[0] + new_nums[-1]
count += n2
# no op
return 0
|
def mean(a):
"""
Return the average of the elements of array a.
"""
return sum(a) / float(len(a))
|
def integer_power(x, n, one=1):
"""Compute :math:`x^n` using only multiplications.
See also the `C2 wiki <http://c2.com/cgi/wiki?IntegerPowerAlgorithm>`_.
"""
assert isinstance(n, int)
if n < 0:
raise RuntimeError("the integer power algorithm does not "
"work for negative numbers")
aux = one
while n > 0:
if n & 1:
aux *= x
if n == 1:
return aux
x = x * x
n //= 2
return aux
|
def extract_value_from_file(f, key, file_type='.dat'):
"""
@param file_type:
@param f:
@param key:
@return:
"""
proceed = f.split('_')
for i, k in enumerate(proceed):
if key in k:
v = proceed[i + 1]
if file_type in v:
return v[:-len(file_type)]
else:
return v
|
def combine_all_sets(sets_a, sets_b):
""" Combines two nested lists of node or element sets into the minimum ammount of set combinations.
Parameters
----------
sets_a : list
First nested list containing lists of element or node keys.
sets_b : list
Second nested list containing lists of element or node keys.
Returns
-------
dic
A dictionary containing the minimum number of set combinations.
"""
comb = {}
for i in sets_a:
for j in sets_b:
for x in sets_a[i]:
if x in sets_b[j]:
comb.setdefault(str(i) + ',' + str(j), []).append(x)
return comb
|
def modify(args, f_storage, name):
"""
args[0] ... dir to be placed at
args[1] ... addr to flip
"""
outdir = args[0]
addr = int(args[1], 16)
if addr > len(f_storage):
return 1
for index in range(0, 8):
out = outdir + name + '_' + str(hex(addr)) + '_' + str(index)
with open(out, 'wb') as f:
tmp = f_storage[addr]
f_storage[addr] ^= 1 << index
f.write(f_storage)
f_storage[addr] = tmp
return 0
|
def duration_convert(duration: int):
""" Converts duration into readable formats. """
minutes = duration // 60
seconds = duration % 60
hours = minutes // 60
minutes %= 60
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
|
def _knockout_index(length, knockout):
"""Convenience function that returns list(range(length)), with knockout removed."""
return list(range(0,knockout)) + list(range(knockout+1, length))
|
def find_heuristic_position(child_partition):
"""
This function finds the starting position of different heuristics in a combined game payoff matrix.
:param child_partition:
:return:
"""
position = {}
i = 0
for method in child_partition:
position[method] = (i, i+child_partition[method])
i += child_partition[method]
return position
|
def call(fn, args=(), kwargs={}):
"""call fn with given args and kwargs.
This is used to represent Apply.__call__
"""
return fn(*args, **kwargs)
|
def normalize(string: str) -> str:
"""[removes spaces and stuff in string]
Args:
string (str): [any string]
Returns:
str: [string without spaces or -_]
"""
string = string.replace(' ', '')
string = string.replace('-', '')
string = string.replace('_', '')
return string.lower()
|
def bestName(inRow):
"""
helper function for annotate_best_CDS
given a row with 'Label' and 'Locus tag', choose the best annotation
choose 'Label' if it's present
otherwise choose 'Locus tag'
return a string with the best name
"""
if inRow['Label'] == '':
result = inRow['Locus Tag']
else:
result = inRow['Label']
return result
|
def parse_cmd(cmd):
"""Validates command."""
cmd_arr = cmd.split()
# Blank Space
if len(cmd_arr) == 0:
return 'blank'
# Clear
if cmd_arr[0] == 'clear':
return 'clear'
# Help
if cmd_arr[0] == 'help':
return 'help'
# Valid Commands
if cmd_arr[0] != 'exit' and cmd_arr[0] != 'test' and cmd_arr[0] != 'get-all' and \
cmd_arr[0] != 'kill' and cmd_arr[0] != 'start-app' and cmd_arr[0] != 'get-slices' \
and cmd_arr[0] != 'get-measurements' and cmd_arr[0] != 'create-project' \
and cmd_arr[0] != 'create-slice' and cmd_arr[0] != 'update-slice' and cmd_arr[0] != 'start-worker' \
and cmd_arr[0] != 'kill-app' and cmd_arr[0] != 'kill-worker' and cmd_arr[0] != 'get-apps' \
and cmd_arr[0] != 'get-workers':
return None
# Argument Length Checks
if (cmd_arr[0] == 'exit' or cmd_arr[0] == 'test' or cmd_arr[0] == 'get-all') and len(cmd_arr) > 1:
return None
elif (cmd_arr[0] == 'get-slices' or cmd_arr[0] == 'get-apps' or cmd_arr[0] == 'kill-worker'
or cmd_arr[0] == 'start-worker') and len(cmd_arr) != 3:
return None
elif (cmd_arr[0] == 'get-workers' or cmd_arr[0] == 'create-project') and len(cmd_arr) != 2:
return None
elif (cmd_arr[0] == 'kill-app' or cmd_arr[0] == 'create-slice') and len(cmd_arr) != 4:
return None
elif cmd_arr[0] == 'get-measurements' and (len(cmd_arr) != 1 and len(cmd_arr) != 3):
return None
elif (cmd_arr[0] == 'update-slice') and (len(cmd_arr) < 4 or len(cmd_arr) > 6):
return None
elif cmd_arr[0] == 'start-app' and (len(cmd_arr) != 5 and len(cmd_arr) != 6):
return None
elif cmd_arr[0] == 'kill' and (len(cmd_arr) < 3 or len(cmd_arr) > 4):
return None
return cmd_arr
|
def structural_parameters(keys, columns):
"""
Gets the structural parameters in a specific order (if catalog is generated by the method in tbridge.binning)
"""
mags = columns[keys.index("MAGS")]
r50s = columns[keys.index("R50S")]
ns = columns[keys.index("NS")]
ellips = columns[keys.index("ELLIPS")]
return mags, r50s, ns, ellips
|
def get_active_layer(layer_keys_pressed, layer_count):
"""
Class representing a keyboard procesing loop..
"""
tmp = 0
if len(layer_keys_pressed) > 0:
for layer_id in layer_keys_pressed:
if layer_id > tmp: # use highest layer number
tmp = layer_id
if tmp >= layer_count:
tmp = layer_count - 1
return tmp
|
def remove_non_ascii(row):
"""
REMOVE NON ASCII CHARACTERS
"""
cleaned = ""
for word in row["description"]:
if word.isascii():
cleaned += word
return cleaned
|
def get_fiberobj_lst(string, delimiter=';'):
"""Split the object names for multiple fibers.
Args:
string (str): Input object string.
delimiter (str): Delimiter of different fibers.
Returns:
list: a list consist of (ifiber, objname), where **ifiber** is an
integer, and **objname** is a string.
"""
object_lst = [s.strip() for s in string.split(delimiter)]
fiberobj_lst = list(filter(lambda v: len(v[1])>0,
enumerate(object_lst)))
return fiberobj_lst
|
def path_name_to_name(path_name):
"""
:param path_name:
:return:
"""
return path_name.replace("\\\\", "\\") \
.replace(r"\.", ".", ) \
.replace(r"\$", "$") \
.replace(r"\|", "|") \
.replace(r"\[", "[") \
.replace(r"\]", "]")
|
def max(a,b):
"""Return the maximum of two values"""
if (a>b):
return a
else:
return b
|
def ToCacheKey(path):
"""Convert a list of items to a string suitable as a cache key.
Args:
path: A list; elements can be strings, objects with a __name__, or anything
that can be converted to a string with str().
Returns:
A string serialization of the key. The items of the list are joined with
commas; commas and backslashes within items are escaped with backslashes.
For non-string items, the item's __name__ is used if present, or the item
is converted to a string with str().
"""
return ','.join(str(getattr(item, '__name__', item) or '')
.replace('\\', '\\\\').replace(',', '\\,')
for item in path)
|
def quote(token):
"""
:param token: string token
:return: properly-quoted string token
"""
if ' ' in token or '"' in token:
return '"' + token.replace('"', '\\"') + '"'
return token
|
def sentihood_strict_acc(y_true, y_pred):
"""
Calculate "strict Acc" of aspect detection task of Sentihood.
"""
total_cases = int(len(y_true) / 4)
true_cases = 0
for i in range(total_cases):
if y_true[i * 4] != y_pred[i * 4]:
continue
if y_true[i * 4 + 1] != y_pred[i * 4 + 1]:
continue
if y_true[i * 4 + 2] != y_pred[i * 4 + 2]:
continue
if y_true[i * 4 + 3] != y_pred[i * 4 + 3]:
continue
true_cases += 1
aspect_strict_Acc = true_cases / total_cases
return aspect_strict_Acc
|
def seconds2string(number):
"""
Convert time in seconds to 'HH:MM:SS' format
Parameters
-----------
number : float
value in seconds
Returns
-------
time_string : str
time in 'HH:MM:SS' format
Example
-------
>>> from ISPy.io import solarnet
>>> solarnet.seconds2string(63729.3)
'17:42:09.300000'
:Author:
Carlos Diaz Baso (ISP/SU 2019)
"""
hour = number//3600.
minute = (number%3600.)//60.
seconds = (number-(hour*3600.+minute*60))/1.
string_output = '{0:02}:{1:02}:{2:09.6f}'.format(int(hour),int(minute),seconds)
return string_output
|
def html_decode(the_string):
"""Given a string, change HTML escaped characters (>) to regular
characters (>).
Args:
the_string (str): String to decode.
Returns:
str: Decoded string.
"""
html_chars = (
("'", "'"),
('"', """),
(">", ">"),
("<", "<"),
("&", "&"),
)
for char in html_chars:
the_string = the_string.replace(char[1], char[0])
return the_string
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.