content stringlengths 42 6.51k |
|---|
def normalize(name):
"""
We normalize directory names to fix some name misalignments in vad/snr data,
unzipped data, and the original meta-data jsons. Examples:
- SNR has typical format of `.../1000things_1807_librivox_wav/1000things_00_fowler.wav`,
when the correspoding meta-data is in `10... |
def get_data_ranges(bin_path, chunk_size):
"""Get ranges (x,y,z) for chunks to be stitched together in volume
Arguments:
bin_path {list} -- binary paths to tif files
chunk_size {list} -- 3 ints for original tif image dimensions
Returns:
x_range {list} -- x-coord int bounds for volum... |
def fix_compile(remove_flags):
"""
Monkey-patch compiler to allow for removal of default compiler flags.
"""
import distutils.ccompiler
def _fix_compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0,
extra_preargs=None, extra_postargs=None, depends=None):
... |
def join_filters(*filters):
"""Joins multiple filters"""
return "[in]{}[out]".format("[out];[out]".join(i for i in filters if i)) |
def _handleTextNotes(s):
"""Split text::notes strings."""
ssplit = s.split('::', 1)
if len(ssplit) == 1:
return s
return u'%s<notes>%s</notes>' % (ssplit[0], ssplit[1]) |
def decode_state(state_id, vert_num, al_size):
"""Converts integer id to state.
Can also be applied to np.array with multiple state ids.
"""
return [(state_id // (al_size ** j)) % al_size for j in range(vert_num)] |
def parse_paths_as_list(arg):
"""
Allow singular path string or list of path strings
:param arg: This could be a string... or it could be a list of strings! Who knows what could happen?
:return: List of strings
"""
invalid_argument = False
if type(arg) is str:
arg = [arg]
elif ... |
def _calculate_f1(tp, fp, fn):
"""Calculate f1."""
return tp * 2.0, (tp * 2.0 + fn + fp) |
def stripPunc(sent):
"""Strips punctuation from list of words"""
puncList = [".",";",":","!","?","/","\\",",","#","@","$","&",")","(","\""]
for punc in puncList:
sent = sent.replace(punc,'')
return sent |
def _reverse_bytes(mac):
"""Helper method to reverse bytes order.
mac -- bytes to reverse
"""
ba = bytearray(mac)
ba.reverse()
return bytes(ba) |
def walk_through_dict(
dictionary, end_fn, max_depth=None, _trace=None, _result=None, **kwargs
):
"""Runs a function at a given level in a nested dictionary.
If `max_depth` is unspecified, `end_fn()` will be run whenever
the recursion encounters an object other than a dictionary.
Parameters
--... |
def triangleType(a,b,c):
"""Categorize tree sides of a triangle into equilateral, unequal sided or isosceled.
Args:
a; int; Side a of the Triangle
b; int; Side b of the Triangle
c; int; Side c of the Triangle
Returns:
str; String of the category
"""
if a == b == c:... |
def merge(l1: list, l2: list):
"""Merge two sorted lists into a single sorted list."""
l = [None] * (len(l1) + len(l2))
i, j = 0, 0
while i < len(l1) and j < len(l2):
if l1[i] < l2[j]:
l[i + j] = l1[i]
i += 1
else:
l[i + j] = l2[j]
j += ... |
def convert_bytes(num):
"""
Converts bytes to human readable format.
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def _is_list(item):
"""Check whether the type is list"""
return isinstance(item, list) |
def IS(x, lower, upper, alp):
"""Interval score.
Parameters
----------
x:
lower:
upper:
alp:
Returns
-------
ndarray
"""
return (upper - lower) + 2.0 / alp * (lower - x) * (x < lower) + 2.0 / alp * (x - upper) * (x > upper) |
def _structure_parent_category(_parent_id, _payload):
"""This function structures the portion of the payload for the parent category.
.. versionadded:: 2.5.0
:param _parent_id: The ID of the parent category (if applicable)
:type _parent_id: str, None
:param _payload: The partially constructed payl... |
def get_unique_id(serial_number: str, key: str) -> str:
"""Get a unique entity name."""
return f"{serial_number}-{key}" |
def clamp(val: float, minimum: float = 0.0, maximum: float = 1.0) -> float:
""" Fix value between min an max"""
if val < minimum:
return minimum
if val > maximum:
return maximum
return val |
def linear_search(arr, item):
""" Searches for an item in a given list and returns
True or False depending if the item is found
args:
arr: list,
item: any type """
for i in arr:
if i == item:
return True
return False |
def __sbiw_rd_i(op):
"""
Decode and return the 'Rd' and 'immediate' arguments of a SBIW opcode
"""
AVR_SBIW_RD_MASK = 0x0030
AVR_SBIW_CONST_MASK = 0x00CF
imm_part = op & AVR_SBIW_CONST_MASK
imm = ((imm_part >> 2) & 0x30) | (imm_part & 0xF)
# rd_part is 2 bits and indicates r24, 26, 28,... |
def fix_id(raw_data: dict) -> dict:
"""Fix known errors in station ids like superfluous spaces."""
if not raw_data:
return raw_data
for station in raw_data:
if "_id" not in station:
continue
station["_id"] = station["_id"].replace(" ", "")
for module in station... |
def find_cdr_exception(
cdr_exceptions,
orig_device_name=None,
dest_device_name=None,
orig_cause_value=None,
dest_cause_value=None,
):
"""For given list of CDRException, find & return first CDRException for given device & cause (optional), else return None.
Parameters, orig or dest r... |
def check_slash(path):
""" Make sure that a slash terminates the string """
if path[-1] == "/":
return path
else:
return path + "/" |
def find_max_index(val, arr, exc=None):
"""Return index of max element in an array not larger than `val`,
excluding index `exc` if provided
>>> find_max_index(1, [1, 2, 3])
0
>>> find_max_index(2, [1, 2, 3, 4])
1
>>> find_max_index(0, [1, 2, 3, 4])
-1
>>> find_max_index(5, [1, 2, 3,... |
def drop_dupes(sequence):
"""Drop duplicate elements from a list or other sequence.
C.f. https://stackoverflow.com/a/7961390
"""
orig_type = type(sequence)
return orig_type(list(dict.fromkeys(sequence))) |
def inner_product(L1, L2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
for word1, count1 in L1:
for word2, count2 in L2:
if word1 == word2:
result += count1 * count2
return result |
def rounddown_100(x):
"""
Project: 'ICOS Carbon Portal'
Created: Tue May 07 09:00:00 2019
Last Changed: Tue May 07 09:00:00 2019
Version: 1.0.0
Author(s): Karolina
Description: Function that takes a number as input and
... |
def link_in_path(link, node_list):
""" This function checks if the given link is in the path defined by this node list.
Works with undirected graphs so checks both link orientations.
Parameters
----------
link : tuple
a link expressed in a node pair tuple
node_li... |
def formatTuples(tuples):
"""
Renders a list of 2-tuples into a column-aligned string format.
tuples (list of (any, any): The list of tuples to render.
Returns: A new string ready for printing.
"""
if not tuples:
return ""
tuples = [(str(x), str(y)) for (x, y) in tuples]
width... |
def is_place_id(location):
""" Checks whether or not the city lookup can be cast to an int, representing a OWM Place ID """
try:
int(location)
return True
except (TypeError, ValueError):
return False |
def add_to_hierarchy(collection,triple):
"""Add TRIPLE to COLLECTION."""
# Comments will illustrate adding the triple
# {'a' : {'b' : ['d']}}
# to an existing collection with various possible features
top=collection.get(triple[0])
if (top):
med=top.get(triple[1])
# we see: {'a' ... |
def clean_street_name(name, mapping):
"""This function takes a string and a mapping dictionary and return a string of a curated street name
found in the boston_massachusetts.osm
This is a modification from
https://classroom.udacity.com/nanodegrees/nd002/parts/0021345404/modules/316820862075461/lessons/... |
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar, and the first date is not after
the second."""
month = month2
year = year2
day = day2 ... |
def EITCamount(basic_frac, phasein_rate, earnings, max_amount,
phaseout_start, agi, phaseout_rate):
"""
Returns EITC amount given specified parameters.
English parameter names are used in this function because the
EITC formula is not available on IRS forms or in IRS instructions;
the ... |
def compute_2(x, offset=1):
"""Compute by looping and checking ahead."""
y = 0
x2 = x + x[:offset] # Lists are concatenated, but they take memory
for i in range(len(x)):
if x2[i] == x2[i+offset]:
y += int(x2[i])
return y |
def version_tuple(ver):
"""Convert a version string to a tuple containing ints.
Parameters
----------
ver : str
Returns
-------
ver_tuple : tuple
Length 3 tuple representing the major, minor, and patch
version.
"""
split_ver = ver.split(".")
while len(sp... |
def _num_to_list(num, length):
"""
258, 2 -> [1,2]
:param int num:
:param int length:
:rtype: list
"""
output = []
for l in range(length):
output = [int((num >> 8*l) & 0xff)]+output
return output |
def Keck_distortion(measured_wave, cutoff=10000.):
"""Telescope dependent distortion function for the Keck sample."""
slope1 = .0600
intercept1 = -100
slope2 = .160
intercept2 = -1500
if measured_wave < cutoff:
return measured_wave * slope1 + intercept1
else:
return measured_... |
def check_not_finished_board(board):
"""
list -> bool
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', \
'*?????5', '*?????*', '*?????*', '*2*1***'])
False
... |
def escape_html(text: str) -> str:
"""Replaces all angle brackets with HTML entities."""
return text.replace('<', '<').replace('>', '>') |
def register_actions(cls):
""" Registers all marked methods in the agent class
:param cls: Agent Subclass of Agent containing methods decorated with @action
"""
for name, method in cls.__dict__.items():
if hasattr(method, "_register_action"):
cls._actions[name] = method
return c... |
def get_file_contents(f):
"""returns contents of file as str"""
data = ""
try:
with open(f, "r") as open_file:
data = open_file.read()
except Exception as e:
print(e)
finally:
return data |
def factorial(n):
"""Compute factorial of n, n!"""
if n <= 1:
return 1
return n * factorial(n-1) |
def auto_ext_from_metadata(metadata):
"""Script extension from kernel information"""
auto_ext = metadata.get('language_info', {}).get('file_extension')
if auto_ext == '.r':
return '.R'
return auto_ext |
def is_localhost(host):
"""Verifies if the connection is local
Parameters
----------
host : str
The requesting host, in general self.request.headers['host']
Returns
-------
bool
True if local request
"""
localhost = ('localhost', '127.0.0.1')
return host.startsw... |
def import_string(path: str):
"""
Path must be module.path.ClassName
>>> cls = import_string('sentry.models.Group')
"""
if "." not in path:
return __import__(path)
module_name, class_name = path.rsplit(".", 1)
module = __import__(module_name, {}, {}, [class_name])
try:
... |
def anchorfree(anchor=5, free=7, start=1, stop=100, step=1):
"""
Return a list of strings consisting of either the number,
the phrase "anchor", "free" or "WOW" when
the number is divisible by anchor, free or both.
:param anchor: return "anchor" when number is divisible by this
:param free: retu... |
def list_neighbors(current_row, current_col, grid):
"""
Args:
current_row: Current row of the animal
current_col: Current column of the animal
grid: The grid
Returns:
List of all position tuples that are around the current position,
without including positions outside the ... |
def encode_int(i):
"""Encode an integer for a bytes database."""
return bytes(str(i), "utf-8") |
def p_a2(npsyns, ninputs):
"""
Probability of selecting one input given ninputs and npsyns attempts. This
uses a binomial distribution.
@param npsyns: The number of proximal synapses.
@param ninputs: The number of inputs.
@return: The computed probability.
"""
p = 1. / ninputs
return npsyn... |
def calculate_iou(gt, pr, form='pascal_voc') -> float:
"""Calculates the Intersection over Union.
Args:
gt: (np.ndarray[Union[int, float]]) coordinates of the ground-truth box
pr: (np.ndarray[Union[int, float]]) coordinates of the prdected box
form: (str) gt/pred coordinates format
... |
def return_other_zones(zones, index):
"""return all other zones not assigned to uav to make as a no fly zone"""
copy = zones
copy.pop(index)
return copy |
def should_run(config):
"""
Checks if canary tests should run.
"""
if "canaries" in config["bootstrap"] and config["bootstrap"]["canaries"] == "none":
return False
if "canaries" in config["test_control"] and config["test_control"]["canaries"] == "none":
return False
return True |
def to_bool(answer, default):
"""
Converts user answer to boolean
"""
answer = str(answer).lower()
default = str(default).lower()
if answer and answer in "yes":
return True
return False |
def health_summary(builds):
"""Summarise the health of a project based on builds.
Arguments:
builds (:py:class:`list`): List of builds.
Returns:
:py:class:`str`: The health summary.
"""
for build in builds:
if build['outcome'] in {Outcome.PASSED}:
return 'ok'
... |
def represents_int(s: str) -> bool:
"""Checks if a string s represents an int.
Args:
s: string
Returns:
boolean, whether string represents an integer value
"""
try:
int(s)
return True
except ValueError:
return False |
def points_match(par_before, par_after):
"""
Do points match?
"""
return (par_before.get("latitude", None) == par_after.get("latitude", None)
and par_before.get("longitude", None) == par_after.get("longitude", None) ) |
def indent(lines, amount, ch=' '):
"""indent the lines in a string by padding each one with proper number of pad characters"""
padding = amount * ch
return padding + ('\n'+padding).join(lines.split('\n')) |
def _flows_finished(pgen_grammar, stack):
"""
if, while, for and try might not be finished, because another part might
still be parsed.
"""
for dfa, newstate, (symbol_number, nodes) in stack:
if pgen_grammar.number2symbol[symbol_number] in ('if_stmt', 'while_stmt',
... |
def generate_query(query_tuples):
"""
Builds a query from a list of tuples.
:param List query_tuples: Lists of tuples to build query item.
:return: SQL compatible query as a string.
"""
# prepend ID and date items
master_query = ("ID integer PRIMARY KEY ASC NOT NULL,"
"d... |
def prod_double(x, y, param_0):
"""
Product
:param x:
:param y:
:param param_0:
:return:
"""
return x * y * param_0 |
def parse_megawatt_value(val):
"""Turns values like "5,156MW" and "26MW" into 5156 and 26 respectively."""
return int(val.replace(',', '').replace('MW', '')) |
def group_split(items, group_size):
"""Split a list into groups of a given size"""
it = iter(items)
return list(zip(*[it] * group_size)) |
def endswith(value, arg):
"""Usage {% if value|endswith:"arg" %}"""
if value:
return value.endswith(arg)
return False |
def DeltaAngle(a, b):
"""
Calculates the shortest difference between
two given angles given in degrees.
Parameters
----------
a : float
Input a
b : float
Input b
"""
return abs(a - b) % 360 |
def concatenate_unique(la, lb):
"""Add all the elements of `lb` to `la` if they are not there already.
The elements added to `la` maintain ordering with respect to `lb`.
Args:
la: List of Python objects.
lb: List of Python objects.
Returns:
`la`: The list `la` with missing elements from `lb`.
""... |
def calculate(expr: str) -> int:
"""Evaluate 'expr', which contains only non-negative integers,
{+,-,*,/} operators and empty spaces."""
plusOrMinus = {'+': lambda x, y: x + y ,
'-': lambda x, y: x - y}
mulOrDiv = {'*': lambda x, y: x * y ,
'/': lambda x, y: x // y}
... |
def convert_string(s):
"""
Converts a string to the appropriate type, either a float type or a int type
Parameters
----------
s : string
The string that should be converted
Returns
-------
float or int : The numerical representation of "s... |
def NormalizeRegEx(regEx):
"""NormalizeRegEx(regEx) -> str
Escapes the special characters in a regular expression so it can be
compiled properly.
arguments:
parent
string of the regular expression where special characters are not
escaped
returns:
... |
def shorten(thelist, maxlen, shorten):
"""
If thelist has more elements than maxlen, remove elements to make it of size maxlen.
The parameter shorten is a string which can be one of left, right, both or middle
and specifies where to remove elements.
:param thelist: the list to shorten
:param max... |
def rm_spaces(filename):
""" Replaces all spaces with underscores in a filename. """
return filename.replace(' ', '_') |
def _geoserver_endpoints(workspace, layer):
"""Form GeoServer WMS/WFS endpoints.
Parameters:
workspace (str): GeoServer workspace
layer (str): Layer name
Returns:
(dict) The GeoServer layer endpoints.
"""
return {
"wms": '{0}/wms?service=WMS&request=GetMap&layers={0... |
def _formatElement(element, count, index, lastSeparator):
"""Format an element from a sequence.
This only prepends a separator for the last element and wraps each element
with single quotes.
Parameters
----------
element : object
Current element.
count : int
Total number of... |
def get_data_center(hostname):
"""Guess data center from Keeper server hostname
hostname(str): The hostname component of the Keeper server URL
Returns one of "EU", "US", "US GOV", or "AU"
"""
if hostname.endswith('.eu'):
data_center = 'EU'
elif hostname.endswith('.com'):
data_ce... |
def parse_time_cmd(s):
""" Convert timing info from `time` into float seconds.
E.g. parse_time('0m0.000s') -> 0.0
"""
s = s.strip()
mins, _, secs = s.partition('m')
mins = float(mins)
secs = float(secs.rstrip('s'))
return mins * 60.0 + secs |
def hexdump(data, offset, size):
"""Return hexdump string of given data in isobuster format."""
def ascii_print(c):
return chr(c) if 32 <= c <= 127 else "."
dump = ""
for i in range(size // 0x10):
line_offset = offset + i * 0x10
line_data = data[line_offset: line_offset + 0x10]
... |
def contain_zh(text):
"""
Check if string contains chinese char
"""
for c in text:
if '\u4e00' <= c <= '\u9fa5':
return True
return False |
def key_pem(cert_prefix):
"""This is the key entry of a self-signed local cert"""
return cert_prefix + '/server.key' |
def format_info(variant, variant_type="snv", nr_cases=None, add_freq=False):
"""Format the info field for SNV variants
Args:
variant(dict)
variant_type(str): snv or sv
nr_cases(int)
Returns:
vcf_info(str): A VCF formated info field
"""
observations = variant.get("o... |
def _ivc_to_model_input(ivc, actual_yield, burst_height):
"""This function converts an International Visibility Code [1-9] into the numbers used in the Soviet thermal impulse model."""
if ivc == 9:
return 1
else:
groundburst = 10 - ivc
if ivc == 3 or ivc == 2:
groundburst... |
def fuzz(val):
""" A fuzzer for json data """
if isinstance(val, int):
return val + 7
if isinstance(val, str):
return "FUZ" + val + "ZY"
if isinstance(val, list):
return ["Q(*.*)Q"] + [fuzz(x) for x in val] + ["P(*.*)p"]
if isinstance(val, dict):
fuzzy = {x: fuzz(y) f... |
def volume(iterable):
"""
Computes the volume of an iterable.
:arg iterable: Any python iterable, including a :class:`Dims` object.
:returns: The volume of the iterable. This will return 1 for empty iterables, as a scalar has an empty shape and the volume of a tensor with empty shape is 1.
"""
... |
def GetQNNSquareLoss(labelValues, predictionValues):
""" Get the Square loss function
"""
lossValue = 0
for label, prediction in zip(labelValues, predictionValues):
lossValue = lossValue + (label - prediction) ** 2
lossValue = lossValue / len(labelValues)
return lossValue |
def _handle_string(val):
"""
Replaces Comments: and any newline found.
Input is a cell of type 'string'.
"""
return val.replace('Comments: ', '').replace('\r\n', ' ') |
def win_check(riddle):
"""
Check whether user have get the whole word.
:param riddle: str, user's guess
:return win: int, 0 = no any un-found alphabet
"""
win = 0
for i in range(len(riddle)):
# check whether any character other than alphabet exist
if str.isalpha(riddle[i]):
... |
def str_committees_header(committees, winning=False):
"""
nicely format a header for a list of committees,
stating how many committees there are
winning: write "winning committee" instead of "committee"
"""
output = ""
if committees is None or len(committees) < 1:
if winning:
... |
def _create_rest_error_output(error_message, error_code):
"""creates rest service error output"""
response = {
"success": "false",
"data": {},
"error": {
"code": error_code,
"message": error_message
}
}
return response |
def penalize_off_pulse(genotype, weight=20):
"""fitness function handling off pulse notes
Args:
genotype ((int, int)[]): list of tuples (pitch, dur) representing genotype of a chromosome
weight (int, optional): Defaults at 20. Defines penalty/reward rate
Returns:
int: aggr... |
def is_transition_allowed(constraint_type: str,
from_tag: str,
to_tag: str):
"""
Given a constraint type and strings ``from_tag`` and ``to_tag`` that
represent the origin and destination of the transition, return whether
the transition is allowed under... |
def try_integer(s) -> int:
"""Attempts to convert some input into an integer"""
try:
return int(s)
except ValueError:
return s |
def cipher(text, shift, encrypt=True):
"""
Encrypt (decrypt) a text (ciphertext) into ciphertext (text)
:param text: The plaintext or ciphertext
:param shift: The shift that encrypts the text
:param encrypt: True for encryption, False for decryption
:return: ciphertext or plaintext
>>> plai... |
def add_app(INSTALLED_APPS, app, prepend=False, append=True):
""" add app to installed_apps """
if app not in INSTALLED_APPS:
if prepend:
return (app,) + INSTALLED_APPS
else:
return INSTALLED_APPS + (app,)
return INSTALLED_APPS |
def rawtext(s):
"""Compile raw text to the appropriate instruction."""
if "\n" in s:
return ("rawtextColumn", (s, len(s) - (s.rfind("\n") + 1)))
else:
return ("rawtextOffset", (s, len(s))) |
def decimal_to_any(decimal: int , base: int) -> str:
"""Convert a positive integer to another base as str."""
if not isinstance(decimal , int):
raise TypeError("You must enter integer value")
if not 2 <= base <= 32:
raise ValueError("base must be between 2 and 36")
def getChar(num: int... |
def sum_squared(x):
""" Return the sum of the squared elements
Parameters
----------
x (list): List of numbers
Return
------
ss (float): sum of the squared """
ss = sum(map(lambda i : i * i, x))
# ss = sum([i**2 for i in x])
return ss |
def vect3_dot(u, v):
"""
u.v, dot (scalar) product.
u, v (3-tuple): 3d vectors
return (float): dot product
"""
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2] |
def K(x, y):
""" Converts K/control codes to bytes
Does not result in 8b10b data; requires explicit encoding.
See the USB3 / PCIe specifications for more information.
"""
return (y << 5) | x |
def pad_middle(seq, desired_length):
"""
Pad the middle of a sequence with gaps so that it is a desired length.
Fail assertion if it's already longer than `desired_length`.
"""
seq_len = len(seq)
assert seq_len <= desired_length
pad_start = seq_len // 2
pad_len = desired_length - seq_len... |
def iid_divide(data, g):
"""divide list data among g groups each group has either int(len(data)/g)
or int(len(data)/g)+1 elements returns a list of groups."""
num_elems = len(data)
group_size = int(len(data) / g)
num_big_groups = num_elems - g * group_size
num_small_groups = g - num_big_groups
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.