content stringlengths 42 6.51k |
|---|
def escape_null(s: str) -> str:
"""Replaces each null character (\\0) in the input with \\\\0"""
return s.replace("\0", "\\0") |
def format_pos(pos):
"""
>>> print(format_pos({'line': 5, 'character': 0}))
6.1
"""
return '{}.{}'.format(pos['line'] + 1, pos['character'] + 1) |
def getBandIdFromBandPath(bandPath):
"""Obtains an image band id from its path"""
return bandPath[-6:-4] |
def time_rep_song_to_16th_note_grid(time_rep_song):
"""
Transform the time_rep_song into an array of 16th note with pitches in the onsets
[[60,4],[62,2],[60,2]] -> [60,0,0,0,62,0,60,0]
"""
grid_16th = []
for pair_p_t in time_rep_song:
grid_16th.extend([pair_p_t[0]] + [0 for _ in range(pair_p_t[1]-1)])
retur... |
def contains_a_letter(word):
"""Helper for :meth:`analyze`"""
for char in word:
if char.isalpha():
return True
return False |
def unflatten_dict(dic: dict, sep=".") -> dict:
"""
Invert the effect of :func:`flatten_dict`
"""
items = list(dic.items())
items.reverse()
out = {}
while items:
k, v = items.pop()
*keys, last_key = k.split(sep)
d = out
for k in keys:
d = d.setde... |
def extend_slice(slice_name, slices, template_size, target_result):
"""
Extend slice
"""
ext_obj = {"name": "Empty", "score": 0.0}
extended_list = [ext_obj] * template_size
el = extended_list
for slice in slices:
if slice["name"] == slice_name:
print("Slice:", slice_name)... |
def _get_mappings(files, label, go_prefix):
"""For a set of files that belong to the given context label, create a mapping to the given prefix."""
mappings = {}
for file in files:
src = file.short_path
#print("mapping file short path: %s" % src)
# File in an external repo looks like:
# '../WORKSPA... |
def get_cache_encrypt_key(key):
"""Prepare key for use with crypto libs.
:param key: Passphrase used for encryption.
"""
key += (16 - (len(key) % 16)) * '-'
return key.encode('utf-8') |
def bits2human(n, format="%(value).1f%(symbol)s"):
"""Converts n bits to a human readable format.
>>> bits2human(8191)
'1023.9B'
>>> bits2human(8192)
'1.0KiB'
"""
symbols = ('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')
prefix = {}
prefix['B'] = 8
for i, s in enum... |
def _cons1_111(m1, L11, d_p2p, keff, Cp):
"""dz constraint for interior sc touching 3 interior sc"""
return m1 * Cp * L11 / 3 / d_p2p / keff |
def is_readonly_property(cls, name):
"""Tell whether a attribute can't be setattr'ed."""
attr = getattr(cls, name, None)
return attr and isinstance(attr, property) and not attr.fset |
def is_listing(op):
"""Tell if given parameter is a listing."""
return isinstance(op, (list, tuple)) |
def calc_clust_similarity(target_size, clust_size):
"""
Linear function to calculate how close the size of the cluster
is to the real epileptogenic cluster that we want to find
"""
if clust_size > target_size:
if clust_size >= 2*target_size:
clust_size = 0
else:
... |
def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : dict
... |
def map_currency(currency, currency_map):
"""
Returns the currency symbol as specified by the exchange API docs.
NOTE: Some exchanges (kraken) use different naming conventions. (e.g. BTC->XBT)
"""
if currency not in currency_map.keys():
return currency
return currency_map[currency] |
def unquote_header_value(value):
"""Unquotes a header value.
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote.
"""
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing thi... |
def _as_graph_element(obj):
"""Convert `obj` to a graph element if possible, otherwise return `None`.
Args:
obj: Object to convert.
Returns:
The result of `obj._as_graph_element()` if that method is available;
otherwise `None`.
"""
conv_fn = getattr(obj, "_as_graph_element", None)
if conv_... |
def expand_tcp_flags(flag_code):
"""
Convert a one character tcp flag to a three character tcp flag
"""
retval=""
for character in flag_code:
if character=="S":
retval=retval+" SYN"
elif character=="P":
retval=retval+" PSH"
elif character=="F":
... |
def make_shell_filestats_url(host: str, shell_port: int, path: str) -> str:
"""
Make the url for filestats data in heron-shell
from the info stored in stmgr.
"""
return f"http://{host}:{shell_port}/filestats/{path}" |
def swap(a_list, index1, index2):
"""assumes a_list is a list,
assumes index1 is an int representing the index of one of the two values to be swaped
assumes index1 is an int representing the index of one of the two values to be swaped
does not modify the inputed list
returns a list, equivalent to ... |
def palindrome(string):
"""palindrome (string) - returns a boolean value for whether the parameter string is a palindrome"""
if str(string) == str(string)[::-1]:
return True
else:
return False |
def puzzle_input(daynumber):
""" return the open file for given day """
filename = f"puzzle_inputs/{daynumber}.txt"
try:
return open(filename)
except FileNotFoundError:
print(f"Oops - couldn't find '{filename}'") |
def extract_properties_when_schemaless(group_objects_list):
"""
If your Active Directory schema does not natively support Unix account attributes
and a schema extension is not possible, Safeguard Authentication Services uses "schemaless"
functionality where Unix account information is stored in the altS... |
def cleanup_description(desc):
"""Clean up a multiline description."""
return " ".join(desc.replace('\n', ' ').replace('\r', ' ').split()) |
def quick_one(lis):
"""
the first item of the list is the key, all items that are less than the key will be on the left of the key,
all items that are larger will be on the right of the key, returns the list and the index of the key.
"""
nList = lis.copy()
key = lis[0]
keyI = 0
pMin = 0
pMax = len(lis)-1
... |
def hyp2id(hyp, dictionary):
"""
Converts an hyphen to its respective id in dictionary.
:param hyp: a string
:param dictionary: a Python dictionary
with string as keys and integers as values.
:return: an integer
"""
return dictionary[hyp] if hyp in dictionary else... |
def decode_topic_name(encoded: str) -> str:
"""
Reverses ``encode_topic_name``.
:param encoded: the encoded SNS topic name
:return: the decoded channel name
"""
decoded = encoded
decoded = decoded.replace("_WCD_", "*")
decoded = decoded.replace("_FWS_", "/")
decoded = decoded.replac... |
def enumerate_genes(genes):
"""Enumerate genes"""
schema={}
for i,x in enumerate(genes):
if x in schema:
schema[x].append(i)
else:
schema[x] = [i]
return schema |
def distance_helper(initial_velocity, acceleration, time):
"""
Calculates the distance traveled given the initial velocity, acceleration, and time, Helper function to the distance
function.
:param initial_velocity: Integer initial velocity
:param acceleration: Integer acceleration
:param ti... |
def mean(data):
"""
Return the sample arithmetic mean of data.
:param data: list of floats or ints.
:return: mean value (float).
"""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
# return sum(data)/n # in Python 2 use sum(data)/float(n)
... |
def get_tool_names():
""" Returns a list of expected DExTer Tools
"""
return [
'clang-opt-bisect', 'help', 'list-debuggers', 'no-tool-',
'run-debugger-internal-', 'test', 'view'
] |
def boundMotorSpeed(speed):
"""
Bound speed to the limits allowed by crickit motor.throttle
"""
if speed < -1:
return -1
if speed > 1:
return 1
return speed |
def create_deets_message(time, size, image):
"""Creates message of image details for the GUI client
Image details returned include the time the image was
uploaded or processed and the image size in pixels. If
the image was original, the upload time is returned. If
the image was inverted, the process... |
def to_underscore_style(text):
"""Changes "Something like this" to "something_like_this"."""
text = text.lower().replace(" ", "_").replace("-", "_")
return "".join(x for x in text if x.isalpha() or x.isdigit() or x == "_") |
def column_of(row, col, width=3, height=3, include=True):
"""Return all coordinates in the column of (col, row) as a list.
Args:
row (int): The row of the field.
col (int): The column of the field.
width (int): The width of the sudoku.
height (int): The height of the sudoku.
... |
def ee_function_tree(name):
"""Construct the tree structure based on an Earth Engine function. For example, the function "ee.Algorithms.FMask.matchClouds" will return a list ["ee.Algorithms", "ee.Algorithms.FMask", "ee.Algorithms.FMask.matchClouds"]
Args:
name (str): The name of the Earth Engine functi... |
def to_upper(inp):
"""
Recursively convert inputs to uppercase strings, except if None.
Parameters
----------
inp : str or list of str
Object to be converted to upper.
Returns
-------
str, list or None
"""
if inp is None:
return None
if isinstance(inp, list... |
def get_destroyed_endpoint(vol, array):
"""Return Destroyed Endpoint or None"""
try:
return bool(array.get_volume(vol, protocol_endpoint=True, pending=True)['time_remaining'] != '')
except Exception:
return False |
def make_flat(list_of_lists: list) -> list:
""" [(1,2), (3,4)] -> [1, 2, 3, 4]"""
return sum([list(item) for item in list_of_lists], []) |
def incremental_mean_differentSizeBatches(xbarj,Nj,xbarm,Nm):
""" Calculates the incremental mean different batch sizes
Args:
float:
xbarj mean of all previous
float:
Nj number of planets in all previous batches
ndarray:
xbarm mean of values in current... |
def build_problem_report(req_data):
"""Returns problem report dict from req_data sent by GitHub hook."""
return {
"product": "Ports & Packages",
"component": "Individual Port(s)",
"version": "Latest",
"summary": "GitHub Pull Request #{number}: {title}".format(
number=... |
def convert_experience_amount(amount: str) -> tuple:
"""
convert_experience_amount - Converts a string into a tuple of amount and type
Args:
amount (str): The string to convert
Returns:
tuple: Index 0 is the amount and index 1 is the type
"""
xp_type = "levels"
if isinstanc... |
def get_ss(ss_string):
"""
Converts secondary structure string into a list of indices of where secondary structure changes (plus start and end coordinates of the sequence)
"""
output = [0]
for i in range(1,len(ss_string)):
if ss_string[i] != ss_string[i-1]:
output.append(i)
i... |
def print_belief_state_woz_requestables(curr_values, distribution, threshold):
"""
Returns the top one if it is above threshold.
"""
requested_slots = []
# now we just print to JSON file:
for idx, value in enumerate(curr_values):
if distribution[idx] >= threshold:
r... |
def __get_http_methods(tagged_item):
"""
extracts the http methods for a tagged link or resource decorator
:param tagged_item:
:return: the list of http methods
"""
def default_method(args):
return ['POST'] if len(args) > 0 else ['GET']
tag_args = tagged_item.get('argspec')
htt... |
def find(word, letter, start_index):
"""
Find the index of a letter in a word starting the search at specific index
"""
index = start_index
while index < len(word):
if word[index] == letter:
return index
index += 1
return -1 |
def _get_folder(gi, folder_name, library, libitems):
"""Retrieve or create a folder inside the library with the specified name.
"""
for item in libitems:
if item["type"] == "folder" and item["name"] == "/%s" % folder_name:
return item
return gi.libraries.create_folder(library.id, fol... |
def listCycle(x, list):
"""Append x to list and maintain length.
Returns updated list."""
list.append(x) # append new value
# list.pop(0) # get rid of first value (to maintain size)
del list[0] # get rid of first value (to maintain size)
return list |
def byte_bit_value(byte, schema):
"""
Extract bit(s) value from a byte.
BYTE INDEX = | 0 | 1 | 2 | 3 || 4 | 5 | 6 | 7 |
msb lsb
128 1
args:
- byte value(int)
- data schema(list): [index, bits]... |
def dev_dupe_remover(finals, dupelist):
"""
Filter dictionary of autoloader entries.
:param finals: Dict of URL:content-length pairs.
:type finals: dict(str: str)
:param dupelist: List of duplicate URLs.
:type duplist: list(str)
"""
for dupe in dupelist:
for entry in dupe:
... |
def build_network_url_from_gateway_url(gateway_href):
"""Build network URI for NSX Proxy API.
It replaces '/api/edgeGatway/' or '/api/admin/edgeGatway/' with
/network/EDGE_ENDPOINT and return the newly formed network URI.
param: str gateway_href: gateway URL. for ex:
https://x.x.x.x/api/admin/edge... |
def split_html(html_string):
"""
Divides an html document into three seperate strings and returns
each of these. The first part is everything up to and including the
<body> tag. The next is everything inside of the body tags. The
third is everything outside of and including the </body> tag.
:ty... |
def tostr(input_string):
""" Change a list of strings into a multiline string """
if isinstance(input_string, list):
return '\n'.join([tostr(i) for i in input_string])
else:
return str(input_string) |
def compare(first, second):
"""Compares the two types for equivalence.
If a type composes another model types, .__dict__ recurse on those
and compares again on those dict values
"""
if not hasattr(second, '__dict__'):
return False
# Ignore any '_raw' keys
def norm_dict(d):
... |
def pixel_scale_interpolation_grid_tag_from_pixel_scale_interpolation_grid(
pixel_scale_interpolation_grid
):
"""Generate an interpolation pixel scale tag, to customize phase names based on the resolution of the interpolation \
grid that deflection angles are computed on before interpolating to the and sub ... |
def importAny(*modules):
"""
Import by name, providing multiple alternative names
Common use case: Support all the different package names found
between 2.0 add-ons, 2.1 AnkiWeb releases, and 2.1 dev releases
Raises:
ImportError -- Module not found
Returns:
module -- I... |
def buy_date_adaptor(buy_date: str):
"""
20200101 -> 2020-01-01
:param buy_date:
:return:
"""
if len(buy_date) == 8:
buy_date = f'{buy_date[:4]}-{buy_date[4:-2]}-{buy_date[-2:]}'
return buy_date |
def subtract(a, b):
"""Subtract two numbers and return the difference"""
difference = round(a-b, 4)
print("The difference of " + str(a) + " and " + str(b) + " is " + str(difference) + ".")
return str(a) + " - " + str(b) + " = " + str(difference) |
def add_to_tracking_totals(totals, item):
"""
Adds totals from item to totals
:param dict totals: Totals to be added to
:param dict item: Item to be added to totals dict
:return: totals dict
:rtype: dict
"""
for key, value in item.items():
if (
type(value) is int and... |
def transcript(cloud_response):
"""Get text transcription with the highest confidence
from the response from google cloud speech-to-text
service.
Args:
cloud_response: response from speech-to-text service
Returns:
(transcription, confidence): string value of transcription
... |
def scaleFromRedshift(redshift):
"""
Converts a redshift to a scale factor.
:param redshift: redshift of the object
:type redshift: float or ndarray
:return: scale factor
:rtype: float or ndarray
"""
return 1. / (redshift + 1.) |
def feature_pairs(f):
"""Expand features to include pairs of features
where one is always a f=v feature."""
pairs = [x + ".x." + y for x in f for y in f if u'=' in y]
return pairs + f |
def cleanObject(obj,dimensions):
"""
Get only the variables required to netcdf2d
Parameters
----------
obj:object
dimensions=list,['nnode','ntime']
Notes
-----
idimensions=['inode','itime']
"""
if not 'variable' in obj:raise Exception("Add {} to the default parameter object".format('var... |
def getshapesidedict() -> dict:
"""Returns a dictionary of side
or polygon definitions for
simple solids
Returns:
dictionary of side or polygon
definitions for basic solids
"""
return {"tetrahedra":((2, 1, 0),
(2, 3, 1),
... |
def serialize_for_deletion(elasticsearch_object_id):
"""
Serialize content for bulk deletion API request
Args:
elasticsearch_object_id (string): Elasticsearch object id
Returns:
dict: the object deletion data
"""
return {"_id": elasticsearch_object_id, "_op_type": "delete"} |
def maybe_flip_x_across_antimeridian(x: float) -> float:
"""Flips a longitude across the antimeridian if needed."""
if x > 90:
return (-180 * 2) + x
else:
return x |
def date_group(date):
"""date_group(date)
Converts a date string into a year/season ID tuple.
Positional arguments:
date (str) - date string, in "MM/DD/YYYY" format
Returns:
(tuple) - tuple with 2-digit year and season ID
(0 for Su, 1 for Fa, 2 for Sp)
The... |
def format_config_parameter(config_parameter, language):
"""
Format the name of config parameter, adding the target language of necessary.
:param config_parameter: Name of config parameter.
:type config_parameter: str
:param language: Pipeline language.
:type language: str
:return: Form... |
def rdict(x):
"""
recursive conversion to dictionary
converts objects in list members to dictionary recursively
"""
if isinstance(x, list):
l = [rdict(_) for _ in x]
return l
elif isinstance(x, dict):
x2 = {}
for k, v in x.items():
x2[k] = rdict(v)
... |
def decode_to_string(data: str or bytes) -> str:
"""
Simple helper function that ensures that data is decoded from `bytes` with `UTF-8` encoding scheme
:param data: takes in both `str` or `bytes` object; represents any type of string or bytes object
:return: string object
"""
return data if isin... |
def _opt_var_str(name):
"""Puts an asterisk superscript on a string."""
return '{}^*'.format(name) |
def parents_at_rank(graph, root, parent_rank):
"""
loop through graph from root taxon, assigning leaf nodes to parent nodes at
a given rank.
"""
parents = {}
def descend(root, parent):
"""
Iteratively descend from a root to generate a set of taxids
unless the child taxid... |
def get_media_stream(streams):
"""Returns the metadata for the media stream in an MXF file,
discarding data streams."""
found = None
for stream in streams:
# skip 'data' streams that provide info about related mxf files
if stream['codec_type'] == 'data':
continue
if s... |
def check_header(line):
""" Check whether a line is header, if it is, change it into html format
:param line: str, a line in markdown file
:return: boolean, whether a line is header
str, the line in html format
"""
header_id = line.replace(' ', '-')
if line[:7] == '###### ':
... |
def translate_inequality(param_name):
"""
Replace GT or LT at the end of a param name by '>' or '<' to
achieve Twilio-like inequalities.
"""
for suffix, replacement in (('GT', '>'), ('LT', '<')):
if param_name.endswith(suffix):
return param_name[:-len(suffix)] + replacement
... |
def bin2state(bin, num_bins, limits):
"""
:param bin: index in the discretization
:param num_bins: the total number of bins in the discretization
:param limits: 2 x d ndarray, where row[0] is a row vector of the lower
limit of each discrete dimension, and row[1] are corresponding upper
l... |
def handle_single_ddc(data):
"""
produces a about node based on DDC
"""
return {"identifier": {"@type": "PropertyValue",
"propertyID": "DDC",
"value": data},
"@id": "http://purl.org/NET/decimalised#c"+data[:3]} |
def hello(who):
"""Say hello to somebody.
- who: the person to say hello to."""
return "Hello %s!" % who |
def x_range(x):
"""Difference between maximum and minimum."""
return max(x) - min(x) |
def real_number(std_num: float) -> float:
"""Get the real value of the standard number.
Args:
std_num: The number you want to reduction.
Returns:
The real value of the number.
"""
return float(std_num) / 100000000 |
def all_equal(values: list):
"""Check that all values in given list are equal"""
return all(values[0] == v for v in values) |
def NearestIndex( vector, value, noPrint=False, debug=False ):
"""Returns nearest two indices which bracket a specified value in a vector.
Given an input list or numpy 1-D array, which is asumed to be monotonically
increasing or decreasing, find the indices of the two points with values closest
to... |
def feedforward(input, layers):
"""Compute and return the forward activation of each layer in layers."""
activations = [input]
X = input
for layer in layers:
Y = layer.forward(X) #feed the input into the layer
activations.append(Y)
X = Y #use the current output as the input for the next layer
return act... |
def populate_candidates(data):
"""Process orig_data and add any ext_id matches as candidates."""
candidates = {}
for entry in data.values():
if not entry.get('ext_ids'):
continue
base_info = {
'orig_photo_id': entry.get('photo_id'),
'orig_long_id': '{}/{}'... |
def extract_name_angle(line):
"""
extract name in <>
"""
idx1 = line.find('<')
idx2 = line.find('>')
name = line[idx1+1:idx2]
return name |
def nested_get(ind, coll, lazy=False):
""" Get nested index from collection
Examples
--------
>>> nested_get(1, 'abc')
'b'
>>> nested_get([1, 0], 'abc')
['b', 'a']
>>> nested_get([[1, 0], [0, 1]], 'abc')
[['b', 'a'], ['a', 'b']]
"""
if isinstance(ind, list):
if lazy... |
def remove_arr_elements(arr_element, count):
"""
Remove the elements from object_state_arr
"""
for _ in range(count):
arr_element.pop()
return arr_element |
def check_issubset(to_check, original):
"""
Check that contain of iterable ``to_check`` is among iterable ``original``.
:param to_check:
Iterable with elements to check.
:param original:
Iterable with elements to check to.
:return:
Boolean.
"""
s = set()
# Need th... |
def counter_value(path):
"""
Converts a zookeeper path with a counter into an integer of that counter
:param path: a zookeeper path
:rtype: the integer encoded in the last 10 characters.
"""
return int(path[-10:]) |
def center(numpoints, refcoords):
"""
Center a molecule using equally weighted points
Parameters
numpoints: Number of points
refcoords: List of reference coordinates, with each set
a list of form [x,y,z] (list)
Returns
refcenter: Ce... |
def wgtd_avg(lines):
"""
Returns the weighted average of a set of line coefficients
"""
avg_coeffs = [0,0,0]
i = 0
n = len(lines)
# Weighted average of line coefficients to get smoothed lane lines
for line in lines:
i += 1
avg_coeffs = avg_coeffs + (i * line.coeffs / ((n*... |
def is_search(splunk_record_key):
"""Return True if the given string is a search key.
:param splunk_record key: The string to check
:type splunk_record_key: str
:rtype: bool
"""
return splunk_record_key == 'search' |
def get_hyperlink(path):
"""Convert file path into clickable form."""
text = "Click to open in new tab"
# convert the url into link
return f'<a href="{path}" target="_blank">{text}</a>' |
def resolve_cyvcf2_genotype(cyvcf2_gt):
"""
Given a genotype given by cyvcf2, translate this to a valid
genotype string.
Args:
cyvcf2_gt (cyvcf2.variant.genotypes)
Returns:
genotype (str)
"""
if cyvcf2_gt[2]:
separator = "|"
else:
... |
def insertion_sort(arr, simulation=False):
"""Insertion Sort
Complexity: O(n^2)
"""
for i in range(len(arr)):
cursor = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > cursor:
# Swap the number down the list
arr[pos] = arr[pos - 1]
pos = pos - ... |
def join_image_tag(image, tag):
""" Join an image name and tag. """
if not tag:
return image
return ':'.join((image, tag)) |
def bubble_sort(x):
"""return a sorted copy of the input list x"""
L = x[:]
swap = False
while not swap:
swap = True
print(L)
for i in range(1,len(L)):
if L[i] < L[i-1]:
swap = False
L[i-1], L[i] = L[i], L[i-1]
return L |
def to_megabytes_factor(unit):
"""Gets the factor to turn kb/gb into mb"""
lower = unit.lower()
if lower == 'gb':
return 1000
if lower == 'kb':
return 0.001
return 1 |
def fibonacci(n):
"""
Time complexity: O(n)
Space complexity: O(n)
Pro: keeps backlog of calculated terms and if the function is called repeatedly on
the same number it will run in O(1)
Con: O(n) space and O(2n) running time in the general case
"""
if not hasattr(fibonacci, "memory"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.