content stringlengths 42 6.51k |
|---|
def get_py_opening_comment(lines):
"""Parse the passed lines of a python script file for a top of file docstring.
This is used to get parameter and experiment file descriptions, so be sure to
always comment your code!"""
content = ""
def check_for_end(line):
if '"""' in line or "'''" in lin... |
def _check_params(params, error_callback):
"""Predicate function returning bool depending on conditions.
List of conditions:
- `host` and `key` must be specified in params,
- `dc` or `env` must be specified in params,
- `sections` must be specified in params.
Returns:
bool:... |
def CtlCode(device_type, function, method, access):
"""Prepare an IO control code."""
return (device_type << 16) | (access << 14) | (function << 2) | method |
def nmatches_table(txt, pat):
"""Find number or matches using table
nmatches_table(text, pattern)
"""
t, p = len(txt), len(pat)
dp = [[0 for _ in range(t+1)] for _ in range(p+1)]
for i in range(len(dp[0])):
dp[0][i]=1
for ip in range(p):
matches = 0
for ... |
def single_key(node):
""" Single key of node dict. """
count = 0
key = None # Avoid pylint warning
for key in node:
count += 1
assert count == 1
return key |
def sumOfSquares(a_list):
"""assumes a_list is a list of numbers
returns a number, the sum of each element**2 of a_list
"""
return sum([x**2 for x in a_list]) |
def machine_config(num_gpus=1, use_tpu=False, master_type=None):
"""Return dict specifying machine config for trainingInput."""
scale_tier = 'BASIC_GPU'
if use_tpu:
scale_tier = 'BASIC_TPU'
elif num_gpus <= 0:
scale_tier = 'BASIC'
elif num_gpus > 1:
scale_tier = 'CUSTOM'
config = {'scaleTier': ... |
def edgesFromNodeIndex(n, N, M):
"""Return the two edges coorsponding to node n AND return the index
of the node on the edge according to the size (N, M)"""
if n == 0:
return 0, 2, 0, 0
if n == 1:
return 0, 3, N - 1, 0
if n == 2:
return 1, 2, 0, M - 1
if n == 3:
r... |
def guess_family(h):
"""
Guess the AR family of a sequence header in ResFinder.
The last if statement and final return statement can take care
of most cases (such as blaXXX, QnrXXX, dfrXX), except e.g.
blaTEM members with capital characters on the end (e.g. blaTEM-1A).
Adding capital charact... |
def _QT(T, tQT):
"""
Basic function for calculating relaxation time due to
quantum tunneling
Input
T: temperature for the calculation
tQT: characteristic time for quantum tunneling
Output
tau: relaxation time due to quantum tunneling
"""
tau = tQT
return t... |
def empirical_power(n_tp, n_at):
"""Computer empirical power.
Input arguments:
================
n_tp : int
The observed number of true positives.
n_at : int
The number of hypotheses for which the alternative is true.
Output arguments:
=================
epwr : float
... |
def gmd(R, S, fm, fs):
"""
Args:
R (list of list): the partition, output of the entity resolution that we want to evaluate
S (list of list): the gold standard
fm(x,y) -> int (function): cost of merging a group of size x with another group of size y
fs(x,y) -> int (function... |
def find_seat_numbers(boarding_passes):
"""Determines the seat number of a boarding pass.
Boarding passes look like `FBFBBFFRLR` where the first
7 characters are the region the seat is in (halfing each time),
while the last three characters half the row the seat is in.
Total rows: 128 (0-127)
... |
def readable(file):
"""Return True if this file can be read from. """
return file.readable() |
def tag_list_to_dict(tags):
"""
Takes a list of dicts and makes a single dict
"""
new_tags = {}
for tag in tags:
new_tags.update({
tag["Key"]: tag["Value"]
})
return new_tags |
def _get_km_kn_shape(shape_a, shape_b, trans_a, trans_b):
"""get_km_kn_shape"""
shape_len = len(shape_a)
if trans_a:
m_shape = shape_a[shape_len - 1]
km_shape = shape_a[shape_len - 2]
else:
m_shape = shape_a[shape_len - 2]
km_shape = shape_a[shape_len - 1]
... |
def get_nested_key(dictionary, *keys):
"""
This dives into a dictionary or list without throwing a AttributeError or KeyError
"""
value = dictionary
try:
for key in keys:
value = value[key]
except Exception:
return None
return value |
def MOTA_frame(mapping_series, frame_id, gt_num, hp_num):
"""calculate MOTA of a frame
params
mapping_series: mapping for frame series
frame_id: id of frame which is processing
gt_num: object num of ground truth
hp_num: object num of hypothesis
-----------
return
MOTA: MOT... |
def isascii(text):
"""Test if ``text`` contains only ASCII characters.
:param text: text to test for ASCII-ness
:type text: ``unicode``
:returns: ``True`` if ``text`` contains only ASCII characters
:rtype: ``Boolean``
"""
try:
text.encode("ascii")
except UnicodeEncodeError:
... |
def mean(xs):
"""Computes and returns the arithmetic mean of the numbers in xs."""
sum_xs = 0.0
for n in xs:
sum_xs += n
return sum_xs/len(xs) |
def calc_intercsection_with_lightness_axis(inter_cusp, outer_cusp):
"""
calculate the intersection of the two cusps
and lightness axis in L*-Chroma plane.
Returns
-------
touple
(L*star, Chroma). It is the coordinate of the L_cusp.
"""
x1 = inter_cusp[1]
y1 = inter_cusp[0]
... |
def get_z_from_xy_values(info, x, y):
""" We fit a plane. """
return (info['z_alpha'] * x) + (info['z_beta'] * y) + info['z_gamma'] |
def bfs_traverse(graph, start):
"""
Traversal by breadth first search.
"""
visited, queue = set(), [start]
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
for next_node in graph[node]:
if next_node not in visited:
... |
def check(product, data):
"""Check if product does not exist in the data"""
if type(data) == dict:
data = data.values()
for d in data:
if product == d:
return False
return True |
def rotate90_augment(aug=None, is_training=True, **kwargs):
"""Rotation by 90 degree augmentation."""
del kwargs
if aug is None:
aug = []
if is_training:
return aug + [('rotate90', {})]
return aug |
def iob_ranges(words, tags):
"""
IOB -> Ranges
"""
assert len(words) == len(tags)
ranges = []
def check_if_closing_range():
if i == len(tags) - 1 or tags[i + 1].split('_')[0] == 'O':
ranges.append({
'entity': ''.join(words[begin: i + 1]),
'typ... |
def indent(s, n=1, indent_str=" "):
"""Inserts `n * indent_str` at the start of each non-empty line in `s`."""
p = n * indent_str
return "".join((p + l) if l.lstrip() else l for l in s.splitlines(True)) |
def gen_owner_html(owners_lst: tuple):
"""Generate the owner html"""
# First owner will always be main and hence should have the crown, set initial state to crown for that
owners_html = '<span class="iconify" data-icon="mdi-crown" data-inline="false"></span>'
owners_html += "<br/>".join([f"<a class='lon... |
def make_list_hexadecimal(value):
"""Turn comma separated string into ditto hexadecimal list."""
value_hexadecimal = []
for val in value:
value_hexadecimal.append("0x%x" % val)
return value_hexadecimal |
def lim_growth(x, s, b0, k):
"""
Function for limited growth. Used in several fits, thus it is implemented
here as a raw function, which can be used in closures, inlining etc.
Parameters
----------
x : float, int, np.ndarray
x values of the growth function.
s : float, optional
... |
def _generate_args_view(args, kwargs):
"""Generate a string representing the arguments given.
All arguments and keyword arguments are separated by ", ".
All keyword arguments are in the form name=value.
:param args: a tuple containing the arguments
:type args: tuple
:param kwargs: a dict containing key/value pai... |
def get_bucket_key(event):
"""
arg:
event: s3 trigger event
return:
bucket, key: bucket and key of the event
"""
bucket = event["Records"][0]["s3"]["bucket"]["name"]
key = event["Records"][0]["s3"]["object"]["key"]
return bucket, key |
def commonPrefix(strings):
""" Find the longest string that is a prefix of all the strings.
"""
if not strings:
return ''
prefix = strings[0]
for s in strings:
if len(s) < len(prefix):
prefix = prefix[:len(s)]
if not prefix:
return ''
for i in ... |
def fix_url(url):
"""Prefix a schema-less URL with http://."""
if '://' not in url:
url = 'http://' + url
return url |
def areaSqr(side: float) -> float:
"""Finds area of square"""
area: float = side ** 2
return area |
def split(string, char):
""" Split a string with a char and return always two parts"""
string_list = string.split(char)
if len(string_list) == 1:
return None, None
return char.join(string_list[:-1]), string_list[-1] |
def is_palindrome(n):
"""Returns if a number is a palindrome"""
return str(n) == str(n)[::-1] |
def ipea_filter_by_date(start=None, end=None):
"""
Filter an IPEA time series by date.
Parameters
----------
start : str
Start date string.
End : str
End date string.
Returns
-------
str
A string to filter by dates.
Examples
--------
>>> url.ip... |
def get_short_description(description, length):
"""
get_short_description(str description, int length) -> str - get
short description
"""
if description is None:
return None
l = len(description)
if l <= 3:
return description
if length-3 <= 0:
return '...'
retu... |
def doc_generator(docstring, attributes):
"""Utility function to augment BaseDataType docstring.
:param str docstring: docstring to augment
:param dict attributes: attributes to add to docstring
"""
docstring = docstring or ""
def bullet(title, text):
return """.. attribute:: %s\n\n ... |
def find_min_2(array: list) -> list:
"""
Best Case:
Worst Case: O(n)
:param array: list of integers
:return: integer
"""
min_so_far = array[0]
for i in array:
if i < min_so_far:
min_so_far = i
return min_so_far |
def _parens_around_char(label):
"""Place parens around first character of label.
:param str label: Must contain at least one character
"""
return "({first}){rest}".format(first=label[0], rest=label[1:]) |
def intersection(bb1, bb2):
""" Calculates the Intersection of two aabb's
"""
min_w = min(bb1[2], bb2[2])
min_h = min(bb1[3], bb2[3])
if bb1[0] < bb2[0]:
leftbb, rightbb = bb1, bb2
else:
leftbb, rightbb = bb2, bb1
if bb1[1] < bb2[1]:
topbb, bottombb = bb1, bb2
el... |
def commonChild(s1, s2):
"""
Args:
s1 (str): first string
s2 (str): second string
Returns:
int: common child max len"""
prev = [0] * (len(s2) + 1)
curr = [0] * (len(s2) + 1)
# loop each string
# increase max common child count if common char is found
for s1_char... |
def search_theme(plot):
"""
>>> search_theme(['get up', 'discussion'])
['loss', 'loss']
"""
plot = ['loss', 'loss']
return plot |
def dist_difference(actual_distribution, expected_distribution):
"""Calculate the difference between two distributions."""
difference = {}
for k, v in expected_distribution.items():
difference[k] = actual_distribution[k] - v
return difference |
def sizeof_fmt(num, suffix='b'):
"""
straight from https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
"""
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
n... |
def kalkulasi_kecepatan_awal(
kecepatan_akhir: float, perecepatan: float, waktu: float
) -> float:
"""
Menghitung kecepatan awal dari suatu pergerakan
dengan percepatan yang berbeda
>>> kalkulasi_kecepatan_awal(10, 2.4, 5)
-2.0
>>> kalkulasi_kecepatan_awal(10, 7.2, 1)
2.8
"""
# j... |
def extract_page_id(full_file_name: str) -> str:
"""
Extract page id from file_name
Example:
Data-loss-94d44921-0a4c-4319-8f78-60ef45267d97.md -> 94d449210a4c43198f7860ef45267d97
"""
file_name, _ = full_file_name.rsplit('.', maxsplit=1)
parts = file_name.rsplit('-', maxsplit=5)
id_... |
def parity(x,N,sign_ptr,args):
""" works for all system sizes N. """
out = 0
s = args[0] # N-1
#
out ^= (x&1)
x >>= 1
while(x):
out <<= 1
out ^= (x&1)
x >>= 1
s -= 1
#
out <<= s
return out |
def string_boolean(value):
"""Determines the boolean value for a specified string"""
if value.lower() in ('false', 'f', '0', ''):
return False
else:
return True |
def _reachable(graph):
"""Return a dictionary with all reachable nodes from the graph nodes.
Args:
graph: dict: dictionary representing a graph. Keys are the nodes
and values is a set containing the linked nodes.
Returns:
a new dictionary with the same keys, but whose values are al... |
def detectFname(path):
"""
Parses filepath for the filename
:returns filename
"""
loc = path.rfind("/")
if (loc == -1):
return path
else:
return path[loc + 1:] |
def bytes_to_gb(number: float) -> float:
"""
Convert bytes to gigabytes.
Parameters
----------
number : float
A ``float`` in bytes.
Returns
-------
float
Returns a ``float`` of the number in gigabytes.
"""
return round(number * 1e-9, 3) |
def button_string(channel, red, blue):
"""Returns the string representation of Combo Direct Mode button."""
return 'CH{:s}_{:s}_{:s}'.format(channel, red, blue) |
def offset_3p(cov, offsets_3p):
"""
Return appropriate offset for 3' transcript ends based on average transcript coverage.
"""
return offsets_3p[0] * cov + offsets_3p[1] |
def hk_st_enabled(bits: list) -> bytes:
"""
First bit should be on the left, bitfield is read from left to right
"""
enabled_bits = 0
bits.reverse()
for i in range(len(bits)):
enabled_bits |= bits[i] << i
return enabled_bits.to_bytes(2, byteorder='big') |
def _default_varlists(dataset):
"""
Return a list of default variables to select and send to the NSIDC subsetter.
"""
common_list = ["delta_time", "latitude", "longitude"]
if dataset == "ATL06":
return common_list + [
"h_li",
"h_li_sigma",
"atl06_quality_... |
def all_entries_of_type(sequence, test_type):
"""
If all elements of sequence are of type test_type, return True, else False.
"""
return sum([int(type(x)==test_type) for x in sequence]) == len(sequence) |
def contains_alpha(text: str) -> bool:
"""If text contains alphabet, return True."""
for character in text:
if character.isalpha():
return True
return False |
def safe_divide(a: float, b: float):
"""Divide that returns zero if numerator and denominator are both zero."""
if b == 0.0:
assert a == 0.0
return 0.0
return a / b |
def emoticons(percent):
"""Display an emoticon face according to the result."""
if percent == 100:
emoticon = ':-)'
elif percent >= 50 < 100:
emoticon = ':-|'
elif percent >= 20 < 50:
emoticon = ':-('
else:
emoticon = ':_('
return emoticon |
def sclip(x, lower=None, upper=None, keepType=False):
"""
Clips the scalar value `x` to the interval [`lower`, `upper`].
Each of `lower` and `upper` can be `None`, meaning no clipping. If
`keepType` is `True`, the returned result has the same type as the input
`x`, otherwise it has either the type ... |
def hailstone(n):
"""Print the hailstone sequence starting at n and return its
length.
>>> a = hailstone(10)
10
5
16
8
4
2
1
>>> a
7
"""
"*** YOUR CODE HERE ***"
i,length = n,1
while i>1:
print(i)
if i%2==0:
i = i//2
el... |
def estimate_count_sql(name):
"""
Generate SQL to estimate the number of rows in a table
See https://wiki.postgresql.org/wiki/Count_estimate
:param name: table name
:return: SQL string
"""
return f"SELECT reltuples::BIGINT AS estimate FROM pg_class WHERE relname='{name}';" |
def lowercase(text):
"""Return lowercased string"""
output = text.lower()
return output |
def filter_for_dataset(dataset_hash, items):
"""
Return only the subset of items that is related to the dataset_hash
"""
filtered = []
for item in items:
if item['file'].startswith(dataset_hash):
filtered.append(item)
return filtered |
def choose_NT(N_max,iffreq=True):
""" calculates number of time samples required to constrain N_max modes
--- equation (21) from Sanders & Binney (2014) """
if(iffreq):
return max(200,9*N_max**3/4)
else:
return max(100,N_max**3/2) |
def num_zero(n):
"""
Number of modes with nonzero horizontal wavenumber in the
system with n total modes of the HK hierarchy.
"""
shells = [4,10,18,28,40,54,70,88,108,130,154,180,208,238]
return min([i+1 for i in range(len(shells)) if shells[i] >= n]) |
def decimalToString(val):
"""
Convert a decimal into a string.
The advantage over applying "str" on a decimal is that the string representation returned here
is minimal, i.e. no unnecessary trailing zeros or dot
Params:
- val (decimal.Decimal): Decimal to convert
Return (str): String repre... |
def inv_symmetric_3x3(
m11,
m22,
m33,
m12,
m23,
m13,
):
"""
Explicitly computes the inverse of a symmetric 3x3 matrix.
Input matrix (note symmetry):
[m11, m12, m13]
[m12, m22, m23]
[m13, m23, m33]
Output matrix (note symmetry):
[a11, a1... |
def _get_or_create_preprocess_rand_vars(generator_func,
function_id,
preprocess_vars_cache,
key=''):
"""Returns a tensor stored in preprocess_vars_cache or using generator_func.
If the tensor was... |
def team_year_key(*args):
"""
Create a key string to identify a combination of team and year.
If 2 arguments are passed, it assumes it must construct a key from a pair of
team and year.
If 1 argument is passed, it assumes it is a key and must de-construct it
into a team and year pair.
"""
... |
def compute_total_time(job_cost_map, proc_pool):
"""
Given a map: jobname -> (procs, est-time), return a total time
estimate for a given processor pool size
>>> job_cost_map = {"A" : (4, 3000), "B" : (2, 1000), "C" : (8, 2000), "D" : (1, 800)}
>>> compute_total_time(job_cost_map, 8)
5160
>>... |
def _access_list(index, iterable):
"""Accessing list by index, different behaviour for negative or
out-of-bounds indices.
:param index: An index we wan to access.
:param iterable: An indexable iterable object which we want to access.
:return: Return the stored value for the corresponding index, if ... |
def permutations_exact(n, k):
"""Calculates permutations by integer division.
Preferred method for small permutations, but slow on larger ones.
Note: no error checking (expects to be called through permutations())
"""
product = 1
for i in range(n - k + 1, n + 1):
product *= i
retur... |
def dot_product(A, B):
"""
Perform a dot product of two vectors or matrices
:param A: The first vector or matrix
:param B: The second vector or matrix
"""
# Section 1: Ensure A and B dimensions are the same
rowsA = len(A)
colsA = len(A[0])
rowsB = len(B)
colsB = len(B[0])... |
def c_nk(n, k):
"""Binomial coefficient [n choose k]."""
if n < k:
return 0
if k > n // 2:
k = n - k
s, i, j = 1, n, 1
while i != n - k:
s *= i
s //= j
i -= 1
j += 1
return s |
def fib2(n):
"""Zwraca liste liczb Fibonacciego mniejszych niz n
"""
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result |
def time_str_ms(delta):
"""Print a hh:mm::ss.fff time"""
fraction = delta % 1
delta -= fraction
delta = int(delta)
seconds = delta % 60
delta /= 60
minutes = delta % 60
delta /= 60
hours = delta
return '%02u:%02u:%02u.%03u' % (hours, minutes, seconds, fraction * 1000) |
def slow_fib(n):
"""This is a very slow implementation
the fibonacci sequence because we are generating
a tree recursion, which means a lot of
redundant computations are happening.
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
return slow_fib(n-1) + slow_fib... |
def sum_multiples_3_and_5(number):
"""Returns the sum of all multiples of 3 and 5 below a given number.
"""
# The first possible integer multiple of 3 and 5 is 3:
counter = 3
# Multiples of 3 and 5 start at 3 and increase according to a pattern:
pattern = (i for i in [2, 1, 3, 1, 2, 3, 3])
s... |
def complete_re(regex_str):
"""Add ^$ to `regex_str` to force match to entire string."""
return "^" + regex_str + "$" |
def p_seg(seg):
"""
String of segment
:param seg: segment
:return: lowercase %segment
"""
return '%' + str(seg).lower() |
def parse_result_line(line):
"""
Params:
line(str):
Returns:
Tuple[str, str, int]:
"""
typename, sep, doc = [x.strip() for x in line.partition(":")]
if not sep:
return typename, "", 0
return typename, doc, 0 |
def numInvalidBytes(data):
"""
Returns the number of invalid bytes in a byte string.
"""
count = 0
for b in data:
if b < 0x20 or 0x80 <= b:
count += 1
return count |
def unnestedDict(exDict):
"""Converts a dict-of-dicts to a singly nested dict for non-recursive parsing"""
out = {}
for kk, vv in exDict.items():
if isinstance(vv, dict):
out.update(unnestedDict(vv))
else:
out[kk] = vv
return out |
def enrich_field(field_type, field):
"""
Semantically enrich a field name with its type
:Example:
>> enrich_field('date', birth)
'birth date'
.. todo:: Generalizing the research of hyponyms using a lexical database such as wordnet
"""
# use field type
if field_ty... |
def findCameraInArchive(camArchives, cameraID):
"""Find the entries in the camera archive directories for the given camera
Args:
camArchives (list): Result of getHpwrenCameraArchives() above
cameraID (str): ID of camera to fetch images from
Returns:
List of archive dirs that matchi... |
def missing_layers(dm_layers, ds_layers):
"""Find missing datamodel-layers in datasets."""
layers = [i.lower() for i in ds_layers]
layers = [i for i in dm_layers if i not in layers]
return layers |
def _nice_down(down):
"""Returns the integer down with a suffix. e.g., `1st`."""
return {
1: '1st', 2: '2nd', 3: '3rd', 4: '4th',
}.get(down, '???') |
def iteratively_query_dict(path: list, d: dict):
"""
Query a multidimensional dict with a list as the key.
:param path:
:param d:
:return:
"""
tmp = d
for key in path:
tmp = tmp[key]
return tmp |
def new_workflow_metadata_required( trans, repository_metadata, metadata_dict ):
"""
Currently everything about an exported workflow except the name is hard-coded, so there's no real way to differentiate versions of
exported workflows. If this changes at some future time, this method should be enhanced acc... |
def int_from_str(s):
"""Converts a string into an integer.
:param s: The string to convert into an integer.
"""
toret = 0
if (s
and s.strip()):
s = s.strip()
try:
toret = int(s)
except ValueError:
toret = 0
return toret |
def deg_to_hms(deg):
"""Convert decimal degrees to (hr,min,sec)"""
h = int(deg)//15
deg -= h*15
m = int(deg*4)
s = (deg-m//4)/15.
return h,m,s |
def is_smaller_chrom(chrA, chrB):
"""
Test if chrA is naturally less than chrB
Returns True if chrA == chrB so comparison will default to position
"""
if chrA.startswith('chr'):
chrA = chrA[3:]
if chrB.startswith('chr'):
chrB = chrB[3:]
# Numeric comparison, if possible
... |
def normalize_numeric_with_zscore(col, mean, std):
"""
INPUT:
- col (string)
- mean (float)
- std (float)
OUTPUT:
- zscored features
"""
return (col - mean)/std |
def _gf2mulxinvmod(a,m):
"""
Computes ``a * x^(-1) mod m``.
*NOTE*: Does *not* check whether `a` is smaller in degree than `m`.
Parameters
----------
a, m : integer
Polynomial coefficient bit vectors.
Polynomial `a` should be smaller degree than `m`.
Returns
-------
... |
def AND( *args ):
""" 'AND' all of the `args` together and return the result """
result = 1
for arg in args:
result = result and arg
return int( result ) |
def _safe_repr(obj):
"""Try to return a repr of an object
always returns a string, at least.
"""
try:
return repr(obj)
except Exception as e:
return "un-repr-able object (%r)" % e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.