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 th... |
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 = ... |
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 < ... |
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:
... |
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 =... |
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", "Cri... |
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/ye... |
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 ... |
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
... |
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 r... |
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
... |
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.P... |
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
... |
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... |
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'... |
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 ... |
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):
st... |
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 ... |
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, pre... |
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 =... |
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': {}}}}... |
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):
... |
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:
... |
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 conditi... |
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 ... |
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 ... |
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 tha... |
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, ... |
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:
magnit... |
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
... |
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"):
# svguti... |
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... |
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
""... |
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... |
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 matc... |
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 fl... |
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"... |
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'):
... |
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 li... |
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 proc... |
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
(ra... |
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... |
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:
... |
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':... |
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, spl... |
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_... |
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] = [no... |
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(... |
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"]["stati... |
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... |
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:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.