content stringlengths 42 6.51k |
|---|
def convert_bytes(bytes_val: int):
"""
Convert bytes to mega/giga/tera bytes.
:type bytes_val: ``int``
:param bytes_val: Bytes to convert
:return: Converted value
"""
if bytes_val is None:
return None
elif bytes_val == 0:
return 0
elif bytes_val > 0:
def cou... |
def get_ingredients_with_allergens(
ingredient_to_food, ingredients_without_allergens):
"""Return ingredients not present in ingredients_without_allergens."""
return {
ingredient: food
for ingredient, food in ingredient_to_food.items()
if ingredient not in ingredients_without_all... |
def flatten(x):
"""
Flatten a list
Performs a single unnesting of a list.
Parameters
----------
x : list
A list to be flattened
Returns
-------
The values of `x` but with a single unnesting
Referneces
----------
https://stackoverflow.com/a/952952/12126576
... |
def containsAny(str, set):
"""Check whether 'str' contains ANY of the chars in 'set'"""
return 1 in [c in str for c in set] |
def get_replaces_to_rule(rules):
"""Invert rules dictionary to list of (replace, rule) tuples."""
replaces = []
for rule, rule_replaces in rules.items():
for replace in rule_replaces:
replaces.append((replace, rule))
return replaces |
def _enumerate(values):
"""Enumerate possible values."""
values = list(values)
if len(values) == 0:
raise ValueError("Values cannot be empty")
if len(values) == 1:
return values[0]
result = ", ".join(map(repr, values[:-1]))
if len(values) > 1:
result = f"{result} or {repr... |
def select_best(population, cost_func, num_to_keep):
"""Selects best specified population based on the cost function
Arguments:
population -- List of shuffled coordinates
cost_func -- Function deriving optimized metric
num_to_keep -- Number of best population to keep
Returns:
List ... |
def reverseComplement(dna_seq):
"""
Returns the reverse complement of the DNA sequence.
"""
tmpseq = dna_seq.upper();
revcomp = ''
for nucleotide in tmpseq:
if nucleotide == 'A':
revcomp += 'T'
elif nucleotide == 'T':
revcomp += 'A'
elif nucleotide... |
def PEO(psi, v):
"""
V |psi>
:param dt: float
time step
:param v_2d: float array
the two electronic states potential operator in grid basis
:param psi_grid: list
the two-electronic-states vibrational state in grid basis
:return: psi_grid(update): l... |
def sindex(string, row, col):
"""Get index of the character at `row`/`col` in `string`.
:Parameters:
- `row`: row number, starting at 1.
- `col`: column number, starting at 1.
:Returns: ``i``, starting at 0 (but may be <1 if row/col<0)
:Note: This works for text-strings with '\... |
def IsStringFloat(string_to_check):
"""Checks whether or not the given string can be converted to a floating
point number.
Args:
string_to_check: Input string to check if it can be converted to a float.
Returns:
True if the string can be converted to a float.
"""
try:
float(string_to_check)
... |
def exception_to_string(exc: Exception) -> str:
"""Turn an exception into something very readable
Currently only __str__ is being used - to be enrichted by file, etc"""
return "%r" % exc |
def average_words(list_, num_tweets):
"""
A function for computing the average number of entity per tweet
"""
if num_tweets < 1: return 0
return 1.0*len(list_)/num_tweets |
def despine_ax(ax=None):
"""
Remove spines and ticks from a matplotlib axis
Parameters
----------
ax : matplotlib.axes.Axes object
axes from which to remote spines and ticks. if None, do nothing
Returns
-------
ax : matplotlib.axes.Axes object
despined ax object
"""... |
def _quantile(sorted_values, q):
"""
For a sorted (in increasing order) 1-d array, return the
value corresponding to the quantile ``q``.
"""
assert ((q >= 0) & (q <= 1))
if q == 1:
return sorted_values[-1]
else:
return sorted_values[int(q*len(sorted_values))] |
def time2frame(time, hop_size=3072, win_len=4096) -> int:
"""
Takes a time position and outputs the best frame representing it.
The input must use the same unity of measure for ``time``, ``hop_size``,
and ``win_len`` (e.g. samples or seconds). Indices start from 0.
Returns and int!
"""
ret... |
def service_from_url(url: str) -> str:
"""
>>> service_from_url("git@github.com:foo/bar")
'github'
>>> service_from_url("git@gitlab.local:foo/bar")
'gitlab'
"""
if url.startswith("git@github.com"):
return "github"
else:
return "gitlab" |
def timeInRange(start, end, x):
"""Return true if x is in the range [start, end]"""
if start <= end:
return start <= x <= end
else:
return start <= x or x <= end |
def _ensure_tuple_or_list(arg_name, tuple_or_list):
"""Ensures an input is a tuple or list.
This effectively reduces the iterable types allowed to a very short
whitelist: list and tuple.
:type arg_name: string
:param arg_name: Name of argument to use in error message.
:type tuple_or_list: seq... |
def find_sum(root, desired_sum, level=0, buffer_list=None, result=[]):
"""
You are given a binary tree in which each node contains a value
Design an algorithm to print all paths which sum up to that value
Note that it can be any path in the tree - it does not have to start at the root
"""
if not... |
def fib(n: int) -> int:
"""Fibonacci numbers with naive recursion
>>> fib(20)
6765
>>> fib(1)
1
"""
if n == 0:
return 0
if n == 1:
return 1
return fib(n-1) + fib(n-2) |
def getPPSA3(ChargeSA):
"""The calculation of atom charge weighted positive surface ares
It is the sum of the products of atomic solvent-accessible
surface area and partial charges over all positively charges atoms.
-->PPSA3"""
res=0.0
for i in ChargeSA:
if float(i[1])>0:
re... |
def exclude_field_data(exclude, sources):
"""
The option to remove field data from analysis.
:param exclude: a list containing the field data that is to be excluded
:param sources: a list containing all field data sources
:return:
"""
if exclude is not None:
for source in exclude:
... |
def split(obj, separator):
"""
Return a list of the words in the string, using sep as the delimiter
string.
"""
return obj.split(separator) |
def sanitize(expr):
"""It takes an expr (the list of IT terms, not an ITExpr class) and
cleans it by removing repeated terms.
This is done because there are two points where repeated terms can be
created: during the generation or after the mutation.
Since the generator guarantees that ever... |
def kind(n, ranks):
"""Return the first rank that this hand has exactly n of.
Return None if there is no n-of-a kind in the hand."""
for r in ranks:
if ranks.count(r) == n: return r
return None |
def should_start_jobs(operation_mode):
""" Check if operation mode is jobs, and returns True or False """
if operation_mode == "jobs":
return True
return False |
def afternoonMinimum(data_list):
"""Find index of hour where afternoon water usage minimum is located, searching between 13pm and 15pm.
:param data_list: list of floats, length = 24
:return: int number index
"""
index = 12
tmp = data_list[12]
for i in range(13, 15):
if tmp > data_li... |
def getDictFromTuple(values: tuple, keys: list, includeNone: bool = True):
"""returns a dict based on the tuple values and assigns the values to the keys provided\n
for instance, values=(1, "bill", 5} and keys=["id", "name", "age"] returns {"id": 1, "name": "bill", "age": 5}
"""
_obj = {}
for _i in ... |
def sum_dict(dictionary: dict):
"""
Author: Alix Leroy, SW
Returns the sum of all the values in a dictionary
:param dictionary: dict: input dictionary of float/int
:return: float: sum of the values in the dictionary
"""
return sum(list(dictionary.values())) |
def low_filter(a, b, alpha):
"""
Applies a simple low-pass filter.
Parameters:
a, b: Input coordinates and sizes.
alpha:
"""
return a*alpha+(1.0-alpha)*b |
def makeReturn(items: dict) -> dict:
"""
Format output for alfred
"""
out = {'items': items}
return out |
def clamp(n, vmin, vmax):
"""Computes the value of the first specified argument clamped to a range defined by the second and third specified arguments
:param n: input Value
:param vmin: MiniMum Value
:param vmax: Maximum Value
:returns: The clamped value of n
"""
return max(min(n, vmax), vm... |
def get_destroyed_volume(vol, array):
"""Return Destroyed Volume or None"""
try:
return bool(array.get_volume(vol, pending=True)['time_remaining'] != '')
except Exception:
return False |
def digest_algorithm(algo: int) -> str:
"""
Source: https://tools.ietf.org/html/rfc4509#section-5
:param algo:
:return:
"""
if algo == 1:
return "SHA1"
elif algo == 2:
return "SHA256"
return "" |
def escape_perl_string(v):
"""Escape characters with special meaning in perl"""
return str(v).replace("$", "\\$").replace("\"", "\\\"").replace("@", "\\@") |
def get_pretty_name(obj):
"""
Gets a pretty name from `obj`.
"""
if not hasattr(obj, "__qualname__") and not hasattr(obj, "__name__"):
obj = getattr(obj, "__class__", obj)
if hasattr(obj, "__qualname__"):
return obj.__qualname__
if hasattr(obj, "__name__"):
return obj.__n... |
def sum(num1,num2):
"""
calculates the sum of two numbers
Parameters
----------
num1 (float)
num2 (float)
Returns
-------
num (float)
Examples
--------
>>> num = sum(1,3)
"""
#return num1 + num2 + 1
return num1 + num2 |
def nest_data(sent_data):
"""
Nests strings into dictionaries eg
{
'site.name': 'SITE1'
}
becomes
{
'site': {
'name': 'SITE1'
}
}
"""
def _create_keys(d, keys, value):
keys = keys.split(".")
for k in keys[:-1]:
if k not... |
def timefmt(sec):
"""Format time to min:sec format."""
return "%d:%02d" % (sec/60, sec%60) |
def is_valid_email(email):
"""
RFC822 Email Address Regex
--------------------------
Originally written by Cal Henderson
c.f. http://iamcal.com/publish/articles/php/parsing_email/
Translated to Python by Tim Fletcher, with changes suggested by Dan Kubb.
Licensed under a Creative Commons A... |
def get_reverse(text):
"""
The below line is for unit tests
>>> get_reverse('This is for unit testing')
'gnitset tinu rof si sihT'
"""
return text[::-1] |
def call_method(obj, name):
"""
Call the method *name* on *obj*.
"""
return getattr(obj, name)() |
def human_size(num, suffix='B'):
"""
Convert bytes length to a human-readable version
"""
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
if abs(num) < 1024.0:
return "{0:3.1f}{1!s}{2!s}".format(num, unit, suffix)
num /= 1024.0
return "{0:.1f}{1!s}{2!s}".forma... |
def engagement_rate(followers_who_engaged, total_followers):
"""Return the engagement rate for a social media account.
Args:
followers_who_engaged (int): Total unique followers who engaged.
total_followers (int): Total number of followers.
Returns:
Engagement rate (float) as follow... |
def merge_pept_dicts(list_of_pept_dicts:list)->dict:
"""
Merge a list of peptide dict into a single dict.
Args:
list_of_pept_dicts (list of dict): the key of the pept_dict is peptide sequence, and the value is protein id list indicating where the peptide is from.
Returns:
dict: the key i... |
def _target_to_aabb_polygons(target):
""" Transforms target AABB into 4 point polygons
The vehicle AABB representation is transformed into:
((xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax))
Parameters
----------
target : dict
single image label as provided by Boxy datase... |
def sanitise_dict(dictionary, inplace=False, recursive=False):
"""Remove dictionary Nones."""
if type(dictionary) is not dict:
return dictionary
output = {}
if inplace:
del_keys = set()
for key, val in dictionary.items():
if val is None:
del_keys.ad... |
def rename_pretrained(name: str):
""" Matches the name of a variable saved in the pre-trained MobileNet
networks with the name of the corresponding variable in this network.
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md
Parameters
----------
name: the orig... |
def get_assembly_ref_from_genome(genome_ref, ws_obj):
"""
Given a Genome object, fetch the reference to its Assembly object on the workspace.
Arguments:
ref is a workspace reference ID in the form 'workspace_id/object_id/version'
ws_obj download workspace object for the genome
Returns a work... |
def _format_time(total_seconds):
"""Format a time interval in seconds as a colon-delimited string [h:]m:s"""
total_mins, seconds = divmod(int(total_seconds), 60)
hours, mins = divmod(total_mins, 60)
if hours != 0:
return f'{hours:d}:{mins:02d}:{seconds:02d}'
else:
return f'{mins:02d}... |
def is_valid_function(paras):
"""Check if a valid method with parameters
Parameters:
paras: A dictionary contains all parameters of the method
Exampls:
For some situation the there will no parameters due to empty doc string. This should be recorded and processed futher, e.g... |
def never_decrease(num: str) -> bool:
"""Check if digits are never decrease."""
return all(int(num[i]) >= int(num[i - 1]) for i in range(1, len(num))) |
def vector_sub(v1=[0,0,0], v2=[0,0,0]):
""" v1 - v2 """
return [v1[0]-v2[0], v1[1]-v2[1], v1[2]-v2[2]] |
def map_to_guass(x1,x2, u, sigma):
"""
Changes the mean and varance to those given
:param x1:
:param x2:
:return:
"""
# First change variance
x1 = x1 * (sigma)
x2 = x2 * (sigma)
# then change the mean
x1 = x1 + u
x2 = x2 + u
return x1, x2 |
def tof_inches(time_of_flight):
"""
EZ1 ultrasonic sensor is measuring "time of flight"
Converts time of flight into distance in inches
"""
convert_to_inches = 147
inches = time_of_flight / convert_to_inches
return inches |
def print_result(result, thresh):
"""Prints output message according to the result and the
prediction threshold.
"""
if result >= thresh:
print('Congrats, it looks like you have a hit! ' + \
'This track is a hit with {:.2f} probability.'.format(result))
else:
print("... |
def equals(v1, v2, epsilon):
"""
Returns True if difference between given values is less then tolerance.
Args:
v1: float
Value one.
v2: float
Value two
epsilon: float
Max allowed difference.
Returns:
bool
... |
def reverse_builtin(value):
"""Reverse string using the "reversed" function."""
return "".join(reversed(value)) |
def area_width_normalized_label(var, area_norm=True, width_norm=True):
"""Returns a label for histograms normalized by any combination of
area/width. For both area and width, the label should be 1/N*dN/d(var).
"""
if area_norm and width_norm:
return '#frac{dN}{Nd('+var+')}'
elif area_norm:
... |
def remove_id(word):
"""Removes the numeric suffix from the parsed recognized words: e.g. 'word-2' > 'word' """
return word.count("-") == 0 and word or word[0:word.rindex("-")] |
def convert_degrees(deg, tidal_mode=True):
"""
Converts between the 'cartesian angle' (counter-clockwise from East) and
the 'polar angle' in (degrees clockwise from North)
Parameters
----------
deg: float or array-like
Number or array in 'degrees CCW from East' or 'degrees CW from North'
... |
def generate_iterables(scan_info, experiment, subjects, sessions=None):
"""Return lists of variables for preproc workflow iterables.
Parameters
----------
scan_info : nested dictionaries
A nested dictionary structure with the following key levels:
- subject ids
- session... |
def _get_artifacts_list_api_url(repo_owner, repo_name):
"""Returns the artifacts_api_url for |repo_name| owned by |repo_owner|."""
return (f'https://api.github.com/repos/{repo_owner}/'
f'{repo_name}/actions/artifacts') |
def generate_sql_verification_data_row(row):
"""Generates the verification text for a given result sql.
Keyword arguments:
row -- the row results from athena
"""
row_string = ""
row_data = row["Data"]
for column_index in range(0, len(row_data)):
if row_data is not None:
... |
def str_to_bool(string):
"""Convert a string to a boolean value."""
if string.upper() in ["1", "ON", "TRUE", "YES"]:
return True
return False |
def get_reasonable_repetitions(natoms):
"""
Choose the number of repetitions
according to the number of atoms in the system
"""
if natoms < 4:
return [3, 3, 3]
if 4 <= natoms < 15:
return [2, 2, 2]
if 15 <= natoms < 50:
return [2, 2, 1]
return [1, 1, 1] |
def _lazy_call(self, args=(), kwargs={}):
"""
Lazy evaluation for callable.
"""
return self(*args, **kwargs) |
def get_subset_from_bitstring(super_set, bitstring):
"""
Gets the subset defined by the bitstring.
Examples
========
>>> get_subset_from_bitstring(['a', 'b', 'c', 'd'], '0011')
['c', 'd']
>>> get_subset_from_bitstring(['c', 'a', 'c', 'c'], '1100')
['c', 'a']
See Also
========
... |
def wrap_code_block(message):
"""
Wrap a message in a discord code block
:param message: The message to wrap
:return: A message wrapped in a code block
"""
return "```\r\n{0}\r\n```".format(message) |
def header(time_type=float):
"""
Return a header that describes the fields of an event record in a
table of events.
The header is (id:int, lo:time_type, hi:time_type, cat:str, typ:str,
val:str, jsn:str).
time_type:
Constructor for type of time / date found in event records:
tim... |
def intcode_five(parameter_list, code_list, i):
"""If first parameter is non-zero, sets instruction pointer to second parameter. Returns i"""
if parameter_list[0] != 0:
i = parameter_list[1]
return i |
def maximum(x, y):
"""Returns the larger one between real number x and y."""
return x if x > y else y |
def relative_change(nr1, nr2):
"""Compute relative change of two values.
:param nr1: The first number.
:param nr2: The second number.
:type nr1: float
:type nr2: float
:returns: Relative change of nr1.
:rtype: float
"""
return float(((nr2 - nr1) / nr1) * 100) |
def get_repo_data(clone_urls):
""" return list of repo data from clone_urls
"""
repos = []
for clone_url in clone_urls:
owner = clone_url.split('/')[3]
name = clone_url.split('/')[-1].replace('.git', '')
item = {
'clone_url': clone_url,
'full_name': f'{own... |
def is_iterable(i):
"""Check if a variable is iterable, but not a string."""
try:
iter(i)
if isinstance(i, str):
return False
return True
except TypeError:
return False |
def parse_priority(priority: str) -> int:
"""
Parses MAL priority string into a 1-3 range
"""
return ('low','medium','high').index(priority.lower()) |
def inverseDict(d):
"""
Returns a dictionay indexed by values {value_k:key_k}
Parameters:
-----------
d : dictionary
"""
dt = {}
for k, v in list(d.items()):
if type(v) in (list, tuple):
for i in v:
dt[i] = k
else:
dt[v] = k
... |
def process_opts(command, look_for):
"""
Refer to 'OPCunix.command_handler.process_opts' for details
"""
size = len(command)
for i in range(size):
if command[i] == look_for:
return command[i+1]
return [] |
def convert_entity_schema(entity_schema):
""" Convert entity schmea to record schema
"""
spots = list()
asocs = list()
spot_asoc_map = dict()
for entity in entity_schema:
spots += [entity]
spot_asoc_map[entity] = list()
return spots, asocs, spot_asoc_map |
def wrap_fn_hessian(fn, i, j, **kwargs):
"""
A wrapper for the QCA batch downloader for Hessians
"""
# out_str = kwargs["out_str"]
# kwargs.pop("out_str")
# prestr = "\r{:20s} {:4d} {:4d} ".format(out_str, i, j)
# elapsed = datetime.now()
objs = [obj for obj in fn(**kwargs)]
# ... |
def get_verification_buffer(message):
"""Returns a serialized string to verify the message integrity
(this is was it signed)
"""
return "{chain}\n{sender}\n{type}\n{item_hash}".format(**message).encode("utf-8") |
def cleanup_code(content) -> str:
"""Automatically removes code blocks from the code."""
if content.startswith('```') and content.endswith('```'):
num = 6 if content.startswith('```py\n') else (4 if content.startswith('```\n') else 3)
return content[num:-3]
else: return content |
def sorted_tree(ls):
"""
Recursively sort a nested list to get a canonical version.
"""
if ls is None: return ls
for i in range(len(ls)):
if type(ls[i]) is list:
ls[i] = sorted_tree(ls[i])
ls.sort()
return ls |
def _idx_to_conv(idx, conv_width, anchors_per_loc):
"""
Converts an anchor box index in a 1-d numpy array to its corresponding 3-d index representing its convolution
position and anchor index.
:param idx: non-negative integer, the position in a 1-d numpy array of anchors.
:param conv_width: the numb... |
def _to_camel_case(snake_str: str):
"""Converts the given snake_case string to camelCase"""
components = snake_str.split("_")
return components[0] + "".join(x.title() for x in components[1:]) |
def IPACExpandType( IPACtp, shrink=False ):
"""Takes the header from an IPAC table and parses it into the full ipac
name of the type if shrink==False. If shrink != False, return the 1
character IPAC table type."""
if len(IPACtp) == 0:
raise ValueError( "IPACExpandType requires a string with ... |
def is_empty_line(line: str) -> bool:
"""Tests if a line (of a text file) is empty."""
if line in ('\n', '\r\n'):
return True
return False |
def short_bubble_sort(a):
"""
Variant of the short bubble, taking advantage of the fact we know that if
no value has been swapped, the list is sorted and we can return early.
"""
length = len(a)
for pass_number in range(length):
has_swapped = False
for i in range(1, length - pass... |
def get_vcond(lambdam, taum):
"""Return conductance velocity in m/s
lambda -- electronic length in m
taum -- membrane time constant
"""
return 2*lambdam/taum |
def simplify_config_key(config_key):
"""
Example:
Arguments:
config_key: "config-env_config-is_shuffle_agents"
Returns:
"c-ec-isa"
"""
config_key = config_key.replace("-", " - ")
config_key = config_key.replace("_", " ")
words = config_key.split()
lett... |
def get_positive_int(obj: dict, name: str) -> int:
"""Get and check the value of name in obj is positive integer."""
value = obj[name]
if not isinstance(value, int):
raise TypeError(f'{name} must be integer: {type(value)}')
elif value < 0:
raise ValueError(f'{name} must be positive integ... |
def take_0_k_th_from_2D_list(obj_list, k=0, verbose=False):
"""returns the element obj_list[0][k] if obj_list is a nested list of depth 2, or obj_list otherwise."""
if isinstance(obj_list, list):
if verbose:
print("obj_list is:", obj_list)
if isinstance(obj_list[0], list):
... |
def get_frame_subframe(sfn_sf):
""" Get the frame and the subframe number from the
received bitstring
"""
sfn_sf_list = []
frame_mask = ~((1<<4) - 1)
frame = (sfn_sf & frame_mask) >> 4
sf_mask = ~(((1<<12) - 1) << 4)
subframe = (sfn_sf & sf_mask)
sfn_sf_list.append(frame)
sf... |
def dt_s_tup_to_string(dt_s_tup):
"""
Parameters
----------
dt_s_tup : tuple
A tuple of length 2.
The first entry is a string specifying the deterministic term without
any information about seasonal terms (for example "nc" or "c").
The second entry is an int specifying t... |
def prettify_label(label: str) -> str:
"""Fix parameter label to look nice for plots.
Replace underscores with whitespace, TeXify some stuff, remove
unnecessary things, etc.
Parameters
----------
label : str
Original label.
Returns
-------
str
Prettified label.
... |
def check_data_names(data, data_names):
"""
Check *data_names* against *data*.
Also, convert ``data_names`` to a tuple if it's a single string.
Examples
--------
>>> import numpy as np
>>> east, north, scalar = [np.array(10)]*3
>>> check_data_names((scalar,), "dummy")
('dummy',)
... |
def update_board(a, b, c, current_board):
""" Update board """
current_board[a][b] = c
return current_board |
def split_leading_comment(inputstring):
"""Split into leading comment and rest."""
if inputstring.startswith("#"):
comment, rest = inputstring.split("\n", 1)
return comment + "\n", rest
else:
return "", inputstring |
def points_interp(points1, points2, weight2):
"""Interpolate between two 2D point lists, returning a new point list.
Specify weighting (0.0 to 1.0) of second list. Lists should have
same number of points; if not, lesser point count is used and the
output may be weird."""
num_points = min(len(points1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.