content
stringlengths 42
6.51k
|
---|
def clean_blocks(blocks):
"""remove *default* block if supplied
- encompassing and irrelevant
"""
#return [b for b in blocks if b.name != "*default*"]
# turns out we need for unix... typical :)
return blocks
|
def translate_field(label, translator_map, **kwargs):
"""
Translate field with an old label into a list of tuples of form (new_label, new_value).
:param translator_map - maps labels to appropriate tuple lists. Supplied by parsing script.
For each label we get a list of tuples (new_label, mapping_function). Mapping_function invoked
in the arguments yields the new value.
:param kwargs - keyword style arguments passed into mapping functions for
calculating the new values. May be arbitrarily long.
"""
try:
new_label_list = []
label_list = translator_map[label]
for (new_label, map_function) in label_list:
new_label_list.append((new_label, map_function(**kwargs)))
except KeyError:
raise ValueError("Unknown label")
return new_label_list
|
def csv_to_json(csv_filename):
"""
converts string referencing csv file to a json file
:param csv_filename: (string) name of data, as a csv file
:return: string of json filename matching csv file
"""
csv_trimmed = csv_filename[:-3]
json_added = csv_trimmed + 'json'
return json_added
|
def dict_delete(a: dict, b: dict):
"""Elements that are in b but not in a"""
return [k for k in a if k not in b]
|
def vec_leq(vec1, vec2):
""" Check that vec1 is less than vec2 elemtwise """
assert isinstance(vec1, list), "Only work with lists"
assert isinstance(vec2, list), "Only work with lists"
assert len(vec1) == len(vec2), "Vector lengths should be the same"
for x, y in zip(vec1, vec2):
# if a coordinate is greater, returning false
if x > y:
return False
# returning True if all xs are <= than ys
return True
|
def parse_csvs(s):
"""
parser for comma separated string fields, returning frozenset
:s: the input string to parse, which should be of the format
string 1, string 2, string 3
:returns: frozenset('string 1', ...)
"""
return frozenset(map(lambda ss: ss.strip(), s.split(',')))
|
def get_path_to_executable_package_location(platform, executable_name, base_destination_node):
"""
Gets the path to the executable location in a package based on the platform.
:param platform: The platform to get the executable location for
:param executable_name: Name of the executable that is being packaged
:param base_destination_node: Location where the platform speicific package is going to be placed
:return: The path to where the executable should be packaged. May be the same as base_destination_node
:rtype: Node
"""
if 'darwin' in platform:
return base_destination_node.make_node(executable_name + ".app/Contents/MacOS/")
elif 'ios' in platform:
return base_destination_node.make_node(executable_name + ".app/Contents/")
else:
return base_destination_node
|
def _mangle(cls, name):
"""
Given a class and a name, apply python name mangling to it
:param cls: Class to mangle with
:param name: Name to mangle
:return: Mangled name
"""
return f"_{cls.__name__}__{name}"
|
def is_number(s):
""" is_number(s)
Try what you passed if is a number value.
Parameters
----------
s : Object
Value you want to try if is a number.
Returns
-------
Boolean
Return if is a number.
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
|
def clean(value) -> str:
"""Strips and converts bytes to str
Args:
value ([type]): [description]
Returns:
[type]: [description]
"""
if isinstance(value, bytes):
value = value.decode()
if isinstance(value, str):
value = value.strip()
return value
|
def unlinearize_term(index, n_orbitals):
"""Function to return integer index of term indices.
Args:
index(int): The index of the term.
n_orbitals(int): The number of orbitals in the simulation.
Returns:
term(tuple): The term indices of a one- or two-body FermionOperator.
"""
# Handle identity term.
if not index:
return (())
elif (0 < index < 1 + n_orbitals ** 2):
# Handle one-body terms.
shift = 1
new_index = index - shift
q = new_index // n_orbitals
p = new_index - q * n_orbitals
assert index == shift + p + q * n_orbitals
return ((p, 1), (q, 0))
else:
# Handle two-body terms.
shift = 1 + n_orbitals ** 2
new_index = index - shift
s = new_index // n_orbitals ** 3
r = (new_index - s * n_orbitals ** 3) // n_orbitals ** 2
q = (new_index - s * n_orbitals ** 3 -
r * n_orbitals ** 2) // n_orbitals
p = (new_index - q * n_orbitals -
r * n_orbitals ** 2 - s * n_orbitals ** 3)
assert index == (shift + p + q * n_orbitals +
r * n_orbitals ** 2 + s * n_orbitals ** 3)
return ((p, 1), (q, 1), (r, 0), (s, 0))
|
def diagonal(mat, diag_index):
"""Returns ith diagonal of matrix, where i is the diag_index.
Returns the ith diagonal (A_0i, A_1(i+1), ..., A_N(i-1)) of a matrix A,
where i is the diag_index.
Args:
mat (2-D list): Matrix.
diag_index (int): Index of diagonal to return.
Returns:
Diagonal of a matrix.
"""
return [mat[j % len(mat)][(diag_index + j) % len(mat)] for j in range(len(mat))]
|
def determine_current_epsilon(time_step,
fifty_percent_chance=100,
start_epsilon=1.0,
min_epsilon=0.1):
"""Determines the current epsilon value.
:param time_step: The current time step from the training procedure.
:param fifty_percent_chance: The time step at which epsilon shall be 0.5.
:param start_epsilon: The initial value for epsilon.
:param min_epsilon: The minimal value for epsilon.
:return: A probability for choosing a random action. (epsilon)
"""
return max(
min_epsilon,
start_epsilon / (1 + (time_step / fifty_percent_chance))
)
|
def _increment_year_month(year, month):
"""Add one month to the received year/month."""
month += 1
if month == 13:
year += 1
month = 1
return year, month
|
def compute_exact_score(predictions, target_lists):
"""Computes the Exact score (accuracy) of the predictions.
Exact score is defined as the percentage of predictions that match at least
one of the targets.
Args:
predictions: List of predictions.
target_lists: List of targets (1 or more per prediction).
Returns:
Exact score between [0, 1].
"""
num_matches = sum(any(pred == target for target in targets) for pred, targets in zip(predictions, target_lists))
return num_matches / max(len(predictions), 0.1)
|
def flaskify_endpoint(identifier):
"""
Converts the provided identifier in a valid flask endpoint name
:type identifier: str
:rtype: str
"""
return identifier.replace('.', '_')
|
def get_item(dictionary, key):
"""
Returns the object for that key from a dictionary.
:param dictionary: A dictionary object
:param key: Key to search for
:return: Object that corresponds to the key in the dictionary
"""
return dictionary.get(key, None)
|
def get_parse_script_date( job ):
"""
The last time the job log file was parsed for the start/stop dates.
"""
if hasattr( job, 'parse_script_date' ):
return job.parse_script_date
return 0
|
def title_case(sentence):
"""
Convert a string to title case.
Title case means that the first character of every word is capitalized
and all the rest are lowercase.
Parameters
----------
sentence: string
String to be converted to title case
Return
------
titled_sentence: string
Sentence in a title case
Examples
--------
>>> title_case('THiS iS a sTrInG tO be COnverTeD.')
'This Is A String To Be Converted.'
"""
if not isinstance(sentence, str):
raise TypeError("Input sentence must be type str")
if len(sentence) == 0:
raise ValueError("Input sentence cannot be empty")
return sentence.title()
|
def find_intermediate_color(lowcolor, highcolor, intermed):
"""
Returns the color at a given distance between two colors
This function takes two color tuples, where each element is between 0
and 1, along with a value 0 < intermed < 1 and returns a color that is
intermed-percent from lowcolor to highcolor
"""
diff_0 = float(highcolor[0] - lowcolor[0])
diff_1 = float(highcolor[1] - lowcolor[1])
diff_2 = float(highcolor[2] - lowcolor[2])
inter_colors = (lowcolor[0] + intermed * diff_0,
lowcolor[1] + intermed * diff_1,
lowcolor[2] + intermed * diff_2)
return inter_colors
|
def check_rent_history(rent_list, username):
"""
return farm ids that the given username has rented before
"""
farm_rent_before = []
for rent in rent_list:
if rent.get('username') == username:
farm_rent_before.append(str(rent.get('farm_id')))
return farm_rent_before
|
def variant_to_5p(hairpin, pos, variant):
"""
From a sequence and a start position get the nts
+/- indicated by iso_5p. Pos option is 0-base-index
Args:
*hairpin(str)*: long sequence:
>>> AAATTTT
*position(int)*: >>> 3
*variant(int)*: number of nts involved in the variant:
>>> -1
Returns:
*(str)*: nucleotide involved in the variant:
>>> T
"""
pos = pos[0]
iso_t5 = [v for v in variant.split(",") if v.startswith("iso_5p")]
if iso_t5:
t5 = int(iso_t5[0].split(":")[-1][-1])
direction_t5 = int(iso_t5[0].split(":")[-1])
if direction_t5 > 0:
return hairpin[pos - t5:pos]
elif direction_t5 < 0:
return hairpin[pos:pos + t5].lower()
return "0"
|
def get_iou(box1, box2):
"""
Computer Intersection Over Union
"""
xA = max(box1[0], box2[0])
yA = max(box1[1], box2[1])
xB = min(box1[2], box2[2])
yB = min(box1[3], box2[3])
inter_area = max(0, xB - xA + 1) * max(0, yB - yA + 1)
box1_area = (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1)
box2_area = (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1)
union_area = (box1_area + box2_area) - inter_area
# compute the IoU
iou = inter_area/float(union_area)
return iou
|
def error(estimated, fitted):
"""
Calculates mean percentage error for fitted values to estimated values.
:param estimated: estimated values
:param fitted: fitted values
:return: percent error
"""
return sum([abs(e / f - 1) for e, f in zip(estimated, fitted)]) / len(estimated)
|
def is_isogram(string: str) -> bool:
"""Return True if a given word or phrase is an isogram."""
letters = [letter for letter in string.casefold() if letter.isalpha()]
return len(letters) == len(set(letters))
|
def is_positive_int(value: str) -> bool:
"""
refs:
- https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python
- isdigit vs isnumeric: https://stackoverflow.com/questions/44891070/whats-the-difference-between-str-isdigit-isnumeric-and-isdecimal-in-python
"""
# return value.isdigit()
return value.isalnum()
return value.isnumeric()
|
def _all_dsym_infoplists(frameworks_groups):
"""Returns a list of Files of all imported dSYM Info.plists."""
return [
file
for files in frameworks_groups.values()
for file in files.to_list()
if file.basename.lower() == "info.plist"
]
|
def bytes_to_big_int(data: bytearray) -> int:
"""Convert bytes to big int."""
return int.from_bytes(data, "big")
|
def fieldargs(field, width):
"""Ensure that the arguments of a function cannot go out of bounds."""
w = width or 1
assert field >= 0, 'Field cannot be negative.'
assert w > 0, 'Width must be positive.'
assert field + w <= 32, 'Bits accessed excede 32.'
return field, w
|
def version_to_sip_tag(version):
""" Convert a version number to a SIP tag. version is the version number.
"""
# Anything after Qt v5 is assumed to be Qt v6.0.
if version > 0x060000:
version = 0x060000
major = (version >> 16) & 0xff
minor = (version >> 8) & 0xff
patch = version & 0xff
return 'Qt_%d_%d_%d' % (major, minor, patch)
|
def get_value(matrix: list, cell: tuple) -> str:
""" Gets the value at the x,y coordinates in the matrix"""
row, col = cell
return str(matrix[row][col])
|
def main(textlines, messagefunc, config):
"""
KlipChop func to to convert lines into a CSV list
"""
result = list()
count = 0
for line in textlines():
if line not in result:
result.append(line)
count += 1
if config['sort']:
result = sorted(result)
result = config['separator'].join(result)
messagefunc(f'{count} unique lines converted into long CSV list.')
return result
|
def _find_split_vs(out_vs, parallel):
"""Find variables created by splitting samples.
"""
# split parallel job
if parallel in ["single-parallel", "batch-parallel"]:
return [v["id"] for v in out_vs]
else:
return []
|
def parseopts(opts):
"""
parses the command-line flags and options passed to the script
"""
params = {}
for opt, arg in opts:
if opt in ["-K"]:
params['K'] = int(arg)
elif opt in ["--input"]:
params['inputfile'] = arg
elif opt in ["--output"]:
params['outputfile'] = arg
elif opt in ["--popfile"]:
params['popfile'] = arg
elif opt in ["--title"]:
params['title'] = arg
return params
|
def get_additional_info_to_write_fc2_supercells(
interface_mode, phonon_supercell_matrix, suffix: str = "fc2"
):
"""Return additional information to write fc2-supercells for calculators."""
additional_info = {}
if interface_mode == "qe":
additional_info["pre_filename"] = "supercell_%s" % suffix
elif interface_mode == "crystal":
additional_info["template_file"] = "TEMPLATE"
additional_info["pre_filename"] = "supercell_%s" % suffix
additional_info["supercell_matrix"] = phonon_supercell_matrix
elif interface_mode == "abinit":
additional_info["pre_filename"] = "supercell_%s" % suffix
elif interface_mode == "turbomole":
additional_info["pre_filename"] = "supercell_%s" % suffix
else:
additional_info["pre_filename"] = "POSCAR_%s" % suffix.upper()
return additional_info
|
def replace_spaces(lst):
"""
Replace all spaces with underscores for strings in the list.
Requires that the list contains strings for each element.
lst: list of strings
"""
return [s.replace(" ", "_") for s in lst]
|
def max_dict(dicts):
"""Merge dicts whose values are int.
if key is present in multiple dict, choose the max.
Args:
dicts (list): list of dicts to merge
Retrun:
(dict) merged dict
"""
ret = {}
for cur_dict in dicts:
for key, value in cur_dict.items():
ret[key] = max(d.get(key, 0) for d in dicts)
return ret
|
def calc_vol(t, env):
"""Calculate volume at time t given envelope env
envelope is a list of [time, volume] points
time is measured in samples
envelope should be sorted by time
"""
#Find location of last envelope point before t
if len(env) == 0: return 1.0
if len(env) == 1:
return env[0][1]
n = 0
while n < len(env) and env[n][0] < t:
n += 1
if n == 0:
# in this case first point is already too far
# envelope hasn't started, just use first volume
return env[0][1]
if n == len(env):
# in this case, all points are before, envelope is over
# use last volume
return env[-1][1]
# now n holds point that is later than t
# n - 1 is point before t
f = float(t - env[n - 1][0]) / (env[n][0] - env[n - 1][0])
# f is 0.0--1.0, is how far along line t has moved from
# point n - 1 to point n
# volume is linear interpolation between points
return env[n - 1][1] * (1.0 - f) + env[n][1] * f
|
def length(database):
"""Computes the total number of tuning entries"""
num_tuning_entries = 0
for section in database["sections"]:
num_tuning_entries += len(section["results"])
return num_tuning_entries
|
def is_number(s: str):
"""
Args:
s: (str) string to test if it can be converted into float
Returns:
True or False
"""
try:
# Try the conversion, if it is not possible, error will be raised
float(s)
return True
except ValueError:
return False
|
def comma_separated_strings(value):
"""Parse comma-separated string into list."""
return [str(k).strip() for k in value.split(",")]
|
def empty_cells(keyword):
"""``empty-cells`` property validation."""
return keyword in ('show', 'hide')
|
def get_cardholder_from_notes(po_line_record):
"""Get cardholder note that begins with a CC- prefix from a PO line record."""
cardholder = "No cardholder note found"
for note in [
n
for n in po_line_record.get("note", [{}])
if n.get("note_text", "").startswith("CC-")
]:
cardholder = note["note_text"][3:]
return cardholder
|
def _to_str(value):
""" Convert value to string if needed.
"""
return '' if value is None else str(value)
|
def find_pivot(array, high, low):
"""
Find the index of the pivot element
"""
if high < low:
return -1
if high == low:
return low
mid = (high + low)/2
if mid < high and array[mid] > array[mid + 1]:
return mid
if mid > low and array[mid] < array[mid - 1]:
return mid - 1
if array[low] >= array[mid]:
return find_pivot(array, low, mid - 1)
else:
return find_pivot(array, mid + 1, high)
|
def measure_url(n: int) -> str:
"""Construct the url suitable for scraping a given measure."""
return f'https://www.ats.aq/devAS/Meetings/Measure/{n}'
|
def beautifulDays(i, j, k):
"""Problem solution."""
def reverse(n):
return int(str(n)[::-1])
c = 0
for day in range(i, j + 1):
if (day - reverse(day)) % k == 0:
c += 1
return c
|
def isgzipped(f):
"""Check if file f is gzipped."""
with open(f, 'rb') as rpkm_file:
magic = rpkm_file.read(2)
return magic == '\037\213'
|
def safe_decode(txt):
"""Return decoded text if it's not already bytes."""
try:
return txt.decode()
except AttributeError:
return txt
|
def degrees_to_miles_ish(dist:float):
""" Convert degrees lat/lon to miles, approximately """
deg_lat = 69.1 # dist_lat_lon(42, 74, 43, 74)
deg_lon = 51.3 # dist_lat_lon(42, 73, 42, 74)
return dist * 60.2
|
def get_max(dic):
"""
Given a dictionary of keys with related values, return the entry with the highest value
Example: A scoreboard of players and their scores.
"""
if len(dic.items()) == 0:
return None
max_item, max_value = list(dic.items())[0]
for elem in dic:
if dic[elem] > max_value:
max_value = dic[elem]
max_item = elem
return { max_item: max_value }
|
def determine_var(w, q2):
"""
:param w: omega as estimated
:param q2: allele freq of SNP in p2
:return: sigma2, estimate of variation
"""
return w * (q2 * (1 - q2))
|
def _get_thumbnail_asset_key(asset, course_key):
"""returns thumbnail asset key"""
# note, due to the schema change we may not have a 'thumbnail_location' in the result set
thumbnail_location = asset.get('thumbnail_location', None)
thumbnail_asset_key = None
if thumbnail_location:
thumbnail_path = thumbnail_location[4]
thumbnail_asset_key = course_key.make_asset_key('thumbnail', thumbnail_path)
return thumbnail_asset_key
|
def _is_solution_mount(mount_tuple):
"""Return whether a mount is for a Solution archive.
Any ISO9660 mounted in `/srv/scality` that isn't for MetalK8s is considered
to be a Solution archive.
"""
mountpoint, mount_info = mount_tuple
if not mountpoint.startswith('/srv/scality/'):
return False
if mountpoint.startswith('/srv/scality/metalk8s-'):
return False
if mount_info['fstype'] != 'iso9660':
return False
return True
|
def group_by_types(units):
"""Return a dictionary of lists of units grouped by type."""
groups = {i.__class__: [] for i in units}
for i in units: groups[i.__class__].append(i)
return groups
|
def hello(friend_name):
"""
say hello to the world
:param friend_name: a String. Ignore for now.
:return: a String containing a message
"""
return f'Hello, {friend_name}!'
|
def _get_line_col(code: str, idx: int):
""" Get line and column (1-based) from character index """
line = len(code[:idx + 1].splitlines())
col = (idx - (code[:idx + 1].rfind('\n') + 1))
return line, col
|
def is_in_references(references, doi):
""" Search for a doi in a list of references.
Args:
references (Iterable): References to loop through.
doi (str): DOI of work to search for.
Returns:
bool: True if doi is in any of the references, else False.
"""
url_doi = doi.replace('/', '%2F')
for reference in references:
if url_doi in reference or doi in reference:
return True
return False
|
def build_current_state(sway_outputs):
"""Constructs an internal representation of the screens info."""
state = dict()
for out_spec in sway_outputs:
state[out_spec['name']] = {
'x': out_spec['rect']['x'],
'y': out_spec['rect']['y'],
'w': out_spec['modes'][-1]['width'],
'h': out_spec['modes'][-1]['height'],
'active': out_spec['active'],
'transform': out_spec.get('transform', 'normal'),
}
return state
|
def max_sub_array(nums):
""" Returns the max subarray of the given list of numbers.
Returns 0 if nums is None or an empty list.
Time Complexity: O(n)
Space Complexity: O(1)
"""
if nums == None:
return 0
if len(nums) == 0:
return 0
dp = [0 for i in range(len(nums))]
dp[0] = nums[0]
for i in range(1,len(nums)):
dp[i] = max(dp[i-1]+nums[i],nums[i])
#print(dp)
return max(dp)
|
def parse(string: str, delimiter: str = ' ', nest_open: str = '(', nest_close: str = ')') -> list:
"""
This function is for parsing a nested string structure into a nested list
>>>parse("hello world")
["hello", "world"]
>>>parse("a b (c d (e f)) g")
["a", "b", ["c", "d", ["e", "f"]], "g"]
"""
nest = [] # For the resultant list
openers = [] # Temp list for indices of opening characters
closers = [] # Temp list for indices of closing characters
nest_pairs = [] # Holds tuples of opening and closing index pairs
# Find the indexes of matching parentheses
for index, character in enumerate(string):
if character == nest_open:
openers.append(index)
elif character == nest_close:
closers.append(index)
if openers and closers and len(openers) >= len(closers):
if openers[-1] > closers[0]:
raise ValueError(f"Cannot parse {string}, invalid parentheses")
nest_pairs.append((openers.pop(-1), closers.pop()))
# If we have pairs, look at each subsection and recursively apply this function if applicable
if nest_pairs:
for pair_index, (open_index, close_index) in enumerate(nest_pairs):
# Check if this pair is a nested pair
nested = False
for sub_pair_index, (sub_open_index, sub_close_index) in enumerate(nest_pairs):
if pair_index == sub_pair_index:
continue
if open_index > sub_open_index and close_index < sub_close_index:
# This pair is nested, so we ignore it
nested = True
# If it isn't nested, recurse, else, a lower level will deal with this pair
if not nested:
parsed_sub = parse(
string=string[open_index + 1:close_index],
delimiter=delimiter,
nest_open=nest_open,
nest_close=nest_close
)
nest.append(parsed_sub)
# Strip any characters from the string which are left at this level
string = ''.join([
char
for index, char in enumerate(string)
if not [
index
for start, end in nest_pairs
if index >= start and index <= end
]
])
nest.extend([word for word in string.split(delimiter) if word])
return nest
|
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
return next(filter(pred, iterable), default)
|
def join(*args):
"""Create pipe separated string."""
return "|".join(str(a) for a in args)
|
def get_value(input_data, field_name, required=False):
"""
Return an unencoded value from an MMTF data structure.
:param input_data:
:param field_name:
:param required:
:return:
"""
if field_name in input_data:
return input_data[field_name]
elif required:
raise Exception('ERROR: Invalid MMTF File, field: {} is missing!'.format(field_name))
else:
return None
|
def is_leap_year(year: int) -> bool:
"""Check if a given year `year` is a leap year."""
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
|
def shorten_file_name(name: str):
"""Description."""
max_length = 60
if len(name) > max_length:
return name[0:max_length] + "..."
return name
|
def dna_to_rna(dna):
"""
Transcribes dna to rna.
Args:
dna (str}: DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T').
Returns:
str: rna where 'T' is replaced by 'U'.
"""
rna = dna.replace("T", "U")
return rna
|
def stata_operator(leadlag, level):
"""Return the prefix applied to variable names in Stata e(b), e(V) matrices
"""
leadlag = int(leadlag)
if leadlag == 0:
ll=''
elif leadlag == 1:
ll='L'
elif leadlag == -1:
ll='F'
elif leadlag > 1:
ll='L'+str(leadlag)
else:
ll='F'+str(abs(leadlag))
if int(level) < 0:
raise ValueError('Negative factor levels are not allowed.')
else:
lv = str(level)
op = lv+ll
return op+'.' if op != '' else op
|
def _label_check(label_string: str, search_label: str):
""" Mask labels with Booleans that appear in row """
for label in label_string.split(' '):
if search_label == label:
return True
return False
|
def parametrize(params):
"""Return list of params as params.
>>> parametrize(['a'])
'a'
>>> parametrize(['a', 'b'])
'a[b]'
>>> parametrize(['a', 'b', 'c'])
'a[b][c]'
"""
returned = str(params[0])
returned += "".join("[" + str(p) + "]" for p in params[1:])
return returned
|
def sufpre(p, w):
""" Return the maximal suffix of p which is also
a prefix of w """
for i in range(0, len(p)):
if w.startswith(p[i:]):
return p[i:]
return ''
|
def int_equals(a, b):
"""Small helper function, takes two objects and returns True if they are equal when cast to int.
This is mainly intended to facilitate checking two strings that may or may not be ints.
Most importantly, it will return False if either cannot be cast to int."""
try:
return int(a) == int(b)
except ValueError:
return False
|
def fill_gaps(indicies, elementss, size, gap):
"""Fill gaps of arrays with size with indicies and elems."""
full = [None] * size
for ind, elem in zip(indicies, elementss):
full[ind] = elem
for ind in range(size):
if full[ind] is None:
full[ind] = gap()
return full
|
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if (
(cp >= 0x4E00 and cp <= 0x9FFF)
or (cp >= 0x3400 and cp <= 0x4DBF) #
or (cp >= 0x20000 and cp <= 0x2A6DF) #
or (cp >= 0x2A700 and cp <= 0x2B73F) #
or (cp >= 0x2B740 and cp <= 0x2B81F) #
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
or (cp >= 0xF900 and cp <= 0xFAFF)
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
): #
return True
return False
|
def fold_dict(data, nb_level=10**5):
"""Fold dict `data`.
Turns dictionary keys, e.g. 'level1/level2/level3', into sub-dicts, e.g.
data['level1']['level2']['level3'].
Parameters
----------
data: dict
dict to be folded.
nb_level: int
Maximum recursion depth.
Returns
-------
dict
Folded dict.
"""
if nb_level <= 0:
return data
groups = dict()
levels = set()
for key, value in data.items():
idx = key.find('/')
if idx > 0:
level = key[:idx]
group_dict = groups.setdefault(level, dict())
group_dict[key[(idx + 1):]] = value
levels.add(level)
else:
groups[key] = value
for level in levels:
groups[level] = fold_dict(groups[level], nb_level - 1)
return groups
|
def remove_prefix(state_dict, prefix):
""" Old style model is stored with all names of parameters sharing common prefix 'module.' """
f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x
return {f(key): value for key, value in state_dict.items()}
|
def fix_indentation(text):
"""Replace tabs by spaces"""
return text.replace('\t', ' ' * 4)
|
def template2solution(code):
""" Convert `code` marked up for exercise + solution to solution format.
Parameters
----------
code : str
String containing one or more lines of code.
Returns
-------
solution_code : str
Code as it will appear in the solution version.
"""
lines = [L for L in code.splitlines() if not L.strip().startswith('#<-')]
return '\n'.join(lines) + '\n'
|
def inv(q, p):
"""
calculate q^-1 mod p
"""
for i in range(p):
if q * i % p == 1:
return i
|
def lerp(x, y):
"""
Linear interpolation between integers `x` and `y` with a factor of `.5`.
"""
# NOTE: integer division with floor
return x + (y - x) // 2
|
def filter_dict(d, keys):
"""
Remove keys from dict "d". "keys" is a list
of string, dotfield notation can be used to
express nested keys. If key to remove doesn't
exist, silently ignore it
"""
if isinstance(keys, str):
keys = [keys]
for key in keys:
if "." in key:
innerkey = ".".join(key.split(".")[1:])
rkey = key.split(".")[0]
if rkey in d:
d[rkey] = filter_dict(d[rkey], innerkey)
else:
continue
else:
d.pop(key, None)
return d
|
def secant(f, a, b, n):
"""Approximate solution of f(x)=0 on interval [a,b] by the secant method.
Parameters
----------
f : function
The function for which we are trying to approximate a solution f(x)=0.
a,b : numbers
The interval in which to search for a solution. The function returns
None if f(a)*f(b) >= 0 since a solution is not guaranteed.
n : (positive) integer
The number of iterations to implement.
Returns
-------
m_N : number
The x intercept of the secant line on the the Nth interval
m_n = a_n - f(a_n)*(b_n - a_n)/(f(b_n) - f(a_n))
The initial interval [a_0,b_0] is given by [a,b]. If f(m_n) == 0
for some intercept m_n then the function returns this solution.
If all signs of values f(a_n), f(b_n) and f(m_n) are the same at any
iterations, the secant method fails and return None.
Examples
--------
>>> f = lambda x: x**2 - x - 1
>>> secant(f,1,2,5)
1.6180257510729614
"""
if f(a) * f(b) >= 0:
print("Secant method fails.")
return None
a_n = a
b_n = b
for n in range(1, n + 1):
m_n = a_n - f(a_n) * (b_n - a_n) / (f(b_n) - f(a_n))
f_m_n = f(m_n)
if f(a_n) * f_m_n < 0:
a_n = a_n
b_n = m_n
elif f(b_n) * f_m_n < 0:
a_n = m_n
b_n = b_n
elif f_m_n == 0:
# print("Found exact solution.")
return m_n
else:
# print("Secant method fails.")
return None
return a_n - f(a_n) * (b_n - a_n) / (f(b_n) - f(a_n))
|
def varint_type_to_length(varint):
""" Return the number of bytes used by a varint type """
if varint == 5:
return (6, "")
elif varint == 6 or varint == 7:
return (8, "")
elif varint == 8:
return (0,0)
elif varint == 9:
return (0,1)
else:
return (varint, "")
|
def whitespace_tokenize(text):
# from UDA [https://github.com/google-research/uda/tree/master/text/bert
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
|
def logg_to_vt_M08(logg):
""" Marino et al. 2008 A&A 490, 625 (from Gratton et al. 1996) """
return 2.22 - 0.322 * logg
|
def make_odd(number):
"""
Return the input number if its odd,
or return input number + 1 if its even or zero.
"""
if number == 0:
number += 1
if number % 2 == 0:
number += -1
return number
|
def get_start_date(participants, host_dict, repo_dates, repo):
""" Finds start date based on participants.
Checks if host participants have start dates associated with them.
Args:
participants: users in the pull request.
host_dict: dictionary with host logins as keys and start dates as
values.
repo_dates: dictionary mapping repositories to start dates.
repo: current repository.
Returns:
Start date or "unknown".
"""
# Special case in which host account has been deleted
if repo not in repo_dates:
for user in participants:
try:
cur_username = user["login"]
except (TypeError, KeyError):
continue
if cur_username in host_dict:
start_date = host_dict[cur_username]
repo_dates[repo] = start_date
return start_date
return "unknown"
return repo_dates[repo]
|
def strip_trailing_fields_json(items):
"""
Strip trailing spaces for field name #456
"""
data = []
for item in items:
od = {}
for field in item:
stripped_field_name = field.strip()
od[stripped_field_name] = item[field]
data.append(od)
return data
|
def remove_spaces(data):
"""
Create a return array and enumerate
through the array and append it to
the return array if the element is
not a space( )
"""
return_array = []
for index, el in enumerate(data):
if el is not " ":
return_array.append(el)
return return_array
|
def is_git(cmd):
"""Test if a git command."""
return cmd.endswith("git-bln")
|
def get_frequency_weighted_iou(n):
"""
Get frequency weighted intersection over union.
Parameters
----------
n : dict
Confusion matrix which has integer keys 0, ..., nb_classes - 1;
an entry n[i][j] is the count how often class i was classified as
class j.
Returns
-------
float
frequency weighted iou (in [0, 1])
Examples
--------
>>> n = {0: {0: 10, 1: 2}, 1: {0: 5, 1: 83}}
>>> get_frequency_weighted_iou(n)
0.8821437908496732
"""
t = []
k = len(n[0])
for i in range(k):
t.append(sum([n[i][j] for j in range(k)]))
a = sum(t)**(-1)
b = sum([(t[i] * n[i][i]) /
(t[i] - n[i][i] + sum([n[j][i] for j in range(k)]))
for i in range(k)])
return a * b
|
def _preprocess_sgm(line, is_sgm):
"""Preprocessing to strip tags in SGM files."""
if not is_sgm:
return line
# In SGM files, remove <srcset ...>, <p>, <doc ...> lines.
if line.startswith("<srcset") or line.startswith("</srcset"):
return ""
if line.startswith("<refset") or line.startswith("</refset"):
return ""
if line.startswith("<doc") or line.startswith("</doc"):
return ""
if line.startswith("<p>") or line.startswith("</p>"):
return ""
# Strip <seg> tags.
line = line.strip()
if line.startswith("<seg") and line.endswith("</seg>"):
i = line.index(">")
return line[i + 1:-6]
|
def hello(name: str) -> str:
"""
Just an greetings example.
Parameters
----------
name : str
Name to greet
Returns
-------
str
Greeting message
Examples
--------
Examples should be written in doctest format, and should illustrate how
to use the function.
>>> hello("Roman")
'Hello Roman!'
Notes
-----
Check that function is only an example
Docstring reference: https://numpydoc.readthedocs.io/en/latest/format.html
"""
return f"Hello {name}!"
|
def cohens_d_multiple(xbar1, xbar2, ms_with):
"""
Get the Cohen's-d value for a multiple comparison test.
Parameters
----------
> `xbar1`: the mean of the one of the samples in the test.
> `xbar2`: the mean of another of the samples in the test.
> `ms_with`: the mean-squared variability of the samples
Returns
-------
The Cohen's-d value for both the samples in the multiple comparison test.
"""
return (xbar1 - xbar2) / (ms_with ** 0.5)
|
def unquote_and_split(arg, c):
"""Split a string at the first unquoted occurrence of a character.
Split the string arg at the first unquoted occurrence of the character c.
Here, in the first part of arg, the backslash is considered the
quoting character indicating that the next character is to be
added literally to the first part, even if it is the split character.
Args:
arg: the string to be split
c: the character at which to split
Returns:
The unquoted string before the separator and the string after the
separator.
"""
head = ''
i = 0
while i < len(arg):
if arg[i] == c:
return (head, arg[i + 1:])
elif arg[i] == '\\':
i += 1
if i == len(arg):
# dangling quotation symbol
return (head, '')
else:
head += arg[i]
else:
head += arg[i]
i += 1
# if we leave the loop, the character c was not found unquoted
return (head, '')
|
def tup_list_maker(tup_list):
"""
Takes a list of tuples with index 0 being the text_id and index 1 being a
list of sentences and broadcasts the text_id to each sentence
"""
final_list = []
for item in tup_list:
index = item[0]
sentences = item[1]
for sentence in sentences:
pair = (index, sentence)
final_list.append(pair)
return final_list
|
def almostequal(first, second, places=7, printit=True):
"""
Test if two values are equal to a given number of places.
This is based on python's unittest so may be covered by Python's
license.
"""
if first == second:
return True
if round(abs(second - first), places) != 0:
if printit:
print(round(abs(second - first), places))
print("notalmost: %s != %s to %i places" % (first, second, places))
return False
else:
return True
|
def filter_list_dicts(list_dicts, key, values):
""" filter out the dicts with values for key"""
return [e for e in list_dicts if e[key] in values]
|
def find_omega(omega_r, omega_theta, omega_phi, em, kay, en, M=1):
"""
Uses Boyer frequencies to find omega_mkn
Parameters:
omega_r (float): radial boyer lindquist frequency
omega_theta (float): theta boyer lindquist frequency
omega_phi (float): phi boyer lindquist frequency
em (int): phi mode
kay (int): theta mode
en (int): radial mode
Keyword Args:
M (float): mass of large body
Returns:
omega (float): frequency of motion
"""
return en * omega_r + em * omega_phi + kay * omega_theta
|
def func_args_realizer(args):
"""
Using an ast.FunctionDef node, create a items list node that
will give us the passed in args by name.
def whee(bob, frank=1):
pass
whee(1, 3) => [('bob', 1), ('frank', 3)]
whee(1) => [('bob', 1), ('frank', 1)]
"""
items = map("('{0}', {0})".format, args)
items_list = "[ {0} ]".format(', '.join(items))
return items_list
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.