content
stringlengths 42
6.51k
|
---|
def merge(nums1, nums2):
"""
:param nums1: Sorted list of numbers.
:param nums2: Sorted list of numbers.
:return: Combined sorted list of numbers.
"""
merged = list()
while len(nums1) != 0 and len(nums2) != 0:
if nums1[0] <= nums2[0]:
merged.append(nums1.pop(0))
else:
merged.append(nums2.pop(0))
while len(nums1) != 0:
merged.append(nums1.pop(0))
while len(nums2) != 0:
merged.append(nums2.pop(0))
return merged
|
def clean_text(raw_text):
""" Clean text by removing extra spaces between words
Args:
raw texts
Returns:
Cleaned text
"""
token_words = raw_text.split()
cleaned_text = ' '.join(token_words)
return cleaned_text
|
def try_number(value):
"""Try converting the value to a number."""
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return value
|
def deep_encode(e, encoding='ascii'):
"""
Encodes all strings using encoding, default ascii.
"""
if isinstance(e, dict):
return dict((i, deep_encode(j, encoding)) for (i, j) in e.items())
elif isinstance(e, list):
return [deep_encode(i, encoding) for i in e]
elif isinstance(e, str):
e = e.encode(encoding)
return e
|
def split_by_value(total, nodes, headdivisor=2.0):
"""Produce, (sum,head),(sum,tail) for nodes to attempt binary partition"""
head_sum, tail_sum = 0, 0
divider = 0
for node in nodes[::-1]:
if head_sum < total/headdivisor:
head_sum += node[0]
divider -= 1
else:
break
return (head_sum, nodes[divider:]), (total-head_sum, nodes[:divider])
|
def infinitve(conjugate, infinitive_map):
"""Get infinitive form of a conjugated verb.
Given a mapping of conjugate to infinitive, this function computes
the infinitive form of a conjugate verb. We provide models available
for downloading, so you do not have to worry about the ``infinitive_map``.
Regretfully we only provide models for Spanish texts.
:param conjugate: Verb to be processed
:type conjugate: string
:param infinitve_map: Lexicon containing maps from conjugate to infinitive.
:type infinitive_map: dict
:return: Infinitive form of the verb, None if not found
:rtype: string
"""
conjugate = conjugate.lower()
for word_list in infinitive_map:
if conjugate in word_list:
infinitive = infinitive_map[word_list]
return infinitive if infinitive else None
return None
|
def egcd(b, n):
"""Calculates GCD iteratively, using Euclid's algorithm."""
x0, x1, y0, y1 = 1, 0, 0, 1
while n != 0:
q, b, n = b // n, n, b % n
x0, x1 = x1, x0 - q * x1
y0, y1 = y1, y0 - q * y1
return b, x0, y0
|
def output(node):
""" outputs a string with the textual representation of the node and it's children"""
if (node == None):
return ""
if node.syntax is None:
o = " (" + "TabooNone"
print("Warning: outputting TabooNone")
else:
o = " (" + node.syntax
if (node.word != None):
o += " " + node.word
return o + output(node.left) + output(node.right) + ")"
|
def remove_extension(file_path):
"""
Removes extension of the given file path
For example, C:/test/rig.py will return rig
:param file_path: str
:return: str
"""
split_path = file_path.split('.')
new_name = file_path
if len(split_path) > 1:
new_name = '.'.join(split_path[:-1])
return new_name
|
def cp_to_str(cp):
"""
Convert a code point (int) to a string.
"""
return "%04X" % cp
|
def sort_hyps(hyps, vocab_size, key_token_ids, complete_hyps):
"""
Return a list of Hypothesis objects, sorted by descending average log probability.
"""
return sorted(
hyps,
key=lambda h: h.score(vocab_size, key_token_ids, complete_hyps),
reverse=True,
)
|
def treeify(dependencies):
"""Treeify a list of dependencies."""
tree = {}
ancestors = []
for dependency in dependencies:
# Dependency is the root of the tree.
if dependency["level"] == 0 and tree == {}:
tree = {
"children": None,
"level": 0,
"dependency": dependency["dependency"],
"version": dependency["version"],
}
ancestors.append(tree)
# Dependency is a daughter of the last ancestor.
elif dependency["level"] == ancestors[-1]["level"] + 1:
if ancestors[-1]["children"] is None:
ancestors[-1]["children"] = []
ancestors[-1]["children"].append({
"children": None,
"level": dependency["level"],
"dependency": dependency["dependency"],
"version": dependency["version"],
})
ancestors.append(ancestors[-1]["children"][-1])
# Dependency is an aunt/sister of the last ancestor.
elif dependency["level"] <= ancestors[-1]["level"]:
while dependency["level"] <= ancestors[-1]["level"]:
ancestors.pop()
if ancestors[-1]["children"] is None:
ancestors[-1]["children"] = []
ancestors[-1]["children"].append({
"children": None,
"level": dependency["level"],
"dependency": dependency["dependency"],
"version": dependency["version"],
})
ancestors.append(ancestors[-1]["children"][-1])
return tree
|
def segments_overlap(a, b):
"""Returns True if GPS segment ``a`` overlaps GPS segment ``b``
"""
return (a[1] > b[0]) and (a[0] < b[1])
|
def _parse_boolean(xml_boolean):
"""Converts strings "true" and "false" from XML files to Python bool"""
if xml_boolean is not None:
assert xml_boolean in ["true", "false"], \
"The boolean string must be \"true\" or \"false\""
return {"true": True, "false": False}[xml_boolean]
|
def remove_exclusion(failed_tasks: list, playbook_exclusion: list):
"""
Checks if one of the failed tasks is from an excluded playbook and if so removes it from the list.
Args:
failed_tasks: A list of failed tasks.
playbook_exclusion: A list of names of playbooks to exclude.
Returns:
The modified list.
"""
for playbook in playbook_exclusion:
for task in failed_tasks:
if playbook in task['Playbook Name']:
failed_tasks.remove(task)
return failed_tasks
|
def partition_subtokens(subtokens):
"""Return list of (start, end , [list of subtokens]) for each token."""
words = []
last = 0
for i, token in enumerate(subtokens):
if token[-1] == '_':
words.append((last, i + 1, subtokens[last:i + 1]))
last = i + 1
return words
|
def margin2(contingency_table, i):
"""Calculate the margin distribution of classifier 2."""
return sum([contingency_table[i][j]
for j in range(len(contingency_table))])
|
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
step_unit = 1000.0 # 1024?
results=[]
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
results.append("%3.2f %s" % (num, x))
num /= step_unit
return results
|
def check_type(data, dtype):
"""
ckeck data type
:param data: data
:param dtype: data type
:return: error
"""
error = ''
for item in data:
if not isinstance(item, type(dtype)):
error = '{0} data type is error!'.format(item)
break
return error
|
def changes_record(bucket_id, collection_id):
"""Utility function to gin up something that is kind of like a kinto-changes record."""
return {
'id': 'abcd',
'last_modified': 123,
'bucket': bucket_id,
'collection': collection_id,
'host': 'http://localhost',
}
|
def getDistance (origin, point):
"""
Returns the distance between two points.
"""
dist = ((origin[0]-point[0])**2 + (origin[1]-point[1])**2)**0.5
return dist
|
def repeat_last_operation(calc):
"""
Returns the result of the last operation executed in the history.
"""
if calc['history']:
return calc['history'][-1][3]
|
def compute_checksum(line):
"""Compute the TLE checksum for the given line."""
return sum((int(c) if c.isdigit() else c == '-') for c in line[0:68]) % 10
|
def mean(feature_vector):
"""
:param feature_vector: List of integer/float/double..
:return: Mean of the feature vector.
"""
return sum(f for f in feature_vector)/len(feature_vector)
|
def get_attribute_terms(product):
"""
Function to iterate through all variants of a variable product and compile a list of attribute terms from them.
:param product: Variable product and variants information
:return: list of term names
"""
attribute_terms = list()
for variation in product['variants']:
if variation['option_1_value'] not in attribute_terms:
attribute_terms.append(variation['option_1_value'])
return attribute_terms
|
def get_sqlserver_hashed_sample_clause(id_clause, sample_pct):
"""Get SQL Server-valid synthax for hashed-sampling an id clause.on
Takes as imput a given sample_pct in (0, 1).
Parameters
----------
id_clause :
sample_pct :
Returns
-------
"""
assert 0 < sample_pct < 1, f'{sample_pct} should be a float in (0,1)'
int_pct = int(sample_pct * 100)
rv = f"""
AND ABS(CAST(HASHBYTES('SHA1',
{id_clause}) AS BIGINT)) % 100 <= {int_pct}"""
return rv
|
def elide(text: str, length: int) -> str:
"""Elide text so it uses a maximum of length chars."""
if length < 1:
raise ValueError("length must be >= 1!")
if len(text) <= length:
return text
else:
return text[:length - 1] + '\u2026'
|
def get_prefixes(snodes):
"""
snodes: List. List of suffix nodes for a header
"""
all_prefixes = []
for node in snodes:
prefix = []
count = node.node_count
while node.parent is not None:
prefix.append(tuple([node.item, count]))
node = node.parent
all_prefixes.append(prefix)
return all_prefixes
|
def triggers_to_event_id(triggers):
"""Convert list or dict of triggers to MNE-style event_id"""
# Convert list to dict with triggers as condition names
if isinstance(triggers, list):
triggers = {str(trigger): trigger for trigger in triggers}
else:
assert isinstance(triggers, dict), \
'`triggers` must be either list or dict'
# Make sure that trigger values are integers (R would pass them as floats)
triggers = {key: int(value) for key, value in triggers.items()}
event_id = triggers
return event_id
|
def are_eq(A,B,tolerance=1e-4):
"""Check two arrays for tolerance [1,2,3]==[1,2,3]; but [1,3,2]!=[1,2,3]
Args:
A, B (lists): 1-D list of values for approximate equality comparison
tolerance: numerical precision for equality condition
Returns:
boolean
"""
are_eq = True
if len(A) != len(B):
are_eq = False
else:
i = 0
while i < len(A):
if abs(A[i] - B[i]) > tolerance:
are_eq = False
i = i + 1
return are_eq
|
def highlight_positives(test_result: bool) -> str:
"""
Highlight positive values in red.
Parameters
----------
test_result : bool
Observed test result
Returns
-------
str
Cell background color definition
"""
color = "red" if test_result else "white"
return f"background-color: {color}"
|
def hamming_distance(lhs, rhs):
"""Returns the Hamming Distance of Two Equal Strings
Usage
>>> nt.hamming_distance('Pear','Pearls')
"""
return len([(x, y) for x, y in zip(lhs, rhs) if x != y])
|
def intersection_of_arrays(l1,l2):
"""
O(n) time
O(n) space
"""
set1 = set()
for elem in l1:
set1.add(elem)
set2 = set()
for elem in l2:
set1.add(elem)
res = []
for elem in set1:
if elem in set2:
res.append(elem)
return res
|
def flatten2Class(*args):
"""
The flatten2Class method answers the class string, made from space separated class names. If
cssClass is a tuple or list, then merge the content. Check recursively in
case the names are nested. If the classes is empty or None or contain an empty
element, then this is ignored.
"""
result = []
for cssClass in args:
if isinstance(cssClass, str):
result.append(cssClass)
elif isinstance(cssClass, (tuple, list)):
s = []
for part in cssClass:
flattened = flatten2Class(part)
s.append(flattened)
result.append(' '.join(s))
elif cssClass is None:
continue
else:
raise TypeError('[Transformer.flatten2Class] Class part must be None, string, tuple or list, not "%s"' % cssClass)
return ' '.join(result)
|
def words_to_sentence(words: list) -> str:
""" This function create a string from a list of strings, separated by space. """
return ' '.join(words)
|
def double_quotes(unquoted):
"""
Display String like redis-cli.
escape inner double quotes.
add outer double quotes.
:param unquoted: list, or str
"""
if isinstance(unquoted, str):
# escape double quote
escaped = unquoted.replace('"', '\\"')
return f'"{escaped}"' # add outer double quotes
elif isinstance(unquoted, list):
return [double_quotes(item) for item in unquoted]
|
def authors_to_string(names):
"""
creates a single string with all authors with only first letter of the firstname followed by a dot and surname.
Author names are sperated by comma except for the last author which is seperated via 'and'.
"""
string_authors = ''
d = ', '
for idx, name in enumerate(names):
first, von, last, jr = name
if first:
first = first[0] + '.'
if idx == len(names)-2:
d = ' and '
if idx == len(names)-1:
d = ''
string_authors += ' '.join(
part for part in [first, von, last, jr] if part) + d
return string_authors
|
def osm_length_sql(grid, osm, cat):
"""
Returns a sql fragment that sums the length of OSM line features per grid
cell by category
Args:
grid (string): a PostGIS table name containing the grid
osm (string): a PostGIS table name containing the OSM line features
cat (string): a PostGIS table containing the OSM line features'
categories
Returns:
sql (string): an sql fragment
"""
sql = ("SELECT "
"SUM(CASE WHEN cat.cat = 1 "
"THEN ST_Length(ST_Intersection(grid.cell, osm.way)) "
"ELSE 0 END) AS lineCult, "
"SUM(CASE WHEN cat.cat = 2 "
"THEN ST_Length(ST_Intersection(grid.cell, osm.way)) "
"ELSE 0 END) AS lineIndus, "
"SUM(CASE WHEN cat.cat = 3 "
"THEN ST_Length(ST_Intersection(grid.cell, osm.way)) "
"ELSE 0 END) AS lineNat, "
"SUM(CASE WHEN cat.cat = 4 "
"THEN ST_Length(ST_Intersection(grid.cell, osm.way)) "
"ELSE 0 END) AS lineStruct, "
"SUM(CASE WHEN cat.cat = 0 "
"THEN ST_Length(ST_Intersection(grid.cell, osm.way)) "
"ELSE 0 END) AS lineMisc, grid.id AS id "
"FROM %s AS grid, "
"%s AS osm, "
"%s AS cat "
"WHERE cat.osm_id = osm.osm_id AND ST_Intersects(grid.cell, osm.way)"
" GROUP BY id")
return sql % (grid, osm, cat)
|
def env_value_student(input_version):
"""Return the Student version Environment Variable name based on an input version string
Parameters
----------
input_version : str
Returns
-------
str
Examples
--------
>>> env_value_student("2021.1")
"ANSYSEMSV_ROOT211"
"""
version = int(input_version[2:4])
release = int(input_version[5])
if version < 20:
if release < 3:
version -= 1
else:
release -= 2
v_key = "ANSYSEMSV_ROOT{0}{1}".format(version, release)
return v_key
|
def make_dict(inp):
"""
Transform the instance ``inp`` into a python dictionary.
If inp is already a dictionary, it perfroms a copy.
Args:
inp (dict): a instance of a Class which inherits from dict
Returns:
dict: the copy of the class, converted as a dictionary
"""
import copy
local_tmp = copy.deepcopy(inp)
local_input = {}
local_input.update(local_tmp)
return local_input
|
def ENDS_WITH(rule_value, tran_value):
"""Return True if tran_value ends with rule_value
Parameters:
rule_value: Value from the rule file to check for.
tran_value: Value from transaction.
Return:
bool: Will return true if `tran_value` ends with `rule_value`.
"""
rule_value = rule_value.lower()
tran_value = tran_value.lower()
tran_value = tran_value.strip()
return tran_value.endswith(rule_value)
|
def convert_to_celsius(fahrenheit: float) -> float:
"""
>>> convert_to_celsius(75)
23.88888888888889
"""
return fahrenheit - 32.0 * 5.0 / 9.0
|
def slice_data(data, info, split):
"""Slice data according to the instances belonging to each split."""
if split is None:
return data
elif split == 'train':
return data[:info['train_len']]
elif split == 'val':
train_n = info['train_len']
val_n = train_n + info['val_len']
return data[train_n: val_n]
elif split == 'test':
val_n = info['train_len'] + info['val_len']
test_n = val_n + info['test_len']
return data[val_n: test_n]
|
def add_trailing_slash(s):
"""Add trailing slash. """
if not s.endswith('/'):
s = s + '/'
return(s)
|
def fib2(n): # return Fibonacci series up to n
"""Return a list containing the Fibonacci series up to n."""
result = []
a, b = 0, 1
while a < n:
result.append(a) # see below
a, b = b, a + b
return result
|
def api_response(data, status, code=200):
"""
Return json response to user.
If the data is a list, return a response of the json of all objects in that list.
If the data is a json blob, return that as the data.
If the data is None, just return the given status.
"""
if type(data) == list:
return {"status": status, "data": [obj.json for obj in data]}, code
elif data:
return {"status": status, "data": data}, code
else:
return {"status": status}, code
|
def remove_app(INSTALLED_APPS, app):
""" remove app from installed_apps """
if app in INSTALLED_APPS:
apps = list(INSTALLED_APPS)
apps.remove(app)
return tuple(apps)
return INSTALLED_APPS
|
def _organize_requests_by_external_key(enrollment_requests):
"""
Get dict of enrollment requests by external key.
External keys associated with more than one request are split out into a set,
and their enrollment requests thrown away.
Arguments:
enrollment_requests (list[dict])
Returns:
(requests_by_key, duplicated_keys)
where requests_by_key is dict[str: dict]
and duplicated_keys is set[str].
"""
requests_by_key = {}
duplicated_keys = set()
for request in enrollment_requests:
key = request['external_user_key']
if key in duplicated_keys:
continue
if key in requests_by_key:
duplicated_keys.add(key)
del requests_by_key[key]
continue
requests_by_key[key] = request
return requests_by_key, duplicated_keys
|
def _clean_label(label):
"""Replaces all underscores with spaces and capitalizes first letter"""
return label.replace("_", " ").capitalize() if label is not None else None
|
def transfer_function_Rec2020_12bit_to_linear(v):
"""
The Rec.2020 12-bit transfer function.
Parameters
----------
v : float
The normalized value to pass through the function.
Returns
-------
float
A converted value.
"""
a = 1.0993
b = 0.0181
d = 4.5
g = (1.0 / 0.45)
if v < b * d:
return v / d
return pow(((v + (a - 1)) / a), g)
|
def normalize(arr, total=1.0):
"""Normalizes an array to have given total sum"""
try:
fac = total/float(sum([abs(v) for v in arr]))
except ZeroDivisionError: fac = 1.0
return [v*fac for v in arr]
|
def option_str_list(argument):
"""
An option validator for parsing a comma-separated option argument. Similar to
the validators found in `docutils.parsers.rst.directives`.
"""
if argument is None:
raise ValueError("argument required but none supplied")
else:
return [s.strip() for s in argument.split(",")]
|
def splitDateTime(string):
""" split Sun May 10 18:23:32 +0000 2015 into NameOfDay Month Day Hour TimeZone Year"""
d = string.split(" ")
return d
|
def split(text):
"""
Convenience function to parse a string into a list using two or more spaces
as the delimiter.
Parameters
----------
text : string
Contains text to be parsed
Returns
-------
textout : list
list of strings containing the parsed input text
"""
textout = [s.strip() for s in text.split(' ') if s.strip()]
return textout
|
def get_indx(scrub_input, frames_in_1D_file):
"""
Method to get the list of time
frames that are to be included
Parameters
----------
in_file : string
path to file containing the valid time frames
Returns
-------
scrub_input_string : string
input string for 3dCalc in scrubbing workflow,
looks something like " 4dfile.nii.gz[0,1,2,..100] "
"""
#f = open(frames_in_1D_file, 'r')
#line = f.readline()
#line = line.strip(',')
frames_in_idx_str = '[' + ','.join(str(x) for x in frames_in_1D_file) + ']'
#if line:
# indx = map(int, line.split(","))
#else:
# raise Exception("No time points remaining after scrubbing.")
#f.close()
#scrub_input_string = scrub_input + str(indx).replace(" ", "")
scrub_input_string = scrub_input + frames_in_idx_str
return scrub_input_string
|
def check_size(grid):
"""
Checks if user input grid is 9x9.
"""
row_count = 0
col_count = 0
for row in grid:
row_count += 1
for col in grid[row]:
col_count += 1
if col_count != 9:
return False
else:
col_count = 0
if row_count != 9:
return False
return True
|
def win_path_join(dirname: str, basename: str) -> str:
"""Join path Windows style"""
d = dirname.rstrip("\\")
return f'{d}\\{basename}'
|
def comma_join(items):
"""
Joins an iterable of strings with commas.
"""
return ', '.join(items)
|
def is_concept_id_col(col):
"""
Determine if column is a concept_id column
:param col: name of the column
:return: True if column is a concept_id column, False otherwise
"""
return col.endswith('concept_id')
|
def canonicalize_eol(text, eol):
"""Replace any end-of-line sequences in TEXT with the string EOL."""
text = text.replace('\r\n', '\n')
text = text.replace('\r', '\n')
if eol != '\n':
text = text.replace('\n', eol)
return text
|
def _join_parameters(parameters):
"""
Takes list of parameter and returns a string with ', ' between parameters
:param parameters: list
:return: parameters concatenated by a semicolon
:rtype: string
"""
parameter_string = ''
for p in parameters:
if p != '':
parameter_string += ', ' + p
parameter_string = parameter_string[2:] # Remove the first ', '
return parameter_string
|
def fewest_cities_needed(total, items):
"""Sum largest cities first until sum exceeds total."""
for i in range(len(items)):
s = sum(items[:i])
if s > total:
return i
return 0
|
def amatch(s: str, pat: str) -> int:
"""
Returns number of matching characters in `s` and `pat` before
a "*" or "#" character in pat. Returns -1 if strings do not match
Example:
amatch("abc", "a*") -> 1
amatch("wx", "wx") -> 2
amatch("xy", "xz") -> -1
"""
for count, (c, p) in enumerate(zip(s, pat)):
if p in "*#":
return count
if c != p:
return -1
return len(s)
|
def check_afm(afm):
"""Check the validity of an AFM number (Greek VAT code).
Check if input is a valid AFM number via its check digit (not if it is actually used).
Return either True of False.
Input should be given as a string. An integer, under certain conditions, could through an exception.
"""
if not isinstance(afm, str):
raise TypeError( "check_afm()", "You should feed to this function only strings to avoid exceptions and errors! Aborting." )
if len(afm) == 11 and afm[:2].upper() == "EL":
afm=afm[2:]
if afm.isdigit() == True and len(afm) == 9:
i, sums = 256, 0
for digit in afm[:-1]:
sums += int(digit) * i
i /= 2
checksum = sums % 11
if int(afm[-1]) == int(checksum) or (checksum==10 and afm[-1]=="0"):
return True
return False
|
def ods_bool_value(value):
"""convert a boolean value to text"""
if value is True:
return "true"
else:
return "false"
|
def calc_w_from_q(q):
"""Calculate water vapor mixing ratio (1) from specific humidity q
(1)."""
return q/(1. - q)
|
def calculate_beta(diffusivity,node_spacing,time_interval):
"""
Calculate beta, a substitution term based on diffusivity, the spacing
of nodes within the modeled grain, and the timestep. After Ketcham, 2005.
Parameters
----------
diffusivity : float
Diffusivity.
node_spacing : float
Spacing of nodes in the modeled crystal (um)
time_interval : float
Timestep in the thermal model (yr)
Returns
-------
beta : float
Beta, after Ketcham, 2005.
"""
beta = (2*(node_spacing**2))/(diffusivity*time_interval)
return(beta)
|
def recover_escape(text: str) -> str:
"""Converts named character references in the given string to the corresponding
Unicode characters. I didn't notice any numeric character references in this
dataset.
Args:
text (str): text to unescape.
Returns:
str: unescaped string.
"""
return text.replace("&", "&").replace("<", "<").replace(">", ">")
|
def find_two_sum(numbers, target_sum):
"""
:param numbers: (list of ints) The list of numbers.
:param target_sum: (int) The required target sum.
:returns: (a tuple of 2 ints) The indices of the two elements whose sum is equal to target_sum
"""
taken = {}
for i, num in enumerate(numbers):
diff = target_sum - num
if diff in taken:
return i, taken[diff]
taken[num] = i
return None
|
def frequency_interaction_fingerprint(fp_list):
"""
Create frequency fingerprint from list of fingerprints.
"""
count_fp = [sum(i) for i in zip(*fp_list)]
frequency_fp = [float(i) / len(fp_list) for i in count_fp]
return frequency_fp
|
def parse_readable_size_str(size_str):
"""Convert a human-readable str representation to number of bytes.
Only the units "kB", "MB", "GB" are supported. The "B character at the end
of the input `str` may be omitted.
Args:
size_str: (`str`) A human-readable str representing a number of bytes
(e.g., "0", "1023", "1.1kB", "24 MB", "23GB", "100 G".
Returns:
(`int`) The parsed number of bytes.
Raises:
ValueError: on failure to parse the input `size_str`.
"""
size_str = size_str.strip()
if size_str.endswith("B"):
size_str = size_str[:-1]
if size_str.isdigit():
return int(size_str)
elif size_str.endswith("k"):
return int(float(size_str[:-1]) * 1024)
elif size_str.endswith("M"):
return int(float(size_str[:-1]) * 1048576)
elif size_str.endswith("G"):
return int(float(size_str[:-1]) * 1073741824)
else:
raise ValueError("Failed to parsed human-readable byte size str: \"%s\"" %
size_str)
|
def madau_17(z):
"""
returns star formation rate as a function of supplied redshift
Parameters
----------
z : `float or numpy.array`
redshift
Returns
-------
sfr : `float or numpy.array`
star formation rate [Msun/yr]
"""
sfr = 0.01 * (1 + z) ** (2.6) / (1 + ((1 + z) / 3.2) ** 6.2)
return sfr
|
def get_http_method_type(method: str):
"""Return lowercase http method name, if valid. Else, raise Exception."""
supported_methods = ["get", "post", "put", "delete" # , "head", "connect", "options", "trace", "patch"
]
m = str(method).lower()
if not m in supported_methods:
raise ValueError(
f"Request method '{method}' not supported. Supported are GET, POST, PUT & DELETE.")
return m
|
def _sim_texture(r1, r2):
"""
calculate the sum of histogram intersection of texture
"""
return sum([min(a, b) for a, b in zip(r1["hist_t"], r2["hist_t"])])
|
def MAP(_input, _as, _in):
"""
Applies an expression to each item in an array and returns an array with the applied results.
See https://docs.mongodb.com/manual/reference/operator/aggregation/map/
for more details
:param _input: An expression that resolves to an array.
:param _as: A name for the variable that represents each individual element of the input array.
:param _in: An expression that is applied to each element of the input array.
:return: Aggregation operator
"""
return {'$map': {'input': _input, 'as': _as, 'in': _in}}
|
def sizeof_fmt(num):
"""
Convert file size to human readable format.
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "{0:.2f} {1}".format(num, x)
num /= 1024.0
|
def int_to_str(item: int) -> str:
"""[summary]
Args:
item (int): [description]
Returns:
str: [description]
"""
"""Converts an int to a str."""
return str(item)
|
def _split_choices_in_list(choices_string):
"""
Riceve una stringa e la splitta ogni ';'
creando una lista di scelte
"""
str_split = choices_string.split(';')
return str_split
|
def evi_func(blue, red, nir):
"""Compute enhanced vegetation index
Parameters
----------
blue : array_like
Blue band (band 1 on Landsat 5/7, band 2 on Landsat 8).
red :
Red band (band 3 on Landsat 5/7, band 4 on Landsat 8).
nir : array_like
Near infrared band (band 4 on Landsat 5/7, band 5 on Landsat 8).
Returns
-------
array_like
References
----------
.. [1] Huete et al. (2002).
Overview of the radiometric and biophysical performance of the MODIS
vegetation indices. Remote Sensing of Environment, 83.
https://doi.org/10.1016/S0034-4257(02)00096-2
"""
return (2.5 * (nir - red)) / (nir + 6 * red - 7.5 * blue + 1)
|
def file_is_ipython_notebook(path):
"""Check whether a file is an iPython Notebook.
Args:
path (str): path to the file.
Examples:
path : source path with .ipynb file '/path/src/my_file.ipynb.
"""
return path.lower().endswith(".ipynb")
|
def remove_dropped(ps_lst):
"""
@brief Removes every item of ps_lst which is marked to drop
@param ps_lst List of PseudoInstructions
@return List of PseudoInstructions
"""
ret = []
for item in ps_lst:
if not item.drop:
ret.append(item)
else:
del item
return ret
|
def calculate_tva(price, tva=20):
"""Calculates the tax on a product
Formula
-------
price * (1 + (tax / 100))
"""
return round(float(price) * (1 + (tva / 100)), 2)
|
def parse_viewed_courses(json):
"""
Parse course viewed statements.
Extract the students that have viewed the course from the course viewed statements.
Return a list of those students.
:param json: All the course viewed statements since a certain time.
:type json: dict(str, str)
:return: List of students who have viewed the course.
:rtype: list(str)
"""
student_list = []
for statement in json['statements']:
student_id = statement['actor']['account']['name']
if student_id not in student_list:
student_list.append(student_id)
return student_list
|
def is_sound_valid(wav_file: str) -> bool:
"""Asserts if sound file is valid.
Args:
wav_file (str): Path to wav file
Returns:
bool: If file is valid
"""
return wav_file.endswith(".wav")
|
def bubble_sort(collection):
"""
contoh
>>> bubble_sort([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
"""
panjang = len(collection)
for i in range(panjang - 1):
swap = False
for j in range(panjang - 1 - i):
if collection[j] > collection[j + 1]:
swap = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
if not swap:
# stop iterasi jika sudah ter sorting
break
return collection
|
def convert_rotate(rotate):
""" 8. Rotate 90,180, 270 degree """
if rotate > 0:
command = "-rotate " + str(rotate)
else:
command = ""
return command
|
def get_decimals(value) -> int:
"""Get the number of decimal places required to represent a value.
Parameters
----------
value : :class:`int` or :class:`float`
The value.
Returns
-------
:class:`int`
The number of decimal places.
"""
val = abs(value)
fraction = val - int(val)
if fraction == 0:
return 0
string = str(val)
split = string.split('e-')
if len(split) == 1:
return len(string) - split[0].index('.') - 1
number, exponential = split
d = int(exponential)
if '.' in number:
return d + len(number) - number.index('.') - 1
return d
|
def bisection_search2(L, e):
"""
Implementation 2 for the divide-and-conquer algorithm
Complexity: O(log n)
:param L: List-object
:param e: Element to look for
:return: Boolean value if element has been found
"""
def helper(L, e, low, high):
if high == low:
return L[low] == e
mid = (low + high) // 2
if L[mid] == e:
return True
elif L[mid] > e:
if low == mid:
return False
else:
return helper(L, e, low, mid - 1)
else:
return helper(L, e, mid + 1, high)
if len(L) == 0:
return False
else:
return helper(L, e, 0, len(L) - 1)
|
def is_valid_str(s: str) -> bool:
"""
Check if the input string is not empty.
:param s: Input string.
:return: True if the string is not empty.
"""
if s is None:
return False
if not isinstance(s, str):
return False
if len(s) <= 0:
return False
return True
|
def update_odds_with_evidence( prevalence, testPower, evdnc ):
""" Compute a new odds of an outcome """
evPos = evdnc
evNeg = 1 - evdnc
oddsPos = prevalence[evPos]/prevalence[evNeg] * testPower[evdnc][evPos]/testPower[evdnc][evNeg]
oddsNeg = float('nan')
if oddsPos > 1:
oddsNeg = 1.0
elif oddsPos > 0:
oddsNeg = 1 / oddsPos
oddsPos = 1.0
return {
evPos : oddsPos ,
evNeg : oddsNeg ,
}
|
def read_16bit_size(data, little_endian=True):
""" Read next two bytes as a 16-bit value """
if little_endian:
return data[0] + data[1] * 256
else:
return data[1] + data[0] * 256
|
def get_reading_level_from_flesch(flesch_score):
"""
Thresholds taken from https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
:param flesch_score:
:return: A reading level and difficulty for a given flesch score
"""
if flesch_score < 30:
return "Very difficult to read"
elif flesch_score < 50:
return "Difficult to read"
elif flesch_score < 60:
return "Fairly difficult to read"
elif flesch_score < 70:
return "Plain English"
elif flesch_score < 80:
return "Fairly easy to read"
elif flesch_score < 90:
return "Easy to read"
else:
return "Very easy to read"
|
def replace_range(old_lines, new_lines, r=None):
"""
>>> a = list(range(10))
>>> b = list(range(11, 13))
>>> replace_range(a, b, (0, 2))
[11, 12, 2, 3, 4, 5, 6, 7, 8, 9]
>>> replace_range(a, b, (8, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 11, 12]
>>> replace_range(a, b, (0, 10))
[11, 12]
>>> replace_range(a, [], (0, 10))
[]
>>> replace_range(a, [], (0, 9))
[9]
"""
start, end = r or (0, len(old_lines))
assert 0 <= start <= end <= len(old_lines)
return old_lines[:start] + new_lines + old_lines[end:]
|
def verify_integer(filter_value):
"""Used to verify that <input> type textboxes that should be integers actually are."""
try:
int(filter_value)
return True
except:
return False
|
def html(module, tag):
"""Mapping for html tags.
Maps tags to title case, so you can type html tags as ``<audio>``
or ``<AuDiO>`` or whichever way.
"""
title = tag.title()
if title in {
"A",
"Abbr",
"Acronym",
"Address",
"Area",
"Article",
"Aside",
"Audio",
"B",
"Base",
"Basefont",
"Bdi",
"Bdo",
"Big",
"Blink",
"Blockquote",
"Br",
"Button",
"Canvas",
"Caption",
"Center",
"Cite",
"Code",
"Col",
"Colgroup",
"Command",
"Content",
"Data",
"Datalist",
"Dd",
"Del",
"Details",
"Dfn",
"Dialog",
"Div",
"Dl",
"Dt",
"Element",
"Em",
"Embed",
"Fieldset",
"Figcaption",
"Figure",
"Font",
"Footer",
"Form",
"Frame",
"Frameset",
"H1",
"H2",
"H3",
"H4",
"H5",
"H6",
"Header",
"Hgroup",
"Hr",
"I",
"Iframe",
"Img",
"Ins",
"Isindex",
"Kbd",
"Keygen",
"Label",
"Legend",
"Li",
"Link",
"Listing",
"Main",
"Map",
"Mark",
"Marquee",
"Meta",
"Meter",
"Multicol",
"Nav",
"Nextid",
"Nobr",
"Noscript",
"Object",
"Ol",
"Optgroup",
"Option",
"Output",
"P",
"Param",
"Picture",
"Plaintext",
"Pre",
"Progress",
"Q",
"Rb",
"Rp",
"Rt",
"Rtc",
"Ruby",
"S",
"Samp",
"Script",
"Section",
"Select",
"Shadow",
"Slot",
"Small",
"Source",
"Spacer",
"Span",
"Strike",
"Strong",
"Sub",
"Summary",
"Sup",
"Table",
"Tbody",
"Td",
"Template",
"Textarea",
"Tfoot",
"Th",
"Thead",
"Time",
"Title",
"Tr",
"Track",
"U",
"Ul",
"Var",
"Video",
"Wbr",
"Xmp",
}:
if title in {"Map", "Object"}:
title = f"{title}El"
return module, title
|
def get_repo_from_tool(tool):
"""
Get the minimum items required for re-installing a (list of) tools
"""
if not tool.get('tool_shed_repository', None):
# Tool or Data Manager not installed from a tool shed
return {}
tsr = tool['tool_shed_repository']
repo = {'name': tsr['name'],
'owner': tsr['owner'],
'tool_shed_url': tsr['tool_shed'],
'revisions': [tsr['changeset_revision']],
'tool_panel_section_id': tool['panel_section_id'],
'tool_panel_section_label': tool['panel_section_name']}
return repo
|
def _split_arrays(arrays, extra_args, nparts):
"""
Split the coordinate arrays into nparts. Add extra_args to each part.
Example::
>>> chunks = _split_arrays([[1, 2, 3, 4, 5, 6]], ['meh'], 3)
>>> chunks[0]
[[1, 2], 'meh']
>>> chunks[1]
[[3, 4], 'meh']
>>> chunks[2]
[[5, 6], 'meh']
"""
size = len(arrays[0])
n = size//nparts
strides = [(i*n, (i + 1)*n) for i in range(nparts - 1)]
strides.append((strides[-1][-1], size))
chunks = [[x[low:high] for x in arrays] + extra_args
for low, high in strides]
return chunks
|
def format_docstring(docstring):
"""
Taken from https://github.com/fecgov/openFEC/blob/master/webservices/spec.py
"""
if not docstring or not docstring.strip():
return ""
formatted = []
lines = docstring.expandtabs().splitlines()
for line in lines:
if line == "":
formatted.append("\n\n")
else:
formatted.append(line.strip())
return " ".join(formatted).strip()
|
def suck_out_editions(reporters):
"""Builds a dictionary mapping edition keys to their root name.
The dictionary takes the form of:
{
"A.": "A.",
"A.2d": "A.",
"A.3d": "A.",
"A.D.": "A.D.",
...
}
In other words, this lets you go from an edition match to its parent key.
"""
editions_out = {}
for reporter_key, data_list in reporters.items():
# For each reporter key...
for data in data_list:
# For each book it maps to...
for edition_key, edition_value in data["editions"].items():
try:
editions_out[edition_key]
except KeyError:
# The item wasn't there; add it.
editions_out[edition_key] = reporter_key
return editions_out
|
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = {}
res_list = []
for i in range(len(nums)):
seen = {}
seen[nums[i]] = 1
for j in range(len(nums)):
if j == i:
continue
else:
if nums[j] in seen:
seen[nums[j]] += 1
else:
seen[nums[j]] = 1
third_num = -(nums[i] +(nums[j] * seen[nums[j]]))
print ("nums[i]: " + str(nums[i]))
print ("nums[j]: " + str(nums[j]) + ": " + str(seen[nums[j]]))
print ("third_num: " + str(third_num) + "\n")
if third_num in seen and seen[third_num] >= 2:
print ("added\n")
res_list.append([nums[i], nums[j], third_num])
seen[third_num] -= 1
return res_list
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.