content stringlengths 42 6.51k |
|---|
def parse_one_line(line):
""" Get one line of a file in this format
16:17:266:2864 3:4:194:2443
and return a couple of lists
[16,17,266,2864], [3,4,194,2443]
"""
line_trial, line_success = line.split(' ')
one_trial = [int(s) for s in line_trial.split(':')]
one_success = [... |
def normalize(pos, size, flip_y=False):
"""
normalize return as float
"""
width, height = size
x = pos[0]
y = pos[1]
x /= float(width)
y /= float(height)
if flip_y:
return x, 1 - y
return x, y |
def students_check_types(row: tuple) -> bool:
"""Returns true if row containing students data has correct types"""
try:
index = int(row[1])
if index < 100000 or index > 999999:
return False
except ValueError:
return False
if not isinstance(row[2], str):
return... |
def scale_p(p, L, pc, nu):
"""
Scales the probability p according to finite size scaling.
:param p: List of values p to be scaled.
:param L: System size.
:param pc: Critical threshold.
:param nu: Critical exponent.
:return list: Scaled probabilites.
"""
return (p - pc) * L*... |
def get_geo_list(geo_lists, geo_filter, add_select=False, user_filter=[]):
"""Get specific Organisational units based on filter and list."""
area_detail, result = {}, ()
if add_select:
area_detail[''] = 'Please Select'
try:
if geo_lists:
for i, geo_list in enumerate(geo_list... |
def digitsum(s: str) -> int:
"""
>>> all(digitsum(str(i)) == (1 if i == 1 else 0) for i in range(100))
True
"""
i = sum(pow(int(c), 5) for c in s)
return i if i == int(s) else 0 |
def calc_total_probe_depth(capture_data):
"""Takes a capture dict and returns a tuple containing the percentage of nucleotide positions
in the target space covered by 0, 1, 2, 3, 4, and 5+ probes."""
total = 0
total_0 = 0
total_1 = 0
total_2 = 0
total_3 = 0
total_4 = 0
total_5 = 0
... |
def closest_pair_strip(cluster_list, horiz_center, half_width):
"""
Helper function to compute the closest pair of clusters in a vertical strip
Input: cluster_list is a list of clusters produced by fast_closest_pair
horiz_center is the horizontal position of the strip's vertical center line
half_wi... |
def _parse_int(value, default=0):
"""
Attempt to cast *value* into an integer, returning *default* if it fails.
"""
if value is None:
return default
try:
return int(value)
except ValueError:
return default |
def insertion_sort(A):
"""Sort list of comparable elements into nondecreasing order."""
for i in range(1, len(A)):
value = A[i]
hole = i
while hole > 0 and A[hole-1] > value:
A[hole] = A[hole-1]
hole -= 1
A[hole] = value
return A |
def est_bien_par_pile(word):
"""verifie la validite d'un mot donne (par pile)"""
stack = []
for c in word:
if c == "(":
stack.append(c)
elif len(stack) == 0:
return False
else:
stack.pop()
return len(stack) == 0 |
def get_space(metric_name, maximum_metric_size):
"""
Gets the space to create a tabulation.
:param metric_name: the metric name
:type metric_name: str
:param maximum_metric_size: the maximum size of the metric name
:type maximum_metric_size: int
:return: the spaces to be appended to the mes... |
def in_symbols(category):
"""Category for code points that are symbols.
Args:
category (str): Unicode general category.
Returns:
bool: True if `category` in set.
"""
return category in {'Sm', 'Sc', 'Sk', 'So'} |
def isiterable(target):
"""
Check if target object is iterable
:param target:
:return: true if target is iterable. Otherwise, return false
"""
try:
iter(target)
except:
return False
else:
return True |
def numpydoc_str_param_list(iterable, indent=4):
"""
Format a list of numpydoc parameters.
Parameters
-------------
iterable : :class:`list`
List of numpydoc parameters.
indent : :class:`int`
Indent as number of spaces.
Returns
-------
:class:`str`
"""
out =... |
def xor_vec(in_val, mask_vec):
"""
Returns the XOR of bits from the result of masking bin_vec with the
mask vector mask_vec.
"""
and_val = in_val & mask_vec
return (bin(and_val).count('1') % 2) |
def parse_http_response(data):
""" don't try to get the body, there are reponses without """
header = data.split('\r\n\r\n')[0]
lines = header.split('\r\n')
cmd = lines[0].split(' ')
lines = map(lambda x: x.replace(': ', ':', 1), lines[1:])
lines = filter(lambda x: len(x) > 0, lines)
head... |
def node_int(node):
"""Returns stripped node text as int, or None."""
if node is None:
return None
text = node.text.strip()
if text.lower() == 'none':
return None
if len(text):
return int(text)
return None |
def provision(tup):
"""
Convert a type URI 9-tuple into a well-formed URI string
"""
#Partitioning
type, name, secret, issuer, algorithm, digits, period = tup
#Assembling
uri = "otpauth://" + type + "/" + issuer + ":" + name + "?" +\
"secret=" + secret +\
"&issuer=" + issuer +\
"&algorithm=" + algorithm.uppe... |
def mean(x):
"""Find the mean of a sample by summing the values and dividing by the size of the sample."""
return sum(x) / len(x) |
def mass_function_abc(m, a, b, c):
"""The parametrized surpression function of the halo mass function"""
return (1 + (a / m)**b )**c |
def is_number(s):
"""check if a data type is numeric
https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float?page=1&tab=votes#tab-top
Arguments:
s {[int,float,str]} -- input to test
Returns:
bool -- is the input a number
"""
try:
float(s)... |
def create_response(status, success=0, failure=0, repository_name=None, branch_name=None):
"""
:param status: Status of EBS deletion request.
:param success: Number of EBS volumes that are deleted successfully.
:param failure: Number of EBS volumes that are not deleted.
:param repository_name: Full ... |
def Upper(v):
"""Transform a string to upper case.
>>> s = Schema(Upper)
>>> s('hi')
'HI'
"""
return str(v).upper() |
def get_hit_dice(monster_data) -> str:
"""Fixes the missing extra HP in the API's hit_dice property."""
# Parse the hit dice string
num, sides = monster_data['hit_dice'].split('d')
num = int(num)
sides = int(sides)
# Predict the total hit points without the bonus
avg_roll = sides / 2 + 0.5
... |
def _label(files_info):
"""Get a suitable label for the files.
Returns "config-2" if the openstack metadata is present.
"""
if any(x.startswith('openstack/') for x in files_info.values()):
return 'config-2'
else:
return 'VMEDIA_BOOT_ISO' |
def package_dir_path(path):
"""Return package path to package install directory"""
return path + '/.pkg' |
def get_grand_mean(samples):
"""
Get the grand mean for a number of samples, or a number of means.
Parameter
---------
> `samples`: A tuple containing a list of samples, or a list of means.
- If the lists are samples, send them like `get_grand_mean([1,2,3,...], [3,4,5,...], [4,5,6,6,7,....], ...)`
Her... |
def cds_query(ra, dec, radius=1.):
"""
Open browswer with CDS catalog query around central position
"""
#rd = self.get('pan fk5').strip()
rd = f'{ra} {dec}'
rdst = rd.replace('+', '%2B').replace('-', '%2D').replace(' ', '+')
url = (f'http://vizier.u-strasbg.fr/viz-bin/VizieR?'
f'-... |
def _make_degrees_digital(parts, max_deg):
"""Assemble the degrees, minutes, and seconds parts from a regular expression result into a decimal number.
"""
num = float(parts['deg'])
if num > max_deg or num < max_deg*-1:
raise ValueError('degrees out of range {}/{}'.format(max_deg*-1, max_deg))
... |
def extract_from_config(config):
"""
When parsing, config can be wraped at dictionary where 'config' contains given config
"""
if isinstance(config, dict) and 'config' in config:
return config['config']
return config |
def divideset(rows, column, value):
"""
Divides the dataset according to an attribute.
param row -- row in dataset
param column -- column in dataset
param value -- dividing threshold
"""
set1 = []
set2 = []
for row in rows:
if row[column] > value:
set1.append(row)
else... |
def _get_type_string(attr_type):
"""Return a string represeting acceptable type(s)."""
if isinstance(attr_type, (list, tuple)):
if len(attr_type) > 1:
return (
", ".join([x.__name__ for x in attr_type[:-1]])
+ " or "
+ attr_type[-1].__name__
... |
def _index_store_path_overridden(copts):
"""Checks if index_while_building must be disabled.
Index while building is disabled when the copts include a custom
`-index-store-path`.
Args:
copts: The list of copts to be scanned.
Returns:
True if the index_while_building must be disabl... |
def bytes_hex(a):
"""
Encode `bytes` into hex on Python 2 or 3.
"""
if hasattr(a, 'hex'):
return a.hex()
return a.encode('hex') |
def rev_comp(seq):
"""Take the reverse compliment of a sequence
Parameters
----------
seq : str
The original sequence.
Returns
-------
new_seq : str
The reverse compliment.
"""
compliment = {"A": "T", "C": "G", "G": "C", "T": "A"}
new_seq = seq[::-1]
new_seq... |
def uniq(objectSequence):
"""Remove the duplicates from a list while keeping the original
list order """
l = []
d = {}
for o in objectSequence:
if o not in d:
d[o] = None
l.append(o)
return l |
def create_session(user_data: dict) -> bytes:
""" Create session based on dict
param data: {"username": username, "secret": password}
return: key value pairs in "key1=value1;key2=value2;"
"""
session = ""
for k, v in user_data.items():
session += f"{k}={v};"
return session.encode() |
def get_nelems(arrays):
"""Computes number of elements from given arrays using the triangular flag.""" # NOQA
nelems = 0
for local_arrays in arrays:
for array, triangular in local_arrays:
if triangular:
if array.shape[0] != array.shape[1]:
raise Runti... |
def prefix_suffix_prep(string1, string2):
"""Calculates starting position and lengths of two strings such
that common prefix and suffix substrings are excluded.
Expects len(string1) <= len(string2)
Parameters
----------
string_1 : str
Base string.
string_2 : str
The string t... |
def check_fit(function, xdata, ydata, func_params):
"""Check the difference between data and a fit to that data.
Parameters
----------
function : callable
A function to use to generate data points from input values.
xdata : array_like
An array of values of shape (N, M) where *N* is ... |
def tex_coord(x, y, size=(32, 32)):
""" Return the bounding vertices of the texture square.
"""
mx = 1. / size[0]
my = 1. / size[1]
dx = x * mx
dy = y * my
return dx, dy, dx + mx, dy, dx + mx, dy + my, dx, dy + my |
def split_list_at_indices(the_list, indices):
"""
Split a list at a given set of indices
>>> split_list_at_indices([1,3,5,7,9], [0, 3])
[[], [1, 3, 5], [7, 9]]
"""
return [the_list[i:j] for i, j in zip([0] + indices, indices + [None])] |
def candidate_union(cells):
"""return the union of candidates in cells. cells is a collection supporting
for loops
"""
return set().union(*(cell.candidates for cell in cells)) |
def ordered_dict_values(dictionary):
"""
A function to obtain unique values from a dictionary
Parameters
----------
dictionary: dict
Dictionary to obtain unique values from
Returns
-------
lst: list
A list of unique values in the dictionary by order of appearan... |
def is_horizontal_rule(line):
""" Check if a line looks like a horizontal rule."""
line = line.strip()
return all(ch == '#' for ch in line) and len(line) > 10 |
def titleize(text: str):
"""
Capitalizes all the words in a String
"""
return " ".join(i.strip().lower().capitalize() for i in text.split()) |
def delchars(stri, chars):
"""Returns a string for which all occurrences of characters in
chars have been removed."""
# Translate demands a mapping string of 256 characters;
# whip up a string that will leave all characters unmolested.
identity = ''.join([chr(x) for x in range(256)])
try:
... |
def convert_plain(text):
"""
text/plain part
"""
lines = text.split('\n')
title = lines[0]
result = []
for line in lines[1:]:
result.append(line.strip())
return '\n'.join((
title, '',
'\n'.join(result)
)) |
def _extract_8_bits(long_value, shift=1):
"""Return an integer in the range 0, 255 by extracting 8 bits from the
input long value. shift determines which 8 bits are taken, by default
the first 8 bits."""
bitmask = (1 << 8 * shift) - 1
return (long_value & bitmask) >> (8 * (shift-1)) |
def type_check(some_input, memory):
"""
Assign the correct type on a user entered equation to avoid
accomodate a failure to input numbers in an equation.
:param some_input: an element from the user input list.
:param memory: user answer stored for future use
"""
try:
some_input = f... |
def Xor(b1, b2):
"""Xors two bit vectors together."""
return [x ^ y for x, y in zip(b1, b2)] |
def cost(z):
""" Cost function. """
return 0.05 + 0.95 * z[0]**1.5 |
def _len_guards(M):
"""Handle small or incorrect window lengths"""
if int(M) != M or M < 0:
raise ValueError('Window length M must be a non-negative integer')
return M <= 1 |
def line_options(strokeColor='black', fillColor='black', strokeWidth=1):
"""Map from RLD line option names"""
return dict(edgecolor=strokeColor, facecolor=fillColor, linewidth=strokeWidth) |
def scaleto255(value):
"""Scale the input value from 0-100 to 0-255."""
return max(0, min(255, ((value * 255.0) / 100.0))) |
def outputids2words(id_list, vocab):
"""Get words from output ids.
"""
words = []
for i in id_list:
w = vocab._id2word(i)
words.append(w)
return words |
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
i = 0
total = 1
while i < k:
total = total *... |
def get_fileno(file):
"""Get the os-level fileno of a file-like object.
This function decodes several common file wrapper structures in an attempt
to determine the underlying OS-level fileno for an object.
"""
while not hasattr(file,"fileno"):
if hasattr(file,"file"):
file = fil... |
def _number_format(count=999):
"""A string format for line numbers
Should give a '%d' format with width big enough to `count` lines
>>> assert _number_format(77) == '%2d: '
"""
digits = len(str(count))
return "%%%dd: " % digits |
def doArc8(arcs, domains, assignments):
"""
Perform the ARC-8 arc checking algorithm and prune domains
@attention: Currently unused.
"""
check = dict.fromkeys(domains, True)
while check:
variable, _ = check.popitem()
if variable not in arcs or variable in assignments:
... |
def all_of(*words: str) -> str:
"""
Format words to query results containing all the desired words.
:param words: List of desired words
:return: String in the format google understands
"""
return " ".join(*words) |
def iterative_grouper(ListOfListOfLabels, seed):
"""
Takes a list of lists containing labels, and seed label.
Returns label co-occurrences for the seed label
"""
aList = []
for i in ListOfListOfLabels:
if len(set(i) & set(seed)) > 0:
aList += i
if set(aList) == set(seed):... |
def calculate_lower_bounds(x_s, y_s):
"""
Calculate lower bounds of total timesteps and average episodic
return per iteration.
Parameters:
x_s - A list of lists of total timesteps so far per seed.
y_s - A list of lists of average episodic return per seed.
Re... |
def _make_links_table(config):
"""Make Markdown links table from configuration."""
if "links" not in config:
return ""
return "\n\n" + "\n".join(f"[{ln['key']}]: {ln['url']}" for ln in config["links"]) |
def make_code_block(text: str, language: str = "GDScript") -> str:
"""
Returns the text surrounded by `
"""
return "```{}\n{}\n```".format(language, text) |
def rs256_jwks_uri(rs256_domain):
"""
Return a jwks uri for use in fixtures from the armasec pytest extension.
"""
return f"https://{rs256_domain}/.well-known/jwks.json" |
def build_kwargs_dict(arg_name, value):
"""Return a dictionary containing `arg_name` if `value` is set."""
kwargs = {}
if value:
kwargs[arg_name] = value
return kwargs |
def ignore(text, to_ignore):
"""
"""
for item in to_ignore:
if item in text:
return True
return False |
def area_triangle(base, height):
"""
"""
return (base * height) / 2.0 |
def break_compound_words(list_of_lists_of_tokens, compound_symbol="-"):
"""
Funcion to break words of the compound form word1<symbol>word2 into the constituting words,
then remove resulting empty strings.
Parameters
----------
list_of_lists_of_tokens : dataframe column or variable contain... |
def drop_logical_repo(repo: str) -> str:
"""Remove the logical part of the repository name."""
return "/".join(repo.split("/", 2)[:2]) |
def huba505(voltage):
"""
Given that v is voltage in Volts, return pressure as given by a HUBA 505 transducer
The transducer is:
0.5V - 0 bar
3.5V - 4 bar
"""
pressure = 4 * (voltage - 0.5) / 3
if pressure > 0:
return pressure
else:
return 0 |
def rgb_int_round(color):
"""
Rounds all values of 255 color (eg. (243.1, 100, 10.3) is returned as (243, 100, 10)
:param color: tuple(int, int, int, int), int color tuple
:return: tuple(int, int, int, int), color converted
"""
return tuple([int(round(color_channel)) for color_channel in color]... |
def time_to_json(pyt, manager):
"""Serialize a Python time object to json."""
if pyt is None:
return None
else:
return dict(
hours=pyt.hour, # Hours, Minutes, Seconds and Milliseconds
minutes=pyt.minute, # are plural in JS
seconds=pyt.second,
... |
def get_prediction_results(ground_truths, predictions, iou_threshold):
"""Calculate the number of true positives, false positives and false
negatives from the given ground truth and predictions."""
true_pos, false_pos, false_neg = None, None, None
# If there are no predictions, then everything is a fal... |
def OCEANprice(firm_valuation: float, OCEAN_supply: float) -> float:
"""Return price of OCEAN token, in USD"""
assert OCEAN_supply > 0
return (firm_valuation / OCEAN_supply) |
def V_d2bV_by_V_Approx(V):
"""
Approximate V*d^2(bV)/dV^2 for single mode fiber.
This value is needed to determine the waveguide dispersion. This
approximation is for the fundamental mode in the fiber and is good
to 1% when 1.4<V<2.4. Approximation by Marcuse (1979)
Args:
V: V-p... |
def substrucure_in_tree(main, sub):
"""
:param main: Big Tree
:param sub: substructure
:return: bool
"""
def compare(main_tree_sub, sub):
"""
:param main_tree_sub: node
:param sub: substructure_root
:return: bool
"""
if not sub:
return... |
def parser_cell_frequency_link_Descriptor(data,i,length,end):
"""\
parser_cell_frequency_link_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "cell_frequency_link", "contents" : unparsed_descriptor_co... |
def read_run_id(run_id: str):
"""Read data from run id"""
parts = run_id.split("/")
if len(parts) < 2:
# It's an old style path
# central-visayas-1600644750-9fdd80c
parts = run_id.split("-")
git_commit = parts[-1]
timestamp = parts[-2]
region_name = "-".join(p... |
def top_three(input_list):
"""Returns a list of the three largest elements input_list in order from largest to smallest.
If input_list has fewer than three elements, return input_list element sorted largest to smallest/
"""
sortedList = sorted(input_list, reverse=True)
return sortedList[:3] |
def prime_factors(n, primes, factors=[]):
"""Return a list of prime factors for a given number in ascending order if
the number of prime factors equals k."""
factors = []
for p in primes:
while n >= (p * p):
if n % p:
break
else:
n = n // p... |
def ex_no_host():
"""No host response in bytes."""
return b"SPAMD/1.5 68 EX_NOHOST\r\n\r\n" |
def thermal_balance_2(q_in, epsilon):
"""
Models bulk thermal balance in an object by using a simple forward Euler
scheme and the Stefan-Boltzmann blackbody radiation equation to find net
heat transfer and hence bulk temperature as a function of time.
"""
theta = 5.670373E-8
T = (q_in / (epsilon * theta... |
def query_string_param_test(**request):
"""
Query string parameters are expected to be mangled based on HB rules in this example.
"""
return {"original_request": request} |
def cliproi(shape, roi):
"""Make sure that a ROI does not exceeds the maximal size.
Args:
shape (n-tuple): array shape (n1, n2, ...)
roi (n-2-tuple): array range indices ((a1,b1),(a2,b2),...)
Returns:
n-2-list: clipped ROI [[a1,b1],[a2,b2],...]
"""
if len(shape) != len(roi)... |
def in_polygon(vertices, point, border_value=True):
"""Return True/False if a pixel is inside a polygon.
@param vertices:
@param point: 2-tuple of integers or list
@param border_value: boolean
@return: True if the pixel is inside a polygon
"""
counter = 0
for i, polypoint1 in enumerate(... |
def default_sid_function(id, rsid):
"""
The default function for turning a Bgen (SNP) id and rsid into a
:attr:`pysnptools.distreader.DistReader.sid`.
If the Bgen rsid is '' or '0', the sid will be the (SNP) id.
Otherwise, the sid will be 'ID,RSID'
>>> default_sid_function('SNP1','rs102343')
... |
def get_trader_energy_offer_ramp_rate(trader_id, ramp_rates):
"""
Given dictionary of trader offer ramp rates, extract the energy offer ramp
rate for a given trader. Not all traders participate in the energy market
so the function may return if no energy offer ramp rate exists.
"""
# Check that... |
def get_xref_mcf(xrefs, xref_to_label):
"""Returns the mcf format of a given string of xrefs.
Convert a list of xrefs to their mcf format of <prop_label>: <prop_text_value>
using the xref_to_label dict to lookup the property label of the given
indentifier. For this import, xref_to_label is either GENE_... |
def compose(shift, org):
"""
Compose the new string correspond to org.
:param shift: int, shift > 0. How many span needed to be shifted
:param org:str, original string
:return: new, str
"""
frag_1 = org[:len(org)-shift]
frag_2 = org[len(org)-shift:]
new = frag_2 + frag_1
return ... |
def create_document(doc, embedding, index_name):
"""Format document"""
return {
"_op_type": "index",
"_index": index_name,
"text": doc["text"],
"title": doc["title"],
"url": doc["url"],
"text_vector": embedding
} |
def multidict_split(bundle_dict):
"""Split multi dict to retail dict.
:param bundle_dict: a buddle of dict
:type bundle_dict: a dict of list
:return: retails of dict
:rtype: list
"""
retails_list = [dict(zip(bundle_dict, i)) for i in zip(*bundle_dict.values())]
return retails_list |
def quote_ident(val):
"""
This method returns a new string replacing " with "",
and adding a " at the start and end of the string.
"""
return '"' + val.replace('"', '""') + '"' |
def deduplicate(values: list):
"""Simple deduplicate that uses python sets"""
return list(set(values)) |
def values(dict):
"""Returns a list of all the enumerable own properties of the supplied object.
Note that the order of the output array is not guaranteed across different
JS platforms"""
return list(dict.values()) |
def md_getPitch(field):
"""Get pitch"""
return field.split(',')[1].strip() |
def splitNamespace(clarkName):
"""Return (namespace, localname) tuple for a property name in Clark Notation.
Namespace defaults to ''.
Example:
'{DAV:}foo' -> ('DAV:', 'foo')
'bar' -> ('', 'bar')
"""
if clarkName.startswith("{") and "}" in clarkName:
ns, localname = ... |
def weighted_average(xvals, yvals):
"""
Determines the weighted average of a group of masses and abundances
:param list xvals: x values
:param list yvals: y values
:return: weighted average, summed intensity
:rtype: tuple of float
"""
if sum(yvals) == 0: # catch for no intensity
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.