content stringlengths 42 6.51k |
|---|
def dicts_union(a, b):
"""
Function calculates some kind of sum of two dictionaries
:param a: Dictionary in form { (i, a) => [(coefficient_A, p_A)] }
:param b: Dictionary in form { (i, a) => [(coefficient_B, p_b)] }
:return: Dictionary in form { (i, a) => [(coefficient_A, p_A), (coefficient_B, p_B)]... |
def _greater_than_equal(input, values):
"""Checks if the given input is >= the first value in the list
:param input: The input to check
:type input: int/float
:param values: The values to check
:type values: :func:`list`
:returns: True if the condition check passes, False otherwise
:rtype: ... |
def pretty_format_args(*args, **kwargs):
"""
Take the args, and kwargs that are passed them and format in a
prototype style.
"""
args = list([repr(a) for a in args])
for key, value in kwargs.items():
args.append("%s=%s" % (key, repr(value)))
return "(%s)" % ", ".join([a for a in args... |
def _mro(cls):
"""
Return the method resolution order for ``cls`` -- i.e., a list
containing ``cls`` and all its base classes, in the order in which
they would be checked by ``getattr``. For new-style classes, this
is just cls.__mro__. For classic classes, this can be obtained by
a depth-first... |
def format_arg(arg: str, **kwargs):
"""apply pythons builtin format function to a string"""
return arg.format(**kwargs) |
def get_separators(clique_list, unique=True):
"""
:param clique_list list(set(int)): A list of cliques satisfying the running intersection property.
:param unique (bool): Whether the returned list of separators should have no duplicates (True)
or allow duplicates (False).
:return sep_list (list... |
def add_matrix(matrix1, matrix2):
"""
Adds matrix2 to matrix1 in place
"""
size = len(matrix1)
for i in range(size):
for j in range(size):
matrix1[i][j] += matrix2[i][j]
return matrix1 |
def currentTurn(turn):
"""
Simply returns the string version of whose turn it is as opposed to adding if/else everywhere
"""
if turn == 0:
return "Red Team"
elif turn == 1:
return "Blue Team" |
def JD2epochJulian(JD):
#---------------------------------------------------------------------
"""
Convert a Julian date to a Julian epoch
:param JD:
Julian date
:type JD:
Floating point number
:Returns:
Julian epoch
:Reference:
Standards Of Fundamental Astronomy,
http://www.iau-sofa.rl.ac.u... |
def make_object(type, data):
""":return: bytes resembling an uncompressed object"""
odata = "blob %i\0" % len(data)
return odata.encode("ascii") + data |
def _byte_string(s):
"""Cast a string or byte string to an ASCII byte string."""
return s.encode('ASCII') |
def no_coords_same(coords):
"""
input: list of coords
output: bool
"""
takenList=[{coord} for coord in coords]
s=set()
for taken in takenList:
s= s.symmetric_difference(taken)
u=set()
for taken in takenList:
u= u.union(taken)
if s!= u:
#notTooClose = Fals... |
def longestIncreasing(array):
"""
return N (length), path(list) as a tuple describing the subsequence
O(n log n)
memo[j] stores the position k of the
smallest value X[k] such that there is an increasing subsequence of length j
ending at X[k] on the range k <= i
prev[k] stores the position ... |
def decodeFontName(font_name):
"""
Presume weight and style based on the font filename.
"""
name = font_name.split('-')[0]
font_name = font_name.lower()
weight = 400
style = 'regular'
weights = {'light': 300,
'extralight': 200,
'bold': 700,
... |
def is_balanced(text, brackets = "()[]{}<>"):
"""
>>> is_balanced("[]asdasdd()aqwe<asd>")
True
"""
counts = {}
left_for_right = {}
for left, right in zip(brackets[::2], brackets[1::2]):
assert left != right, "The brackets must be differ"
counts[left] = 0
left_for_ri... |
def IsEven(i):
"""Returns a Z3 condition for if an Int is even"""
return i % 2 == 0 |
def included(combination, exclude):
"""
Checks if the combination of options should be included in the Travis
testing matrix.
@param exclude: A list of options to be avoided.
"""
return not any(excluded in combination for excluded in exclude) |
def find_executable(name):
"""
Is the command 'name' available locally?
:param name: command name (string).
:return: full path to command if it exists, otherwise empty string.
"""
from distutils.spawn import find_executable
return find_executable(name) |
def qs2 (array):
""" another longer version"""
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
... |
def agg_event_role_tpfpfn_stats(pred_records, gold_records, role_num):
"""
Aggregate TP,FP,FN statistics for a single event prediction of one instance.
A pred_records should be formated as
[(Record Index)
((Role Index)
argument 1, ...
), ...
], where argument 1 should sup... |
def coco_split_class_ids(split_name):
"""Return the COCO class split ids based on split name and training mode.
Args:
split_name: The name of dataset split.
Returns:
class_ids: a python list of integer.
"""
if split_name == 'all':
return []
elif split_name == 'voc':
return [
1, 2,... |
def getRow(rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex == 0:
return [1]
if rowIndex == 1:
return [1,1]
current_row = [1,1]
for i in range(rowIndex-1):
next_row = [1]+[current_row[i]+current_row[i+1] for i in range(len... |
def rotate(nums, k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
# nums = nums[k + 1:] + nums[:k + 1]
for i in range(k):
nums.insert(0, nums[-1])
nums.pop()
return nums |
def treelist_to_dict(treelist):
"""
take list with entries
(nodenumber, qname, lbranch_node_number, rbranch_node_number)
return dict with dict entries
nodenumber: {"question": qname, "no_branch": lb, "yes_branch": rb}
"""
treelist = [(node, {"question": qname, "no_branch": no_branch,\
... |
def extractOutput(queryResults):
"""convenience function to extract results from active query object"""
if not queryResults:
return None
try:
return [x.toDict() if x else None for x in queryResults]
except TypeError:
return queryResults.toDict()
return None |
def get_configurations(configs):
"""Builds a list of all possible configuration dictionary
from one configuration dictionary that contains all values for a key
Args:
configs (dict[str: List[any]]): a dictionary of configurations
Returns:
List: A list of configuration
"""
if... |
def _to_seconds(raw_time):
""" Converts hh:mm:ss,ms time format to seconds. """
hours, mins, secs = raw_time.split(':')
return int(hours) * 3600 + int(mins) * 60 + float(secs.replace(',', '.')) |
def _splitstrip(string):
"""Split string at comma and return the stripped values as array."""
return [ s.strip() for s in string.split(u',') ] |
def str2bool(stringToConvert):
"""Convert a string to a boolean.
Args:
* *stringToConvert* (str): The following string values are accepted as ``True``: "true", "t", "yes", "y", "on", "1". The following string values are accepted as ``False``: "false", "f", "no", "n", "off", "0". Input string evalua... |
def _nested_reduce(f, x):
"""Fold the function f to the nested structure x (dicts, tuples, lists)."""
if isinstance(x, list):
return f([_nested_reduce(f, y) for y in x])
if isinstance(x, tuple):
return f([_nested_reduce(f, y) for y in x])
if isinstance(x, dict):
return f([_nested_reduce(f, v) for (_... |
def get_reverse_endian(bytes_array):
"""
Reverse endianness in arbitrary-length bytes array
"""
hex_str = bytes_array.hex()
hex_list = ["".join(i) for i in zip(hex_str[::2], hex_str[1::2])]
hex_list.reverse()
return bytes.fromhex("".join(hex_list)) |
def get_s3_video_path(user_id: int, video_id: int) -> str:
"""Gets s3 video path
path structure: users/<user_id>/videos/<video_id>
Args:
user_id: user_id
video_id: video_id
Returns:
string url
"""
return f"users/{user_id}/videos/{video_id}" |
def dict_loudassign(d, key, val):
"""
Assign a key val pair in a dict, and print the result
"""
print(key + ": " + str(val), flush=True)
d[key] = val
return d |
def remove_brackets_from_end_of_url(url_: str) -> str:
"""
Removes square brackets from the end of URL if there are any.
Args:
url_ (str): URL to remove the brackets from.
Returns:
(str): URL with removed brackets, if needed to remove, else the URL itself.
"""
return url_[:-1] i... |
def get_next_page_link(links, index=1):
"""
Get the next page url of github from the response header
returns none if the response do not contain next page
"""
link_list = links.split(',')
for link in link_list:
if 'rel="next"' in link:
next_link= link.split('>;')[0][index:]
... |
def linear(x, out=None):
"""
Linear function.
Parameters
----------
x : numpy array
Input data.
out : numpy array, optional
Array to hold the output data.
Returns
-------
numpy array
Unaltered input data.
"""
if out is None or x is out:
retu... |
def clamp(val, mini, maxi):
"""
Returns val, unless val > maxi in which case mini is returned
or val < mini in which case maxi is returned
"""
return max(mini, min(maxi, val)) |
def _card(item):
"""Handle card entries
Returns: title (append " - Card" to the name,
username (Card brand),
password (card number),
url (none),
notes (including all card info)
"""
notes = item.get('notes', "") or ""
# Add car... |
def split_token(tdata, seplist=[':','*']):
"""
like str.split(), but allow a list of separators, and return
the corresponding list of separators (length should be one less
than the length of the value list) along with the list of elements,
i.e. return [split values] [separators]
"""
#... |
def unique( List ):
"""
return a compact set/list (only unique elements) of input list :List
"""
Res = [List[0]]
for x in List:
if x not in Res:
Res.append(x)
return Res |
def should_cache_download(*args, **kwargs) -> bool: # pragma: no cover
"""
Determine whether this specific result should be cached.
Here, we don't want to cache any files containing "-latest-" in their filenames.
:param args: Arguments of decorated function.
:param kwargs: Keyword arguments of de... |
def apply_perm(values, perm):
"""Apply the permutation perm to the values."""
return [values[pi] for pi in perm] |
def search_for_attr_value(obj_list, attr, value):
"""
Finds the first object in a list where it's attribute attr is equal to value.
Finds the first (not necesarilly the only) object in a list, where its attribute 'attr' is equal to 'value'.
Returns None if none is found.
:param list obj_list: list... |
def _splitshortoptlist(shortoptlist):
"""Split short options list used by getopt.
Returns a set of the options.
"""
res = set()
tmp = shortoptlist[:]
# split into logical elements: one-letter that could be followed by colon
while tmp:
if len(tmp) > 1 and tmp[1] is ':':
... |
def is_nullable_list(val, vtype):
"""Return True if list contains either values of type `vtype` or None."""
return (isinstance(val, list) and
any(isinstance(v, vtype) for v in val) and
all((isinstance(v, vtype) or v is None) for v in val)) |
def is_valid(sentString, recvString):
"""Check to see if the value recieved has the command inside of it.String
is received directly from arduino.
Rule: string must be in this format: [1,2,3]{4,5,6}
"""
if sentString in recvString:
return True
else:
return False |
def get_frequency(text):
"""
"""
if text[-1].isdigit():
freq = float(text[:-1])
elif text[-1] == "M":
freq = float(text[:-1])*1e6
else:
raise RuntimeError("Unknown FROV suffix %s", text[-1])
return freq |
def _calculate_total_mass_(elemental_array):
"""
Sums the total weight from all the element dictionaries in the elemental_array after each weight has been added (after _add_ideal_atomic_weights_())
:param elemental_array: an array of dictionaries containing information about the elements in the system
... |
def cut(value,arg):
"""
this cut all values of arg from string
"""
return value.replace(arg,'') |
def get_loss(current_hospitalized, predicted) -> float:
"""Squared error: predicted vs. actual current hospitalized."""
return (current_hospitalized - predicted) ** 2.0 |
def is_palindrome3(w):
"""iterate from start and from end and compare, without copying arrays"""
for i in range(0,round(len(w)/2)):
if w[i] != w[-(i+1)]:
return False
return True # must have been a Palindrome |
def font_style(keyword):
"""``font-style`` descriptor validation."""
return keyword in ('normal', 'italic', 'oblique') |
def fix_census_date(x):
"""Utitlity function fixing the last census date in file with country info
Parameters
----------
x : str
Year or Year with adnotations
Returns
-------
str
Year as string
"""
x = str(x)
if x == "Guernsey: 2009; Jersey: 2011.":
ret... |
def _get_rn_trail(trail, reactions):
"""Returns a textual representation of the CoMetGeNe trail using R numbers
instead of the default internal KGML reaction IDs.
:param trail: CoMetGeNe trail
:param reactions: dict of dicts storing reaction information (obtained by
parsing a KGML file)
:r... |
def rayleight_range(w0, k):
"""
doc
"""
return k * w0**2 |
def calculate_speeds(times, distances):
"""
:param times: A list of datetime objects which corresponds to the timestamps on transmissions
:param distances: A list of calculated distances. Each I distance corresponds to location difference between I and I+1
Description:
Takes a list of times and distances and... |
def is_pingdom_recovery(data):
"""Determine if this Pingdom alert is of type RECOVERY."""
return data["current_state"] in ("SUCCESS", "UP") |
def get_ip_sn_fabric_dict(inventory_data):
"""
Maps the switch IP Address/Serial No. in the multisite inventory
data to respective member site fabric name to which it was actually added.
Parameters:
inventory_data: Fabric inventory data
Returns:
dict: Switch ip - fabric_name mappin... |
def square_n(n):
"""Returns the square of a number"""
return int(n * n) |
def sort_proxy_stats_rows(proxy_stats, column):
"""
Sorts proxy statistics by specified column.
Args:
proxy_stats: A list of proxy statistics.
column: An int representing a column number the list should be sorted by.
Returns:
A list sorted by specified column.
"""
return sorted(proxy_stats, ke... |
def get_sfdc_conn(**p_dict):
""" Args: dictionary with SFDC connection credentials
Returns: SFDC connection string required by Simple-salesforce API
Syntax SFDC connection:
sf = Salesforce(username='', password='', security_token='')
"""
sfdc_conn = "Salesforce(username='" + p_dict['username'] + "', password=... |
def restore(segments, original_segments, invalid_segments, merged_segments):
"""
Replaces invalid segments with earlier segments.
Parameters
----------
segments : list of segments
The current wall segments.
original_segments : list of segments
The wall segments before any mergin... |
def format_condition_value(conditions):
"""
@summary:
['111', '222'] -> ['111', '222']
['111', '222\n333'] -> ['111', '222', '333']
['', '222\n', ' 333 '] -> ['222', '333']
@param conditions:
@return:
"""
formatted = []
for val in conditions:
formatted += [it... |
def apply_matrix(src, mtx):
"""
src: [3]
mtx: [3][3]
"""
a = src[0] * mtx[0][0] + src[1] * mtx[0][1] + src[2] * mtx[0][2]
b = src[0] * mtx[1][0] + src[1] * mtx[1][1] + src[2] * mtx[1][2]
c = src[0] * mtx[2][0] + src[1] * mtx[2][1] + src[2] * mtx[2][2]
return a, b, c |
def get_non_conflicting_name(template, conflicts, start=None, get_next_func=None):
""" Find a string containing a number that is not in conflict with any of
the given strings. A name template (containing "%d") is required.
You may use non-numbers (strings, floats, ...) as well. In this case
... |
def get_sstl(l, f):
"""space-separated token list"""
token_list = []
for node in l:
if token_list:
token_list.append(' ')
token = f(node)
token_list.extend(token)
return token_list |
def update_inc(initial, key, count):
"""Update or create a dict of `int` counters, for StatsDictFields."""
initial = initial or {}
initial[key] = count + initial.get(key, 0)
return initial |
def str_to_bool(value):
"""Represents value as boolean.
:param value:
:rtype: bool
"""
value = str(value).lower()
return value in ('1', 'true', 'yes') |
def make_dict(v: list) -> dict:
"""Make an alphabetically sorted dictionary from a list
:param v<list>: list of an attribute type
:return <dict>: in format {1: v[0], 2: v[1], ...}
"""
k = list(range(1, len(v) + 1))
return dict(zip(k, sorted(v))) |
def grow_utopian_tree(n):
"""
:type n: int
:rtype: int
"""
# height = 1
# for i in range(n):
# height = height * 2 if i % 2 == 0 else height + 1
height = 2 ** ((n + 3) // 2) - 2 + (n + 1) % 2
return height |
def withinEpsilon(x, y, epsilon):
"""x,y,epsilon floats. epsilon > 0.0
returns True if x is within epsilon of y"""
return abs(x - y) <= epsilon |
def is_already_latest_version(version: str) -> bool:
"""Returns ``True`` if the version is already the latest version"""
try:
with open('VERSION', 'r') as fp:
other = fp.read().strip()
except OSError:
return False
else:
lhs = tuple(map(int, version.split('.')))
... |
def both_positive(x, y):
"""
Returns True if both x and y are positive.
>>> both_positive(-1, 1)
False
>>> both_positive(1, 1)
True
"""
"*** YOUR CODE HERE ***"
return x > 0 and y > 0 |
def linode_does_not_exist_for_operation(op, linode_id):
""" Creates an error message when Linodes are unexpectedly not found for some operation
:param op: operation for which a Linode does not exist
:param linode_id: id that we expected to find
:return: a snotty message
"""
return "Attempted to ... |
def my_function(x, y):
"""
A simple function to divide x by y
"""
print('my_function in')
solution = x / y
print('my_function out')
return solution |
def filter_overrides(overrides):
"""
:param overrides: overrides list
:return: returning a new overrides list with all the keys starting with hydra. fitlered.
"""
return [x for x in overrides if not x.startswith("hydra.")] |
def get_paths(level=15):
"""
Generates a set of paths for modules searching.
Examples
========
>>> get_paths(2)
['ISPy/__init__.py', 'ISPy/*/__init__.py', 'ISPy/*/*/__init__.py']
>>> get_paths(6)
['ISPy/__init__.py', 'ISPy/*/__init__.py', 'ISPy/*/*/__init__.py',
'ISPy/*/*/*/__init_... |
def format_pattern(bit, pattern):
"""Return a string that is formatted with the given bit using either % or .format on the given pattern."""
try:
if "%" in pattern:
return pattern % bit
except:
pass
try:
return pattern.format(bit)
except:
return pattern |
def verifid_output(cmd_op):
"""vefifies if command output is in valid state. Multiline string are splits with
CR. and retuns as list. if input is a list, it will be returned as is.
any other input will throw error.
Args:
cmd_op (list, str): Either list or Multiline string of output
Raises:
TypeErro... |
def _isNumeric(j):
"""
Check if the input object is a numerical value, i.e. a float
:param j: object
:return: boolean
"""
try:
x = float(j)
except ValueError:
return False
return True |
def remove_more_info(dictionary):
"""
Removes the compilation information from the ACFGS : for each source function, transforms the map compilation option -> ACFG into a list containing only the ACFGs.
"""
return {filename: list(other_map.values()) for filename, other_map in dictionary.items()} |
def convert_month_to_sec(time_month):
"""Function to convert time in months to secs"""
ans = time_month * 30 * 24 * 60 * 60
return ans |
def combine_extensions(lst):
"""Combine extensions with their compressed versions in a list.
Valid combinations are hardcoded in the function,
since some extensions look like compressed versions of one another, but are not.
Parameters
----------
lst : list of str
Raw list of extensions... |
def buildn(s):
"""
>>> buildn(4)
4
>>> buildn(10)
19
>>> buildn(20)
299
>>> buildn(21)
399
"""
n, d = 0, 0
while s > 9:
n = 10 * n + 9
s -= 9
d += 1
if s != 0:
if n != 0:
n = s * (10 ** d) + n
else:
n = s... |
def _prep_certificate(certificate):
"""
Append proper prefix and suffix text to a certificate. There is no
standard way for storing certificates. OpenSSL expects the demarcation
text. This method makes sure that the text the markers are present.
:type text: :class:`str`
:param text: The certifi... |
def _get_info_names(profile):
"""Get names of infos of tasks."""
info_names = sorted(set().union(*(set(val) for val in profile.values())))
return info_names |
def envelope_square(t, t_pulse, t_start=0, **not_needed_kwargs):
"""
Envelope for a square pulse (1 or 0).
Parameters
----------
t : float
Time at which the value of the envelope is to be returned.
t_pulse : float
The total duration of the pulse.
t_start : float, default=0
... |
def label_to_onehot(labels):
""" Convert label to onehot .
Args:
labels (string): sentence's labels.
Return:
outputs (onehot list): sentence's onehot label.
"""
label_dict = {'THEORETICAL': 0, 'ENGINEERING':1, 'EMPIRICAL':2, 'OTHERS':3}
onehot = [0,0,0,0]
for ... |
def parse_import_path(import_path: str):
"""
Takes in an import_path of form:
[subdirectory 1].[subdir 2]...[subdir n].[file name].[attribute name]
Parses this path and returns the module name (everything before the last
dot) and attribute name (everything after the last dot), such that the
at... |
def infer_missing_dims(frame_size, ref_size):
"""Infers the missing entries (if any) of the given frame size.
Args:
frame_size: a (width, height) tuple. One or both dimensions can be -1,
in which case the input aspect ratio is preserved
ref_size: the reference (width, height)
R... |
def ignoreRead(chr_l, loc_l, chr_r, loc_r, chrHash):
"""Check if a fragment aligned in particular location is to be excluded from analysis
Inputs:
chr_l: chr name of left alignment
chr_r: chr name of right alignment
loc_l: left alignment 'arrow-tip' location
loc_r: right alignmen... |
def validate_signature(public_key, signature, message):
"""Verifies if the signature is correct. This is used to prove
it's you (and not someone else) trying to do a transaction with your
address. Called when a user tries to submit a new transaction.
"""
return True
# public_key = (base64.b64dec... |
def is_year_leap(year):
"""Determines whether a year is a leap year"""
if year % 4 == 0 and year % 100 != 0:
return True
elif year % 400 == 0:
return True
else:
return False |
def declare_draw_if_no(player_one, player_two):
"""
Return True to continue
"""
if player_one.find('no') > 1:
return None
elif player_two.find('no') > 1:
return None
else:
return True |
def truncate_msg(msg, max_len=2000):
"""
Truncate a message string so it doesn't get lost (todo: automatically do this in realtime logger class)
"""
if len(msg) <= max_len:
return msg
else:
trunc_info = '<log message truncated to fit buffer>'
assert len(trunc_info) < max_len
... |
def _python3_selectors(read_fds, timeout):
"""
Use of the Python3 'selectors' module.
NOTE: Only use on Python 3.5 or newer!
"""
import selectors # Inline import: Python3 only!
sel = selectors.DefaultSelector()
for fd in read_fds:
sel.register(fd, selectors.EVENT_READ, None)
... |
def _pick_align_split_size(total_size, target_size, target_size_reads, max_splits):
"""Do the work of picking an alignment split size for the given criteria.
"""
# Too many pieces, increase our target size to get max_splits pieces
if total_size // target_size > max_splits:
piece_size = total_siz... |
def oversampled(semibmaj, semibmin, x=30):
"""
It has been identified that having too many pixels across the restoring
beam can lead to bad images, however further testing is required to
determine the exact number.
:param Semibmaj/semibmin: describe the beam size in pixels
:returns: True if bea... |
def get_out_type(string: str):
"""Return SCPI representation of voltage, current, or resistance."""
string = str(string)[0].upper()
return ('VOLT' if 'V' in string else ('CURR' if 'C' in string
else ('RES' if 'R' in string else 'ERR'))) |
def square_area(side):
"""Returns the area of a square"""
# You have to code here
# REMEMBER: Tests first!!!
return pow(side, 2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.