content stringlengths 42 6.51k |
|---|
def _extract_args(cmd_line, args):
"""
Extract specified arguments and sorts them. Also removes them from the
command line.
:param cmd_line: Array of command line arguments.
:param args: List of arguments to extract.
:returns: A tuple. The first element is a list of key, value tuples represent... |
def sec_to_time(s):
""" Returns the hours, minutes and seconds of a given time in secs
"""
return (int(s//3600), int((s//60)%60), (s%60)) |
def get_ids_to_values_map(values):
"""
Turns a list of values into a dictionary {value index: value}
:param values: list
:return: dictionary
"""
return {id: category for id, category in enumerate(values)} |
def add_ul(text, ul):
"""Adds an unordered list to the readme"""
text += "\n"
for li in ul:
text += "- " + li + "\n"
text += "\n"
return text |
def get_names_in_waveform_list(waveform_list) -> list:
"""Gets the names of all Waveform objects in a list of Waveforms
Parameters
----------
waveform_list : list
A list of Waveform objects
Returns
-------
list
A list of the names of the Waveform objects in waveform_list
... |
def prod(iterable, start=1):
"""Multiplies ``start`` and the items of an ``iterable``.
:param iterable: An iterable over elements on which multiplication may be
applied. They are processed from left to right.
:param start: An element on which multiplication may be applied, defaults to
``1... |
def sum_of_digits(n: int) -> int:
"""
Find the sum of digits of a number.
>>> sum_of_digits(12345)
15
>>> sum_of_digits(123)
6
>>> sum_of_digits(-123)
6
>>> sum_of_digits(0)
0
"""
n = -n if n < 0 else n
res = 0
while n > 0:
res += n % 10
n = n // ... |
def exporigin(mode, db):
"""Return the expected origins for a given db/mode combo."""
if mode == 'local' and not db:
return 'file'
elif mode == 'local' and db:
return 'db'
elif mode == 'remote' and not db:
return 'api'
elif mode == 'remote' and db:
return 'api'
el... |
def conf_primary(class_result, ordinal):
"""
Identify the confidence of the primary cover class for the given
ordinal day. The days between and around segments identified through the
classification process comprise valid segments for this. They also receive
differing values based on if they occur at... |
def MakeDeclarationString(params):
"""Return a C-style parameter declaration string."""
string = []
for p in params:
sep = "" if p[1].endswith("*") else " "
string.append("%s%s%s" % (p[1], sep, p[0]))
if not string:
return "void"
return ", ".join(string) |
def is_iterable(x):
"""Returhs True if `x` is iterable.
Note:
This won't work in Python 3 since strings have __iter__ there.
"""
return hasattr(x, "__iter__") |
def make_str_from_column(board, column_index):
""" (list of list of str, int) -> str
Return the characters from the column of the board with index column_index
as a single string.
>>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
'NS'
>>> make_str_from_column([['r', 's'... |
def get_lang(filename):
""" get language from filename """
filename = filename.replace("_cn", '.zh').replace("_ch", '.zh').replace("_", ".")
if filename.endswith(".sgm") or filename.endswith(".txt"):
return filename.split('.')[-2]
else:
return filename.split('.')[-1] |
def num_bytes(byte_tmpl):
"""Given a list of raw bytes and template strings, calculate the total number
of bytes that the final output will have.
Assumes all template strings are replaced by 8 bytes.
>>> num_bytes([0x127, "prog_bytes"])
9
"""
total = 0
for b in byte_tmpl:
if i... |
def str2float(string: str) -> float:
"""Converts a string to a float."""
try:
if "/" not in string:
return float(string)
else:
return float(string.split("/")[0]) / float(string.split("/")[1])
except:
return 1.0 |
def human2bytes(size, unit, *, precision=2, base=1024):
"""
Convert size from human to bytes.
Arguments:
size (int): number
unit (str): converts from this unit to bytes
'KB', 'MB', 'GB', 'TB', 'PB', 'EB'
Keyword arguments (opt):
precision ... |
def split_url_path(url):
"""Split url into chunks"""
#Ensure trailing slash to get parts correct
if url =='' or url[-1] != '/':
url = url + '/'
parts = url.split('/')
try:
#Final part is now blank
return parts[0:-1]
except:
return parts |
def _vector_to_list(vectors):
""" Convenience function to convert string to list to preserve iterables. """
if isinstance(vectors, str):
vectors = [vectors]
return vectors |
def _add_char(num, char=' '):
"""Creates a string value give a number and character.
args:
num (int): Amount to repeat character
kwargs:
char (str): Character value to lopp
Returns (str): Iterated string value for given character
"""
string = ''
for i in range(num):
s... |
def indentation(level, word):
"""
Returns a string formed by word repeated n times.
"""
return ''.join([level * word]) |
def bootstrap_dirname(suite, arch):
"""From the suite/arch calculate the directory name to extract debootstrap into"""
return "./" + suite + "-" + arch |
def solve(task):
"""
:param task: string of the task to be evaluated
:return: if solved returns solution, else returns None
"""
try:
solution = eval(task)
return solution
except SyntaxError:
return None |
def organization_id(data: list, organization_ids: list) -> list:
"""
Select only features that contain the specific organization_id
:param data: The data to be filtered
:type data: dict
:param organization_ids: The oragnization id(s) to filter through
:type organization_ids: list
:return:... |
def count_bases(seq):
""""THis function is for counting the number of A's in the sequence"""
# Counter for the As
count_a = 0
count_c = 0
count_g = 0
count_t = 0
for b in seq:
if b == "A":
count_a += 1
elif b == "C":
count_c += 1
elif b == "G... |
def first(iterable):
""" Return the first object in an iterable, if any. """
return next(iterable, None) |
def linear_rampup(current, rampup_length):
"""Linear rampup"""
assert current >= 0 and rampup_length >= 0
if current >= rampup_length:
lr = 1.0
else:
lr = current / rampup_length
#print (lr)
return lr |
def rle_subseg( rle, start, end ):
"""Return a sub segment of an rle list."""
l = []
x = 0
for a, run in rle:
if start:
if start >= run:
start -= run
x += run
continue
x += start
run -= start
start = ... |
def intbase(dlist, b=10):
"""convert list of digits in base b to integer"""
y = 0
for d in dlist:
y = y * b + d
return y |
def search_global_list(id, list):
"""[summary]
Args:
id ([type]): [description]
list ([type]): [description]
Returns:
[type]: [description]
"""
for object in list:
if object._id == id:
return True
return False |
def sub_time_remaining_fmt(value):
"""
Finds the difference between the datetime value given and now()
and returns appropriate humanize form
"""
if not value:
return "EXPIRED"
days = int(value/24)
hours = value - days * 24
return "{} days {} hrs".format(days,hours) |
def convert_to_celsius(fahrenheit: float) -> float:
"""
:param fahrenheit: float
:return: float
"""
return (fahrenheit - 32.0) * 5.0 / 9.0 |
def numbits(num_values: int) -> int:
"""
Gets the minimum number of bits required to encode given number of different values.
This method implements zserio built-in operator numBits.
:param num_values: The number of different values from which to calculate number of bits.
:returns: Number of bits ... |
def _common_interval_domain(dom1, dom2):
""" Determine the interval domain that is common to two interval domains
Args:
dom1: First interval domain
dom2: Second interval domain
Returns:
Common domain
"""
return (max(dom1[0], dom2[0]), min(dom1[1], dom2[1])) |
def aidstr(aid, ibs=None, notes=False):
""" Helper to make a string from an aid """
if not notes:
return 'aid%d' % (aid,)
else:
assert ibs is not None
notes = ibs.get_annot_notes(aid)
name = ibs.get_annot_names(aid)
return 'aid%d-%r-%r' % (aid, str(name), str(notes)) |
def parse_distance(line):
"""Parse line to tuple with source, target and distance."""
cities, distance = line.split(' = ')
source, target = cities.split(' to ')
return source, target, int(distance) |
def get_box_delta(halfwidth):
"""
Transform from halfwidth (arcsec) to the box_delta value which gets added
to failure probability (in probit space).
:param halfwidth: scalar or ndarray of box sizes (halfwidth, arcsec)
:returns: box deltas
"""
# Coefficents for dependence of probability on ... |
def form_array_from_string_line(line):
"""Begins the inversion count process by reading in the stdin file.
Args:
line: A string of input line (usually from a text file) with integers
contained within, separated by spaces.
Returns:
array: List object (Python's standard '... |
def Garbage(length, uppercase=True, lowercase=True, numbers=True, punctuation=False):
"""\
Return string containing garbage.
"""
import random
uppercaseparts = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercaseparts = "abcdefghijklmnopqrstuvwxyz"
numberparts = "0123456789"
punctuationparts = ".-_"... |
def __compare(x, y):
"""
Parameters
----------
x : comparable
y : comparable
Returns
-------
result : int
Returns 1 if x is larger than y, -1 if x is smaller
then y, 0 if x equals y.
"""
if x > y:
return 1
elif x < y:
return -1
else:
... |
def _most_specific(a, b, default = None):
"""
If a and b are from the same hierarcy, return the more specific of
[type(a), type(b)], or the default type if they are from different
hierarchies. If default is None, return type(a), or type(b) if a
does not have a type_cls
"""
if (hasattr(a, 'type_cls') and h... |
def replace_version(content, from_version, to_version):
"""
Replaces the value of the version specification value in the contents of
``contents`` from ``from_version`` to ``to_version``.
:param content: The string containing version specification
:param to_version: The new version to be set
:re... |
def __get_base_name(input_path):
""" /foo/bar/test/folder/image_label.ext --> test/folder/image_label.ext """
return '/'.join(input_path.split('/')[-3:]) |
def row_has_lists(row: list) -> bool:
""" Returns if the dataset has list or not. """
for item in row:
if isinstance(item, list):
return True
return False |
def format_resp(number, digits=4):
"""
Formats a number according to the RESP format.
"""
format_string = "%%-10.%dE" % digits
return format_string % (number) |
def face_is_edge(face):
"""Simple check to test whether given (temp, working) data is an edge, and not a real face."""
face_vert_loc_indices = face[0]
face_vert_nor_indices = face[1]
return len(face_vert_nor_indices) == 1 or len(face_vert_loc_indices) == 2 |
def unescape(string):
"""Return unescaped string."""
return bytes(string, 'ascii').decode('unicode_escape') |
def test(name, age):
"""
Description: Function description information
Args:
name: name information
age: age information
Returns:
Returned information
Raises:
IOError: An error occurred accessing the bigtable.Table object.
"""
name = 'tom'
age = 11
re... |
def firstDateIsEarlier(d1, d2):
"""
Given dates in the form {"year":1970, "month": 01, "day": 01},
return True if the first date is the earlier of the two
"""
yyyymmdd1 = str(d1["year"]) + str(d1["month"]) + str(d1["day"])
yyyymmdd2 = str(d2["year"]) + str(d2["month"]) + str(d2["day"])
retur... |
def schedule_url(year, semester, subject, kind="all"):
"""
kind: All, UGRD, or GRAD
semester: Fall, Spring, or Summer
subject: an int; a key from constants.SUBJECTS
"""
return (
"http://registrar-prod.unet.brandeis.edu/registrar/schedule/classes"
f"/{year}/{semester}/{subject}/{k... |
def add_inverse(a, b):
"""Adds two values as a parallel connection.
Parameters
----------
a: float, ndarray
b: float, ndarray
Returns
-------
out: float
the inverse of the sum of their inverses
"""
if a and b:
return (a**(-1) + b**(-1))**(-1)
else:
r... |
def maxSeq(arr):
"""
A function to extract the sub-sequence of maximum length which
is in ascending order.
Parameters:
arr (list); the sequence from which the sub-sequence of maximum length
should be extracted
Returns:
maximumSeq (list); the sub-sequence of maxi... |
def order_verts(v1, v2):
"""
get order of vert inds for dihedral calculation.
"""
common_verts = set(v1).intersection(set(v2))
ordered_verts = [list(set(v1).difference(common_verts))[0],
list(common_verts)[0],
list(common_verts)[1],
list... |
def get_all_python_expression(content_trees, namespaces):
"""Return all the python expressions found in the whole document
"""
xpath_expr = (
"//text:a[starts-with(@xlink:href, 'py3o://')] | "
"//text:user-field-get[starts-with(@text:name, 'py3o.')] | "
"//table:table-cell/text:p[reg... |
def _sanitize_numbers(uncleaned_numbers):
"""
Convert strings to integers if possible
"""
cleaned_numbers = []
for x in uncleaned_numbers:
try:
cleaned_numbers.append(int(x))
except ValueError:
cleaned_numbers.append(x)
return cleaned_numbers |
def filter_empty_tracks(score):
"""
Filters out empty tracks and returns new score
"""
return list(filter(
lambda score_track: score_track,
score)) |
def region_states(pl, pr, region1, region3, region4, region5):
"""
:return: dictionary (region no.: p, rho, u), except for rarefaction region
where the value is a string, obviously
"""
if pl > pr:
return {'Region 1': region1,
'Region 2': 'RAREFACTION',
'Region... |
def find_all_indexes(input_str, search_str):
"""
Searches for substring/character in input_str
:param input_str: String in which to search substring
:param search_str: Substring to be searched
:return: Indexes of all substring matching position
"""
l1 = []
length = len(input_str)
index = 0
while ind... |
def abs_distance(temp_vals):
"""Takes a list of numbers and returns the idex of the number in the list
that has the smallest distance to 20.
Args:
temp_vals ([temp_vals]): List of numbers
Returns:
[Int]: Index of the number in the list that is closest to 20
Note:
If multip... |
def extract_qa_bits(band_data, bit_location):
"""Get bit information from given position.
Args:
band_data (numpy.ma.masked_array) - The QA Raster Data
bit_location (int) - The band bit value
"""
return band_data & (1 << bit_location) |
def no_float_zeros(v):
"""
if a float that is equiv to integer - return int instead
"""
if v % 1 == 0:
return int(v)
else:
return v |
def dmp_copy(f, u):
"""
Create a new copy of a polynomial ``f`` in ``K[X]``.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dmp_copy
>>> f = ZZ.map([[1], [1, 2]])
>>> dmp_copy(f, 1)
[[1], [1, 2]]
"""
if not u:
retu... |
def _NameValueListToDict(name_value_list):
"""Converts Name-Value list to dictionary.
Takes an array of strings of the form 'NAME=VALUE' and creates a dictionary
of the pairs. If a string is simply NAME, then the value in the dictionary
is set to True. If VALUE can be converted to an integer, it is.
"""
... |
def semeval_Acc(y_true, y_pred, score, classes=4):
"""
Calculate "Acc" of sentiment classification task of SemEval-2014.
"""
assert classes in [2, 3, 4], "classes must be 2 or 3 or 4."
if classes == 4:
total=0
total_right=0
for i in range(len(y_true)):
... |
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (iterable of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
""... |
def form_binary_patterns(k: int) -> list:
"""
Return a list of strings containing all binary numbers of length not exceeding 'k' (with leading zeroes)
"""
result = []
format_string = '{{:0{}b}}'.format(k)
for n in range(2 ** k):
result.append(format_string.format(n))
return result |
def sqlize_list(l):
""" magic """
return ', '.join(map(lambda x: "(\"{}\")".format(x), l)) |
def alternative_string_arrange(first_str: str, second_str: str) -> str:
"""
Return the alternative arrangements of the two strings.
:param first_str:
:param second_str:
:return: String
>>> alternative_string_arrange("ABCD", "XY")
'AXBYCD'
>>> alternative_string_arrange("XY", "ABC... |
def cohens_d(xbar, mu, s):
"""
Get the Cohen's d for a sample.
Parameters
----------
> xbar: mean of the sample
> mu: mean of the population
> s: standard distribution of the sample
Returns
-------
Cohen's d, or the number of standard deviations the sample mean is away from the population mean
... |
def camelcase(string):
"""Convert a snake_cased string to camelCase."""
if '_' not in string or string.startswith('_'):
return string
return ''.join([
x.capitalize() if i > 0 else x
for i, x in enumerate(string.split('_'))
]) |
def wrap_text(text, line_length):
"""Wrap a string of text based on the given line length.
Words that are longer than the line length will be split with a dash.
Arguments:
text (Str): the text that will be wrapped
line_length (Int): the max length of a line
Returns:
List [Str]
... |
def ordinal(num: int) -> str:
"""
Returns the ordinal representation of a number
Examples:
11: 11th
13: 13th
14: 14th
3: 3rd
5: 5th
:param num:
:return:
"""
return (
f"{num}th"
if 11 <= (num % 100) <= 13
else f"{num}{['th', '... |
def only_one_image(supdata, max):
"""Place have one image"""
return max == 1 or isinstance(supdata['photo_ref'], str) |
def pad_range_1d(low, high, amount):
"""Pad range by `amount`, keeping the range centered."""
pad = amount / 2
return low - pad, high + pad |
def resolve_insee_sqlfile(tablename):
"""Retrieve the name of the SQL file according to the name of the table
"""
name = "_".join(tablename.split("_")[:-1])
return "create_infra_" + name + ".sql" |
def get_identitypool_id(identitypools, name):
"""
Get identity pool id based on the name provided.
"""
for identitypool in identitypools:
if identitypool["Name"] == name:
return identitypool["Id"] |
def reverse(A):
"""
reverse an array: [3,6,7,9] = [9,7,6,3]~
"""
A_len = len(A)
for i in range(A_len // 2):
print("-----------------------")
print("Renge: %s" % i)
k = A_len - i - 1
print("k = %s" % k)
print("Before Change A[i] = %s, A[k] = %s " % (A[i], A[k])... |
def get_html_subsection(name):
"""
Return a subsection as HTML, with the given name
:param name: subsection name
:type name: str
:rtype: str
"""
return "<h2>{}</h2>".format(name) |
def chrom_header(sample_name: str) -> str:
"""Create final header line. Single sample only"""
s = "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{0}".format(
sample_name
)
return s |
def ine(x):
"""convert "" to None"""
if not x:
return None
return x |
def parse_imslp_date(year, month, day):
"""Return a date from imslp. Only return if all 3 components exist, and are integers
This prevents parsing items that only have some components (e.g. yyyy-mm), or approximate
values (e.g. c 1600)"""
if year and month and day:
try:
year = int(ye... |
def nl(h, q):
"""
h is a public key for NTRU Cryptosystem.
The private key [f, g] is in NTRU Lattice
[[I, H],
[O, qI]],
where H = cyclic permutations of the coefficients of h.
>>> h = [1, 2, 3]
>>> nl(h, 32)
[[ 1, 0, 0, 1, 2, 3],
[ 0, 1, 0, 3, 1, 2],
... |
def _transpose(list_):
"""
Transposes a list of lists.
"""
transposed_ = [[row[col] for row in list_] for col in range(len(list_[0]))]
transposed = [col for col in transposed_ if col]
return transposed |
def pi(dest, E):
"""Return ``s`` in ``(s, d, w)`` with ``d`` == `dest` and `w` minimized.
:param dest: destination vertex
:type dest: int
:param E: a set of edges
:type E: [(int, int, float), ...]
:return: vertex with cheapest edge connected to `dest`
:rtype: ... |
def dictlist_lookup(dictlist, key, value):
"""
From a list of dicts, retrieve those elements for which <key> is <value>.
"""
return [el for el in dictlist if el.get(key)==value] |
def three_points_to_rectangle_params(a, b, c):
"""Takes three corners of a rectangle and
returns rectangle parameters for matplotlib (xy, width, height)"""
x_low = min([a[0], b[0], c[0]])
y_low = min([a[1], b[1], c[1]])
x_high = max([a[0], b[0], c[0]])
y_high = max([a[1], b[1], c[1]])
xy = (... |
def sum_of_multiples(limit, multiples):
"""
Find the sum of all the unique multiples of particular numbers
up to but not including that number.
:param limit int - The highest resulting product of multiples.
:param multiples list - The multiples to multiply and sum.
:return int - The total o... |
def removeByTypesFromNested(l, typesRemove : tuple):
"""Remove items in the input iterable l which are of one of the types in
typesRemove
Args:
l : Input iterable
typesRemove (tuple): Input types to be removed
Returns: Iteratable with all nested items of the types removed
"""
#... |
def grid_enc_inv (w,l,k):
"""
Note: i, j, and c all start at 1
"""
i = ((k-1) % w)+1
j = (((k - i) % (w*l)))/w + 1
c = (k - i - ((j - 1) * w))/(w*l) + 1
return (i,j,c) |
def check_is_left(name):
"""
Checks if the name belongs to a 'left' sequence (/1). Returns True or
False.
Handles both Casava formats: seq/1 and 'seq::... 1::...'
"""
if ' ' in name: # handle '@name 1:rst'
name, rest = name.split(' ', 1)
if rest.startswit... |
def text_get_line(text, predicate):
"""Returns the first line that matches the given predicate."""
for line in text.split("\n"):
if predicate(line):
return line
return "" |
def _fetch_first_result(fget, fset, fdel, apply_func, value_not_found=None):
"""Fetch first non-none/empty result of applying ``apply_func``."""
for f in filter(None, (fget, fset, fdel)):
result = apply_func(f)
if result:
return result
return value_not_found |
def median(seq):
"""Returns the median of *seq* - the numeric value separating the higher half
of a sample from the lower half. If there is an even number of elements in
*seq*, it returns the mean of the two middle values.
"""
sseq = sorted(seq)
length = len(seq)
if length % 2 == 1:
... |
def _stringify_performance_states(state_dict):
""" Stringifies performance states across multiple gpus
Args:
state_dict (dict(str)): a dictionary of gpu_id performance state values
Returns:
str: a stringified version of the dictionary with gpu_id::performance state|gpu_id2::performance_sta... |
def _tagshortcuts(event, type, id):
"""given type=conv, type=convuser, id=here expands to event.conv_id"""
if id == "here":
if type not in ["conv", "convuser"]:
raise TypeError("here cannot be used for type {}".format(type))
id = event.conv_id
if type == "convuser":
... |
def parse_lambda_arn(function_arn):
"""Extract info on the current environment from the lambda function ARN
Parses the invoked_function_arn from the given context object to get
the name of the currently running alias (either production or development)
and the name of the function.
Example:
... |
def giftcertificate_order_summary(order):
"""Output a formatted block giving attached gift certifificate details."""
return {'order' : order} |
def _hex_to_triplet(h):
"""Convert an hexadecimal color to a triplet of int8 integers."""
if h.startswith('#'):
h = h[1:]
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)) |
def myFilter(f, L):
"""puts a function on each element of list"""
def filterHelp(f, L, lst):
if(L == []):
return lst
if(f(L[0])==True):
return filterHelp(f, L[1:], lst + [L[0]])
else:
return filterHelp(f, L[1:], lst)
return filterHelp(f, L, []) |
def initialize_beliefs(grid):
"""
Fill grid with intializ beliefs (continious distribution)
"""
height = len(grid)
width = len(grid[0])
area = height * width
belief_per_cell = 1.0 / area
beliefs = []
for i in range(height):
row = []
for j in range(width):
... |
def get_mpi_env(envs):
"""get the slurm command for setting the environment
"""
cmd = ''
for k, v in envs.items():
cmd += '%s=%s ' % (k, str(v))
return cmd |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.