content stringlengths 42 6.51k |
|---|
def expand(inputs):
"""Expands a flat dict based on the key structure.
The output of a model might be in the form {'output_4_1_1: tensor, ...} which
means that the tensor is nest inside a tuple of depth 3, on the 4th position
at the first level, the first one at the second etc. The goal of this function
is t... |
def format_flux_mode_indices(atom_indices):
""" formats the atom indices for flux modes
"""
# Build string containing the values of each keyword
flux_mode_idx_string = ''
for vals in atom_indices:
flux_mode_idx_string += '{0:<4d}'.format(vals)
return flux_mode_idx_string |
def rstrip(s, strip):
"""What I think str.rstrip should really do"""
if s.endswith(strip):
return s[:-len(strip)] # strip it
else:
return s |
def ensure_end(haystack, ending):
"""
Ensure that string ends with specific character sequence.
@type: haystack: str
@type: ending: str
@returns: str
"""
if haystack.endswith(ending):
return haystack
else:
return haystack+ending |
def _looks_like_an_s3_bucket_name(bucket):
"""
Return True if bucket looks like a valid S3 bucket name. For this test, we
assume S3 bucket names should be lower case ASCII alphanumeric,
dash-delimited.
"""
# return list of characters in range - inclusive of both ends
def _chr_range(a, b):
... |
def generate_mock_har(*args) -> dict:
"""build facility for unit tests used to generate hars with GA hits
GA hits will get values in argument
Args:
schema (list): 'dp' parameters for GA hits "A" ,"x", "B",..
Returns :
dict : har
example : generate_mock_har_ga("A","B") ->
... |
def grab_external_id(stix_object, source_name):
"""Grab external id from STIX2 object"""
for external_reference in stix_object.get("external_references", []):
if external_reference.get("source_name") == source_name:
return external_reference["external_id"] |
def get_connections(data):
"""Build a graph of all the connections between the rooms."""
connections = dict()
for passage in data:
start, end = passage.split('-')
if start in connections.keys():
connections[start].append(end)
else:
connections[start] = [end]
... |
def pressure_delta ( density, r_cut ):
"""Calculates correction for Lennard-Jones pressure due to discontinuity in the potential at r_cut."""
import math
# density, r_cut, and the results, are in LJ units where sigma = 1, epsilon = 1
sr3 = 1.0 / r_cut**3
return math.pi * (8.0/3.0) * ( sr3**3 ... |
def render_form_delete_widget(field):
"""Renders the widget for a form's DELETE `field`."""
if isinstance(field, str):
return {}
context = {}
context['widget'] = field.as_widget(
attrs={'aria-label': 'delete field checkbox'})
return context |
def pair(iterable):
"""
Returns the first to elements of iterable, supplemented with None values
if the iterable has less than 2 elements.
"""
l = list(iterable)[:2]
return l if len(l) > 1 else ((l + [None, ]) if l else [None, None]) |
def get_by_lcp_name(yaml, lcpname):
"""Returns the loopback by a given lcp name, or None,None if it does not exist"""
if not "loopbacks" in yaml:
return None, None
for ifname, iface in yaml["loopbacks"].items():
if "lcp" in iface and iface["lcp"] == lcpname:
return ifname, iface
... |
def metric_improved(metrics, best_metric, metric_type):
""" Function that returns True if the current metric is better than the best so far; Else False """
if metric_type == "val_f1" or metric_type == "val_accuracies":
return metrics[metric_type][-1] >= best_metric
else:
return metrics[... |
def travis_env_to_tox_env(travis_env):
"""Converts a Travis-style environment (e.g.: "2.6") to a Tox-style
environment (e.g.: "py26")."""
travis_env = str(travis_env)
if not travis_env.startswith('py') and travis_env[1] == '.':
return 'py' + travis_env.replace('.', '')
else:
return... |
def get_percentage(part, whole):
"""Utility method for getting percentage of part out of whole
Parameters
----------
part: int, float
whole: int, float
Returns
-------
int : the percentage of part out of whole
"""
if 0 in [part, whole]:
return float(0)
return 100 * ... |
def _get_dir_names(param):
"""Gets the names of the directories for testing the given parameter
:param param: The parameter triple to be tested.
:returns: A list of directories names to be used to test the given
parameter.
"""
return [
'-'.join([param[0], str(i)])
for i in ... |
def create_test_suite_attrib(junit_results):
"""Returns a JSON with attributes for JUnit testsuite: https://llg.cubic.org/docs/junit/
The JMeter JTL file must be in CSV format.
"""
return {
'id': '1',
'name': 'load test',
'package': 'load test',
'hostname': 'Azure DevOps',
'time': str(junit_results['time'... |
def splitFill(text, delim, count, fill=u""):
"""
Split text by delim into up to count pieces. If less
pieces than count+1 are available, additional pieces are added containing
fill.
"""
result = text.split(delim, count)
if len(result) < count + 1:
result += [fill] * (count + ... |
def parse_otu_map(lines):
"""Returns {rep: [members]}, members include rep"""
res = {}
for l in lines:
fields = l.strip().split('\t')
rep = fields[1]
members = fields[1:]
res[rep] = members
return res |
def _check_target_size(size):
"""
Common check to enforce type and sanity check on size tuples
:param size: Should be a tuple of size 2 (width, height)
:returns: True, or raises a ValueError
"""
if not isinstance(size, (list, tuple)):
raise ValueError("Size must be a tuple")
if len(... |
def relative_to_absolute_scale_factors(scale_factors):
""" Convert relative to absolure scale factors.
Arguments:
scale_factors (list[int]): relative scale factors
"""
abs_scale_factors = [scale_factors[0]]
for scale_factor in scale_factors[1:]:
abs_scale_factor = [abs_sf * sf for a... |
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as a tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs |
def _parse_date(text):
"""Parse a text date like ``"2004-08-30`` into a triple of numbers.
May fling ValueErrors or TypeErrors around if the input or date is invalid.
It should at least be a string--I mean, come on.
"""
return tuple(int(i) for i in text.split('-')) |
def ilen_exhaustive(seq):
"""
Given a finite iterator, return the number of items. As a necessary side
effect, this also exhausts the iterator.
>>> iterator = iter('abc')
>>> ilen_exhaustive(iterator)
3
>>> ilen_exhaustive(iterator)
0
"""
count = 0
for _ in seq:
coun... |
def get_bri_screen_mouse_direc(direc="right"):
"""
get_bri_screen_mouse_direc()
Returns direction for screen and mouse.
Optional args:
- direc (str): direction
Returns:
- direc (str): direction wrt screen and mouse
"""
if "right" in direc or "temp" in direc:
direc... |
def _translate_to_str(val):
"""Reusable by most interpreters"""
return '{}'.format(val) |
def fun(x):
""" (function) -> float
<x> is the function to differentiate
"""
return 3 * x ** 2 + 5 |
def numbered_file_split_key(x):
""" for sorting purposes, split filenames like '238048.11', '238048.17',
'238048.0' into lists of integers. E.g.:
for fname in sorted(filenames, key=numbered_file_split_key):
do_things_ordered_by_integer_sort()
"""
try:
return [int(i) for... |
def formatMultiplier(stat : float) -> str:
"""Format a module effect attribute into a string, including a sign symbol and percentage symbol.
:param stat: The statistic to format into a string
:type stat: float
:return: A sign symbol, followed by stat, followed by a percentage sign.
"""
return f... |
def duR_calc(i,u,i_ref,wp):
"""Calculate derivate of 1st order filter- real component"""
duR = (wp)*(-u.real + i_ref.real - i.real)
return duR |
def tasks_are_available(tasks):
"""
Are there tasks that can be scheduled?
:param tasks: list of tasks
:return: if there are still available tasks to schedule
"""
task_not_finished_not_scheduled_count = len(tasks)
for task in tasks:
if task.getisTaskFinished():
continue
... |
def firstLetterCipher(ciphertext):
"""
Returns the first letters of each word in the ciphertext
Parameters:
ciphertext (str): The encrypted text
Returns:
plaintext (str): The decrypted text
Example:
Cipher Text: Horses evertime look positive
Decoded text: Help
"""
ciphert... |
def _pairs(items):
"""Given an list of items [a,b,a,b...], generate pairs [(a,b),(a,b)...].
Args:
items: A list of items (length must be even)
Returns:
A list of pairs.
"""
assert len(items) % 2 == 0
return list(zip(items[::2], items[1::2])) |
def enumerate(s, start=0):
"""Returns a list of lists, where the i-th list contains i+start and
the i-th element of s.
"""
return list(list([i+start, s[i]]) for i in range(0, len(s))) |
def set_all(n):
"""
Returns a new set composed by `n` elements.
Examples
========
Build a set with 10 elements within it:
>>> bin(set_all(10))
'0b1111111111'
"""
return (1 << n) - 1 |
def uidGenerator(size=6):
"""
A function which will generate a 'random' string of the specified length based on the UUID
"""
import uuid
randomStr = str(uuid.uuid4())
randomStr = randomStr.replace("-","")
return randomStr[0:size] |
def camel_to_snake(text):
"""Convert string in camelCase to snake_case."""
import re
str1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', str1).lower() |
def map_attributes(attributes):
"""
By default pandoc will return a list of string for the paired attributes.
This function will create a dictionary with the elements of the list.
:param attributes: A list of in the order of: key1, value1, key2, value2,...
:type attributes: list[str]
:return: T... |
def merge_numbers(string):
"""Merge numbers that have their first digit separated from the rest by white spaces
Parameters
----------
string : string
Text needs processing
Returns
-------
s : string
New string without numbers having their first digit separated from... |
def _set_dim_and_center(dim, center, default_dim=2):
"""
A helper function to check that a user provided dim and center match, or if no user provided dim and center exist
sets default values: dim=2 and center=the origin in R^dim.
"""
# Set the dimension
if dim is None:
if center is None:... |
def hovertext_ip_addr(ip_addr):
"""
Passed an IP address and return it
wrapped in extra text to convey context
"""
return "IP Address: " + str(ip_addr) |
def findCharacter(stringList, patternCharacter):
"""
Find the specific character from the list and return their indices
"""
return([ind for ind, x in enumerate(list(stringList)) if x == patternCharacter]) |
def is_number(x):
"""Is x a number? We say it is if it has a __int__ method."""
return hasattr(x, '__int__') |
def parse_value(value):
"""
Tries to convert `value` to a float/int/str, otherwise returns as is.
"""
for convert in (int, float, str):
try:
value = convert(value)
except ValueError:
continue
else:
break
return value |
def hash_mid_square(item, tablesize):
"""
Another numerical technique for constructing a hash function is called the mid-square method.
We first square the item, and then extract some portion of the resulting digits. For example,
if the item were 44, we would first compute 442=1,936442=1,936. By extrac... |
def get_metrics_str__(metrics_list, batch_or_cum_metrics, validation_dataset=False):
""" internal helper functions: formats metrics for printing to console """
metrics_str = ''
for i, metric in enumerate(metrics_list):
if i > 0:
metrics_str += ' - %s: %.4f' % (
me... |
def escape_list(mylist, escape_func):
"""Escape a list of arguments by running the specified escape_func
on every object in the list that has an escape() method."""
def escape(obj, escape_func=escape_func):
try:
e = obj.escape
except AttributeError:
return obj
... |
def cleanup(dirty):
""" remove invalid characters from phone number """
allowed = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
newstring = ""
for char in dirty:
if char in allowed:
newstring += char
return newstring |
def coach_dead_zone(motor_output, coach_dead_zone):
"""This is the dead zone with Coach's equation. I really doubt I wrote
this correctly, please double-check before deployment"""
if motor_output == 0:
return 0
elif motor_output > 0:
return (motor_output**3 + motor_output)/2
else:
... |
def maketmp(name):
"""Make a tmp variable name"""
return "tmp" + str(name) |
def str_format(text, data, enc_char):
"""This takes a text template, and formats the encapsulated occurences with data keys
Example: if text = 'My name is $$name$$', provided data = 'Bob' and enc_char = '$$'.
the returned text will be 'My name is Bob'.
"""
for key in data:
val = data[key]
text = tex... |
def _get_live_channels(Xs, channel_indices=None):
"""
Determine which channels are not None.
Parameters
----------
Xs : list
List of feature matrices and None placeholders.
channel_indices : int, list/array of ints, or None, default=None
- If int or list/array of int: Indices of... |
def htmlcolors_to_rgba(colors):
"""
:param colors: a 1d list of 5 html colors of the format "#RRGGBBAA".
return a 1d list of 20 floats in range [0, 1].
"""
return [int(x, 16) / 255.0 for s in colors \
for x in (s[1:3], s[3:5], s[5:7], s[7:])] |
def display(choices, slug):
"""
Get the display name for a form choice based on its slug. We need this function
because we want to be able to store ACS data using the human-readable display
name for each field, but in the code we want to reference the fields using their
slugs, which are easier to ch... |
def get_rank(string):
"""
Parses a string representing a rank. Returns a string in the correct form
for the lookup table. Returns None if the input could not be parsed.
"""
if "ace" in string or string=="a":
return "A"
if "king" in string or string=="k":
return "K"
if "queen"... |
def conv_output(shape, Kernel, Padding=(0, 0, 0), Stride=(1, 1, 1)):
"""
Z : depth
Y : height
X : width
P : padding
K : kernel
"""
Z, Y, X = shape
Z_out = ((Z + 2 * Padding[0] - (Kernel[0] - 1) - 1) / Stride[0]) + 1
Y_out = ((Y + 2 * Padding[1] - (Kernel[1] - 1) - 1) / Stride[1]... |
def ip_is_ipv6(ip):
"""IP address is IPv6 or not, return True if it is"""
if ip.find(':') != -1:
return True
elif ip.find('.') != -1:
return False
else:
raise ValueError("Formatting error in IP address input. "
"Contains neither ':' or '.'") |
def _property_name_to_values(entities):
"""Returns a mapping of entity property names to a list of their values.
For example:
_property_name_to_values([{'cat': 5, 'dog': 10},
{'dog': 15, 'mouse': 'happy'}])
=> {'cat': [5], 'dog': [10, 15], 'mouse': ['happy']}
Args:
enti... |
def merge_protocols(ports=[]):
"""
This function merge rows having the exact same data (port, name,
description) but a different protocol.
:param ports: the list of ports
:return: all ports with merged protocols
:rtype: list
"""
keys = {}
for port in ports:
key = "{}-{}-{}".... |
def assignment_params_and_context(context, arg):
"""Expected assignment_params_and_context __doc__"""
return "assignment_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg) |
def _extract_source_file_path(label):
"""Gets relative path to source file from bazel deps listing"""
if label.startswith('//'):
label = label[len('//'):]
# labels in form //:src/core/lib/surface/call_test_only.h
if label.startswith(':'):
label = label[len(':'):]
# labels in form //t... |
def ms2min_sec(ms: int):
"""Convert milliseconds to 'minutes:seconds'."""
min_sec = f'{int(ms / 60000):02d}:{int(ms / 1000) % 60:02d}'
return min_sec |
def make_modbusmap_channel(i, chan, device_type_name):
"""Make a channel object for a row in the CSV."""
json_obj = {
"ah": "",
"bytary": None,
"al": "",
"vn": chan['subTitle'], # Name
"ct": "number", # ChangeType
"le": "16", # Length(16 or 32)
"grp": ... |
def is_short_option(argument):
"""
Check if a command line argument is a short option.
:param argument: The command line argument (a string).
:returns: ``True`` if the argument is a short option, ``False`` otherwise.
"""
return len(argument) >= 2 and argument[0] == '-' and argument[1] != '-' |
def validate_user_input(user_input):
"""
Validates user input
:param user_input: Input entered by user, in response to primary menu item
:return: (bool) True if user input is expected, False otherwise
"""
if user_input not in ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']:
pr... |
def binomial(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke.
See http://stackoverflow.com/questions/3025162/statistics-combinations-in-python
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1):
ntok *= n
... |
def get_overlap(window1, window2):
"""
Get the overlap of two time windows.
Parameters:
window1: the first of two time windows.
window2: the second of two time windows.
Returns:
A list of two: start and end times of the overlap.
"""
r, s = window1
p, q = window2... |
def _fix_url(url: str) -> str:
""" Add 'https://' to the start of a URL if necessary """
corrected_url = url if url.startswith("http") else "https://" + url
return corrected_url |
def escape_string(s):
""" Logic taken from the official rcon client.
There's probably plenty of nicer and more bulletproof ones
"""
st = ""
for index in range(len(s)):
st = (st + s[index] if s[index] != '\\' else st + "\\\\") if s[index] != '"' else st + "\\\""
return st |
def presses(phrase): # pragma: no cover
"""Given an old phone, how many touches for a given phrase."""
key_pad = {'1ADGJMPTW ': 1, 'BEHKNQUX0': 2, 'CFILORVY': 3,
'SZ234568': 4, '79': 5}
presses = 0
for i in phrase.upper():
for k, v in key_pad.items():
if i in k:
... |
def direction(col_spec):
"""
Gets direction for column expression (1 for ascending - 1 for descending).
"""
if isinstance(col_spec, int):
return 1 if col_spec >= 0 else -1
else:
assert col_spec
return 1 if col_spec[0] != "-" else -1 |
def get_captions(captions):
""" Group captions by image """
image_captions = {}
for caption in captions:
img_id = caption['image_id']
if not img_id in image_captions:
image_captions[img_id] = []
parsed_caption = caption['caption'].strip()
parsed_caption = ''.join(... |
def FileNameFromPath(pathplusfile, sep):
"""Return the filename string from a directory path"""
return pathplusfile.split(sep)[-1] |
def sumsq(values):
"""
Calculates the sum of squares of a list of values.
"""
return sum(map(lambda x: x ** 2, values)) |
def str_state(state,indent=4):
"""Print each variable in state, indented by indent spaces."""
result = ""
if state != False:
for (name,val) in vars(state).items():
if name != '__name__':
for x in range(indent): result = result + ' ' #sys.stdout.write(' ')
... |
def inside_angle_range(x, start, end, tol=0.0):
"""Assuming end is clockwise from start, is the angle x inside [start,end]
within some tolerance?
Parameters:
x (float): angle to test, in degrees
start (float): start angle of range, in degrees
end (float): end angle of range, in degr... |
def EmptyCheck(_data:list, _index:int, _indexList:list) -> bool:
"""
check if any element (index given by indexList) in Data is non zero
return True if any element is non zero; used for return_StarExistingData
"""
for i in _indexList:
if ( _data[0][_index][i] != '' ):
return... |
def get_storage_status(f):
"""Gets the storage status
"""
if f:
return f.get_storage_status() |
def make_title(msg: str) -> str:
"""Returns basic title string."""
return (
f'+{(len(msg) + 2)*"="}+\n'
f'| {msg} |\n'
f'+{(len(msg) + 2)*"="}+'
) |
def mapActions(symbols, actions, turtle):
"""Takes a sequence of symbols and maps them to actions.
symbols is a sequence.
actions is a dictionary mapping symbol->action
turtle is an implementation of the turtle interface.
Non mapped symbols are ignored (they do not generate an error!)
... |
def group_repr(group_keys):
"""Get a string representation of a list of group keys"""
if len(group_keys) == 0:
return "{}"
elif len(group_keys) == 1:
return str(group_keys[0])
else:
out = f"{group_keys[0]}"
for key in group_keys[1:]:
out += " x "
o... |
def fixup_columns(cols):
"""Replace index location column to name with `col` prefix
Args:
cols (list): List of original columns
Returns:
list: List of column names
"""
out_cols = []
for col in cols:
if type(col) == int:
out_cols.append('col{:d}'.format(col)... |
def iscc_clean(i):
"""Remove leading scheme and dashes"""
return i.split(":")[-1].strip().replace("-", "") |
def non_none_dict(d):
"""return a copy of the dictionary without none values."""
return dict([a for a in d.items() if a[1] is not None]) |
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
return {
'install': ['init']
} |
def is_None(obj):
"""returns True if object is None."""
return (obj is None) |
def R_sfg_halflight(mstar, alpha=0.115, beta=0.898, gamma=0.199, M0=3.016e10):
"""
Half-light radius of star-forming galaxies, assuming exponential profile.
Taken from Eq. 15 of Bonaldi et al. (arXiv:1805.05222).
Parameters
----------
mstar : array_like
Stellar mass, in Msun.
... |
def parse_tags(tagset):
"""Convert the tagset as returned by AWS into a normal dict of {"tagkey": "tagvalue"}"""
output = {}
for tag in tagset:
# aws is inconsistent with tags sometimes they use caps and sometimes not
if 'Key' in tag:
output[tag['Key']] = tag['Value']
if ... |
def _string_to_list(string_list):
""" Take a string with comma separated elements a return a list of
those elements.
:param string_list: String with comma separated elements.
:type string_list: str
:return: List with elements.
:rtype: list
"""
string_list_no_spaces = string_list.replace... |
def format_path(path):
"""
(str) -> str
Make sure that path ends with a backslash '/'
"""
return path if path.endswith('/') else path + '/' |
def is_native_reference(name):
"""Check if the given name belongs to a natively supported method of Python"""
return name in ['int', 'str', 'len', 'filter', 'enumerate', 'float', 'list', 'dict', 'pow', 'sum'] |
def is_variable(v):
"""Returns if input is of variable type."""
return type(v).__name__ == 'Variable' |
def get_dummy_stratas(metadatas: dict) -> dict:
"""
Create a dummy, one-factor 'no_stratification' categorical
metadata variables to stratify on for each metadata table.
Parameters
----------
metadatas : dict
Key = Metadata file path.
Value = Metadata table.
Returns
... |
def _base64_len(length):
"""Converts a length in 8 bit bytes to a length in 6 bits per byte base64 encoding"""
# Every 24 bits (3 bytes) becomes 32 bits (4 bytes, 6 bits encoded per byte)
# End is padded with '=' to make the result a multiple of 4
units, trailing = divmod(length, 3)
if trailing... |
def _zero_based_index(i, l, start=True):
"""Compute the 0-based index from the slice index i in a list of length l
Assuming step is 1.
Examples
--------
>>> _concrete_index(2, 100)
2
>>> _concrete_index(2, 100, start=False)
2
>>> _concrete_index(-1, 100, start=False)
99
>>> ... |
def check_items_equal(l):
"""
Check if all items from a list are equal
:param grammar: input list
:return: True if all items are equal. False otherwise
"""
return l[1:] == l[:-1] |
def is_none_string(val):
"""Check if a string represents a None value."""
if not isinstance(val, str):
return False
return val.lower() == 'none' |
def format_docstring(contents):
"""Python doc strings come in a number of formats, but LSP wants markdown.
Until we can find a fast enough way of discovering and parsing each format,
we can do a little better by at least preserving indentation.
"""
contents = contents.replace("\t", "\u00A0" * 4)
... |
def smallest_multiple_of_n_geq_m(n: int, m: int) -> int:
"""
Returns the smallest multiple of n greater than or equal to m.
:param n: A strictly positive integer.
:param m: A non-negative integer.
:return: The smallest multiple of n that is greater or equal to m.
"""
return m + ((n - (m % n... |
def add_class(value, arg):
"""
Adds arg class(es) to value (non form elements).
"""
print(value)
vals = value.split('\n')
final = ''
for val in vals:
# make sure list item is not blank
if val is not "":
i = val.find('>')
# insert class ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.