content stringlengths 42 6.51k |
|---|
def expand_prefix(prefix):
"""Expand prefix string by adding a trailing period if needed.
expandPrefix(p) should be used instead of p+'.' in most contexts.
"""
if prefix and not prefix.endswith('.'):
return prefix + '.'
return prefix |
def get_optimal_value(capacity, weights, values):
"""knapsack problem:
get the optimal fractional configuration of values/weights that fills
the capacity.
"""
assert len(weights) == len(values)
value = 0.
weights_values = list(zip(weights, values))
weights_values.sort(key=lambda x: x[1]... |
def _adjust_kinds(value):
"""Ensure kind is lowercase with a default of "metric".
Rewrite deprecated field definitions for DivideMetirc, WtdAvgMetric,
IdValueDimension, LookupDimension.
"""
if isinstance(value, dict):
kind = value.get("kind", "metric").lower()
# measure is a synonym... |
def convex_hull_graham_scan(points):
"""
Adapted from Tom Switzer
"""
from functools import reduce
TURN_LEFT, TURN_RIGHT, TURN_NONE = 1, -1, 0
def cmp(a, b):
return (a > b) - (a < b)
def turn(p, q, r):
vectorial_product = (q[0] - p[0]) * (r[1] - p[1]) - (r[0] - p[0]) * (
... |
def mul_of_3_or_5(limit: int) -> int:
"""Computes the sum of all the multiples of 3 or 5 below the given limit,
using filter and range.
:param limit: Limit of the values to sum (exclusive).
:return: Sum of all the multiples of 3 or 5 below the given limit.
"""
return sum(filter(
lambda ... |
def linked_embeddings_name(channel_id):
"""Returns the name of the linked embedding matrix for some channel ID."""
return 'linked_embedding_matrix_%d' % channel_id |
def list_pad(l, pad_tok, max_length):
"""
Args:
sequences: a generator of list or tuple
pad_tok: the char to pad with
max_seq_len: max len for padding
Returns:
a list of list where each sublist has same length
"""
result = [l[x] if x < len(l) else pad_tok for x in ran... |
def get_Deborah_number(flow_rate, beam_size, q_vector, diffusion_coefficient):
"""May 10, 2019, Y.G.@CHX
get Deborah_number, the ratio of transit time to diffusion time, (V/beam_size)/ ( D*q^2)
flow_rate: ul/s
beam_size: ul
q_vector: A-1
diffusion_coefficient: A^2/s
return Deborah_numb... |
def _remove_none(**kwargs):
"""Drop optional (None) arguments."""
return {k: v for k, v in kwargs.items() if v is not None} |
def isItPublic(stringIp):
"""
Is this IP address public?
Parameters: string IP address of format "0.0.0.0" - "255.255.255.255"
If IPv4, public, and not reserved return True, else return False.
"""
# Private IPs
if stringIp[0:3] == "10.":
return False
for i in range(16, 32):
... |
def annotations_to_ytbb_labels(annotations, label_list, reverse_ytbb_map):
"""Convert annotations from labeling UI to match YTBB index labels.
Args:
annotations (List[Dict]): Contains list of annotation objects with keys
'key', 'notes', 'labels'.
label_list (List[str]): List of label... |
def _space_all_but_first(s: str, n_spaces: int) -> str:
"""Pad all lines except the first with n_spaces spaces"""
lines = s.splitlines()
for i in range(1, len(lines)):
lines[i] = ' ' * n_spaces + lines[i]
return '\n'.join(lines) |
def _format_ligand_dict(json_dict):
"""
Format ligand dictionary.
Parameters
----------
json_dict : dict
Dictionary with JSON file information.
Returns
-------
dict
Formatted dictionary as needed to initialize a Ligand object using **kwargs.
"""
ligand_dict = {... |
def decompose_fields(fields: list):
"""
Auxiliary func to check if 'fields' has a relationship expressed as <rel_name.rel_property>
:return Tuple (A, B) where A is the list of fields divided into possible relations and its subproperties,
and B is a boolean expressing if there is at least one rel... |
def millions(x, pos):
"""The two args are the value and tick position"""
if x:
return '%1.0f\\,M' % (x * 1e-6)
else:
return '0' |
def get_next_locations(cur_x, cur_y):
"""Get next locations from (cur_x, cur_y) location."""
changes = (
(-1, 0),
(1, 0),
(0, 1),
(0, -1),
)
return [(cur_x + change_x, cur_y + change_y)
for change_x, change_y in changes] |
def resolve_boolean_attribute_val(val):
""" To avoid boolean values to be handled as strings, this function returns the boolean value of a string.
If the provided parameter is not resolvable it will be returned as it was.
Args:
val:
Returns:
val
"""
try:
val = bool(in... |
def hsv_to_rgb(h, s, v):
"""
Taken from stackoverflow 24852345
"""
if s == 0.0: return (v, v, v)
i = int(h*6.)
f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6
if i == 0: return (v, t, p)
if i == 1: return (q, v, p)
if i == 2: return (p, v, t)
if i == 3: return (... |
def appendPasswordAsRootCommand(Command: str, Password: str) -> str:
"""Pipe 'process as SUDO' Command to the given Command.\n
Password might is a correct Sudopassword.\n
Return type: String.
"""
suffix = f"echo {Password} | sudo -S "
__Command = f'{suffix}{Command}'
return __Command |
def is_number(num):
"""Checks if num is a number"""
try:
int(num)
except ValueError:
return False
return True |
def _get_first_if_all_equal(lst):
"""
Get the first element of a list if all the elements of the list are
equivalent.
:param lst: The list of elements.
:type lst: list
"""
first = lst[0]
for el in lst[1:]:
if el != first:
return None
return first |
def days_per_month(leap=False):
"""Return array with number of days per month."""
ndays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if leap:
ndays[1]+= 1
return ndays |
def find_index(text, pattern):
"""Return the starting index of the first occurrence of pattern in text,
or None if not found.
O(n*m) where n is the length of the pattern and m is the length of the text"""
assert isinstance(text, str), 'text is not a string: {}'.format(text)
assert isinstance(pattern... |
def is_float(s):
"""
:param s: s is a string
:return: True if string s can be cast to a float
"""
try:
x = float(s)
return True
except:
return False |
def spechum2mixr(q):
"""
Calculate mixing ratio from specific humidity.
**Inputs/Outputs**
Variable I/O Description Units
-------- --- ----------- -----
q I Specific humidity kg/kg
r O Mixing ratio kg/kg
"""
return q/(1-q) |
def index_to_alg(cnt):
""" Convert a bit index to algebraic notation """
column = "abcdefgh" [int(cnt % 8)]
rank = "12345678" [int(cnt // 8)]
return column + rank |
def round_mean(avg_bias, sentences, k=4):
"""Compute the average and round to k places"""
avg_bias = round(float(avg_bias) / float(len(sentences)), k)
return avg_bias |
def findUniformStruct(sourceText):
""" Return uniform structures dict from glsl source code.
Args:
sourceText (str): glsl source code
Returns:
dict: uniform structures
"""
# Find uniform structure
structures = {}
index = sourceText.find('struct')
start =... |
def next(some_list, current_index):
"""
Returns the next element of the list using the current index if it exists.
Otherwise returns an empty string.
https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/#writing-custom-template-filters
"""
try:
return some_list[int(current_i... |
def fzmatch(haystack, needle, casesensitive=None):
"""Very simple fuzzy match, checks to see if all the characters in needed
are in the haystack in left-to-right order.
The function will attempt to match a space character, if no match is found
space is ignored and moves on to matching the next characte... |
def float_in_filename(num):
""" Function to remove the "." of the float to avoid it in filenames.
It convert the Numeric input into a str
If the input is simply an int, it just converts it into str
Parameters
----------
num: Numeric
Returns:
str
the string "dot" will replace the ... |
def breakWords(str):
"""This function will break up words for us."""
words = str.split(' ')
return words |
def add_header_field16(field_name, field_width):
"""
This method returns header field declaration
:param field_name: the name of the field
:type field_name: str
:param field_width: the size in bit of the field
:type field_width: int
:returns: str -- the code in plain text
:raises: None... |
def Cumfreq(symbol, dictionary):
"""
This Function Takes as inputs a symbol and a dictionary containing
all the symbols that exists in our stream and their frequencies
and returns the cumulative frequency starting from the very
beginning of the Dictionary until that Symbol.
Arguments:
symbol {[t... |
def auto_example(x):
"""Docstring"""
print('Called example function: ' + str(x))
return x |
def hsv2rgb(hue, saturation, value):
"""Transform a HSV color to a RGB color."""
c = value * saturation
x = c * (1 - abs((hue / 60) % 2 - 1))
m = value - c
if 0 <= hue < 60:
return c + m, x + m, m
elif 60 <= hue < 120:
return x + m, c + m, m
elif 120 <= hue < 180:
ret... |
def unit_interval(x, xmin, xmax, scale_factor=1.):
"""
Rescale tensor values to lie on the unit interval.
If values go beyond the stated xmin/xmax, they are rescaled
in the same way, but will be outside the unit interval.
Parameters
----------
x : Tensor
Input tensor, of a... |
def primary_container_name(names, default=None, strip_trailing_slash=True):
"""
From the list of names, finds the primary name of the container. Returns the defined default value (e.g. the
container id or ``None``) in case it cannot find any.
:param names: List with name and aliases of the container.
... |
def YCbCrtoRGB(Y, Cb, Cr):
""" convert YUV to RGB color
:param Y: Y value (0;255)
:param Cb: Cb value (0;255)
:param Cr: Cr value (0;255)
:return: RGB tuple (0;255) """
cb = Cb - 128.0
cr = Cr - 128.0
R = Y + (1.402 * cr)
G = Y - (0.34414 * cb) - (0.71414 * cr)
B = Y + (1.772 * ... |
def get_probabilistic_loss_weight(current_step, annealing_step):
"""
Tiny function to get adaptive probabilistic loss weight for consistency across all methods.
"""
probabilistic_loss_weight = min(1.0, current_step / annealing_step)
probabilistic_loss_weight = (100 ** probabilistic_loss_weight - 1.0... |
def is_cjk(ch):
"""
"""
code = ord(ch)
return 0x4E00 <= code <= 0x9FFF or \
0x3400 <= code <= 0x4DBF or \
0x20000 <= code <= 0x2A6DF or \
0x2A700 <= code <= 0x2B73F or \
0x2B740 <= code <= 0x2B81F or \
0x2B820 <= code <= 0x2CEAF or \
0xF900 <= code <= 0xFA... |
def zaid2za(zaid):
"""
Convert ZZAAA to (Z,A) tuple.
"""
# Ignores decimal and stuff after decimal.
zaid = str(int(zaid))
Z = int(zaid[:-3])
A = int(zaid[-3:])
return (Z, A) |
def parse_env_latex(key, value):
"""Parse paragraph opening to extract environment name."""
if key == 'Para':
if len(value) >= 1:
content = value[0]['c']
if content[:6] == 'begin+' or content[:6] == 'begin-':
return 'begin', content[6:]
if content[:4] ... |
def translate(seq):
"""Translate a string containing a nucleotide sequence into a string
containing the corresponding sequence of amino acids . Nucleotides are
translated in triplets using the table dictionary; each amino acid 4 is
encoded with a string of length 1. """
table = {
'ATA': 'I',... |
def attrib(name, type, doc=None, objectpath=None, filepath=None, extra=None):
"""
Helper function for codecompletion tree.
"""
return (name, type, doc, objectpath, filepath, extra) |
def respond_raw(request, template, context=None, args=None, headers=None):
"""Sends a raw response, that is the parameters passed to the
respond function that is mentioned in corresponding stubout.Set
"""
return {
'request': request,
'template': template,
'context': context,
'args': arg... |
def urljoin(*pieces):
"""Join componenet of url into a relative url
Use to prevent double slash when joining subpath
"""
striped = [s.strip('/') for s in pieces]
return '/'.join(s for s in striped if s) |
def counter_table(sai_id):
"""
:param if_name: given sai_id to cast.
:return: COUNTERS table key.
"""
return b'COUNTERS:oid:0x' + sai_id |
def bbh_keys_from_simulation_keys(simulation_keys):
"""Extract BBH simulations from a list of all simulations
Note that this function is maintained here for precise backwards-compatibility.
More useful functions may be found in `sxs.utilities`.
"""
return [simulation_key for simulation_key in simu... |
def getattribute(value, arg):
"""
Gets an attribute of an object dynamically from a string name
Example: {{ variable|getattribute:"name" }}
Example: {{ variable|getattribute:variable }}
"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key'):
... |
def tab_to(num_tabs, line):
"""Append tabs to a line of text to reach a tab stop.
Args:
num_tabs (int): Tab stop to obtain (0 = column 0, 1 = column 8, etc.)
line (str): Line of text to append to
Returns:
str: line with the correct number of tabs appeneded. If the line already
... |
def split_input_target(chunk):
"""[summary]
Define the function for splitting x & y
Args:
chunk ([type]): [description]
Returns:
[type]: [description]
"""
input_seq = chunk[:-1]
output_seq = chunk[1:]
return input_seq, output_seq |
def str_choices(choices):
"""Returns {choice1, ..., choiceN} or the empty string"""
if choices:
return '{%s}' % ', '.join(choices)
return '' |
def crit_lt(val, tol):
"""Less than criterion."""
return val < 0 and -val < tol |
def dot3(v1, v2):
"""
dot3
"""
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2] |
def _is_unquoted(s):
"""Check whether this string is an unquoted identifier."""
s = s.replace('_', 'a')
return s.isalnum() and not s[:1].isdigit() |
def IdentityLayer(inp, inp_dim, outp_dim, vs, name="identity_layer", use_bias=True, initializer=None):
"""An identity function that takes the same parameters as the above layers."""
assert inp_dim == outp_dim, "Identity layer requires inp_dim == outp_dim."
return inp |
def get_list_labels(paths, num_classes):
"""
create a list with all labels from paths
:param paths: path to all images
:param num_classes: number of classes considered (an be either 10 or 50)
:return: the list of labels
"""
# ex : paths[0] -> 's11/o1/C_11_01_000.png'
# [o1, ..., o5] ->... |
def map_to_twinmaker_data_type(attr_name, data_type):
"""
DATA_TYPE Type
-------------------
6 Int16
8 Int32
11 Float16
12 Float32
13 Float64
101 Digital
104 Timestamp
105 String
102 Blob
"""
... |
def address_string(content, labels=False):
"""content is a dict of the form::
{u'private': [{u'version': 4,
u'addr': u'10.35.23.30',
u'OS-EXT-IPS:kind':u'fixed'},
{u'version': 4,
u'addr': u'198.202.120.194',
... |
def palindrome(word : str) -> int:
"""
Given a string, calculates the amount of palindromes that exist within that string
Parameters
----------
word : str
String that may contain palindrome sub-strings
Returns
-------
int
number of palindromes in string
"""
... |
def _spark_calc_values_chunk(points):
"""
Compute some basic information about the chunk points values
The returned information are :
* count : the number of points in chunk
* max : the maximum value in chunk
* min : the minimum value in chunk
* sum : the sum of the values in chunk
* sq... |
def baseQ(n, b):
"""
Convert base 10 into base b.
"""
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1] |
def getData (tup):
"""
argument: tuple with tuple of int[0] and string[1] inside
return: int for smallest int, largest int, number of unique strings
"""
numbers = ()
words = ()
for elem in tup:
if elem[0] not in numbers and (type(elem[0])==int):
numbers = numbers + (elem... |
def invoke(collection, method_name, *args, **kargs):
"""Invokes the method named by `method_name` on each element in the
`collection` returning a list of the results of each invoked method.
Args:
collection (list|dict): Collection to iterate over.
method_name (str): Name of method to invoke... |
def merge_location(lng, lat):
""" merge location to amap str
>>> merge_location(111.1, 22.22) == u'111.100000,22.220000'
True
>>> merge_location(111.11111123242, 22.22222212) == u'111.111111,22.222222'
True
:param lng: longitude,
:param lat: latitude
:return formatted location
"""
... |
def truncate_field(content):
"""
Truncate a string to Discord's requirement for embed fields,
i.e. a maximum length of 1024.
Args:
content (str): String to truncate.
Returns:
str: Possibly truncated string, with ellipsis if truncated.
Todo:
This currently uses a naive ... |
def is_uninformative(index_list, max_len):
"""
a boolean function to determine whether an input text is informative or not.
Since the index 0 is used for padding and the index 1 is used for out-of-vocabulary tokens, when all token indices
for an input text is either 0 or 1 only (equivalently small t... |
def isWall(mapObj, x, y):
"""Returns True if the (x, y) position on
the map is a wall, otherwise return False."""
if x < 0 or x >= len(mapObj) or y < 0 or y >= len(mapObj[x]):
return False # x and y aren't actually on the map.
elif mapObj[x][y] in ('#', 'x'):
return True # wall is bloc... |
def compute_iou(box1, box2):
"""xmin, ymin, xmax, ymax"""
A1 = (box1[2] - box1[0])*(box1[3] - box1[1])
A2 = (box2[2] - box2[0])*(box2[3] - box2[1])
xmin = max(box1[0], box2[0])
ymin = max(box1[1], box2[1])
xmax = min(box1[2], box2[2])
ymax = min(box1[3], box2[3])
if ymin >= ymax or xm... |
def _isn(val1, val2) -> float:
"""Distance computation for 'is not'"""
if val1 is not val2:
return 0.0
return 1.0 |
def datestring_to_sql_parameter(datestring):
"""
Converting date string into a dictionary suitable for the sql parameters
:param datestring (string): string that contain a start and end date in the format %Y%m%d_to_%Y%m%d
:return date_sql_param (dict): dictionary with the date parameters defined to con... |
def _getcontextrange(context, config):
"""Return the range of the input context, including the file path.
Return format:
[filepath, line_start, line_end]
"""
file_i = context['_range']['begin']['file']
filepath = config['_files'][file_i]
line_start = context['_range']['begin']['line'][0]
... |
def calculate_xy_coords(image_size, screen_size):
"""Calculates x and y coordinates used to display image centered on screen.
Args:
image_size as tuple (int width in pixels, int height in pixels).
screen_size as tuple (int width in pixels, int height in pixels).
Returns:
tuple (int x... |
def remove_item(inventory, item):
"""
Remove an item from inventory if it exists.
:param inventory: dict - inventory dictionary.
:param item: str - item to remove from the inventory.
:return: dict - updated inventory dictionary with item removed.
"""
if item in inventory:
del inven... |
def str_to_candidates(s):
"""
>>> str_to_candidates("345")[4]
True
"""
return {i: str(i) in s for i in range(10)} |
def find_prime(chart):
"""
:param chart:
:return:
"""
prime = []
for col in range(len(chart[0])):
count = 0
pos = 0
for row in range(len(chart)):
# find essential
if chart[row][col] == 1:
count += 1
pos = row
... |
def fixture_ref_flattened_dashes():
"""Flattened version of `ref` with a `.` delimiter."""
ref_flattened_dashes = {"a": 1, "b-c": 2, "d-e-f": 3}
return ref_flattened_dashes |
def cnt_ovlp_occur(string, sub):
"""
Count overlapping occurrence of `sub` in `string`. E.g. `cnt_ovlp_occur("CCC", "CC")` would return 2.
Python's `str.count(word)` function does NOT count overlapping occurrence. E.g. "CCC".count("CC") only returns 1.
:param string:
:param sub:
:return:
"... |
def signed(val: float) -> float:
"""Value might be negative."""
if val > 0x7FFF:
return val - 0xFFFF
return val |
def internal_filter(path, parent, children):
"""Skip any object with "internal" in the name."""
del path
del parent
children = [
(name, value) for (name, value) in children if "internal" not in name
]
return children |
def preprocess(data, fill_value, max_value, add_offset, scale_factor):
""" scale it into [0, 1]
"""
for v in [fill_value, max_value, add_offset, scale_factor]:
#print(v, type(v))
pass
return (data-add_offset)/(max_value*scale_factor - add_offset) |
def _is_mmf_header(line):
"""Returns whether a line is a valid MMF header."""
return line.startswith('---------- ') or line.startswith('MMMMM----- ') |
def get_broadcast_shape(x_shape, y_shape, prim_name):
"""
Doing broadcast between tensor x and tensor y.
Args:
x_shape (list): The shape of tensor x.
y_shape (list): The shape of tensor y.
prim_name (str): Primitive name.
Returns:
List, the shape that broadcast between ... |
def get_seed_nodes_json(json_node: dict, seed_nodes_control: dict) -> dict:
""" We need to seed some json sections for extract_fields.
This seeds those nodes as needed. """
seed_json_output = {}
for node in seed_nodes_control:
for key, value in node.items():
if value in json_node... |
def bool_like(value, name, optional=False, strict=False):
"""
Convert to bool or raise if not bool_like.
Parameters
----------
value : object
Value to verify
name : str
Variable name for exceptions
optional : bool
Flag indicating whether None is allowed
stric... |
def without_last(string: str) -> str:
"""
>>> without_last('abc')
'ab'
"""
return string[:-1] |
def isUrl(Path):
"""
Determine if the source is a URL or a file system path.
"""
if Path != None and ("http:" in Path or "https:" in Path):
return True
return False |
def parse_command(command_str, valid_comms):
"""
valid_comms: Collection of valid commands
"""
command_str = command_str.strip()
if command_str in valid_comms:
return command_str
else:
raise ValueError |
def _error_factory(message, error):
"""
Package the error info in the proper format for the marshalling function
:param message:
:param error:
:return: ErrorResponseModel
"""
return {
'message': message,
'error': error
} |
def add_geocodes(row, **kw):
"""Fill up the country and region fields."""
row['beneficiary_country_code'] = kw['country_code']
row['beneficiary_country'] = kw['country']
row['beneficiary_nuts_code'] = kw['nuts_code']
row['beneficiary_nuts_region'] = kw['region']
return row |
def static_regions_to_regions(static_regions):
"""Convert a list of static regions to ordinary regions"""
return [sr.to_region() for sr in static_regions] |
def new_value(start, end, frac):
"""Get value at a fraction of an interval
Args:
start (number): Start of interval
end (number): End of interval
frac (number): Fraction of interval
Returns:
number: Value at a fraction of an interval
"""
return (end - start) * frac +... |
def normalize_run_info(run_info):
"""Normalize all dictionaries describing a run.
Args:
run_info (List[Dict]): The list of dictionaries to be normalized.
Returns:
List[Dict]: The input run_info but with each dictionary now having all the same keys. Note
that there will be empty ... |
def parse_links(this_sample_id, links, verbose=False):
"""
Parse the links field
:param this_sample_id:
:param links:
:param verbose: more output
:return:
"""
link_text=""
for child in links:
if 'type' in child.attrib and "entrez" == child.attrib['type']:
link_te... |
def normalise_dict(d):
""" Recursively convert dict-like object (eg OrderedDict) into plain dict.
And sorts list values.
:param d: dict input
"""
out = {}
for k, v in d.items():
if hasattr(v, 'items'):
out[k] = normalise_dict(v)
elif isinstance(v, list):
... |
def uws(t: int, tstart: int, eps: float, alpha: int) -> float:
"""Unbounded-window scheduling function."""
# assert 0 <= tstart
# assert 0.0 <= eps
# assert 0 <= alpha
t = max(t, tstart)
multiplier = (1 / float(t - tstart + 1)) ** alpha
multiplier = 0.0 if multiplier < eps else mu... |
def laplacian_term(root_dist, weighted):
"""Correction term based on the training dataset distribution
"""
if weighted:
category_map = {category[0]: 0.0 for category in root_dist}
else:
total = float(sum([category[1] for category in root_dist]))
category_map = {category[0]: cat... |
def parse_to_boolean(val):
"""
Convert value to boolean.
"""
return val in [True, 'True', 'true', 1, '1', 'Yes', 'yes'] |
def minMax(xs):
"""Calcule le minimum et le maximum d'un tableau de valeur xs (non-vide !)"""
min, max = xs[0], xs[0]
for x in xs[1:]:
if x < min:
min = x
elif x > max:
max = x
return min,max |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.