content stringlengths 42 6.51k |
|---|
def csSchoolYearsAndGroups(years, groups):
"""
group_letters = ["a", "b", "c", "d"]
output_list = ""
for year in range(years):
for group in range(groups):
output_list += (str(year+1) + group_letters[group] + ", ")
return output_list[:-2]
"""
"""
group_letters ... |
def config_identifier(converter, model_name):
"""Create identifier of configuration based on data `converter` and `model_name`"""
return model_name.lower().replace('-', '_') + '_' + converter |
def part2(instructions):
"""
>>> part2([0, 3, 0, 1, -3])
10
>>> part2(read_input())
23948711
"""
size = len(instructions)
index = 0
count = 0
while 0 <= index < size:
jump = instructions[index]
if jump >= 3:
instructions[index] = jump - 1
el... |
def smallest_difference(value1, value2):
"""
Finds smallest angle between two bearings
:param value1:
:param value2:
:return:
"""
abs_diff = abs(value1 - value2)
if abs_diff > 180:
smallest_diff = 360 - abs_diff
else:
smallest_diff = abs_diff
return smallest_diff |
def _to_z_score(scaled_score, expected_score, test):
""" Turn scaled and expected score to a z score
:param scaled_score: scaled score, result from raw_to_scaled function
:param expected_score: expected score, result from get_expected_score function
:param test: test of interest
:return: z-score fo... |
def decapitalize(string: str) -> str:
"""
Decapitalize a string.
Returns:
[type]: Decapitalized string.
>>> decapitalize('a')
'a'
>>> decapitalize('A')
'a'
>>> decapitalize('Ab')
'ab'
>>> decapitalize('AB')
'aB'
"""
if len(string) <= 1:
return str... |
def single_quote_to_double(input_value):
"""
Special for eggplant lists - replaces single quotes around all values with double quotes
"""
s = str(input_value)
s = s.replace("['", "[\"") # ['A'] --> ["A']
s = s.replace("']", "\"]") # ['A'] --> ['A"]
s = s.replace("',", "\",") # ['A', 'B'] ... |
def populate_list_category(dict_in):
"""A function that creates a list of the root and subroot categories"""
list_out = []
for key, value in dict_in.items():
list_out.append(key)
list_out.extend(value)
return [x.lower() for x in list_out] |
def is_file_like(data):
"""Check for file-like object"""
return hasattr(data, 'read') and hasattr(data, 'seek') |
def get_ssl_dict(parser_options=None):
"""Returns a dictionary with the SSL certificates
parser_options[in] options instance from the used option/arguments parser
Returns a dictionary with the SSL certificates, each certificate name as
the key with underscore instead of dash. If no certificate has b... |
def convert_bboxm_to_bboxcen(bbox):
"""
convert (xa,ya,xb,yb) to (x,y,w,h)
"""
cls = bbox[0]
bbox_copy = bbox[1:]
x = (bbox_copy[0] + bbox_copy[2]) / 2
y = (bbox_copy[1] + bbox_copy[3]) / 2
w = (bbox_copy[2] - bbox_copy[0])
h = (bbox_copy[3] - bbox_copy[1])
return [cl... |
def check_won (grid):
"""return True if a value>=32 is found in the grid; otherwise False"""
for i in range(4):
for j in range(4):
if grid[i][j] >= 32:
return True
return False |
def fix_static(lines):
"""Fix image links to handle new static path."""
def fix_static_line(line):
return line.replace('/static/images', '/images')
return [fix_static_line(line) for line in lines] |
def is_iterable(obj):
"""
Returns True if an object is iterable and False if it is not.
This function makes the assumtion that any iterable object can be
cast as an iterator using the build-in function `iter`. This might
not be the case, but works within the context of PySCeSToolbox.
Parameter... |
def rpt_slv_log(master, slaves, **kwargs):
"""Method: rpt_slv_log
Description: Function stub holder for mysql_rep_admin.rpt_slv_log.
Arguments:
master -> Stub holder
slaves -> Stub holder
"""
status = True
json_fmt = kwargs.get("json_fmt", None)
if master and slaves a... |
def get_executable_path(executable, venv):
"""
:param executable: the name of the executable
:param venv: the venv to look for the executable in.
"""
return '{0}/bin/{1}'.format(venv, executable) if venv else executable |
def blanknone(v):
"""
Return a value, or empty string if it's None.
"""
return '' if v is None else v |
def calc_grid_pos(pos, cols):
"""
A little function to calculate the grid position of checkboxes
:param pos:
:param cols:
:return:
"""
calc_row = pos // cols
calc_col = pos % cols
return calc_row, calc_col |
def foldr(seq, op, init):
"""Recursive sum.
>>> foldr( [2,3,5,7], lambda x,y: x+y, 0 )
17
"""
if len(seq) == 0:
return init
return op(seq[0], sum(seq[1:])) |
def remove_suffix(input_string, suffix):
"""Returns the input_string without the suffix"""
if suffix and input_string.endswith(suffix):
return input_string[:-len(suffix)]
return input_string |
def line(x1, y1, x2, y2):
"""Returns a list of points in a line between the given points.
Uses the Bresenham line algorithm. More info at:
https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm"""
# Check for the special case where the start and end points are
# certain neighbors, which this f... |
def is_individual_controller_url(url: str) -> bool:
"""Checks if the url implies the controller is a person."""
return "persons" in url and "individual" in url |
def get_pxe_address_x64(virtual_address, pte_base):
"""
The functions gives the PTE address for a virtual address
Based on: https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf
@param virtual_address: the virtual address to convert
@param pte_base: the base address for... |
def escape_star(line):
"""Escape all unmatched stars (*) so Sphinx know they aren't markup"""
line_split = line.split()
for index, value in enumerate(line_split):
# Star is only added to the end of the word, if the are used for markup
if not value.endswith('*'):
line_split[index... |
def escape_json(raw_str):
"""
Shell-Escape a json input string.
Args:
raw_str: The unescaped string.
"""
json_list = '['
json_set = '{'
if json_list not in raw_str and json_set not in raw_str:
return raw_str
str_quotes = '"'
i_str_quotes = "'"
if str_quotes in r... |
def try_conversion(value):
"""called when encountering a string in the xml
Arguments:
value {str} -- value to be converted, if possible
Returns:
[str, float, int] -- converted value
"""
try:
return int(value)
except (ValueError, TypeError):
pass
try:... |
def getCSRCommand(csrFile, keyStoreLocation, keystorePassword):
"""
:type sslRequest: SSLRequest
"""
commandString = "keytool -certreq -alias tomcat -file " + csrFile + "-keystore " + keyStoreLocation + " -noprompt -srcstorepass " + keystorePassword
return commandString |
def check_max_boundary_of_measurement(value, boundary):
"""
:return:
"""
if boundary is None:
return None
elif float(value) < float(boundary):
return True
else:
return False |
def _residual_str(name):
"""Make a residual symbol."""
return '\\mathcal{R}(%s)' % name |
def _extract_ip_address(string):
"""
Addresses from Ceph reports can come up with subnets and ports using ':'
and '/' to identify them properly. Parse those types of strings to extract
just the IP.
"""
port_removed = string.split(':')[0]
return port_removed.split('/')[0] |
def chunk_secret_value(data, chunk_size):
"""Yield successive chunk_size chunks from data."""
chunks = []
for x in range(0, len(data), chunk_size):
chunks.append(data[x:x + chunk_size])
return chunks |
def wavelength_to_rgb(wavelength, gamma=0.8):
"""
taken from http://www.noah.org/wiki/Wavelength_to_RGB_in_Python
This converts a given wavelength of light to an
approximate RGB color value. The wavelength must be given
in nanometers in the range from 380 nm through 750 nm
(789 THz through 400 T... |
def is_newline(character):
"""
Function to determine whether a given character is a newline character.
:param character: The character to be checked
:return: Whether the character is a newline character or not as a boolean value
"""
if character == '\n':
return True
else:
ret... |
def make_hrf_amount(amount: int, currency_precision: int) -> str:
"""Returns human readable format of the amount."""
return f"{amount / (10 ** currency_precision):.{currency_precision}f}" |
def del_job(jobs, source_id, job_id):
"""
delete the job from job list according to source_id and job_id
:param jobs: job list
:param source_id : target job's source_id
:param job_id: target job's job_id
:return: bool True or False
"""
if source_id not in jobs.keys():
return Fals... |
def check_t_test(trials_a, trials_b):
"""
Utility function to check if t test or not.
Parameters
----------
trials_a : int
number of successful clicks or successful events.
trials_b : int
number of impressions or events.
Return
------
flag : bool
True if t t... |
def RGB2HEX(color):
"""
Conversion from RGB to Hex
"""
return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2])) |
def get_spaceweather_imageurl(iu_address, iu_date, iu_filename, iu_extension, \
verbose):
"""Returns a complete image url string tailored to the spaceweather site by
concatenating the input image url (iu) strings that define the
address, the date folder, the filename root, and the filename extensio... |
def parseContentType(s):
"""Parses content-type string and returns list of parts"""
parts = s.lower().split(';')
plist = {}
if len(parts) > 1:
for p in parts[1:]:
v = p.split('=', 1)
if len(v) > 1:
plist[v[0].strip()] = v[1].strip()
... |
def groups_tags_string(groups):
"""Returns a string of tags in groups."""
tags = set()
for group in groups:
for tag in group.tags.all():
tags.add(str(tag))
return ', '.join(tags) |
def _CLsForPatches(patches):
"""Get GerritChangeTuples corresponding to the give GerritPatchTuples."""
return set(p.GetChangeTuple() for p in patches) |
def dt2freq(dt):
"""Converts a time step in hours to a DER-VET readable code"""
if dt == .25:
return '15min'
elif dt == 1:
return 'H'
elif dt == .5:
return '30min'
else:
print('Invalid dt input in Load screen. Assuming 15 minute intervals')
return '15min' |
def sum_of_minimums(numbers):
"""
Given a 2D list of size m * n. Your task is to find the sum of minimum value in each row.
:param numbers: a list of size m * n.
:return: the sum of each minimum value in each row.
"""
return sum(min(x) for x in numbers) |
def _create_list_from_string(text):
""" eg. "['word1', 'word2']" -> ['word1', 'word2']
"""
text = text[1:-1]
words = text.split(',')
return [word[1:-1] for word in words] |
def spec(t : str) -> str: # Should it be?
"""A special text beautifying.
Returns ``t.lstrip('>').rstrip('<').strip()''. Example:
``spec(">italic<")'' -> "italic".
Such a situation could happen at using this module's functions.
``Reader(<i>Text in tags 'i'</i>).between("i")'' gives a ``>...<'',
... |
def encode3(Married):
"""
This function encodes a loan status to either 1 or 0.
"""
if Married == 'Yes':
return 1
else:
return 0 |
def binary_search(items, value, exact=True, ascending=True, initial_guess=None):
"""Performs binary search for an item matching `value`
in a list of `items`.
Finds an exact match if `exact is True`, else as close as possible without crossing `value`
`items` sorted in ascending order if `ascending is Tr... |
def write_taxonomy_sklearn(
out_qza: str,
out_fp_seqs_qza: str,
ref_classifier_qza: str
) -> str:
"""
Classify reads by taxon using a fitted classifier.
https://docs.qiime2.org/2020.2/plugins/available/feature-classifier/classify-sklearn
Parameters
----------
out_qza
... |
def class_text_to_int(cls_name, label_map):
"""
Get index of class name
:param cls_name: name of class
:param label_map: label map
:return: index of class if found
"""
if cls_name in label_map:
return label_map[cls_name]
raise ValueError('Invalid class') |
def _unscale(x,rmin,rmax,smin,smax):
"""
Undo linear scaling.
"""
r = (smax-smin)/(rmax-rmin)
x_ = smin + r * (x-rmin)
return x_ |
def containsDuplicate(nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) == 0:
return False
# set also can be used instead of dict
elem_dict = {}
for n in nums:
if n in elem_dict:
return True
... |
def parse_parameters(parameters):
""" Parse input parameters from the command line """
parameter_list = [x for x in parameters.split(',')]
return dict([y.split('=') for y in parameter_list]) |
def predict_recursive(current_node):
"""
Helper function to recurse though lower branches of the trie and find more potential words
PARAMETERS:
----
current_node : dictionary
A dictionary to search for words or further nested dictionaries
RETURNS:
----
List
A list of tu... |
def _rule_statuses_changed(current_statuses, last_statuses):
"""Checks the rule evaluation statuses for SageMaker Debugger and Profiler rules."""
if not last_statuses:
return True
for current, last in zip(current_statuses, last_statuses):
if (current["RuleConfigurationName"] == last["RuleCo... |
def div_up(n:int, d:int)->int:
"""
Integer divide and round up.
Equivalent to: `int(ceil(float(n) / float(d)))`
"""
return (n + d - 1) // d |
def csv_restore_booleans(data):
"""Turn `True` and `False` into proper booleans, where possible"""
def _(x):
if x.lower() == "true":
return True
elif x.lower() == "false":
return False
else:
return x
for ds in data:
for key, value in ds.i... |
def convert_position_to_conventional_format(position):
"""Convert engine position format to conventional format.
position can be an integer from 0 to 63. For example 0 is converted to "a1".
"""
[r, c] = [position // 8 + 1, position % 8]
return "abcdefgh"[c] + str(r) |
def removeOverlappingExonsFromEachTranscript( transcript_info ):
"""
Scans each transcript and removes those exons that are subsets of other exons
"""
for transcript_id in transcript_info:
remove_these_exons = []
i = 0
while i < len( transcript_info[transcript_id]["exons"] ):
... |
def rbo_score(ground_truth, simulation, p=0.95):
"""
Rank biased overlap (RBO) implementation
http://codalism.com/research/papers/wmz10_tois.pdf
A ranked list comparison metric which allows non-overlapping lists
Inputs:
ground_truth - ground truth data
simulation - simulation data
p - R... |
def filter_predictions(predictions, max_regions, threshold):
"""
Filters predictions down to just those that are above or equal to a certain threshold, with
a max number of results controlled by 'max_regions'.
"""
results = [entry for entry in predictions if entry["prob"] >= threshold]
results =... |
def iou(box1, box2):
"""Compute the Intersection-Over-Union of two given boxes.
Args:
box1: array of 4 elements [cx, cy, width, height].
box2: same as above
Returns:
iou: a float number in range [0, 1]. iou of the two boxes.
"""
lr = min(box1[0] + 0.5 * box1[2], box2[0] + 0.5 * b... |
def _coalesce(*args):
""" Returns first non-null argument, or None if all are null. """
return next((a for a in args if a is not None), None) |
def calculate_luminance(srgb_value: float) -> float:
"""Converts gamma-compressed (sRGB) values into gamma-expanded (linear)."""
if srgb_value < 0.03928:
return srgb_value / 12.92
return ((srgb_value + 0.055) / 1.055) ** 2.4 |
def _remove_trailing_zeros_in_headers(d):
"""Remove the suffix '.0' from keys."""
d1 = {}
for key, value in d.items():
if isinstance(value, dict) and key.endswith('.0'):
d1[key[:-2]] = value
else:
d1[key] = value
return d1 |
def load_overrides(config, cmd_params):
"""Overrides configuration parameters (at the first level only) with the given cmd_params
:rtype: dict
:param config: a python dict containing the configuration parameters
:param cmd_params: a python list containing the overriding key, values i.e. value follows ke... |
def to_str(s, def_val=''):
"""
multi-byte compliant version of str() unicode conversion...
"""
ret_val = def_val
try:
ret_val = str(s)
except:
try:
ret_val = s.encode('utf-8')
except:
pass
return ret_val |
def get_combined_challenge(combined_challenge, delay_spec, noise_spec,
perturb_spec, dimensionality_spec):
"""Returns the specs that define the combined challenge (if applicable)."""
# Verify combined_challenge value is legal.
if (combined_challenge is not None) and (
combined_cha... |
def convert_to_ids(dataset, vocabulary):
"""Convert tokens to integers.
:param dataset a 2-d array, contains sequences of tokens
:param vocabulary a map from tokens to unique ids
:returns a 2-d arrays, contains sequences of unique ids (integers)
"""
return [[vocabulary[token] for token in sample... |
def _split_feature_trait(ft):
"""Feature is up to first '_'. Ex. 'line_color' => ['line', 'color']"""
ft = ft.split('_', 1)
return ft if len(ft)==2 else ft+[None] |
def validate_direction(value):
"""Raise exception if direction not one of the allowed values."""
if value and value not in ["INBOUND", "OUTBOUND"]:
return "satisfy enum value set: [INBOUND, OUTBOUND]"
return "" |
def prelogin_url(urlname):
"""
Fetches the correct dimagi.com url for a "prelogin" view.
"""
urlname_to_url = {
'go_to_pricing': 'https://dimagi.com/commcare/pricing/',
'public_pricing': 'https://dimagi.com/commcare/pricing/',
}
return urlname_to_url.get(urlname, 'https://dimagi... |
def col(red, green, blue):
"""Convert the given colours [0, 255] to HTML hex colours."""
return "#%02x%02x%02x" % (red, green, blue) |
def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float:
"""
Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
>>> fahrenheit_to_... |
def my_add_up_to_number(data, k):
"""My solution."""
for n1 in data:
for n2 in data:
if n1 + n2 == k:
print(
"Found two numbers that add up to {}; ({} and {}).".format(k, n1, n2))
return True
print("No numbers add up to {}.".f... |
def _match_apple(crosstool_top, cpu):
"""_match_apple will try to detect wether the inbound crosstool/cpu is
targeting the Apple ecosystem. Apple crosstool CPUs are prefixed, so
matching is easy."""
platform = {
"darwin_x86_64": "darwin_amd64",
"ios_arm64": "ios_arm64",
"ios_armv... |
def fmt(method: str, username: str, description: str) -> str:
"""
Log message formatter
:param method: http method name
:param username:
:param description: event description
:return: string
"""
return f"Method: {method} | Username: `{username}` | {description}" |
def get_log_attr( logline, attrname ):
"""
Looks for 'attrname' in the list of fields 'logline'. If found, the
value for the attribute is returned, otherwise None. For example, if
logline = [ 'launch', 'file=/my/file' ]
attrname = 'file'
will return "/my/file".
"""
pfx = attr... |
def omit_nulls(data):
"""Strips `None` values from a dictionary or `RemoteObject` instance."""
if not isinstance(data, dict):
if not hasattr(data, '__dict__'):
return str(data)
data = dict(data.__dict__)
for key in data.keys():
if data[key] is None:
del data[k... |
def compare_list(x, y):
"""
Compare lists by content. Ordering does not matter.
Returns True if both lists contain the same items (and are of identical
length)
"""
cmpx = [set(cluster) for cluster in x]
cmpy = [set(cluster) for cluster in y]
all_ok = True
for cset in cmpx:
all_ok &= ... |
def _cmp_with_None_as_2(o0, o1):
"""
:return: 0 if o0 == o1, -1 if o0 < o1, 1 if o0 > o1
"""
if isinstance(o1, tuple):
for _o0, _o1 in zip(o0, o1):
cmp = _cmp_with_None_as_2(_o0, _o1)
if cmp != 0:
return cmp
return 0
else:
if o0 is Non... |
def linear_rampdown(current, rampdown_length):
"""Linear rampdown"""
if current >= rampdown_length:
return 1.0 - current / rampdown_length
else:
return 1.0 |
def create_url(*args: str) -> str:
"""
Creates URL for HTTP request.
- doesn't contains trailing slash at the end.
:param *args: Segments to join. Order will be saved.
:returns: Created URL.
"""
separator = "/"
return separator.join(
[x[:-1] if x.endswith(separator) else x fo... |
def get_display(key, list):
""" Funcao que captura o label dos choices """
d = dict(list)
if key in d:
return d[key]
return None |
def all_equal(array):
"""
This function ...
:param array:
:return:
"""
first = array[0]
for i in range(1, len(array)):
if array[i] != first: return False
return True |
def check_isotope_in_library(isotope, lib_isos):
"""
Check if an isotope is in the acelib library
used for this simulation
Parameters
----------
isotope : str
Isotope to check for (i.e. 'H-1.09c')
lib_isos : list
List of strings containing possible isotopes in library
... |
def _split_ietf(tag):
"""
Splits a IETF language tag into its language part and country part.
"""
tag = tag.split("-")
lang = tag[0]
country = tag[1] if len(tag) > 1 else tag[0]
return lang, country |
def chrange(start, stop):
"""
Construct an iterable of length-1 strings beginning with `start` and ending
with `stop`.
Parameters
----------
start : str
The first character.
stop : str
The last character.
Returns
-------
chars: iterable[str]
Iterable of ... |
def _unify_gens(f_gens, g_gens):
"""Unify generators in a reasonably intelligent way. """
f_gens = list(f_gens)
g_gens = list(g_gens)
if f_gens == g_gens:
return tuple(f_gens)
gens, common, k = [], [], 0
for gen in f_gens:
if gen in g_gens:
common.append(gen)
... |
def f_simulation_day_X_simulation_time(simulation_time):
"""
:param simulation_time:
:return: day corresponding to the simulation time
"""
day = None
if simulation_time >= 0.0:
day = int((simulation_time + 0.00001) // 86400) + 1
return day |
def concat_classes(classes):
"""
merges a list of classes and return concatinated string
"""
return ' '.join(_class for _class in classes if _class) |
def parse_field(field):
"""
Parse a field dictionary and return a properly formatted string
Args:
field (dict): A dictionary of model field arguements
Returns:
str: A formatted string of the model field
"""
quote_fields = ['db_column', 'db_tablespace', 'help_text',
... |
def find_set_points(minmax_terms, var_name):
"""Return a list of sorted set points.
Args:
minmax_terms (list): A list of minmax_term objects.
var_name (str): A character, which is the name of the variable.
Returns:
list: An empty list if there are variables but all coefficients are... |
def _get_index_from_direction(direction):
"""Returns numerical index from direction
"""
directions = ['x', 'y', 'z']
try:
# l and r are subcases of x
if direction in 'lr':
index = 0
else:
index = directions.index(direction)
except ValueError:
m... |
def process_settings(pelicanobj):
"""Sets user specified Katex settings"""
katex_settings = {}
katex_settings['auto_insert'] = True
katex_settings['process_summary'] = True
return katex_settings |
def select_params(input_dict, profile_prefix):
"""
Get just the parameters and values for a given profile prefix.
Args:
input_dict (dict): the dictionary to search
profile_prefix (str): i.e. "PLANE_1-OBJECT_2-LIGHT_PROFILE_1-"
Returns:
parameter dictionary for profile
"""
... |
def extract_richer_tex(context_tex: str, tex: str) -> str:
"""
Extracting richer context tex for better regex matching:
Currently `context_tex` is made of concatenating a fixed length of prefix and postfix of `tex`. In that case, `context_tex` may include a lot of other information, causing errors in extrac... |
def smoothstep(edge0: float, edge1: float, x: float) -> float:
"""A smooth transition function.
Returns a value that smoothly moves from 0 to 1 as we go between edges.
Values outside of the range return 0 or 1.
"""
y = min(1.0, max(0.0, (x - edge0) / (edge1 - edge0)))
return y * y * (3.0 - 2.0 ... |
def _get_partitions(obj):
"""Check if any entry has partitions"""
for name, _ in obj:
if int(name.split('.')[-2]) > 0:
return True
return False |
def divided_diff(order, ys, dts):
"""Caluclate divided differences of the list of values given
in ys at points separated by the values in dts.
Should work with symbols or numbers, only tested with symbols.
"""
assert(len(ys) == order+1)
assert(len(dts) == order)
if order > 1:
retur... |
def _get_batch_representative(items, key):
"""Retrieve a representative data item from a batch.
Handles standard bcbio cases (a single data item) and CWL cases with
batches that have a consistent variant file.
"""
if isinstance(items, dict):
return items, items
else:
vals = set(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.