content stringlengths 42 6.51k |
|---|
def get_nice_str_list(items, *, item_glue=', ', quoter='`'):
"""
Get a nice English phrase listing the items.
:param sequence items: individual items to put into a phrase.
:param str quoter: default is backtick because it is expected that the most
common items will be names (variables).
:retur... |
def maxabs(vals):
"""convenience function for the maximum of the absolute values"""
return max([abs(v) for v in vals]) |
def build_initiator_target_map(connector, target_wwns, lookup_service):
"""Return a dictionary mapping server-wwns and lists of storage-wwns."""
init_targ_map = {}
initiator_wwns = connector['wwpns']
if lookup_service:
dev_map = lookup_service.get_device_mapping_from_network(
initiat... |
def create_edge_adjacency(npoints:int):
"""This describes how the points are connected with each other
example:
[[0, 1],
[1, 2],
[3, 4],
[4, 0]]
This says point 0 is connected to 1. 1 is connected to 2 and eventually 4 is connecte... |
def assign_prodstage(x):
"""
Takes a series object from df['dev_stage'] and returns the appropriate value for df['prod_stage']
based on conversion logic set below. Update as needed.
Prototype: prototype production
LRP: low rate production
FRP: full rate production
"""
... |
def print_message(name):
"""Print greeting message."""
res = f"Hello {name}!"
print(res)
return {
'message': res,
} |
def coding_strand_to_rna(strand):
"""returns the coding strand to the rna strand (T --> U)"""
strand = strand.upper().replace("T","U")
return strand |
def normalize_version_number(version_number):
"""Clean up the version number extracted from the header
Args:
version_number (str): Version number to normalize.
Returns:
The normalized version number.
"""
return version_number.replace('.', '_') |
def _replace_null(value, fallback):
"""Replaces a null value with a fallback."""
if value is None:
return fallback
return value |
def getChapterTitles(dirs):
"""
Returns a list of chapter names created by the user.
"""
titles = []
for folder in dirs:
print("\nThe folder name is:", folder)
titles.append(str(input("Chapter Title?: ")))
return titles |
def save_fields_to_vocab(fields):
"""
Save Vocab objects in Field objects to `vocab.pt` file.
"""
vocab = []
for k, f in fields.items():
if 'vocab' in f.__dict__:
f.vocab.stoi = dict(f.vocab.stoi)
vocab.append((k, f.vocab))
return vocab |
def get_repo_sig_ownership(repo, sigs):
"""
Get repository ownership
"""
for sig in sigs:
if repo in sig['repositories']:
return sig['name']
return "" |
def _find_comment_index(line):
"""
Finds the index of a ; denoting a comment.
Ignores escaped semicolons and semicolons inside quotes
"""
ret = []
escape = False
quote = False
for i, char in enumerate(line):
if char == '\\':
escape = True
continue
... |
def resolve_location_type_enum(location_id):
"""Resolve the location item ID to its type name."""
if 30000000 <= location_id <= 39999999:
return "solar_system"
if 60000000 <= location_id < 64000000:
return "station"
if location_id >= 100000000:
return "item"
return "other" |
def get_hosts_last_cpu_usage(ceilo, hosts):
"""Get last cpu usage of hosts.
:param ceilo: A Ceilo client.
:type ceilo: *
:param hosts: A set of hosts
:type hosts: list(str)
:return: A dictionary of (host, cpu_usage)
:rtype: dict(str: *)
"""
hosts_cpu_usage = dict() #dict of (h... |
def heron(a):
"""Calculates the square root of a"""
eps = 0.0000001
old = 1
new = 1
while True:
old,new = new, (new + a/new) / 2.0
print([old, new])
if abs(new - old) < eps:
break
return new |
def _r(alpha, d, M, e):
"""
Solve Eq. 10
"""
return 3. * alpha * d * (d - 1. + e) * M + M**3 |
def search_directories_for_file(f,*args):
"""search a given set of directories for given filename, return 1st match
Args:
f (str): filename to search for (or a pattern)
*args (): set for directory names to look in
Returns:
f (str): the *first* full path to where f is found, or f if... |
def coin_change(n, coins):
"""Finds minimum change for n"""
min_coins = [0] * (n+1)
for i in range(1, n+1):
if i in coins:
min_coins[i] = 1
else:
possible = []
for c in coins:
if i - c > 0:
possible.append(1 + min_... |
def dfs(graph, vertex, path):
"""
performs Depth First Search on a given graph (2D array matrix)
:param graph: 2D Array Matrix representing a directed graph
:param vertex: Current vertex being computed for traversal
:param path: Running path of search, required output for this problem
:return: D... |
def required_error(name):
"""
The error message presented when a required field is not present
"""
return "You must specify a value for {0}".format(" ".join(name.split("_"))) |
def adapt_value(value: str) -> str:
"""
Adapt string in PTB
"""
value = value.replace("-LRB-", "(")
value = value.replace("-RRB-", ")")
value = value.replace("-LSB-", "[")
value = value.replace("-RSB-", "]")
value = value.replace("-LCB-", "{")
value = value.replace("-RCB-", "}")
... |
def cal_intersection(points):
"""
Calculate the intersection of diagonals.
x=[(x3-x1)(x4-x2)(y2-y1)+x1(y3-y1)(x4-x2)-x2(y4-y2)(x3-x1)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)]
y=(y3-y1)[(x4-x2)(y2-y1)+(x1-x2)(y4-y2)]/[(y3-y1)(x4-x2)-(y4-y2)(x3-x1)]+y1
:param points: (x1, y1), (x2, y2), (x3, y3), (x4, y4... |
def graph_char(percentage):
"""Return the glyph representing `percentage` as close as possible.
:percentage: value to be represented
:returns: string consisting of the glyph
"""
if percentage > 1:
percentage = 1
# level contains the UTF-8 glyphs that represent percentages.
level = [... |
def compute_P(new_h, past_observations):
"""Computes weighting factor.
Parameters
----------
new_h : float
Altitude of current observation.
past_observations : list
List of past ``Observation`` objects of the same source.
"""
if len(past_observations) == 0:
P = 1
... |
def bit_count(i):
"""
Calculate the number of set bits (1's) in an int
:param int i: An int
:returns: The number of set bits in *i*
:rtype: int
"""
count = 0
while i:
i &= i - 1
count += 1
return count |
def is_list_child(tags, tag):
"""tag type
:type tag str
:type tags list
:return:
"""
i = 0
for t in tags:
if i > 1:
return True
if t == tag:
i += 1
return i > 1 |
def gcd(a : int, b : int) -> int:
"""
fast gcd
"""
while b != 0:
a, b = b, a % b
return a |
def ilog(n, base):
"""
Find the integer log of n with respect to the base.
>>> import math
>>> for base in range(2, 16 + 1):
... for n in range(1, 1000):
... assert ilog(n, base) == int(math.log(n, base) + 1e-10), '%s %s' % (n, base)
"""
count = 0
while n >= ba... |
def generate_specs_file_name(file_prefix):
""" Generate file name and suffix for specs-file (.json). """
return f"{file_prefix}-specs.json" |
def pad(sequences, max_length, pad_value=0):
"""Pads a list of sequences.
Args:
sequences: A list of sequences to be padded.
max_length: The length to pad to.
pad_value: The value used for padding.
Returns:
A list of padded sequences.
"""
out = []
for sequence in ... |
def imgsort(files):
"""
Sorts images from a directory into a list
"""
convFiles = []
for i in range(0, len(files)):
convFiles.append(int(files[i].split('.')[0]))
convFiles.sort(reverse=False)
for num in range(0, len(convFiles)):
convFiles[num] = str(convFiles[num])
ret... |
def _calc_type_bit_size(bit_size: int) -> int:
"""Calculate the bit length of a data type which can express the given bit length"""
if bit_size <= 8:
return 8
elif bit_size <= 16:
return 16
else:
return 32 |
def identity_fn(*args, **kwargs):
"""
Act as the default function for the :term:`conveyor operation` when no `fn` is given.
Adapted from https://stackoverflow.com/a/58524115/548792
"""
if not args:
if not kwargs:
return None
vals = kwargs.values()
return next(ite... |
def merge(d1, d2, merge_fn):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2.
Examples:
>>> d1
{'a': 1, 'c': 3, 'b': 2}
>>> ... |
def _coerce_run_param(name, val):
"""Ensures that named param is valid for the run command."""
if name == "flags":
return tuple(val)
return val |
def _assure_zipped(iterables):
""" """
if hasattr(iterables, '__len__'):
if len(iterables) == 1:
return iterables
else:
return zip(*iterables)
else:
return zip(*iterables) |
def _rxcheck(model_type, interval, iss_id, number_of_wind_samples):
"""Gives an estimate of the fraction of packets received.
Ref: Vantage Serial Protocol doc, V2.1.0, released 25-Jan-05; p42"""
# The formula for the expected # of packets varies with model number.
if model_type == 1:
_expec... |
def _checksum(railcar_number):
"""
Calculate checksum for a railcar number
@param {number} railcar_number
@return {number} checksum
"""
railcar_number = str( int( railcar_number) );
digit = 0
total = 0
for i in range(0, len(railcar_number), 1):
digit = int(railcar_number[i])... |
def can_import_module(module_name):
"""
Check if the specified module can be imported.
Intended as a silent module availability check, as it does not print ModuleNotFoundError traceback to stderr when
the module is unavailable.
Parameters
----------
module_name : str
Fully-qualifie... |
def median(data):
"""
Return the median of numeric data, unsing the "mean of middle two" method.
If ``data`` is empty, ``0`` is returned.
Examples
--------
>>> median([1, 3, 5])
3.0
When the number of data points is even, the median is interpolated:
>>> median([1, 3, 5, 7])
4.... |
def _RebuildArgs(**kwargs):
"""Filter out the args that were set to None - they were optional"""
result = {}
for key, value in kwargs.items():
if value is not None:
result[key] = value
return result |
def reorder_events(new_events):
"""
Place marginalize events at end of events
"""
new_events_reordered = []
for event in new_events:
if event[0] != 'marginalize':
new_events_reordered.append(event)
for event in new_events:
if event[0] == 'marginalize':
new... |
def invertir(palabra):
"""Esta funcion invierte un texto"""
tamano = len(palabra)
nueva_palabra = ""
for i in range( 1, ( tamano + 1 ) ):
nueva_palabra = nueva_palabra + palabra[-i]
return nueva_palabra |
def primeiro_pai(sub_pergaminho):
"""
:param pergaminho: sub_pergaminho a ser lido
:return: String com o nome do primeiro pai
"""
lista1 = []
lista2 = []
for i in range(len(sub_pergaminho)):
lista1.append(sub_pergaminho[i][1]) #extraindo filhos
lista2.append(sub_pergaminho[i]... |
def inverse_scale(X_, X_min, X_max):
"""
X_ is scaled
X is unscaled
"""
# with min=0, max=1
#sigma = X_
X = X_ * (X_max - X_min) + X_min
#with min=-1, max=1
X = (1/2)*(X_+1)*(X_max-X_min)+X_min
return X |
def is_config_field(attr: str):
"""Every string which doesn't start and end with '__' is considered to be a valid usable configuration field."""
return not (attr.startswith('_') or attr.endswith('_')) |
def generate_triples(x, y):
""" Use complex number squaring idea from https://www.youtube.com/watch?v=QJYmyhnaaek
to generate pythagorean triples.
Here, x > y and sum of generated triplets = 2x(x + y)
"""
n1 = x**2 - y**2
n2 = 2*x*y
n3 = x**2 + y**2
return n1, n2, n3 |
def moles_to_volume(pressure: float, moles: float, temperature: float) -> float:
"""
Convert moles to volume.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws
Wiki... |
def write_float(data):
"""Writes a formatted string from a float.
Floats are printed out in exponential format, to 8 decimal places and
filling up any spaces under 16 not used with spaces.
For example 1.0 --> ' 1.00000000e+00'
Args:
data: The value to be read in.
Returns:
A formatted... |
def primer_clean(primer):
"""Handle non-IUPAC entries in primers, maps I for inosine to N.
>>> primer_clean("I")
'N'
Inosine is found naturally at the wobble position of tRNA, and can match
any base. Structurally similar to guanine (G), it preferentially binds
cytosine (C). It sometimes used i... |
def normalize_column_to_midi_range(column, target_range, target_min_value):
"""
Normalizes the values to the values range used by the MIDI format
:param column: A list with the values that should be sonified
:param target_range: The target range
:param target_min_value: The target minimum value
... |
def chain_set(mixed_chains):
"""
Gives you a set of all the chains contained in the PDB file
"""
return set([i[0] for i in mixed_chains]) |
def compute_new_shape(origin_shape, indexes_shapes_info):
"""Compute new shape between origin shape with final shape."""
new_shape = []
for i in indexes_shapes_info:
if i == origin_shape:
new_shape.extend(origin_shape)
else:
new_shape.append(1)
return tuple(new_sh... |
def prepareHoverSignal(label, type_, posData, posPixel, draggable, selectable):
"""See Plot documentation for content of events"""
return {'event': 'hover',
'label': label,
'type': type_,
'x': posData[0],
'y': posData[1],
'xpixel': posPixel[0],
... |
def get_boundaries(bio):
"""
Extracts an ordered list of boundaries. BIO label sequences can be either
- Raw BIO: B I I O => {(0, 2, None)}
- Labeled BIO: B-PER I-PER B-LOC O => {(0, 1, "PER"), (2, 2, "LOC")}
"""
boundaries= []
i = 0
while i < len(bio):
if bio[i]... |
def sort_separation_tuple(separation):
"""Sort a separation
:param separation: Initial separation
:return: Sorted tuple of separation
"""
if len(separation[0]) > len(separation[2]):
return (
tuple(sorted(separation[2])),
tuple(sorted(separation[1])),
tupl... |
def match_2d(puzzle, row, col, word):
"""
Match word in current position in 4 directions
:param puzzle:
:param row:
:param col:
:param word:
:return: Tuple x, y end coordinates or None
"""
# Directions - left, down, right, up and 4 directions diagonally
dirs = [(1, 0), (0, 1), (... |
def sort_configs(configs): # pylint: disable=R0912
"""Sort configs by global/package/node, then by package name, then by node name
Attributes:
configs (list): List of config dicts
"""
result = []
# Find all unique keys and sort alphabetically
_keys = []
for config in configs:
... |
def is_color(s):
"""Test if parameter is one of Black or Red"""
return s in "BR" |
def _pack_image(pixels):
"""Do create 2d list of pixels and return the list."""
packed_pixels = []
pixel_length = pixels[0]
for i in range(0, len(pixels[1]), pixel_length):
packed_pixels.append(tuple(pixels[1][i:i + pixel_length]))
return packed_pixels |
def _valid_mutator_no_contributions_None(data):
"""
Contributions can be absent, in which case the Pydantic model will set the
default value to None, and not the empty list, make sure that works.
"""
data["contributions"] = None
return data |
def format_path_nodes(urls):
"""
Takes the content response from a neo4j REST API paths call (URLs to paths)
and returns a list of just the node ID's
"""
nodeIds = []
for url in urls:
nodeIds.append(url.split("/")[-1])
return nodeIds |
def _as_list(list_str, delimiter=','):
"""Return a list of items from a delimited string (after stripping
whitespace).
:param list_str: string to turn into a list
:type list_str: str
:param delimiter: split the string on this
:type delimiter: str
:return: string converted to a list
:r... |
def greatest_common_divisor(x, y):
"""get the greatest common divisor of rhs, lhs."""
if not isinstance(x, int) or not isinstance(y, int):
raise TypeError("Input of greatest common divisor should be integer")
if y < x:
y, x = x, y
if x == 0:
raise ValueError("Input can not be zer... |
def update_output_div(input_value):
"""Format the input string for displaying"""
return 'You\'ve entered "{}"'.format(input_value) |
def get_slot(datetime_sec, band):
"""
Return IBP schedule time slot (0 ... 17) from given datetime_sec (second
from UNIX time epoch) and band (14, 18, ..., 28) MHz value
"""
time_xmit = 10 # sec (transmitting time length)
n_slots = 18 # number of slots
period_sched = n_slots * time_xmit
... |
def subtract_plus(joined_fields):
"""Split the feature list by the delimiter to run per-element
checks
"""
return joined_fields.split('+') |
def needs_cblas_wrapper(info):
"""Returns true if needs c wrapper around cblas for calling from
fortran."""
import re
r_accel = re.compile("Accelerate")
r_vec = re.compile("vecLib")
res = False
try:
tmpstr = info['extra_link_args']
for i in tmpstr:
if r_accel.sear... |
def calculate_radius(mu, alpha):
"""
BUILD THIS FUNCTION TO RETURN A VALUE IN METERS
"""
return float(mu + alpha) / 10. |
def _zero_to_nan(values):
"""Replace every 0 with 'nan' and return a copy."""
return [float('nan') if x==0 else x for x in values] |
def __find_tokens_for_terms(index, search_terms):
"""Returns matching token objects for the given terms
"""
search_tokens = []
needles = set(search_terms)
for token in index:
for needle in needles:
if needle == token.term:
search_tokens.append(token)
... |
def make_json(structure, variable_name=None, indent=1, **k):
"""Converts something into a json string, optionally attributing the result
to a variable.
It also escapes the forward slash, making the result suitable
to be included in an HTML <script> tag.
"""
import json
s = json.dumps(struct... |
def remove_pickle_problems(obj):
"""doc_loader does not pickle correctly, causing Toil errors, remove from
objects.
"""
if hasattr(obj, "doc_loader"):
obj.doc_loader = None
if hasattr(obj, "embedded_tool"):
obj.embedded_tool = remove_pickle_problems(obj.embedded_tool)
if hasat... |
def remove_sp_chars(text):
"""
This removes special characters from the text
"""
return text.encode("ascii", "ignore").decode("ascii") |
def trigger_source_adv(session, Type='Int32', RepCap='', AttrID=1150052, buffsize=0, action=['Get', '']):
"""[Advanced Trigger Source <int32>]
Specifies the advanced trigger source, which are can be selected from enums of AgM933XTriggerSourceEnum.
These sources may be chosen as individual sources or logica... |
def list_to_string(list):
"""Transform a list to string"""
result = ""
for i in list:
result += i
return result |
def check_ipv6_rule_exists(rules, address, port):
""" Check if the rule currently exists """
for rule in rules:
for ip_range in rule['Ipv6Ranges']:
if ip_range['CidrIpv6'] == address and rule['FromPort'] == port:
return True
return False |
def export_report(ss, report_id, export_format, export_path, sheet_name):
"""
Exports a report, given export filetype and location. Allows export format 'csv' or 'xlsx'.
:param ss: initialized smartsheet client instance
:param report_id: int, required; report id
:param export... |
def format_bases(bases):
"""
Generate HTML that colours the bases in a string.
Args:
bases: A string containing a genetic sequence.
Returns:
An HTML string.
"""
formatted = ''
for b in bases:
formatted += '<span class="base-{}">{}</span>'.format(b,b)
return forma... |
def buy_sell_hold(*args):
"""
DOCSTRING
"""
columns = [c for c in args]
requirement = 0.02
for column in columns:
if column > requirement:
return 1
if column < -requirement:
return -1
return 0 |
def convert_SI(val, unit_in, unit_out):
"""Based on unitconverters.net."""
SI = {'Meter':1, 'Kilometer':1000, 'Centimeter':0.01, 'Millimeter':0.001,
'Micrometer':0.000001, 'Mile':1609.35, 'Yard':0.9144, 'Foot':0.3048,
'Inch':0.0254}
return val*SI[unit_in]/SI[unit_out] |
def bucket_sort(my_list: list) -> list:
"""
>>> data = [-1, 2, -5, 0]
>>> bucket_sort(data) == sorted(data)
True
>>> data = [9, 8, 7, 6, -12]
>>> bucket_sort(data) == sorted(data)
True
>>> data = [.4, 1.2, .1, .2, -.9]
>>> bucket_sort(data) == sorted(data)
True
>>> bucket_sor... |
def _convert_det_result_to_track_cal(det_data):
"""
det_data: kps, center, scale.
"""
image_id_list = []
for i in range(len(det_data['annotations'])):
image_id_list.append(det_data['annotations'][i]['image_id'])
image_id_set = list(set(image_id_list))
image_id_set.sort()
det_dat... |
def format_number_d(n: int, c: str) -> str:
"""
Formats a number on thousands.
:param n: Number
:param c: Format char
:return: Formatted number
"""
assert isinstance(n, int)
return format(n, ',').replace(',', c) |
def sanitize(value: str) -> str:
"""
On GCP publish format, the pattern adopted to define a row
is to use comma-separated values:
<IMAGE_NAME>,<TASK_NAME>,<TAGS>
Thus, we must sanitize the inputs <IMAGE_NAME>, <TASK_NAME>
and <TAG> to not include any "," characters, which could
break th... |
def get_families(current_algo, ml_algo):
"""
Given current algorithm we get its families.
current_algo : String
Input algorithm specified
ml_algo : Dictionary
key, value dictionary with family as key and algorithms as list of values
return: List
List of families returned
"""
... |
def contains_sublist(lst, sublst):
"""
Check if one list contains the items from another list (in the same order).
:param lst: The main list.
:param sublist: The sublist to check for.
:returns: :data:`True` if the main list contains the items from the
sublist in the same order, :data:... |
def fib2(n): # return Fibonacci series up to n
"""Calculates Fibonacci series up to n
Args:
n: High limit of the serie
Returns:
A list of the elements of the serie
"""
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a + b
return result |
def log_url(ip, port, project, spider, job):
"""
get log url
:param ip: host
:param port: port
:param project: project
:param spider: spider
:param job: job
:return: string
"""
url = 'http://{ip}:{port}/logs/{project}/{spider}/{job}.log'.format(
ip=ip, port=port, project=... |
def congruent_linear_generator(a : int, m : int, c : int, x0 : int):
"""
:def: Linear Congruent Generator Technique
: Method to generate pseudo-randoms
:
:param a: Random Parameter
:type a: int
:param c: Constant used to create bigger variation of generated numbers
:type c: int
... |
def power_level(x, y, num):
"""
>>> power_level(3, 5, 8)
4
>>> power_level(122, 79, 57)
-5
>>> power_level(217, 196, 39)
0
>>> power_level(101, 153, 71)
4
"""
rack_id = x + 10
power_level = rack_id * y
power_level += num
power_level *= rack_id
i... |
def get_mean(size, numbers):
"""
Gets the average for N elements in an array
Input:
- size(int): number of elements
- number(array[float]): list of element to calculate the mean
Returns:
- res(float): mean of the elements
"""
sum_nums = 0
for element in numbers:
sum_nums... |
def _make_sampling_table_ordering(tables, root_name):
"""
Returns a list of table names with the join_root at the front.
"""
return [root_name
] + [table.name for table in tables if table.name != root_name] |
def get_loc_offset(box_gt, box_anchor):
"""Computes the offset of a groundtruth box and an anchor box.
Args:
box_gt (array): groundtruth box.
box_anchor (array): anchor box.
Returns:
float: offset between x1 coordinate of the two boxes.
float: offset between y1 coordinate o... |
def get_time_group_max(time_group):
"""Return dictionary with max values for each time group."""
dict_time_max = {'year': 5000, # dummy large value for year since unbounded ...
'season': 4,
'quarter': 4,
'month': 12,
... |
def fahrenheit_to_celsius(temperature_F):
""" converts F -> C """
return (temperature_F - 32) * (5.0 / 9.0) |
def is_engine_in_list(engines_list, engine_class):
"""Checks if engine in the list
:param list engines_list: list of engines
:param engine_class: engine class
:returns: True if engine in the list
False if engine not in the list
"""
engines = filter(
lambda engine: isinsta... |
def index(item, seq):
"""Helper function that returns -1 for non-found index value of a seq"""
if item in seq:
return seq.index(item)
else:
return -1 |
def check_private_exponent(a, B=512):
"""
Checks the bit length of the given private exponent.
If you've asked for a random number of bit length at least :param:`B`, but are retrieving
numbers that are smaller than said size, you might want to check your RNG.
>>> B = 8
>>> a = 0b11111111
>... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.