content stringlengths 42 6.51k |
|---|
def collimate(lst,delimiter):
"""Helper function for producing nicely aligned text output"""
out = []
maxlen = [0] * len(lst[0].split(delimiter))
for string in lst:
for i,s in enumerate(string.split(delimiter)):
maxlen[i] = max([len(s), maxlen[i]])
for string in lst:
... |
def createMysqlEscapeList(num):
"""Create a string with a list of %s for escaping."""
esc_str = ''
for i in range(num):
esc_str += '%s, '
return esc_str.rstrip(', ') |
def validate_keep(keep):
"""validates the value of the keep parameter
If it's not coercable to an int or equal to the special string values,
raise a ValueError. Otherwise, return `keep`.
:param keep: value to validate
:type keep: int or str
:return: the validated value of keep
:rtype: eith... |
def get_integer(value='0'):
"""
Converts string to integer.
If string has non-numerical character, it returns None
"""
try:
return int(value)
except ValueError:
return None |
def solution3(n):
"""
This function returns list of prime factors.
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors |
def divisors(num):
"""
Takes a number and returns all divisors of the number, ordered least to greatest
:param num: int
:return: list (int)
"""
list = []
x = 0
for var in range(0, num):
x = x + 1
if num % x == 0:
list.append(x)
return list |
def SanitizeUUID(uuid):
"""Sanitizes a UUID by lowercasing and removing any prepended "CN=" string.
Args:
uuid: str uuid.
Returns:
str uuid.
"""
uuid = uuid.lower()
if uuid.startswith('cn='):
uuid = uuid[3:]
return uuid |
def page_limit_from_proto(page_limit):
"""
Translates the proto value for `page_limit` to the client equivalent.
For user-friendliness, the client stores ``None`` to mean "no page limit:
return everything" whereas the our backend API uses ``-1``.
Parameters
----------
page_limit : int
... |
def convert_years_to_scale(data):
"""Converts the actual years in B.C./A.D. to a scale usable in a plot."""
# Get the years.
return {key: value for key, value in zip(data.keys(), range(len(data.keys())))} |
def select_keys_py3(dct, keys):
"""Returns a dict containing only those entries in dict whose key is in
keys.
"""
return {k:v
for k,v in dct.items()
if k in keys} |
def fstime_floor_secs(ns):
"""Return largest integer not greater than ns / 10e8."""
return int(ns) / 10**9; |
def flatten(lst_of_lst):
""" Flatten list of list objects.
"""
lst = []
for l in lst_of_lst:
if isinstance(l, list):
lst += flatten(l)
else:
lst.append(l)
return lst |
def get_dict(key, value):
"""Returns the dictionary with command:page.html
:rtype : dict
:param key: commands
:param value: html page name
:return: dictionary of the commands and names of the pages
"""
return {k.lower(): v for (k, v) in zip(key, value)} |
def convertToPx(quantity, unit):
"""
INTERNAL: Convert values to pixels
:param quantity: value
:param unit: unit for that value
:return: quantity in pixels
"""
if unit == "in":
return quantity * 96
if unit == "cm":
return quantity * 37.79375
if unit =... |
def convertMappingDict(mdict):
""" This method converts a mapping proxy object to
a dict object. mapping proxies create read-only dicts
but we don't have that concept in transcrypt yet.
"""
ret = {}
for k in mdict.keys():
ret[k] = mdict[k]
return(ret) |
def calc_kcorrected_properties(frequency, redshift, time):
"""
Perform k-correction
:param frequency: observer frame frequency
:param redshift: source redshift
:param time: observer frame time
:return: k-corrected frequency and source frame time
"""
time = time / (1 + redshift)
frequ... |
def get_inverse(a, b, c, d):
"""
Return inverse for a 2 x 2 matrix
with elements (a, b), (c, d).
"""
D = 1 / (a * d - b * c)
return d * D, -b * D, -c * D, a * D |
def base64_text_to_data_url(base64_text, data_format):
"""Convert data in form of base64 text to a data URL with suitable prefix."""
# Argument processing
if data_format == 'jpg':
data_format = 'jpeg'
# Transformation
# - MIME type
if data_format in ['jpeg', 'png', 'gif', 'webp']:
... |
def get_func_and_script_url_from_initiator(initiator):
"""Remove line number and column number from the initiator."""
if initiator:
return initiator.rsplit(":", 2)[0].split(" line")[0]
else:
return "" |
def validate_input_data(data):
"""
Takes in user input data
Checks if all the keys are provided
Raise key error if a key is missing
Returns a validated data in a dict format
"""
cleaned_data = {}
for key in data:
if data[key] is None:
assert False, key + ' key is miss... |
def define_guidelines(guides):
"""Defines special racial and class guidelines."""
if guides is not None:
creation_guides = dict()
for guide in guides.split("|"):
(guide_name, guide_increment) = guide.split(",")
creation_guides[guide_name] = int(guide_increment)
#... |
def head(title):
"""Create head string."""
output = ''
output += '<!doctype html>\n'
output += '<html lang="en">\n'
output += '<head>\n'
output += '<title>' + title + ' - Daniel Teal</title>\n'
output += '<meta charset="utf-8">\n'
output += '<meta name="referrer" content="no-referrer">\n... |
def _html_param_builder(params):
"""
Build a HTML params string out of a dictionary of the option names and their values. If a list is the value
(it is intended in a select case) the original list is returned instead of a string
:param dict params:
:return str | list: the composed parameters string... |
def get_login_tokens(login_response_body_dict):
"""Creates dictionary of login keys to use to make additional request calls to USPS
Args:
login_response_body_dict: response body (type dictionary) returned by the USPS logon endpoint.
Returns:
Dictionary containing logon key and... |
def isobject(x):
"""Is x a class object?"""
if hasattr(x, "__len__"):
return False # array
if hasattr(x, "__dict__"):
return True
return False |
def lookup(pair, date, cache):
"""
query cache: if answer not existing, return None.
"""
price = None
prices = cache.get(pair, None)
if prices:
price = prices.get(date, None)
return price |
def divide(a, b):
"""
Safe divide a and b
"""
try:
return a/b
except ZeroDivisionError:
return 0
except:
raise |
def get_index_of_value_interval_vector(vector, value):
"""
Function returns the index of the smallest closest value to a given number inside a vector
"""
if value < vector[0]:
return 0
for i in range(len(vector) + 1):
if value < vector[i + 1] and value > vector[i]:
return i + 1
return len(vector) - 1 |
def rgb_to_hex(r, g, b):
""" Red, Green, Blue colors 0-255,
returns hex color string.
"""
return f'#{r:02x}{g:02x}{b:02x}' |
def onlyKeepSameNumbers(array1, array2):
"""
Returns an array, which only contains all numbers, which where part of both given arrays
"""
result = []
for x1 in range(0, len(array1)):
found = False
for x2 in range(0, len(array2)):
if(array1[x1] == array2[x2] & array1[x1] !... |
def remove_final_char(string):
"""
Removes the final character from a string from a string.
Replaces this character with an empty space.
Example
--------
>>> Input: "PO15 5RR"
>>> Output: "PO15 5R "
"""
substring_ = string[:-1]
return substring_ |
def z_ss(n, s, t):
"""Spin observable: z-direction
"""
if s == t:
return (-1)**s
else:
return 0 |
def skip_lines(text: str, lines_to_skip: int) -> int:
"""
Skip specified number of lines from the beginning of a text string.
:param text: Text string with zero or many '\n' in.
:param lines_to_skip: Number of lines to skip.
:return: Return position of the first charact... |
def repr_attributes(attributes: dict, separator: str = " "):
"""used for pretty-printing the attributes of a model
:param attributes: a dict
:returns: a string
"""
return separator.join([f"{k}={v!r}" for k, v in attributes.items()]) |
def stock_prices_1_brute_force(stock_prices):
"""
Solution: Brute force iterative solution compares each stock price with
all subsequent stock prices.
Complexity:
Time: O(n^2)
Space: O(1)
"""
if len(stock_prices) < 2:
raise ValueError('stock price list must be at least 2 items long')
highest_profit = None... |
def string_to_list(string_):
"""Convert string into list_."""
results = []
results = [x.strip() for x in string_.splitlines()]
results = list(filter(None, results)) ## remove blank lines from list -- http://stackoverflow.com/questions/3845423/remove-empty-strings-from-a-list-of-strings
return resul... |
def format_sentence_for_image(
sentence: str, character_name: str, service_name: str
) -> str:
"""
Given the sentence, character name, and service name, e.g. "Twitter", form the string
to write upon the quote image.
:param sentence: str
:param character_name: str
:param service_name: str
... |
def get_parameters(line):
"""Get parameters output by iostat.
Args:
line: Process line, hopefully containing the parameters.
Returns:
Tuple: (param_type, param_list)
Where:
param_type is one of ('avg-cpu:', 'Device:')
param_list is a list of parameter names ... |
def index_from(sequence, x, start_from=0):
""" Index from a specific start point
:param sequence: a sequence
:type sequence: List[object]
:param x: an object to index
:type x: object
:param start_from: start point
:type start_from: int
:return: indices of the matched objects
:rtype:... |
def get_green():
"""
Get color green for rendering
"""
return [0.651, 0.929, 0] |
def make_folder_list(number):
"""
Generates a list of folder names to be created
:param number: total number of folders to generate
:return: returns the list of all folders
"""
folder_list = []
for i in range(number):
name = f'sim_{i:04}'
folder_list.append(name)
... |
def bottles(n):
"""Formats plural according to number of bottles."""
return ('1 bottle' if n == 1 else str(n) + ' bottles') + ' of beer' |
def get_varkeys(constraints):
"""
Finds all of the variables in the constraints
:param constraints: GPkit constraints
:return: GPkit variables
"""
variables = set()
for constraint in constraints:
variables = variables.union(constraint.varkeys)
return variables |
def is_timerange(item: str) -> bool:
"""
Returns True if the item is a TAF to-from time range
"""
return (
len(item) == 9 and item[4] == "/" and item[:4].isdigit() and item[5:].isdigit()
) |
def CheckWrong(predicted, correct):
"""
Takes in array of predicted values and verifies that each prediction has the correct label.
If any of the predictions are wrong, the test fails.
Returns
-------
report : True or False
"""
for prediction in predicted:
if prediction != corr... |
def getDirection(startPoint, endPoint):
"""
@ Parameter:
startPoint (int, int)
the coordinate of starting point
endPoint (int, int)
the coordinate of ending point
@ Return:
a list of integer indicating the best direction to do the
recurs... |
def get_commands_to_remove_portchannel(device, group):
"""Gets commands required to remove a port channel
Args:
device (Device): This is the device object of an NX-API enabled device
using the Device class within device.py
group (str): port-channel group number/ID
Returns:
... |
def beta_to_normal(a, b):
"""
Reparametrize
:param a:
:param b:
:return:
"""
m = a / (a + b)
v = a * b / (a + b) ** 2 / (a + b + 1)
return m, v ** .5 |
def gen_backend_tfvars_files(environment, region):
"""Generate possible Terraform backend tfvars filenames."""
return [
"backend-%s-%s.tfvars" % (environment, region),
"backend-%s.tfvars" % environment,
"backend-%s.tfvars" % region,
"backend.tfvars"
] |
def set_parity_bit(binary):
"""Use the binary string's rightmost bit as an even parity bit."""
parity_bit = '0' if binary[:-1].count('1') % 2 == 0 else '1'
return binary[:-1] + parity_bit |
def get_repository_name(url):
""" This function returns the name of the repository for splitting the
url of the repository.
:Arguments:
1. url (str) = url of the repository as stated by the user in
the xml file
:Returns:
string = name of the repository
"""
li_temp_1 = url.rsplit(... |
def web_container_config(container_config, web_config):
"""Merge our two favorites config: container (Rabbit and Redis) and web"""
return {**web_config, **container_config} |
def _pad_binary(bin_str, req_len=8):
"""
Given a binary string (returned by bin()), pad it to a full byte length.
"""
bin_str = bin_str[2:] # Strip the 0b prefix
return max(0, req_len - len(bin_str)) * '0' + bin_str |
def is_integer(s):
"""True if s in an integer."""
try:
c = float(s)
return int(c) == c
except (ValueError, TypeError):
return False |
def get_depths_to_prune(node_name, node_list):
"""Return non-minimum depth values given a (duplicate) node name"""
depth_list = [node[node_name] for node in node_list]
depth_list.remove(min(depth_list))
return depth_list |
def lcm(a, b):
"""
Simple version of lcm, that does not have any dependencies
"""
tmp_a = a
while (tmp_a % b) != 0:
tmp_a += a
return tmp_a |
def to_word(word):
"""
Convert an underscored key name into a capitalised word
"""
return word.replace("_", " ").capitalize() |
def to_seconds(hours, minutes, seconds):
"""Returns the amount of seconds in the given hours, minutes, and seconds."""
return hours*3600+minutes*60+seconds |
def reverse_complement(dna, reverse=True, complement=True):
"""
Make the reverse complement of a DNA sequence. You can also just make the
complement or the reverse strand (see options).
Input: A DNA sequence containing 'ATGC' base pairs and wild card letters
Output: DNA sequence as a string.
... |
def concat(*args):
"""
This function join all substring in one string
:param args: list of substrings
:return: joint string
"""
return ''.join(args) |
def _semantic_version_to_name(version):
"""Converts a semantic version string (e.g. X.Y.Z) to a suitable name string (e.g. X_Y_Z).
Args:
version: A semantic version `string`.
Returns:
A `string` that is suitable for use in a label or filename.
"""
return version.replace(".", "_") |
def parse_affiliations(response):
"""Parse the author affiliations from a MAG API response.
Args:
response (json): Response from MAG API in JSON format. Contains all paper information.
Returns:
affiliations (:obj:`list` of :obj:`dict`): List of dictionaries with affiliation information.
... |
def sanitize_releasability(releasability, user_sources):
"""
Remove any releasability that is for sources a user does not have access to
see.
:param releasability: The releasability list for a top-level object.
:type releasability: list
:param user_sources: The sources a user has access to.
... |
def _sanitize(hex_str, comment_strings=None, ignore_strings=None):
"""
Sanitize string input before attempting to write to file.
:param hex_str: the string input to sanitize
:param comment_strings: a tuple of strings identifying comment characters
:param ignore_strings: a tuple of strings to igno... |
def firmwareVersionToString (fwversion):
"""
Converts a raw integer value into a human readable string a.b.c.d.
:param int fwversion: raw value as received from the generator
:return str: a human readable string 'a.b.c.d'.
"""
a = (fwversion >> 24) & 0xFF
b = (fwversion >> 16) & 0xFF
c = (fwversion >> 8) & 0xF... |
def getattr_chained(obj, methods):
"""Return value from chained method calls
- eg a = 'A Big Thing' > getattr_chained(a, 'str.lower')
"""
try:
for method in methods.split('.'):
obj = getattr(obj, method)()
return obj
except Exception:
return None |
def prune_invalid_repository_dependencies( repository_dependencies ):
"""
Eliminate all invalid entries in the received repository_dependencies dictionary. An entry is invalid if the value_list of the key/value pair is
empty. This occurs when an invalid combination of tool shed, name , owner, changeset_re... |
def school_abbreviation(name):
"""
Creates the abbreviation used for the school based on the long name. Removes intermediary words.
:param name: (String) Long name for the school
:return: (String) abbreviated name for the school
"""
name = name.split()
abbv = ""
no_lst = ["of", "the", "i... |
def is_class_session(session):
"""
Check is a session has a class_session type.
:param: session: The session to check.
:type: session: {Str:Str}
:return: True if the session is of class_session type, False otherwise.
:rtype: bool
"""
try:
session_type = session['type']
... |
def optional_g(text):
"""Method for parsing an 'optional' generalized number."""
if text == '#VALUE!':
return None
if text:
return float(text)
else:
return None |
def myhomeserver_to_hass_brightness(value: int):
"""Convert MyHomeSERVER brightness (0..100) to hass format (0..255)"""
return int((value / 100.0) * 255) |
def get_env_path(key, default):
"""
Same as os.environ.get, but converts
paths to their absolute representation.
"""
import os
path = os.environ.get(key, default)
path = os.path.expanduser(path)
path = os.path.abspath(path)
print(f'[\033[95m{key}\033[0m]: \033[90m{path}\03... |
def ser(predicted, ground_truth, pass_ids):
"""Segment error rate.
Args:
predicted (list):
ground_truth (list):
pass_ids (list): list of id which does not start a new tag (inside)
Returns:
correct (int):
count (int):
"""
count = 0
correc... |
def random_min_var(pbcids, actual_votes, xs, nonsample_sizes):
"""
Choose the county to audit by choosing the county that minimizes the
variance for the estimated number of final votes for A in that county.
This formula uses the normal approximation as seen in Rivest's estimation
audit paper: in p... |
def myget(_adict, _akey, _default):
"""my version of dict.get()"""
if _akey in _adict.keys() and _adict[_akey]:
result = _adict[_akey]
else:
result = _default
return result |
def byteunits(n,typ):
""" it simply convert dimensions from pixels to bytes"""
if typ=='Int16':
byteperpixel=2
else:
byteperpixel=4
n_byte= byteperpixel*n
return n_byte |
def find_scenario_number_from_string(scenario):
"""
Reverse of the above method. Not currently used, but likely to be needed.
Args:
scenario: Scenario string
Returns:
scenario_number: The scenario number or None for baseline
"""
# strip of the manual if being used in model_runn... |
def hide_signature(app, what, name, obj, options, sig, anno):
"""
Enables the 'nodsigniture' option.
"""
if what in ['mirclass', 'mirmodule']:
if 'nosignature' in options:
return '', None
return sig, anno |
def solar_true_anomaly(solar_geometric_mean_anomaly, solar_equation_of_center):
"""Returns the Solar True Anomaly with Solar Geometric Mean Anomaly,
solar_geometric_mean_anomaly, and Solar Equation of Center,
solar_equation_of_center."""
solar_true_anomaly = solar_geometric_mean_anomaly + solar_equatio... |
def get_seq_from_module(module_dict):
"""
Get one line sequence of a motif from its parameters.
:param module_dict: dict - motif parameters
:return: str - sequence of a motif
"""
return ','.join([m['seq'] for m in module_dict]) |
def apply_var_bound(var1, var2, var3, var1_ub, var2_ub, var3_ub, var1_lb, var2_lb, var3_lb):
""" if var exceeds the bound, then don't pass gradient through it"""
if var1 > var1_ub or var1 < var1_lb:
var1 = var1.detach()
if var2 > var2_ub or var2 < var2_lb:
var2 = var2.detach()
if v... |
def _bbox(layers):
"""Find box containing all the points in layers (curves could go out)."""
minx = miny = maxx = maxy = 0
for layer in layers:
for curve_point in layer.points:
minx = min(minx, curve_point.point.x)
miny = min(miny, curve_point.point.y)
maxx = max(maxx, curve_point.point.x)
... |
def dict_diff(dict_target, dict_source,
udpate_modified_keys=False,
udpate_added_keys=False,
udpate_removed_keys=False,
path=""):
"""
:param dict_target: The dictionary to be modified
:param dict_source: The dictionary to be compared with
:param udpate_modified_keys:
:param udpate_added_keys:
... |
def avoid_duplicate_names(new_column_name, columns, suffix):
"""Adds a suffix in case of a column name collision in a recursive way
:param new_column_name: a possible new column name
:type: str
:param columns: existing column names
:type: list
:param suffix: suffix to add to prevent collisions
... |
def update_output_tab2(value):
"""
:return: Minimum number of games selected
output text on tab 2 based on slider input.
"""
return "Min Ratings: {}".format(value) |
def valid_codons(blocks):
"""Gets all valid codons from blocks"""
result = []
for b in blocks.values():
result.extend(b)
return result |
def check_old_policy(policy):
"""
Checks the validity of a single policy using the
rules from part 1 of day 2.
"""
letter_count = policy["passwd"].count(policy["letter"])
result = dict(policy)
result["valid"] = policy["low"] <= letter_count <= policy["high"]
return result |
def VersionValue(val):
"""Function for comparing version values
Args:
val (string): version number of the program (Eg: 2.3.1)
Returns:
int: converts the number to an int (Eg: 2.3.1 becomes 231)
"""
NewVal = str(val).replace(".","")
if len(NewVal) == 2:
return int(str(Ne... |
def hasNLines(N,filestr):
"""returns true if the filestr has at least N lines and N periods (~sentences)"""
lines = 0
periods = 0
for line in filestr:
lines = lines+1
periods = periods + len(line.split('.'))-1
if lines >= N and periods >= N:
return True;
return Fa... |
def check_list_duplicates(list_of_elements):
"""Check if given list contains any duplicates.
:param list_of_elements: List of SPICE kernel names
:type list_of_elements: list
:return: True if the input list contains
duplicates, False otherwise
:rtype: bool
"""
for elem in list_o... |
def notGreater(i, j):
"""Determine which operator will have higher priority."""
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3, 'sqrt': 4}
try:
a = precedence[i]
b = precedence[j]
return True if a <= b else False
except KeyError:
return False |
def gradient_color(min_val, max_val, val, color_palette):
""" Computes intermediate RGB color of a value in the range of min_val
to max_val (inclusive) based on a color_palette representing the range.
"""
max_index = len(color_palette)-1
delta = max_val - min_val
if delta == 0:
# del... |
def factor_num_ops(dim, exp):
"""
:return: the amount of operations required to evaluate the scalar factor
"""
if exp >= 2:
# 1 MUL + 1 POW
return 2
else:
# 1 MUL
return 1 |
def _create_col_dict(allowed_output_cols, req_cols):
"""Creates dictionary to apply check condition while extracting tld.
"""
col_dict = {col: True for col in allowed_output_cols}
if req_cols != allowed_output_cols:
for col in allowed_output_cols ^ req_cols:
col_dict[col] = False
... |
def compute_transitive_closure(graph):
"""Compute the transitive closure of a directed graph using Warshall's
algorithm.
:arg graph: A :class:`collections.abc.Mapping` representing a directed
graph. The dictionary contains one key representing each node in the
graph, and this key maps t... |
def loop_struct_has_for_loop(loop_struct):
"""Examine if the leaf node of the loop struct has any for loop."""
if "loop" in loop_struct:
return 1
elif "mark" in loop_struct:
child = loop_struct["mark"]["child"]
if child == None:
return 0
else:
return l... |
def prediction_to_vad_label(
prediction,
frame_size: float = 0.032,
frame_shift: float = 0.008,
threshold: float = 0.5,
):
"""Convert model prediction to VAD labels.
Args:
prediction (List[float]): predicted speech activity of each **frame** in one sample
e.g. [0.01, 0.03, 0... |
def _is_income_level(code):
"""
"""
return code in ["NOC","OEC","HIC","HPC","LIC","LMC","LMY","MIC","UMC",
"Z4","Z7","XD","ZJ","XM","XN","XO","ZQ","XP","XR",
"XS","ZG","XT", "XE"] |
def listifyMatrix(MatrixObjectdata):
"""
This function returns a single list of all values in the matrix object's
nested list structure.
"""
matrixdata = MatrixObjectdata
listifiedmatrix = []
for i in range(len(MatrixObjectdata)):
for j in range(len(MatrixObjectdata[i])):
... |
def param_filter(curr_dict, key_set, remove=False):
"""
Filters param dictionary to only have keys in the key set
Args:
curr_dict (dict): param dictionary
key_set (set): set of keys you want
remove (bool): filters by what to remove instead of what to keep
Returns:
filter... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.