content
stringlengths 42
6.51k
|
---|
def isY( ch ):
""" Is the given character an x?"""
return ch == 'y' or ch == 'Y'
|
def split_by_len(item, itemlen, maxlen):
""""Requires item to be sliceable (with __getitem__ defined)."""
return [item[ind:ind + maxlen] for ind in range(0, itemlen, maxlen)]
|
def get_single_field(fields):
"""Finds neurons with and indices of single fields.
Parameters
----------
fields : dict
Where the key is the neuron number (int), value is a list of arrays (int).
Each inner array contains the indices for a given place field.
Eg. Neurons 7, 3, 11 that have 2, 1, and 3 place fields respectively would be:
{7: [[field], [field]], 3: [[field]], 11: [[field], [field], [field]]}
Returns
-------
fields : dict
Where the key is the neuron number (int), value is a list of arrays (int).
Each inner array contains the indices for a given place field.
Eg. For the above input, only neuron 3 would be output in this dict:
{3: [[field]]}
"""
fields_single = dict()
for neuron in fields.keys():
if len(fields[neuron]) == 1:
fields_single[neuron] = fields[neuron]
return fields_single
|
def _relative(src_path, dest_path):
"""Returns the relative path from src_path to dest_path."""
src_parts = src_path.split("/")
dest_parts = dest_path.split("/")
n = 0
done = False
for src_part, dest_part in zip(src_parts, dest_parts):
if src_part != dest_part:
break
n += 1
relative_path = ""
for i in range(n, len(src_parts)):
relative_path += "../"
relative_path += "/".join(dest_parts[n:])
return relative_path
|
def rol(s,shift):
"""
Rotate Left the string s by a count of 'shift'
'shift' supports negetive numbers for opposite rotate
"""
split = (shift % len(s))
return s[split:]+s[:split]
|
def subarray_with_given_sum(numbers, size, required_sum):
"""
Given an unsorted array of non-negative integers,
find a continuous sub-array which adds to a given number.
"""
start = 0
current_sum = numbers[0]
for i in range(1, size + 1):
while current_sum > required_sum and start < i - 1:
current_sum -= numbers[start]
start += 1
if current_sum == required_sum:
return (start + 1, i)
if i < size:
current_sum += numbers[i]
return -1
|
def all_with_label(pages, label):
"""
pages: list(Page)
label: str
returns: list(Page)
Filter for pages that are tagged with the given label.
"""
return [page for page in pages if label in page.get("labels", [])]
|
def getOutputFilename(runId, TRindex):
""""Return station classification filename"""
filename = "percentChange_run-{0:02d}_TR-{1:03d}.txt".format(runId, TRindex)
return filename
|
def get_reference_mcf(info):
"""Generate mcf line for all the reference properties."""
reference_codes = ['ADR', 'ARX']
# reference example in the dataset
# ADR PDB:6ZCZ
# ARX DOI:10.1101/2020.06.12.148387
reference_map = {}
for code in reference_codes:
if code not in info:
continue
reference_string = info[code]
database = reference_string.split(':')[0]
id_num = reference_string[len(database) + 1:]
reference_map[database] = id_num
mcf_list = []
database_to_property = {
'PDB': 'rcsbPDBID',
'Cellosaurus': 'cellosaurusID',
'IMGT/mAb-DB': 'imgtMonoclonalAntibodiesDBID',
'NeuroMab': 'neuroMabID',
'ginas': 'ginasID',
'RAN': 'recombinantAntibodyNetworkID',
'Addgene': 'addgeneID',
'PMID': 'pubMedID',
'Patent': 'patentID',
'DOI': 'digitalObjectID'
}
for database in reference_map:
id_num = reference_map[database]
if database not in database_to_property:
return ''
mcf_list.append(database_to_property[database] + ': "' + id_num + '"\n')
return ''.join(mcf_list)
|
def is_image_file(filename):
""" Return true if the file is an image. """
filename_lower = filename.lower()
return any(filename_lower.endswith(extension) for extension in ['.png', '.jpg', '.bmp', '.mat'])
|
def replace_last(full, sub, rep=''):
"""
replaces the last instance of a substring in the full string with rep
:param full: the base string in which the replacement should happen
:param sub: to be replaced
:param rep: replacement substring default empty
:return:
"""
end = ''
count = 0
for c in reversed(full):
count = count + 1
end = c + end
if sub in end:
return full[:-count] + end.replace(sub, rep)
return full
|
def filter(submissions):
"""Filter submission in the assignment list based on a criteria.
As written, this looks at the assignment title
Args:
submissions (list): List of Canvas assignments
Returns:
[list]
"""
# Filter based on any criteria.
allowed = ["Criteria 1", "Criteria 2"]
# Check for the criteria in the assignment name.
# You can filter based on any key in the assignment object
filtered = [
item
for item in submissions
if any(word in item.assignment["name"] for word in allowed)
]
return filtered
|
def snake_to_camelcase(name):
"""Convert snake-case string to camel-case string."""
return "".join(n.capitalize() for n in name.split("_"))
|
def delete_empty_lines(log):
"""Delete empty lines"""
return "\n".join([line for line in log.split("\n") if line.strip() != ""])
|
def dataAvailable (date, databaseList, dataAvailability):
"""Checks that there is some data available for the queried date.
.. warning:
Assumes date has been validated using dateValidation.
:param date: The queried date
:type date: list[str, str, str]
:param databaseList: List of months/years for which data is available
:type databaseList: list[tuple]
:param list dataAvailability: Determines range of dates available for
month/year in question
:return: date, if valid
:rtype: list[str, str, str] or None
"""
if date is not None:
monthToCheck = date[0], date[2]
availability = 1 <= int(date[1]) <= len(dataAvailability)
if monthToCheck in databaseList and availability:
return date
|
def post_process_seq(seq, eos_idx):
"""
Post-process the beam-search decoded sequence. Truncate from the first
<eos> and remove the <bos> and <eos> tokens currently.
"""
eos_pos = len(seq)
for i, idx in enumerate(seq):
if idx == eos_idx:
eos_pos = i
break
seq = seq[1:eos_pos]
return seq
|
def sr(a):
"""
in:
a: 1d array
ou:
list of range tupples
"""
r = []
i = 0
# enter loop directly, no need to worry 1-el list
while i < len(a):
n = a[i]
# w/i boundary and in sequence
while i + 1 < len(a) and a[i + 1] - a[i] == 1:
i += 1
if a[i] != n:
r.append((n, a[i]))
else:
r.append((n, n))
i += 1
return r
|
def contains_secret(line: str, secret: str) -> bool:
"""Returns True if `line` contains an obfuscated version of `secret`"""
return f'"{secret[:6]}' in line and f'{secret[-6:]}"' in line
|
def upper(value):
"""Uppercase the string passed as argument"""
return value.upper() if value else value
|
def str2v(s):
""" s is a cube (given by a string of 0,1,- and result is a list of 0,1,2
called a vector here"""
res = []
for j in range(len(s)):
if s[j] == '-':
res = res +[2]
elif s[j] == '0':
res = res + [0]
else:
res = res + [1]
return res
|
def coord_Im2Array(X_IMAGE, Y_IMAGE, origin=1):
""" Convert image coordniate to numpy array coordinate """
x_arr, y_arr = int(max(round(Y_IMAGE)-origin, 0)), int(max(round(X_IMAGE)-origin, 0))
return x_arr, y_arr
|
def radixsort(lst):
"""Recursive function to order a list quickly."""
radix_buckets = 10
max_length = False
temp = -1
mover = 1
while not max_length:
max_length = True
buckets = [list()for _ in range(radix_buckets)]
for i in lst:
temp = i//mover
buckets[temp%radix_buckets].append(i)
if max_length and temp > 0:
max_length = False
counter = 0
for j in range(radix_buckets):
empty_bucket = buckets[j]
for i in empty_bucket:
lst[counter] = i
counter += 1
mover *= radix_buckets
return lst
|
def remove_b_for_nucl_phys(citation_elements):
"""Removes b from the volume of some journals
Removes the B from the volume for Nucl.Phys.Proc.Suppl. because in INSPIRE
that journal is handled differently.
"""
for el in citation_elements:
if el['type'] == 'JOURNAL' and el['title'] == 'Nucl.Phys.Proc.Suppl.' \
and 'volume' in el \
and (el['volume'].startswith('b') or el['volume'].startswith('B')):
el['volume'] = el['volume'][1:]
return citation_elements
|
def qualify(ns, name):
"""Makes a namespace-qualified name."""
return '{%s}%s' % (ns, name)
|
def filter_float(value):
"""Change a floating point value that represents an integer into an
integer."""
if isinstance(value, float) and float(value) == int(value):
return int(value)
return value
|
def _numericize(loaded_data):
"""
If a number can be turned into a number, turn it into a number
This avoids duplicates such as 1 and "1"
"""
new_iterable = []
for i in loaded_data:
var = i
try:
var = int(i)
except (ValueError, TypeError):
pass
finally:
new_iterable.append(var)
return new_iterable
|
def is_tiff(data):
"""True if data is the first 4 bytes of a TIFF file."""
return data[:4] == 'MM\x00\x2a' or data[:4] == 'II\x2a\x00'
|
def _array_chunk_location(block_id, chunks):
"""Pixel coordinate of top left corner of the array chunk."""
array_location = []
for idx, chunk in zip(block_id, chunks):
array_location.append(sum(chunk[:idx]))
return tuple(array_location)
|
def validate_for_scanners(address, port, domain):
"""
Validates that the address, port, and domain are of the correct types
Pulled here since the code was the same
Args:
address (str) : string type address
port (int) : port number that should be an int
domain (str) : domain name that should be a string
"""
if not isinstance(address, str):
raise TypeError(f"{address} is not of type str")
if not isinstance(port, int):
raise TypeError(f"{port} is not of type int")
if domain is not None and not isinstance(domain, str):
raise TypeError(f"{domain} is not a string")
return True
|
def count_contents(color, data):
"""Returns the number of bags that must be inside a bag of a given color"""
return sum(
inside_count * (1 + count_contents(inside_color, data))
for inside_color, inside_count in data[color].items()
)
|
def count_words(wordlst: list):
"""
count words in tweet text from list of list, dict, or str
:param wordlst: list of tweets
:return: word count, tweet count
"""
wrd_count: int = 0
tw_count: int = 0
for tw in wordlst:
if isinstance(tw, dict):
tw_wrds: list = tw['text'].split()
elif isinstance(tw, str):
tw_wrds: list = tw.split()
else:
tw_wrds: list = tw
tw_count += 1
wrd_count += len(tw_wrds)
return wrd_count, tw_count
|
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return':0}
|
def super_signature(signatures):
""" A signature that would break ambiguities """
n = len(signatures[0])
assert all(len(s) == n for s in signatures)
return [max([type.mro(sig[i]) for sig in signatures], key=len)[0] for i in range(n)]
|
def extract_characteristics_from_string(species_string):
"""
Species are named for the SBML as species_name_dot_characteristic1_dot_characteristic2
So this transforms them into a set
Parameters:
species_string (str) = species string in MobsPy for SBML format (with _dot_ instead of .)
"""
return set(species_string.split('_dot_'))
|
def checkStarts(seq):
"""
Check the starts
"""
flag = False
ss = ["CATG", "AATT", "NATG", "NATT"]
for s in ss:
if seq.startswith(s):
flag = True
break
return flag
|
def gen_urdf_box(size):
"""
:param size: Three element sequence containing x, y and z dimensions (meters) of box, ``seq(float)``
:returns: urdf element sequence for a box geometry, ``str``
"""
return '<geometry><box size="{0} {1} {2}" /></geometry>'.format(*size)
|
def newman_conway(num, storage=None):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if storage is None:
storage = [None, 1, 1]
if num == 0:
raise ValueError
while num >= len(storage):
storage.append(storage[storage[-1]] + storage[len(storage) - storage[-1]])
str_storage = [str(num) for num in storage[1:num+1]]
return " ".join(str_storage)
|
def pascal_case_to_snake_case(input_string):
"""
Converts the input string from PascalCase to snake_case
:param input_string: (str) a PascalCase string
:return: (str) a snake_case string
"""
output_list = []
for i, char in enumerate(input_string):
if char.capitalize() == char: # if the char is already capitalized
if i == 0:
output_list.append(char.lower()) # the first char is only made lowercase
else:
output_list.append('_')
output_list.append(char.lower()) # other capital chars are prepended with an underscore
else:
output_list.append(char)
output = ''.join(output_list)
return output
|
def Fibonacci(num):
""" Create a list from 0 to num """
fib, values = lambda x: 1 if x <= 1 else fib(x-1) + fib(x-2), []
for i in range(0, num):
values.append(fib(i))
return values
|
def minimize(solution):
"""Returns total difference of solution passed"""
length = len(solution)
result = 0
for index, number1 in enumerate(solution):
for nr_2_indx in range(index + 1, length):
result += abs(number1 - solution[nr_2_indx])
return result
|
def extract_month(datestring):
"""
Return month part of date string as integer.
"""
return int(datestring[:2])
|
def merge_dictionaries(dicts):
""" Merge multiple dictionaries.
# Arguments
dicts: List of dictionaries.
# Returns
result: Dictionary.
"""
result = {}
for dict in dicts:
result.update(dict)
return result
|
def add_unit_prefix(num: float, unit='B') -> str:
"""
source: https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
"""
for prefix in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, prefix, unit)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', unit)
|
def greet(name):
"""
Greets a person.
:param name: a string input.
:return: None if string empty or None else greets the name.
"""
if name == "" or name is None:
return None
else:
return "hello " + name + "!"
|
def parse_http_list(s):
"""A unicode-safe version of urllib2.parse_http_list"""
res = []
part = u''
escape = quote = False
for cur in s:
if escape:
part += cur
escape = False
continue
if quote:
if cur == u'\\':
escape = True
continue
elif cur == u'"':
quote = False
part += cur
continue
if cur == u',':
res.append(part)
part = u''
continue
if cur == u'"':
quote = True
part += cur
# append last part
if part:
res.append(part)
return [part.strip() for part in res]
|
def word_tree(words):
"""
This builds a tree according to a list of words to later be searched
whilst looking for valid words in search(...)
Example tree for NANDO, NATTY, NANNY and NERDS
{'N':
{'A': {'N': {'D': {'O': {}},
'N': {'Y': {}}},
'T': {'T': {'Y': {}}}},
'E': {'R': {'D': {'S': {}}}}}}
"""
tree = {'N': {}}
for w in words:
T = tree[w[0]]
for depth in range(1, len(w)):
if w[depth] not in T.keys():
T[w[depth]] = {}
T = T[w[depth]]
return tree
|
def is_2dlist(x):
"""check x is 2d-list([[1], []]) or 1d empty list([]).
Notice:
The reason that it contains 1d empty list is because
some arguments from gt annotation file or model prediction
may be empty, but usually, it should be 2d-list.
"""
if not isinstance(x, list):
return False
if len(x) == 0:
return True
return all(isinstance(item, list) for item in x)
|
def find_active_firmware(boot_config_sector):
"""Returns a tuple of the active firmware's configuration"""
for i in range(8):
app_entry = boot_config_sector[i*32:i*32+32]
config_flags = int.from_bytes(app_entry[0:4], 'big')
active = config_flags & 0b1 == 0b1
if not active:
continue
app_address = int.from_bytes(app_entry[4:4+4], 'big')
app_size = int.from_bytes(app_entry[8:8+4], 'big')
return app_address, app_size, i
return None, None, None
|
def solution(pegs):
"""
Sequence a_n is defined by
a_0=0 and
a_{i+1}=a_i+(-1)^i(pegs_{i+1}-pegs_i)
Withs these, the radii of the wheels are
r_i = (-1)^{i-1}(a_i-r)
where r is the radius of the first wheel.
We impose that r=2*r_{n-1} and that r_i>=1.
The latter condition is not very clear in the problem.
In the statement it can seem like they only ask this condition
for the radius of the first wheel.
"""
n = len(pegs)
if n<2:
return (-1,-1)
an = 0
pm_one = -1
max_even_a = -float("inf")
min_odd_a = float("inf")
for i in range(n-1):
an -= pm_one*(pegs[i+1]-pegs[i])
pm_one *=-1
if not i&1:
min_odd_a = min(min_odd_a, an)
else:
max_even_a = max(max_even_a, an)
numerator = 2*an
denominator = abs(1+2*pm_one)
if numerator < denominator*(max_even_a+1) \
or numerator > denominator*(min_odd_a-1):
return (-1,-1)
if pm_one == 1 and numerator%3==0:
numerator //=3
numerator = abs(numerator)
denominator = 1
return (numerator, denominator)
|
def calc_recall(tp, fn):
"""Calculate recall from tp and fn"""
if tp + fn != 0:
recall = tp / (tp + fn)
else:
recall = 0
return recall
|
def isVowelStart(str):
"""
A utility function to return true if the first letter in the str is a vowel
"""
retval = False
if str and len(str) > 0:
vowels = ['A', 'E', 'I', 'O', 'U']
firstLetter = str.upper()[0:1]
if firstLetter in vowels:
retval = True
return retval
|
def substitute_variables(cmd, variables):
"""Given a cmd (str, list), substitute variables in it."""
if isinstance(cmd, list):
return [s.format(**variables) for s in cmd]
elif isinstance(cmd, str):
return cmd.format(**variables)
else:
raise ValueError(f"cmd: {cmd}: wrong type")
|
def print_character(ordchr: int) -> str:
"""Return a printable character, or '.' for non-printable ones."""
if 31 < ordchr < 126 and ordchr != 92:
return chr(ordchr)
return "."
|
def removeWhitespaces(target):
"""
this function takes in a string, and returns it after removing all
leading and trailing whitespeces
logic: to find a starting index and ending index to slice the string
"""
# initialise start and end variable
start = 0
end = len(target)
# find the first non-space char
for i in range(end):
if target[i] != " ":
start = i
break
# find the last non-space char
while end >= 1:
if target[end - 1] != " ":
break
end -= 1
# slice the string and return
return target[start:end]
|
def split_input(text):
"""Meh
>>> split_input(EXAMPLE)
[(0, 7), (1, 13), (4, 59), (6, 31), (7, 19)]
"""
lines = text.strip().split()
return list(
(i, int(bline)) for i, bline in enumerate(lines[1].split(",")) if bline != "x"
)
|
def find_col_index_with_name(name, trained_schema):
"""
finds the index of the column with name 'name' and returns the index
:param name: name of the column to look for
:type name: str
:param trained_schema:
:type trained_schema: List(dict)
:return: index of the element in trained_schema that has the given name
:rtype: int
"""
for i in range(len(trained_schema)):
if trained_schema[i]['name'] == name:
return i
return None
|
def get_params(context, *args):
"""
Get param from context
:param context: step context
:param args: A tuple containing value and parameter name
:return:
"""
items = []
for (val, param_name) in args:
if val is not None:
items.append(val)
elif hasattr(context, param_name):
items.append(getattr(context, param_name))
return items
|
def area(r, shape_constant):
"""Return the area of a shape from length measurement R."""
assert r > 0, 'A length must be positive'
return r * r * shape_constant
|
def sortNTopByVal(tosort, top, descending=False):
"""
Sort dictionary by descending values and return top elements.
Return list of tuples.
"""
return sorted([(k, v) for k, v in tosort.items()], key=lambda x: x[1], reverse=descending)[:top]
|
def remove_unknowns(disj):
"""
Filter out all conjunctions in a disjunction that contain 'Unknown' keywords.
This can be applied to the resulting value from `flatten_expr`
"""
return [conj for conj in disj if 'Unknown' not in conj]
|
def __get_int(section, name):
"""Get the forecasted int from xml section."""
try:
return int(section[name])
except (ValueError, TypeError, KeyError):
return 0
|
def human_format(num):
"""Format number to get the human readable presentation of it.
Args:
num (int): Number to be formatted
Returns:
str: Human readable presentation of the number.
"""
num = float("{:.3g}".format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude += 1
num /= 1000.0
return "{}{}".format(
"{:f}".format(num).rstrip("0").rstrip("."), ["", "k", "m", "b", "t"][magnitude]
)
|
def percfloat(a, b, ndigits=0):
"""Calculate a percent.
a {number} Dividend.
b {number} Divisor.
[ndigits] {int} Number of digits to round to. Default is 0.
return {float} quotient as a rounded percent value (e.g. 25.1 for .251)
"""
return int(round((a/float(b) * 100), ndigits))
|
def largest_continous(l):
"""
Runtime: O(n)
"""
max_sum = 0
start = 0
end = 1
while (end < len(l)):
if l[start] + l[start+1] > 0:
curr_sum = sum(l[start:end])
max_sum = max(curr_sum, max_sum)
end += 1
else:
# Start new sequence
start = end + 1
end = start + 1
return max_sum
|
def normalize_container(container: str) -> str:
"""Ensures all containers begin with a dot."""
assert container
if container and container[0] != ".":
container = f".{container}"
return container.lower()
|
def getNegativeSamples(target, dataset, K):
""" Samples K indexes which are not the target """
indices = [None] * K
for k in range(K):
newidx = dataset.sampleTokenIdx()
while newidx == target:
newidx = dataset.sampleTokenIdx()
indices[k] = newidx
return indices
|
def get_svg_string(svg):
"""Return the raw string of an SVG object with a ``tostring`` or ``to_str`` method."""
if isinstance(svg, str):
return svg
if hasattr(svg, "tostring"):
# svgwrite.drawing.Drawing.tostring()
return svg.tostring()
if hasattr(svg, "to_str"):
# svgutils.transform.SVGFigure.to_str()
return svg.to_str()
raise TypeError(f"SVG cannot be converted to a raw string: {svg}")
|
def first(xs, fn=lambda _: True, default=None):
"""Return the first element from iterable that satisfies predicate `fn`,
or `default` if no such element exists.
Args:
xs (Iterable[Any]): collection
fn (Callable[[Any],bool]): predicate
default (Any): default
Returns:
Any
"""
return next((i for i in xs if fn(i)), default)
|
def _ray_remote(function, params):
"""This is a ray remote function (see ray documentation). It runs the `function` on each ray worker.
:param function: function to be executed remotely.
:type function: callable
:param params: Parameters of the run.
:type params: dict
:return: ray object
"""
r = function(params)
return r
|
def tie_breaker_index(tie_breaker, name):
"""
Return the index of name in tie_breaker, if it is present
there, else return the length of list tie_breaker.
Args:
tie_breaker (list): list of choices (strings)
list may be incomplete or empty
name (str): the name of a choice
Returns:
(int): the position of name in tie_breaker, if present;
otherwise the length of tie_breaker.
Example:
>>> tie_breaker = ['a', 'b']
>>> tie_breaker_index(tie_breaker, 'a')
0
>>> tie_breaker_index(tie_breaker, 'c')
2
"""
if name in tie_breaker:
return tie_breaker.index(name)
return len(tie_breaker)
|
def parse_categories(anime):
"""Return list of category names.
Args:
anime: anime dictionary from `get_anime()`
Returns:
list: category names
"""
return [attr['attributes']['slug'] for attr in anime['included']]
|
def naive_string_matcher(string, target):
""" returns all indices where substring target occurs in string """
snum = len(string)
tnum = len(target)
matchlist = []
for index in range(snum - tnum + 1):
if string[index:index + tnum] == target:
matchlist.append(index)
return matchlist
|
def enable_custom_function_prefix(rq, prefix):
"""Add SPARQL prefixe header if the prefix is used in the given query."""
if ' %s:' % prefix in rq or '(%s:' % prefix in rq and not 'PREFIX %s:' % prefix in rq:
rq = 'PREFIX %s: <:%s>\n' % (prefix, prefix) + rq
return rq
|
def state_to_tuple(state):
"""
Converst state to nested tuples
Args:
state (nested list (3 x 3)): the state
Returns:
nested tuple (3 x 3): the state converted to nested tuple
"""
return tuple(tuple(row) for row in state)
|
def microsecond_to_cm(delta_microseconds: float) -> float:
"""
Convert ticks_diff(ticks_us(), ticks_us()) -> centimeters
- Divide by 2 to (the sound wave went "out" then "back")
- Divide by the speed of sound in microseconds
Speed of sound: 343.2 meters/second = 1cm/29.1 microseconds
:param float delta_microseconds: Pulse duration (microseconds)
:returns float:
"""
return (delta_microseconds / 2) / 29.1
|
def extract_timing_quality(trace):
"""Writes timing quality parameters and correction to source document."""
def __float_or_none(value):
"""Returns None or value to float."""
if value is None:
return None
return float(value)
trace = trace["miniseed_header_percentages"]
# Add the timing correction
return {
"timing_correction": __float_or_none(trace["timing_correction"]),
"timing_quality_min": __float_or_none(trace["timing_quality_min"]),
"timing_quality_max": __float_or_none(trace["timing_quality_max"]),
"timing_quality_mean": __float_or_none(trace["timing_quality_mean"]),
"timing_quality_median": __float_or_none(trace["timing_quality_median"]),
"timing_quality_upper_quartile": __float_or_none(trace["timing_quality_upper_quartile"]),
"timing_quality_lower_quartile": __float_or_none(trace["timing_quality_lower_quartile"])
}
|
def detect_format_from_data(data):
"""Try to detect the format of the given binary data and return None if it fails."""
fmt = None
try:
if b'<svg' in data[:500]:
fmt = 'svg'
elif data.startswith(b'%PDF'):
fmt = 'pdf'
elif data.startswith(b'%!PS'):
if b'EPS' in data[:100]:
fmt = 'eps'
else:
fmt = 'ps'
else:
import imghdr
fmt = imghdr.what(file=None, h=data)
assert fmt is not None
except Exception:
pass
return fmt
|
def word_score(word):
"""Returns the boggle score for a given word"""
wl = len(word)
if wl < 3:
return 0
if ((wl == 3) or (wl == 4)):
return 1
if wl == 5:
return 2
if wl == 6:
return 3
if wl == 7:
return 5
if wl >= 8:
return 11
|
def btod(binary):
"""
Converts a binary string to a decimal integer.
"""
return int(binary, 2)
|
def matrix_mul(m_a, m_b):
"""function that multiplies 2 matrices:
Args:
m_a (list int or float): Matrix a
m_b (list int or float): Matrix b
"""
if type(m_a) is not list:
raise TypeError("m_a must be a list")
if type(m_b) is not list:
raise TypeError("m_b must be a list")
for row in m_a:
if type(row) is not list:
raise TypeError("m_a must be a list of lists")
for row in m_b:
if type(row) is not list:
raise TypeError("m_b must be a list of lists")
if m_a is None or len(m_a) == 0:
raise ValueError("m_a can't be empty")
if m_b is None or len(m_b) == 0:
raise ValueError("m_b can't be empty")
length = len(m_a[0])
for row in m_a:
if row is None or len(row) == 0:
raise ValueError("m_a can't be empty")
if len(row) != length:
raise TypeError("each row of m_a must be of the same size")
for col in row:
if type(col) is not int and type(col) is not float:
raise TypeError("m_a should contain only integers or floats")
length = len(m_b[0])
for row in m_b:
if row is None or len(row) == 0:
raise ValueError("m_b can't be empty")
if len(row) != length:
raise TypeError("each row of m_b must be of the same size")
for col in row:
if type(col) is not int and type(col) is not float:
raise TypeError("m_b should contain only integers or floats")
if len(m_a[0]) != len(m_b):
raise ValueError("m_a and m_b can't be multiplied")
m_c = list()
for i in range(len(m_a)):
m_c.append(list([0] * len(m_b[0])))
for i in range(len(m_a)):
for k in range(len(m_b[0])):
for j in range(len(m_a[0])):
m_c[i][k] += m_a[i][j] * m_b[j][k]
m_c[i][k] = round(m_c[i][k], 2)
return m_c
|
def rfclink(string):
"""
This takes just the RFC number, and turns it into the
URL for that RFC.
"""
string = str(string);
return "https://datatracker.ietf.org/doc/html/rfc" + string;
|
def IsProcessAlive(pid, ppid=None):
"""Returns true if the named process is alive and not a zombie.
A PPID (parent PID) can be provided to be more specific to which process you
are watching. If there is a process with the same PID running but the PPID is
not the same, then this is unlikely to be the same process, but a newly
started one. The function will return False in this case.
Args:
pid: process PID for checking
ppid: specified the PID of the parent of given process. If the PPID does
not match, we assume that the named process is done, and we are looking at
another process, the function returns False in this case.
"""
try:
with open('/proc/%d/stat' % pid) as f:
stat = f.readline().split()
if ppid is not None and int(stat[3]) != ppid:
return False
return stat[2] != 'Z'
except IOError:
return False
|
def scientific(x, n):
"""Represent a float in scientific notation.
This function is merely a wrapper around the 'e' type flag in the
formatting specification.
"""
n = int(n)
x = float(x)
if n < 1: raise ValueError("1+ significant digits required.")
return ''.join(('{:.', str(n - 1), 'e}')).format(x)
|
def lens_rotation(alpha0, s0, dalpha, ds, t, tb):
"""Compute the angle alpha and projected separation s for each
time step due to the lens orbital motion.
:param alpha0: angle alpha at date tb.
:param s0: projected separation at date tb.
:param dalpha: float, angular velocity at date tb
(radians.year^-1).
:param ds: change rate of separation (year^-1).
:param t: list of dates.
:param tb: time reference for linear development.
:type alpha0: float
:type s0: float
:type dalpha: float
:type ds: float
:type t: numpy array
:type tb: float
:return: unpacked list of actual alpha and s values at each date.
:rtype: numpy array, numpy array
"""
Cte_yr_d = 365.25 # Julian year in days
alpha = alpha0 - (t - tb) * dalpha / Cte_yr_d
s = s0 + (t-tb) * ds / Cte_yr_d
return alpha, s
|
def addJunctionPos(shape, fromPos, toPos):
"""Extends shape with the given positions in case they differ from the
existing endpoints. assumes that shape and positions have the same dimensionality"""
result = list(shape)
if fromPos != shape[0]:
result = [fromPos] + result
if toPos != shape[-1]:
result.append(toPos)
return result
|
def parse_range(response):
"""Parse range response. Used by TS.RANGE and TS.REVRANGE."""
return [tuple((r[0], float(r[1]))) for r in response]
|
def arg_hex2int(v):
""" Parse integers that can be written in decimal or hex when written with 0xXXXX. """
return int(v, 0)
|
def which(cmd):
"""Same as `which` command of bash."""
from distutils.spawn import find_executable
found = find_executable(cmd)
if not found:
raise Exception("failed to find command: " + cmd)
return found
|
def texlabel(key, letter):
"""
Args:
key (list of string): list of parameter strings
letter (string): planet letter
Returns:
string: LaTeX label for parameter string
"""
if key.count('mpsini') == 1:
return '$M_' + letter + '\\sin i$'
if key.count('rhop') == 1:
return '$\\rho_' + letter + '$'
if key.count('a') == 1:
return "$a_" + letter + "$"
|
def _create_file_link(file_data, shock):
""" This corresponds to the LinkedFile type in the KIDL spec """
return {
'handle': shock['handle']['hid'],
'description': file_data.get('description'),
'name': file_data.get('name', ''),
'label': file_data.get('label', ''),
'URL': shock['handle']['url'] + '/node/' + shock['handle']['id']
}
|
def get_data(dataset):
"""
Returns data without the header row
"""
return dataset[1:len(dataset)]
|
def return_min_tuple(tuple1, tuple2):
"""
implement function min for tuples (dist, i, j)
"""
ret_tuple = tuple1
if tuple2[0] < tuple1[0]:
ret_tuple = tuple2
return ret_tuple
|
def _get_output_filename(dataset_dir, split_name):
"""Creates the output filename.
Args:
dataset_dir: The dataset directory where the dataset is stored.
split_name: The name of the train/test split.
Returns:
An absolute file path.
"""
return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name)
|
def _analyze_unittest_feeds(iterator):
"""Return statistics on the number of valid/empty/corrupt unittest feeds.
"""
feed_data_by_feed_url = {}
for (feed, timestamp, file_path) in iterator:
(feed_id, feed_url, _, _) = feed
if feed_url not in feed_data_by_feed_url:
feed_data_by_feed_url[feed_url] = {
'valid': 0,
'corrupt': 0,
'empty': 0
}
with open(file_path, 'r') as f:
content = f.read()
if content == '':
feed_data_by_feed_url[feed_url]['empty'] += 1
else:
try:
int(content)
feed_data_by_feed_url[feed_url]['valid'] += 1
except ValueError:
feed_data_by_feed_url[feed_url]['corrupt'] += 1
return feed_data_by_feed_url
|
def reverse_direction(graph):
""" returns a new graph = the original directed graph with all arcs reversed """
rev = {}
for node, neighbors in graph.items():
for nbr in neighbors:
if nbr in rev.keys():
rev[nbr].append(node)
else:
rev[nbr] = [node]
return rev
|
def escape(text: str) -> str:
"""
Replaces the following chars in `text` ('&' with '&', '<' with '<' and '>' with '>').
:param text: the text to escape
:return: the escaped text
"""
chars = {"&": "&", "<": "<", ">": ">"}
for old, new in chars.items(): text = text.replace(old, new)
return text
|
def get_feeds_links(data):
"""Extracts feed urls from the GTFS json description."""
gtfs_feeds_urls = []
for feed in data:
if feed["spec"] != "gtfs":
continue
if "urls" in feed and feed["urls"] is not None and feed["urls"]:
gtfs_feeds_urls.append(feed["urls"]["static_current"])
return gtfs_feeds_urls
|
def reachability_matrix(graph: list) -> list:
"""
DFS can be used to create it.
time complexity: O(V*(V+E)). For a dense graph E -> V*V, then it will become O(V^3)
space complexity: O(V) # not counting the matrix itself, which is O(V*V)
"""
def dfs(v1: int, v2: int): # O(V+E)
nonlocal dim
matrix[v1][v2] = 1
for i in range(dim):
if graph[v1][i] and not matrix[v1][i]:
matrix[v1][i] = 1
dfs(i, i)
dim: int = len(graph)
matrix: list = [[0] * dim for _ in range(dim)]
for i in range(dim): # O(V)
dfs(i, i)
return matrix
|
def apply_with_return_error(args):
"""
:see: https://github.com/ionelmc/python-tblib/issues/4
"""
return args[0](*args[1:])
|
def sample_n_unique(sampling_f, n):
"""Helper function. Given a function `sampling_f` that returns
comparable objects, sample n such unique objects.
"""
res = []
times_tried = 0
while len(res) < n and times_tried < 100:
candidate = sampling_f()
if candidate not in res:
res.append(candidate)
else:
times_tried += 1
return res
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.