content stringlengths 42 6.51k |
|---|
def euler_step(dydt, t0, y0, dt):
"""Perform a single Euler Forward step.
Args:
dydt (:obj:`callable`): Derivative of target w.r.t time. ``dydt(t,y)`` should return the
temporal derivative of a Parial Differential Equation (PDE) at time t for spatial field y.
t0 (:obj:`float`): Time... |
def browse(i):
"""
Input: {
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
# TBD: should calculate url
url='https://github.com... |
def parseMovie(line):
"""
Parses a movie record in MovieLens format movieId::movieTitle .
"""
fields = line.split("::")
return int(fields[0]), fields[1] |
def _rm_std_nme(d):
"""
Return a dict which does not contain the standard name
"""
d = d.copy()
# necessary to use a copy, or it will pop the item from the original dict
try:
d.pop("standard_name")
except KeyError:
pass
return d |
def calculateExtents(values):
"""
Calculate the maximum and minimum for each coordinate x, y, and z
Return the max's and min's as:
[x_min, x_max, y_min, y_max, z_min, z_max]
"""
x_min = 0; x_max = 1
y_min = 0; y_max = 1
z_min = 0; z_max = 2
if values:
initial_value = values[... |
def nest(l, depth=1, reps=1):
"""create a nested list of depth 'depth' and with 'reps' repititions"""
if depth == 0:
return(None)
elif depth == 1:
return(l)
else:
return([nest(l, depth-1, reps)] * reps) |
def b(string):
"""
convert string (unicode, str or bytes) to binary representation
"""
if isinstance(string, bytes):
return string
return string.encode('utf-8') |
def create_examples(candidate_dialog_paths, examples_num, creator_function):
"""
Creates a list of training examples from a list of dialogs and function that transforms a dialog to an example.
:param candidate_dialog_paths:
:param creator_function:
:return:
"""
i = 0
examples = []
un... |
def f_to_c(temperature):
"""
Converts a temperature in Fahrenheit to Celsius.
"""
return (temperature - 32) * 5 / 9 |
def letterize(bytes_):
"""
Canonicalize a byte sequence.
Removes non-alphabetic characters and converts to lower case.
"""
return bytes(b for b in bytes_ if chr(b).isalpha()).lower() |
def serialize_name(name):
""" Return a serialized name.
For now it only replaces ' ' with '_' and lower the letters.
"""
if name is not None:
return '_'.join(name.lower().split(' '))
else:
return None |
def escape_characters(data: bytes) -> bytes:
"""
Characters that are used for telegram control are replaced with others
so that it easier to parse the message over the wire.
Final character is never replaced.
'\x0d' -> '\x1b\x0e'
'\x1b' -> '\x1b\x1b'
'\x8d' -> '\x1b\x0f'
"""
if not ... |
def setup(i):
"""
Input: {
cfg - meta of this soft entry
self_cfg - meta of module soft
ck_kernel - import CK kernel module (to reuse functions)
host_os_uoa - host OS UOA
host_os_uid - host OS UID
... |
def truncate_float(number, decimals=3):
"""
Args:
number: float with lots of decimal values
decimals: number of decimals to keep
Returns: a truncated version of the NUMBER
"""
return round(number * 10**decimals) / 10**decimals |
def ignore_transitive_dependency(name):
"""
Return True if @name should not be included in the Steam Runtime
tarball or directly depended on by the metapackage, even though
packages in the Steam Runtime might have dependencies on it.
"""
return name in (
# Must be provided by host system
'libc6',
'libegl-me... |
def vector(s):
"""NOTE: NOT YET BEING USED"""
return [float(n) for n in s.split(',')] |
def SanityCheck(s):
"""
Class performs a simple text-based SanityCheck
to validate generated SMILES. Note, this method
does not check if the SMILES defines a valid molecule,
but just if the generated SMILES contains the
correct number of ring indices as well as opening/closing
brackets.
... |
def split_to_chunks(extent, block):
"""
Splits the trip count value to chunks and block, returns the remainder as well
the chunks and blocks covers or overlaps the origin value
If extent can be divisible by block:
extent = chunks * block
else
extent = (chunks - 1) * block + tail
... |
def hms2h(h = 0, m = 0, s=0) :
"""Converts from hours, minutes and seconds to decimal hours
Used for Right Ascension within a range [0h0m0s -> 23h59h59s]
Parameters
----------
h : float, optional
hours, by default 0
m : float, optional
minute, by default 0
s : float, opti... |
def filter_dict(d: dict, keys: list) -> dict:
"""
Given a dictionary, filter the contents and return a new dictionary containing the given keys
Parameters
----------
d : dict
dictionary to filter
keys : list
list of keys to include in new dictionary
Returns
-------
... |
def _is_dunder(name):
"""Test, if name is dunder name."""
return name[:2] == name[-2:] == '__' |
def interpolation_between_two_points(pair1, pair2, x):
"""Linearly interpolates between two points to find the ordinate to a given abscissa value (x).
Parameters
----------
pair1: List of two floats
pair2: List of two floats
x: float
Abscissa of the point for which the ordinate is calcu... |
def get_smaller_channel(channel, channel_range):
"""
get channels which is smaller than inputs
:param channel:input channel
:param channel_range:list,channel range
:return:list,channels which is larger than inputs
"""
return list(filter(lambda x: x < channel, channel_range)) |
def get_alternated_ys(ys_count, low, high):
"""
A helper function generating y-positions for x-axis annotations, useful when some annotations positioned along the
x axis are too crowded.
:param ys_count: integer from 1 to 3.
:param low: lower bound of the area designated for annotations
:param h... |
def DMS2deg(val):
"""converts DDDMMMSSS to degrees"""
if val > 1.e19:
return val
ival = int(val)
s = str(ival).zfill(9)
deg = float(s[:3])
mn = float(s[3:6])
sec = float(s[6:9])
r = val - ival
return deg + mn / 60. + sec / 3600. + r / 3600. |
def trunc(s,min_pos=0,max_pos=75,ellipsis=True):
"""Return a nicely shortened string if over a set upper limit
(default 75 characters)
What is nicely shortened? Consider this line from Orwell's 1984...
0---------1---------2---------3---------4---------5---------6---------7---->
When we are omn... |
def shift_differences_for_missing_bp(missing_bp, differences, imgtDifferences, closestAlleleSequence):
"""if part of UTR5 is missing, shift differences in 3' direction
so they mark positions in the alignment, no the target sequence
"""
len_seq = len(closestAlleleSequence)
# shift differences:
... |
def values_attr(mapping, attr_name):
"""Map attribute getter on dictionary values."""
return [getattr(value, attr_name) for value in mapping.values()] |
def get_range_of_data(percentage_list, move=0, percentage=20):
"""Generating range of data with custom percentage
:param percentage_list: list of str
:param move: int
defines the position of data (default is 0)
0 -> top,
1 -> last,
-1 -> range
:param percentage: int
... |
def add_proper_name (w,lx):
"""adds a name to a lexicon, checking if first letter is uppercase"""
if ('A' <= w[0] and w[0] <= 'Z'):
lx.add(w,'P')
return ''
else:
return (w + " isn't a proper name") |
def factorial(number):
"""
Recursive function that calculates the factorial of the given number.
:return a number (factorial)
"""
if not isinstance(number, int):
raise Exception('Enter an integer number to find the factorial')
if number == 1 or number == 2:
return 1
else:
... |
def longueur_chemin(chemin, distance):
"""
Retourne la longueur d'un chemin.
"""
s = 0
nb = len(chemin)
for i in range(0, nb):
s += distance(chemin[i], chemin[(i + 1) % nb])
return s |
def filename_in_ignorelist(bfilename, filename_ext):
""" ignore certain files from processing.
:param bfilename: basefilename to inspect
:param filename_ext: extention of the filename
"""
if filename_ext in ['pdf', 'txt', 'doc']:
return True
elif bfilename in ('readme', 'license'... |
def detokenize_wordpiece(toks):
"""Combine split tokens from worpiece."""
tok_text = " ".join(toks)
# De-tokenize WordPieces that have been split off.
tok_text = tok_text.replace(" ##", "")
tok_text = tok_text.replace("##", "")
# Clean whitespace
tok_text = tok_text.strip()
tok_text = " ".join(tok_text.... |
def get_primes(length: int = 26, min_prime: int = 2,
max_prime: int = 101) -> list:
"""Get list of primes.
Given a length, minimum, and maximum prime number, return a list of prime
numbers.
Args:
length (int): Number of prime numbers to return. Defaults to ``26``.
min_pr... |
def damerau_levenshtein_distance(s1, s2):
"""Compute the Damerau-Levenshtein distance between two given strings (s1 and s2)"""
d = {}
lenstr1 = len(s1)
lenstr2 = len(s2)
for i in range(-1, lenstr1+1):
d[(i, -1)] = i + 1
for j in range(-1, lenstr2 + 1):
d[(-1, j)] = j + 1
for... |
def seconds_to_human(seconds, decimal=3):
"""
Convert seconds to HH:MM:SS[.SSS]
If decimal==0 only full seconds are used.
"""
secs = int(seconds)
fraction = seconds - secs
mins = int(secs / 60)
secs = secs % 60
hours = int(mins / 60)
mins = mins % 60
ret = f"{hours:02d}:{... |
def match_type(obj, matchers):
"""Matches a given object using the given matchers list/iterable.
NOTE(harlowja): each element of the provided list/iterable must be
tuple of (valid types, result).
Returns the result (the second element of the provided tuple) if a type
match occurs, otherwise none i... |
def safeguard(base_execution_url: str) -> str:
"""
Build the URL to fetch safeguards from for an execution
"""
return '/'.join([base_execution_url, 'policies']) |
def v_prefix(release):
"""Prefix a release number with 'v'."""
return "v" + release |
def check_if_account_is_integer(string):
""" Checks if the account number is an integer
:param string: input string
:return: Boolean, if the input is integer
"""
try:
int(string)
return True
except ValueError:
return False |
def format_error_message(exception_message, task_exception=False):
"""Improve the formatting of an exception thrown by a remote function.
This method takes a traceback from an exception and makes it nicer by
removing a few uninformative lines and adding some space to indent the
remaining lines nicely.
... |
def seq(n):
"""Return a list of [F0...Fn]"""
def fib_gen():
"""Fibonacci sequence generator. 0, 1, 1, 2, 3, 5, ..."""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fg = fib_gen()
return [next(fg) for _ in range(n + 1)] |
def hamming_with_n(s1, s2):
"""
Hamming Distance without counting wildcard smbols.
Args:
s1: the first sequence for comparison.
s2: the second sequence for comparison.
Returns:
the distance without accounting unrestricted sites.
"""
distance = 0
for c1, c2 in zip(s1... |
def denoise (val=None):
""" Set or get denoise """
global _denoise
if val is not None:
_denoise = val
return _denoise |
def GetNumberCodeBlocks(separators):
"""Gets the number of code blocks to break classes into."""
num_blocks = len(separators) + 1
assert num_blocks >= 2
return num_blocks |
def polygon_trans(p):
"""
:param p: polygon list with dict("lat": v1, "lng": v2) as elements
:return: polygon list with (v_lat, v_lng) as elements
"""
new_p = []
for point in p:
new_p.append((point["lat"], point["lng"]))
return new_p |
def get_maximum(list_values):
"""
function to obtain the max score of ppmi
:param list_values:
:return:
"""
max_score = max(list_values)
return max_score |
def word_value(word):
"""word is alrady upper case"""
a = ord('A')
return sum([ord(char) - a + 1 for char in word]) |
def arrival_times(all_events):
"""creates a list of customer arrival times"""
arrivals = []
queuing = 0
for e in all_events:
if 'q' in e:
arrivals.append(float(e.split()[0]))
queuing += 1
elif 's' in e:
if queuing>0:
queuing -= 1
... |
def parse_data_path(data_path):
"""
Parse a data path of the form <instrument>/<data>
"""
instrument = None
data_id = None
toks = data_path.split('/')
if len(toks) == 1 and len(toks[0]) > 0:
data_id = toks[0]
elif len(toks) == 2 and len(toks[0]) > 0 and len(toks[1]) > 0:
... |
def first_roll_result(sum_dice):
"""
Compare the total number of first dice
If the sum is 7 or 11
Return to win
If the sum is 2 or 3
Return loss
Otherwise,
Return to the point
Returns: The boolean value (boolean)
"""
if sum_dice == 7 or sum_dice == 11:
... |
def divide_split_dict(state):
"""Split-Dictionary Divider
Returns:
A list of two dictionaries. The first dictionary stores the
first half of the key-value pairs in ``state``, and the second
dictionary stores the rest of the key-value pairs.
.. note:: Since dictionaries are unor... |
def unsupported_commands(comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
"""
Suppress certain commands, because Grbl cant handle them.
"""
if cmd.startswith('M110 '):
# Reset line numbers not supported in Grbl
return None,
if cmd == 'M105':
# Translate temperatu... |
def size_sort(long_format_list):
"""This function returns the sorted list of final output based on size of the files
"""
size_sorted_list=sorted(long_format_list, key = lambda x:x[4])
return size_sorted_list |
def _to_helm_values_list(values):
"""
The sh lib doesn't allow you to specify multiple instances of the same
kwarg. https://github.com/amoffat/sh/issues/529
The best option is to concatenate them into a list.
"""
values_list = []
for key, val in values.items():
values_list += ["--se... |
def find_timestamp_slow(schedule):
"""Find earliest departure timestamp, when busses depart at offsets
matching position in list.
Not very efficient for big list."""
first_departure, first_bus = max(schedule, key=lambda item: item[1])
relative_schedule = [
(minute - first_departure, bus)
... |
def complement_base(base):
""" Returns the Watson-Crick complement of a base."""
if base == 'A' or base == 'a':
return 'T'
elif base == 'T' or base == 't':
return 'A'
elif base == 'G' or base == 'g':
return 'C'
else:
return 'G' |
def escape_hive(field_name):
""" We don't want to allow the use of hive reserved words. If there is a field using that as a name we need to add something to it
to make it different enough to not cause a conflict """
# set up the list of reserved words
reserved_words = ['ALL', 'ALTER', 'AND', 'ARRAY'... |
def is_isogram(string):
"""
Check is a word is isogram
"""
char_set = set()
for char in string.lower():
if char.isalpha():
if char in char_set:
return False
char_set.add(char)
return True |
def show_player(player):
"""
Returns a list of three elements which form one cell in the game view.
"""
return [" ", " {} ".format(player), " "] |
def version_lower_than(gaphor_version, version):
"""
if version_lower_than('0.3.0', (0, 15, 0)):
...
"""
parts = gaphor_version.split(".")
try:
return tuple(map(int, parts)) < version
except ValueError:
# We're having a -dev, -pre, -beta, -alpha or whatever version
... |
def sentence_to_bigrams(sentence):
"""
Add start '<s>' and stop '</s>' tags to the sentence and tokenize it into a list
of lower-case words (sentence_tokens) and bigrams (sentence_bigrams)
:param sentence: string
:return: list, list
sentence_tokens: ordered list of words found in the sentenc... |
def generate_trail(wire_directions):
"""Given a list of wire directions, generate a set of coordinate pairs for the wire's path"""
trail = set()
current_location = (0, 0)
for direction in wire_directions:
heading = direction[0]
distance = int(direction[1:])
while distance > 0:
... |
def locale_to_coords(locale):
"""Return a tuple of coordinates, coresponding to the default map location for the given locale."""
return {
'sl': (46.0, 14.5),
'en': (52.0, -1.7),
}[locale] |
def cmake_quote_string(value):
"""
cmake_quote_string(value) -> str
Return a quoted form of the given value that is suitable for use in CMake
language files.
"""
# Currently, we only handle escaping backslashes.
value = value.replace("\\", "\\\\")
return value |
def key_return(method_name, dict_name, dict_of_values, key):
"""
Many of our operations require a mode that is set via a dict, this will return the mode requested if it exists
or raise a key error with information to the user of what they submitted vs what was expected.
"""
try:
return dict_... |
def output_key_header(key, tabs, value="", indent=4) -> str:
"""Output a key"""
output = ""
if value != "": # Prepend a space to value if it exists.
value = " " + str(value)
output += (" " * indent) * tabs + str(key) + ":" + value + "\n"
return output |
def _check_array_range(istart, iend, npts):
"""
Takes two indices, checks that they are in the correct order, ie. start
is smaller than end, checks that start>=0 and end<=npts, and checks
that start!=end.
"""
istart = int(istart if istart<iend else iend)
iend = int(istart if istart>iend ... |
def try_convert(value, typing):
"""Try converting input value to specific variable types,
e.g. int, float..
"""
converted = True
try:
value = typing(value)
except:
converted = False
return converted |
def file_number_of_lines(file_name):
"""Counts the number of lines in a file
"""
try:
item = (0, None)
with open(file_name) as file_handler:
for item in enumerate(file_handler):
pass
return item[0] + 1
except IOError:
return 0 |
def single_title(title):
"""Convert the two parts of an icon.sys title into one string."""
title = title[0] + " " + title[1]
return u" ".join(title.split()) |
def is_better(new_metric, current_best_metric, metric_to_watch='acc'):
"""
Determines which of the two metrics is better, the higher if watching acc or lower when watching loss
:param new_metric: the new metric
:param current_best_metric: the compared to metric
:param metric_t... |
def validate_port(port):
"""Port number format validator
return validated port number as string or False if not valid
"""
if not port:
return False
port = port.strip()
if port.isdigit() and int(port) > 0 and int(port) < 65536:
return port
return False |
def _get_representative_batch(merged):
"""Prepare dictionary matching batch items to a representative within a group.
"""
out = {}
for mgroup in merged:
mgroup = sorted(list(mgroup))
for x in mgroup:
out[x] = mgroup[0]
return out |
def calcuate_aggregated_weights(program_tree, program_weights, node):
"""Calculate the aggregated weights for each node and all child nodes."""
aggregated_weights = {}
def walk_tree(node):
"""Walk the tree from the bottom up"""
aggregated_weights[node] = aggregated_weights[node] \
... |
def first_matching(iterable, predicate):
"""The first item matching a predicate.
Args:
iterable: An iterable series of items to be searched.
predicate: A callable to which each item will be passed in turn.
Returns:
The first item for which the predicate returns True.
Raises:
... |
def pigment(depigm, incpigm, cga, anyga):
"""
any pigm abn (depig, inc pig, noncentral GA)
Returns:
0, 1, 88
"""
if depigm == 1 or incpigm == 1 or (anyga == 1 and cga == 0):
return 1
elif depigm == 0 and incpigm == 0 and anyga == 0:
return 0
else:
return 88 |
def outer_split(expression, sep='()'):
""" Splits given ``expression`` by outer most separators.
>>> outer_split('123')
['123']
>>> outer_split('123(45(67)89)123(45)67')
['123', '45(67)89', '123', '45', '67']
If expression is not balanced raises ``ValueError``.
>>>... |
def get_urls(num):
"""get sample urls
: https://fpalette.netlify.app/
Args:
num(int): number of urls to return
Returns:
list: list of sample urls
"""
url = "https://fpalette.netlify.app/"
return [url for i in range(num)] |
def positive_int(x) -> int:
"""
Checks that the provided input is a positive integer. Used for PID
validation in the CLI arguments.
Parameters
----------
x
A positive integer
Returns
-------
"""
x = int(x)
if x < 0:
raise ValueError("A positive integer is... |
def reverse32_bits(num):
"""Reverse the bits of a 32-bit number"""
num = ((num & 0x55555555) << 1) | ((num & 0xaaaaaaaa) >> 1)
num = ((num & 0x33333333) << 2) | ((num & 0xcccccccc) >> 2)
num = ((num & 0x0f0f0f0f) << 4) | ((num & 0xf0f0f0f0) >> 4)
num = ((num & 0x00ff00ff) << 8) | ((num & 0xff00ff00)... |
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n) because the number of calculations performed depends on the size of num.
Space Complexity: Space complexity is also O(n) becuase newman_conway_nums array to store sequence valu... |
def get_module_in_url(base_url):
"""Get module from Kodi base URL (sys.argv[0])
Args:
base_url (str): Base URL string passed to the addon (e.g. plugin://plugin.video.catchuptvandmore/resources/lib/websites/culturepub/list_shows)
Returns:
str: Module found in the base URL (e.g. resources.lib... |
def total_hours(hours, days, weeks):
"""Total hours in w weeks + d days + h hours."""
return hours + 24 * (days + 7 * weeks) |
def get_tags_gtf(tagline):
"""Extract tags from given tagline in GTF format"""
tags = dict()
for t in tagline.strip(';').split(';'):
tt = t.strip(' ').split(' ')
tags[tt[0]] = tt[1].strip('"')
return tags |
def _n_choose_2(n):
"""Calculates the number of 2-combinations of n elements."""
return (n * (n - 1)) // 2 |
def update_dictionary_fc(fields, values, dictionary):
"""Update values in a dictionary using a table row"""
for i in range(0, len(fields)):
# Update the dictionary with the more recent values
dictionary[fields[i]] = values[i]
i += 1
return dictionary |
def _translate_virDomainState(state):
""" Return human readable virtual domain state string. """
states = {}
states[0] = 'NOSTATE'
states[1] = 'Running'
states[2] = 'Blocked'
states[3] = 'Paused'
states[4] = 'Shutdown'
states[5] = 'Shutoff'
states[6] = 'Crashed'
states[7] = 'pmSu... |
def _normalize_encoding(encoding):
"""returns normalized name for <encoding>
see dist/src/Parser/tokenizer.c 'get_normal_name()'
for implementation details / reference
NOTE: for now, parser.suite() raises a MemoryError when
a bad encoding is used. (SF bug #979739)
"""
if encoding is ... |
def mutate_modified(record, rule):
"""Mutate a record for a "MODIFIED" action.
"""
field = rule['metadata']['field']
new_value = rule['metadata']['new_value']
if '.' in field:
f, n = field.split('.')
else:
f, n = (field, None)
if not rule['filters'](record) or f not in record... |
def types_matching_data_requirements(given_types, required_types):
"""Verifies if all given types match the requirements.
Requirements may vary and support multiple options."""
matches = True
i = 0
for item in given_types:
#print ("item: %r req: %r" % (item, required_types[i]))
... |
def get_level_value(level: str) -> int:
"""
Get the level value of a log level.
:param level: The log level.
:return: The level value.
"""
level = level.upper()
if level == "TRACE":
return 1
elif level == "DEBUG":
return 10
elif level == "INFO":
return 20
... |
def quote_value(value):
"""Quote a configuration value."""
if not value:
return ''
if value.strip() == value and value[0] not in '"\'' and \
value[-1] not in '"\'' and len(value.splitlines()) == 1:
return value.encode('utf-8')
return '"%s"' % value.replace('\\', '\\\\') \
... |
def multiply(multiplicand: list, multiplier: list) -> list:
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
multiplicand_row, multiplicand_col = len(multiplicand), len(multiplicand[0])
multiplier_row, multiplier_col = len(multiplier), len(multiplier[0])
... |
def cell_genotype(image_name):
"""returns cell genotype from the name"""
c_name=image_name.upper()
if (c_name.find('E3') != -1):
genotype="E3"
elif (c_name.find('E4') != -1):
genotype="E4"
else:
genotype="Unknown"
return genotype |
def _format_kinase_name(kinase_name):
"""
Format kinase name(s): One or multiple kinase names (additional names in brackets) are formatted to list of
kinase names.
Examples:
Input: "EPHA7 (EphA7)", output: ["EPHA7", "EphA7"].
Input: "ITK", output: ["ITK"].
Parameters
----------
kin... |
def htTable(listOfDicts, keys=None):
"""Return an HTML table for a list of dictionaries.
The listOfDicts parameter is expected to be a list of
dictionaries whose keys are always the same. This function
returns an HTML string with the contents of the table.
If keys is None, the headings are taken fr... |
def name_list(string):
"""Convert Zotero name list to Python name list.
Input is a string of semicolon separated 'Lastname, Firstname' names.
Output is a Python list of 'Firstname Lastname' names.
"""
names = []
for name in string.split('; '):
if ', ' in name:
last_comma... |
def calculate_last_spoken(numbers: list, turns: int) -> int:
"""calculate the last spoken number at specified turn"""
spoken = [0]*turns
last_spoken = -1
for turn, number in enumerate(numbers, 1):
spoken[number] = turn
last_spoken = number
for prev_turn in range(len(numbers), turns... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.