content stringlengths 42 6.51k |
|---|
def validate_string(str_argument, str_argument_name):
""" Validates if the given argument is of type string and returns it"""
if not isinstance(str_argument, str):
raise ValueError(f"Illegal str argument: {str_argument_name}")
return str_argument |
def get_all_parent(children):
"""
"""
parent_dict = {}
for value in children:
parent_dict.update({value[0]: "/".join(value[0].split("/")[:-1])})
return parent_dict |
def is_ascii_problem(s):
"""
Test if a string contains other chars than ASCII
:param androguard.core.mutf8.MUTF8String s: a string to test
:return: True if string contains other chars than ASCII, False otherwise
:rtype: bool
"""
try:
# As MUTF8Strings are actually bytes, we can simp... |
def parse_star_rating(row):
"""
Extract hotel star rating data from `star_rating` column
"""
row = row[1]["star_rating"]
return float(row.strip("-star")) |
def get_instance_id_to_volume_id_map(volume_info):
"""Generate instance_id to volume id map. Unattached volumes will be ignored."""
instance_id_to_volume_id_map = {}
for volume_id in volume_info:
volume = volume_info.get(volume_id)
if volume.get("Attachments"):
# Attached volu... |
def escape_filter_chars(assertion_value,escape_mode=0):
"""
Replace all special characters found in assertion_value
by quoted notation.
escape_mode
If 0 only special chars mentioned in RFC 4515 are escaped.
If 1 all NON-ASCII chars are escaped.
If 2 all chars are escaped.
"""
if escape_mo... |
def classify(value, breaks):
"""
Helper function for govf
Assign pixels to classes based on jenks breaks
Paramaters
----------
value: float
pixel value from input image
breaks: list
current class breaks from govf
"""
for i in range(1, len(breaks)):
if value ... |
def TabReplacer(line, file_path, line_number):
"""Replaces Tabs with 4 whitespaces."""
if '\t' in line:
print('Replacing Tab with whitespace in %s:%s' % (file_path, line_number))
return line.replace('\t', ' ') |
def clean_filename(filename):
"""
"""
return filename.replace(' ', '_').replace('.','') |
def select_best(population, cost_func, num_to_keep):
"""Select a given number of paths with the lowest cost (the best paths)
Arguments received:
population -- an array of lists of coordinates representing paths
cost_func -- function to calculate cost of a path
num_to_keep -- number of paths to sele... |
def set_intersection(*sets):
"""Return the intersection of all the given sets.
As of Python 2.6 you can write ``set.intersection(*sets)``.
Examples
========
>>> from sympy.core.compatibility import set_intersection
>>> set_intersection(set([1, 2]), set([2, 3]))
set([2])
>>> set_inters... |
def _non_empty_lines(output):
"""Helper to turn a string into a list of not
empty lines and returns it.
"""
return [line for line in
output.splitlines() if line.strip()] |
def to_ssml(text):
"""Adds SSML headers to string.
"""
return '<speak>'+ text + '</speak>' |
def GuessTargetArch(bisect_bot):
"""Returns target architecture for the bisect job."""
if 'x64' in bisect_bot or 'win64' in bisect_bot:
return 'x64'
elif bisect_bot in ['android_nexus9_perf_bisect']:
return 'arm64'
else:
return 'ia32' |
def _field_to_tuple(field):
"""
Convert an item in the `fields` attribute into a 2-tuple.
"""
if isinstance(field, (tuple, list)):
return (field[0], field[1])
return (field, None) |
def _prioritify(line_of_css: str, css_props_text_as_list: tuple) -> tuple:
"""Return args priority, priority is integer and smaller means higher."""
sorted_css_properties, groups_by_alphabetic_order = css_props_text_as_list
priority_integer, group_integer = 9999, 0
for css_property in sorted_css_propert... |
def find_headers(lines):
"""Identify headers and line breaks."""
for i in range(len(lines)):
if lines[i][1] == '-'*78:
lines[i][0] = 'pagebreak'
lines[i+2][0] = 'header'
i += 3
return lines |
def htf_cp(T_C, *args):
"""
provide T in degr Celsius
kJ/kg-k specific heat
"""
try:
htftype = args[0]
except IndexError:
htftype = 17
if htftype == 10:
#Salt_465_LiF_115_NaF_42KF
return 2.010;
elif htftype == 17:
#Salt_60_NaNO3_40_KNO3
... |
def blocktrans_cen2side(cen_size):
""" Convert from center rep to side rep
In center rep, the 6 numbers are center coordinates, then size in 3 dims
In side rep, the 6 numbers are lower x, y, z, then higher x, y, z """
cx = float(cen_size[0])
cy = float(cen_size[1])
cz = float(cen_size[2])
sx... |
def remove_metadata(module_data, start_line, start_col, end_line, end_col):
"""Remove a section of a module file"""
lines = module_data.split('\n')
new_lines = lines[:start_line]
if start_col != 0:
new_lines.append(lines[start_line][:start_col])
next_line = lines[end_line]
if len(next_l... |
def _parse_latex_out(output):
"""
Converts pdfLaTeX command output into a dictionary of
data about it
:param output: pdflatex command output string
:return: dictionary of important output
"""
out = {}
out["errors"] = []
out["messages"] = []
lines = output.split("\n")
... |
def is_text_all_capital(text):
"""Returns true of the entire text is written with capitals. False otherwise."""
return text == text.upper() |
def label_to_onehot(labels):
""" Convert label to onehot .
Args:
labels (string): sentence's labels.
Return:
outputs (onehot list): sentence's onehot label.
"""
label_dict = {'BACKGROUND': 0, 'OBJECTIVES':1, 'METHODS':2, 'RESULTS':3, 'CONCLUSIONS':4, 'OTHERS':5}
o... |
def obtain_value(entry):
"""Extract value from entry.
The entries could be like: '81.6', ': ', '79.9 e', ': e'.
"""
entry = entry.split(' ', maxsplit=-1)[0] # Discard notes.
if not entry or entry == ':':
return None
return float(entry) |
def char_length(sentence):
""" Length of a sentence in characters
:param sentence:
:param sentence:
"""
return sum(1 for c in sentence if c != ' ') |
def has_precedence(op1, op2):
"""
Determines which operator has higher priority: parentheses first,
then multiplication and division, addition and subtraction last.
:param op1: first operator
:param op2: second operator
:return: True if `op1` has higher precedence than `op2`
"""
if op2 ... |
def validate_volume_type(volume_type):
"""
Validate VolumeType for ElasticsearchDomain
Property: EBSOptions.VolumeType
"""
VALID_VOLUME_TYPES = ("standard", "gp2", "io1")
if volume_type not in VALID_VOLUME_TYPES:
raise ValueError(
"Elasticsearch Domain VolumeType must be on... |
def squeeze_nested(orig):
"""
recursively flattens hierarchy if all nested elements have the same value
>>> squeeze_nested({'a': 1, 'b': 1})
1
"""
if isinstance(orig, (dict, list)):
keys = list(orig.keys() if isinstance(orig, dict) else range(len(orig)))
squeezed = True
... |
def normalize_str(string: str) -> str:
"""
Normalize a string by applying on it lowercase and replacing '-' to '_'.
>>> normalize_str("Content-Type")
'content_type'
>>> normalize_str("X-content-type")
'x_content_type'
"""
return string.lower().replace("-", "_") |
def keysAtLevel(db, level, dlm=':'):
"""Returns the set of keys at the given "level".
This is defined as the number of elements of the key, when split by 'dlm'.
"""
level = int(level)
ret = [k for k in db.keys() if len(k.split(dlm)) == level]
return ret |
def pluck(text, start, end, default=None):
# type (str, str, str, Any) -> Any
"""Attempts to extract string between start and end from text"""
if default is None:
default = ""
index = text.find(start) + len(start)
try:
return text[index:text.find(end, index)]
except IndexError:
... |
def _get(d, path):
"""Get a value (or None) from a dict by path given as a list
Integer values represent indexes in lists, string values are for dict keys
"""
if not isinstance(path, list):
raise LookupError("The path needs to be a list")
for step in path:
try:
d = d[ste... |
def iou_xywh(box1, box2):
"""
Arguments:
box1 -- rectangles of object proposals with coordinates (x, y, w, h)
box2 -- rectangle of ground truth with coordinates (x1, y1, w, h)
"""
xi1 = max(box1[0], box2[0])
yi1 = max(box1[1], box2[1])
xi2 = min(box1[0] + box1[2], box2[0] + box2[2])
... |
def not_followed_by(pattern):
""" a pattern to exclude after a match
:param pattern: an `re` pattern
:type pattern: str
:rtype: str
"""
return r'(?!{:s})'.format(pattern) |
def _lm_tail(k, lm):
"""Return elements of `Lm` with indices `k..N`."""
n = len(lm)
assert k >= 1, k
assert k <= n, (k, n)
start = k - 1
assert start >= 0, start
r = lm[start]
for i in range(start, n):
r |= lm[i]
return r |
def get_reverse(string):
"""Take a string and return its reverse."""
reverse = string[::-1]
return reverse |
def unique(seq):
"""Remove duplicates from a list in Python while preserving order.
:param seq: a python list object.
:return: a list without duplicates while preserving order.
"""
seen = set()
seen_add = seen.add
"""
The fastest way to sovle this problem is here
Pytho... |
def round_function(i):
"""
Number of arms to be played in a round before Estimation/Elimination routine.
Parameters
----------
i : round number
Returns
-------
int : number of arms to be played in the current round
"""
# return 2*i
# return 2**i
return 1 |
def sub(a,b):
"""Subtract a vector b from a, or subtract a scalar"""
if hasattr(b,'__iter__'):
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
return [ai-bi for ai,bi in zip(a,b)]
else:
return [ai-b for ai in a] |
def spark_submit_service(mem_limit, worker_mem_limit, image, command):
"""
:type mem_limit: int
:type worker_mem_limit: int
:type image: str
:type command: str
:rtype: dict
"""
executor_ram = worker_mem_limit - (2 * 1024 ** 3)
service = {
'name': "spark-submit",
'dock... |
def central_difference(f, x, h=1e-10):
"""Central difference method for approximating the derivartive of f
Args:
f: a function taking x as input
x: an int or float input to the function
h: a float small constant used for finding the derivative
Returns:
f_prime: approximatio... |
def _is_beneath(a, b):
"""Is 'a' beneath 'b'?
Args:
a : string (path)
b : string (path)
Returns:
bool: True if a is beneath (or equal to) b
"""
# Everything is beneath the top ("")
if (b==""):
return True
# If paths are both blank, they are equal
if (b... |
def validate_slice_int(the_int: int, bound: int, include=True):
"""
Ensure that the given integer makes sense as a slice entry, and move to
a normalized form.
Parameters
----------
the_int : int
bound : int
include : bool
Returns
-------
int
"""
if not isinstance(b... |
def _round_to_next_multiple(n, m):
"""
Round up the the next multiple.
:param n: The number to round up.
:param m: The multiple.
:return: The rounded number
"""
return n if n % m == 0 else n + m - n % m |
def build_command(cmd, arg_list = []):
"""
Builds the command string to send to the Mecademic Robot
from the function name and arguments the command needs
:param cmd: command name to send to the Mecademic Robot
:param arg_list: list of arguments the command requires
:ret... |
def getJDX(URL,molecule_name):
"""
This function retrieves the JDX Formatted file of a specific molecule taking in the NISTWebBook URL and the molecule's name
INPUT: URL (mass spectrum in JCAMP-DX format download URL) | molecule_name (specific molecule's name to name the jdx formatted file in the outpu... |
def set_tuple_item(tup, index, item):
"""Tuples are immutable. Therefore, this method provides item assigned to a
copy of the initial tuple.
Args:
tup: The tuple, that should be mutated.
index: The index of the item in tup that should be mutated.
item: The value that should be assig... |
def part1(lines):
"""
>>> part1([+1, +1, +1])
3
>>> part1([+1, +1, -2])
0
>>> part1([-1, -2, -3])
-6
"""
return sum(int(i) for i in lines) |
def _get_distinct_objs(objs):
"""
Return a list with distinct elements of "objs" (different ids).
Preserves order.
"""
ids = set()
res = []
for obj in objs:
if not id(obj) in ids:
ids.add(id(obj))
res.append(obj)
return res |
def is_applied(migrations_applied, migration_name):
"""
Check if a migration we want to run is already in the list of applied migrations
"""
return [True for migration in migrations_applied if migration['name'] == migration_name] |
def str_dict(d: dict):
"""
>>> str_dict({1: 1, "1": "1"})
"{'1': '1', 1: 1}"
>>> str_dict({(2, 3): "1", 1: "2", 2: "3", "a": "4", "b": {"1": 1}})
"{'a': '4', 'b': {'1': 1}, (2, 3): '1', 1: '2', 2: '3'}"
"""
def to_str(x):
if isinstance(x, str):
return "'" + x + "'"
... |
def word_feats(words):
"""Creates the matrix of words.
:param words:
:return:
"""
return dict([(word, True) for word in words]) |
def _fix_location_end(feature):
""" if end not present, set it based on start, ref & alt length"""
end = feature.get('end', 0)
start = feature.get('start', 0)
ref_len = 0
alt_len = 0
if feature.get('ref', None):
ref_len = len(feature.get('ref', ''))
if feature.get('alt', None):
... |
def _jrc(a, n, divide):
"""Coefficients in Jacobi polynomial recurrence relation."""
return (
divide((a + 2 * n + 1) * (a + 2 * n + 2), 2 * (n + 1) * (a + n + 1)),
divide(a * a * (a + 2 * n + 1), 2 * (n + 1) * (a + n + 1) * (a + 2 * n)),
divide(n * (a + n) * (a + 2 * n + 2), (n + 1) * (a... |
def get_two_digit_month(month: int) -> str:
""" Two digit month """
output = str(month)
while len(output) < 2:
output = "0" + output
return output |
def clamp(x, inf=0, sup=1):
"""Clamps x in the range [inf, sup]."""
return inf if x < inf else sup if x > sup else x |
def formatItalic(t: str = "", close: bool = True) -> str:
"""
Applies IRC italic formatting to the provided text (t),
optionally resetting formatting at the end of it (True by default).
"""
reset = '\x0f'
return f"\x1d{t}{reset if close else ''}" |
def _normalize(name):
"""Private normalizing function.
Replaces '_' by spaces and add spaces between 'aA' sequences.
"""
package = None
if '.' in name:
package, name = name.rsplit('.', 1)
aux = ''
n_len = len(name)
for i, char in enumerate(name):
if char == '_':
... |
def format_number(number):
"""
Formats a number from float (with or without units) to a latex-like number.
"""
try:
units = f"\\; {number.units.latex_repr}"
except:
units = ""
try:
mantissa, exponent = ("%.3g" % number).split("e+")
exponent = f" \\times 10^{{{in... |
def strip_previous(location):
"""
Strip previous location
"""
if location is None:
return None
return location[0] |
def flatten(lst, *, recursive=True):
"""Flatten a nested list.
Useful for splicing in transformations of statement suites.
"""
out = []
for elt in lst:
if isinstance(elt, list):
sublst = flatten(elt) if recursive else elt
out.extend(sublst)
elif elt is not No... |
def gen_prod_basepath(repro3=False, file_ext=None):
"""
Generate filename, GPSDate obj from datetime
Optionally, move reference_dt back by "shift" hours
"""
if repro3:
basepath = "gnss/products/repro3/"
elif (file_ext == "bia") & (repro3 == False):
basepath = "gnss/products/bias/... |
def float_rounded_up(float):
"""Round up a float to the nearest integer"""
integer = int(float)
if int(float) != float:
integer = int(float + 1)
return integer |
def srid_to_urn(srid):
"""
Take a postgis srid and make it into a OGC CRS URN
As suggested by http://www.geojson.org/geojson-spec.html#named-crs
This is pretty dumb right now and just assumes EPSG as the authority
except for 4326 which uses:
4326 -> urn:ogc:def:crs:OGC:1.3:CRS84
"""
if... |
def count_dots(paper):
"""
Count dots on the paper
:param paper: paper with dots
:return: number of dots
"""
counter = 0
for row in paper:
for dot in row:
if dot:
counter += 1
return counter |
def sortedDictValues(inputDict, reverse=False):
"""
Returns the given dictionary as a list of keys sorted deterministically by value then key::
{"spam": 0, "eggs": 1, "ham": 1} => ["spam", "eggs", "ham"]
:param dict inputDict:
:param bool reverse: Reversed sorting
:rtype: list
"""
... |
def unique(sequence):
""" Returns the sequence without duplicate elements """
return list(set(sequence)) |
def match_words(words, phones):
"""
Matches a dict of phones to a dict of words using their indexes
produces a dict of words with begin time (begin of first phone)
and end time (end of last phone)
Parameters
----------
words : dict
a dict of words and their indexes
phones : dict... |
def do_range(value):
"""
Returns a range from value, including stop value.
"""
start, stop = value
try:
start = int(start)
except ValueError:
start = 0
try:
stop = int(stop)
except ValueError:
stop = 0
return range(start, stop + 1) |
def list_to_array_syntax( l ):
"""Convert a python list to PGSQL array syntax for insertion"""
l_text = str(l)
l_text = "'{" + l_text[1:-1] + "}'"
return l_text |
def mapChrForVersion(c):
"""
Only for human genome. If this is applied to other species, futher
modification is needed.
"""
if c.startswith('chrM'):
return 998
elif c == 'chrX':
return 999
elif c == 'chrY':
return 1000
else:
return int(c[3:]) |
def intersect(a, b):
"""Find intersection of two lists, sequences, etc.
Returns a list that includes repetitions if they occur in the inputs."""
return [e for e in a if e in b] |
def make_album(
artist_name, album_title,
num_of_songs = None):
"""Builds a dictionary describing a music album"""
album = {'Artist': artist_name.title(), 'Album': album_title.title()}
if num_of_songs:
album['num_of_songs'] = num_of_songs
return album |
def divide_dims(dims):
"""takes in the variable dims (aka dimentions) from javascript/flask, and
returns width and height
>>> divide_dims("827,880")
('827', '880')
>>> divide_dims("1679,892")
('1679', '892')
"""
mid = dims.find(",")
width = dims[0:mid]
height = dims[mid+1:len(... |
def get_message(messages_list):
"""
This method receives list with 3 list of string.
It returns an string with the decoded message.
Note: Messages could have gaps at the beggining.
>>> get_message([
["Este", " ", " ", "mensaje"],
[" ", " ", "es", " ", "mensaje"],
[" ", " ",... |
def find_midpoint(n: int):
"""
Returns the biggest power of 2 less than n.
"""
k = 1
m = n / 2
while k < m:
k *= 2
return k |
def increment(x):
"""increments x by 1"""
return(x + 1) |
def phase(pos):
"""
Defines an n-dimensional hypersphere.
"""
return int(sum(x ** 2 for x in pos) <= 1) |
def add_mod_c(a, b, c):
"""
Integer addition mod c.
Parameters
----------
a,b : int
Integers to be added
c : int
Integer to mod out by
Returns
-------
s : a + b (mod c)
"""
s = a + b
return s % c |
def append_code(html, code, *args):
"""
Appends the given code to the existing HTML code
"""
if args:
# Format added code first
code = code.format(*args)
return "{0}\n{1}".format(html, code) |
def serialize(root):
"""
:param root:tree root
:return:pre-order val list
"""
def preorder(root):
if not root:
seq.append('$')
return
seq.append(root.val)
preorder(root.left)
preorder(root.right)
return seq
seq = []
preorder(roo... |
def samerule (rulea, ruleb) :
"""check is rule a & b are the same
Parameters
a, b : rules to compare
Returns
True or False
"""
if len(rulea) == len(ruleb) :
for opa, opb in zip (rulea, ruleb) :
if not (opa.type == opb.type and opa.val == opb.val) :
return False
return True
else :
return False |
def IsDate(word):
"""
Test if word is a date
"""
boo = False
if len(word) > 7:
if (word[-3] == "/") and (word[-6]=="/"):
boo = True
else:
pass
else:
pass
return boo |
def reverse_dict(d):
"""Reverses the direction of a dependency dict.
>>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
>>> reverse_dict(d) # doctest: +SKIP
{1: ('a',), 2: ('a', 'b'), 3: ('b',)}
:note: dict order are not deterministic. As we iterate on the
input dict, it make the output of this f... |
def is_time_between(start_time, end_time, check_time):
"""
Checks if a current_time is between two other times.
Time Complexity: O(1)
:param start_time: The start current_time.
:param end_time: The end current_time.
:param check_time: The current_time to check.
:return: True if the current_t... |
def get_class_path(cls):
"""Return class path
:param cls: class object
:return: class path
:rtype: str
"""
return '{cls.__module__}.{cls.__name__}'.format(cls=cls) |
def next_recipe_digits(cur_recipe):
"""Calculate next recipe, based on the cur_recipe."""
if cur_recipe == 0:
return [0]
digits = []
while cur_recipe > 0:
digits.append(cur_recipe % 10)
cur_recipe = cur_recipe // 10
return digits[::-1] |
def kBU_(B,kBU,Cooperativity,P):
"""Returns the receptor unbinding rate kUB for either the cooperative or the non-cooperative binding model.
Parameters
----------
B : float
Number of bound receptors.
kBU : float
Rate at which AMPARs unbind from PSD slots.
Cooperativity : 0, 1
... |
def safe_is_subclass(subclass, superclass) -> bool:
"""
A clone of :func:`issubclass` that returns ``False`` instead of throwing a :exc:`TypeError`.
.. versionadded:: 1.2
"""
try:
return issubclass(subclass, superclass)
except TypeError:
return False |
def trueifset(xeval, typematch=False):
"""return True if @xeval is set, otherwise False"""
if typematch:
if not (xeval is False or xeval is None): return True
else: return False
else:
if xeval: return True
else: return False |
def select_config(configs, project):
""" returns the first config that matches the project """
for c in configs:
if c['content']['repository'].endswith(f'/{project}'):
return c
return None |
def log_Gaussian(x,mu,sigma,offset):
"""
Calculates a log Gaussian function.
Args:
x: (array) input array on which to calculate a Gaussian.
mu: (float) center of Gaussian.
sigma: (float) standard deviation of Gaussian.
offset: (float) vertical offset of the log Gaussian.... |
def c_unique(seq):
"""Implements 'unique' of a list.
"""
seen = set()
seen_add = seen.add
return [ x for x in seq if not (x in seen or seen_add(x))] |
def get_iscam_mws(intensities, mw_intensity_line_pars=None):
"""
Calculate the molecular weights of the intensities with the line parameters
`mw_intensity_line_pars`
Parameters
----------
intensities : np.ndarray
inensities of an iscam measurements
mw_intensity_line_pars : array lik... |
def _compute_average_precision(gold_labels, ranked_lines):
""" Computes Average Precision. """
precisions = []
num_correct = 0
num_positive = sum([1 if v == 1 else 0 for k, v in gold_labels.items()])
for i, line_number in enumerate(ranked_lines):
if gold_labels[line_number] == 1:
... |
def response_error(response, message):
""" return a 500: Internal server error message """
if response != message:
return "500: Internal server error" |
def adjacent_cloud_Sentinel(Fmask, cloud_shadow, dilatation):
"""
Return Fmask with all classes (adjacent cloud included).
"""
cloud_shadow_Fmask = cloud_shadow * Fmask
dilatation_Fmask = (dilatation - cloud_shadow) * 4
other_Mask = - (dilatation - 1)
remain_Fmask = other_Mask * Fmask
re... |
def correction_factor(rt, lt, icr=None, ocr=None):
"""
Calculate the deadtime correction factor.
Parameters:
-----------
* rt = real time, time the detector was requested to count for
* lt = live time, actual time the detector was active and
processing counts
* icr = true inpu... |
def nameToPath(name):
""" Converts camel case name into full node path where uppercase letters denote
intermediate nodes in path. Node path ends in dot '.'
Assumes Name is of the correct format to be Identifier.
"""
pathParts = []
nameParts = list(name)
for c in nameParts:
i... |
def pd_isnan(val):
"""
Utility function for identifying None or NaN (which are indistinguishable in pandas).
Parameters
----------
val : numeric
value to test
Returns
-------
bool
True if val is a GDX encoded special value that maps to None or numpy.nan;
False o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.