content stringlengths 42 6.51k |
|---|
def service_update_flags( #pylint: disable=too-many-arguments
target_rep_size=None, instance_count=None, rep_restart_wait=None,
quorum_loss_wait=None, standby_rep_keep=None, min_rep_size=None,
placement_constraints=None, placement_policy=None, correlation=None,
metrics=None, move_cost=No... |
def vowel_count(phrase):
"""Return frequency map of vowels, case-insensitive.
>>> vowel_count('rithm school')
{'i': 1, 'o': 2}
>>> vowel_count('HOW ARE YOU? i am great!')
{'o': 2, 'a': 3, 'e': 2, 'u': 1, 'i': 1}
"""
# MUCH quicker way: VOWELS = set("aeiou")
vow... |
def calc_t_ramp(t_int, n_reset, t_frame):
"""Calculates the ramp time -- or the integration time plus overhead for resets.
Parameters
----------
t_int : float
Integration time (in seconds).
n_reset : int
Rest frames per integration
t_frame : float
Frame time (in seconds)... |
def combine_quality( dqarr1, dqarr2 ):
"""
Combines two data quality arrays to make a third.
The bitwise nature of the data quality flags means that two
arrays can be combined without needing to know the meaning
of the underlying flags.
:Parameters:
dqarr1: numpy arra... |
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
return val # return positive value as is
|
def encode_query(parsed_query):
"""
Take a parsed query and encode it to a query string.
"""
def escape_parens(value):
return value.replace('(', '\\(').replace(')', '\\)')
encoded_clauses = []
for clause in parsed_query['clauses']:
type = clause['type']
text = escape_pare... |
def sort_models_topologically(models):
"""Sort models topologically so that parents will precede children."""
models = set(models)
seen = set()
ordering = []
def dfs(model):
if model in models and model not in seen:
seen.add(model)
for child_model in model._meta.rever... |
def dna_starts_with(dna, pattern):
""" Return True if 'dna' starts with 'pattern' """
# Sanitize input
dna = dna.upper()
pattern = pattern.upper()
if not (set(dna) <= set('CGTA')):
raise ValueError('DNA contains garbage: %s' % set(dna))
if not (set(pattern) <= set('CGTA')):
rais... |
def remove_dollars(text):
"""remove dollars from start/end of text"""
while text.startswith("$"):
text = text[1:]
while text.endswith("$"):
text = text[0:-1]
return text |
def negate_conf(c):
"""Negate a line of configuration."""
return "no %s" % c |
def oldWikiWordToLabel(word):
"""
Strip '[' and ']' if non camelcase word and return it
"""
if word.startswith(u"[") and word.endswith(u"]"):
return word[1:-1]
return word |
def get_invalid_request_param(message):
"""
Returns error response for invalid request parameters
:param str error: message
:return: error_response
:rtype: object
"""
error_response = {"status": 400, "data": [], "message": message}
return error_response |
def map_value_in_list_to_dictionary_key(event, mapping_dict_with_lists, existing_column, new_column, allow_nulls, passthrough):
""" Maps a value from a list back to the key. Useful to map values to categories.
:param event: A dictionary
:param mapping_dict_with_lists: A mapping dict with lists in the val... |
def product_trial_rate(number_of_first_time_purchases, total_purchasers):
"""Returns the percentage of customers who trialled a product for the first time during a period.
Args:
number_of_first_time_purchases (int): Total number of unique first-time purchasers during a period.
total_purchasers ... |
def fibonacci_sum_squares(n: int):
"""
Computes the last digit of F0^2 + F1^2 + ... + Fn^2.
:param n: the sequence size of Fibonacci numbers
:return: the last digit of the sum of squares
Example 1:
0+1+1+4+9+25+64+169=273
>>> fibonacci_sum_squares(7)
3
Example 2:
F73 = 1,052,4... |
def card(n):
"""Return the playing card numeral as a string for a positive n <= 13."""
assert type(n) == int and n > 0 and n <= 13, "Bad card n"
specials = {1: 'A', 11: 'J', 12: 'Q', 13: 'K'}
return specials.get(n, str(n)) |
def parse_csv_value(s):
"""Parse and convert value to suitable types
Args:
s (str): value on csv
Returns:
Suitable value (int, float, str, bool or None)
"""
try:
return int(s)
except (OverflowError, ValueError):
try:
return float(s)
except (Ov... |
def convexHull(points):
"""
Compute the convex hull of the given {points}
"""
# set up the two corners
p_min = []
p_max = []
# zip all the points together, forming as many streams of coordinates as there are
# dimensions
for axis in zip(*points):
# store the minimum value in ... |
def example_func(x: str = 'Hello', y: bool = True, z: float = 12.1) -> str:
"""
A test function
:param x: The exxxx param
:param y: The whyyyyyyy param
:return: A string showing all values, repeated 10x to test long return values (Should be truncated to 256 chars)
"""
return f'x is: {x}, y i... |
def is_anti_symmetric(L):
"""
Returns True if the input matrix is anti-symmetric, False otherwise.
"""
result = len(L) == len(L[0])
for i in range(len(L)):
for j in range(len(L)):
result *= L[i][j] == -L[j][i]
return result |
def is_correct_educator_name(text):
"""
Checks if the text is correct
:param text: input text
:type text: str
:return: True or False
:rtype: bool
"""
return text.replace(".", "").replace("-", "").replace(" ", "").isalnum() |
def extract(string, start='(', stop=')', firststop=True):
""" Return substring between `start` and first/last `stop` characters
Args:
string (string): the string to extract from
start (string): the left delimiter string
stop (string): the right delimiter string
... |
def check_dynamic_shape(shape):
"""
Function Description:
check dynamic shpae
Parameter:
shape:shape
Return Value:
False or True
"""
dynamic_shape = False
for item in shape:
if item is None or isinstance(item, str):
dynamic_shape = True
... |
def subnet_str(cidr):
"""Convert the cidr string to x.x.x.x_y format
:param cidr: CIDR in x.x.x.x/y format
"""
if cidr is None:
return None
return cidr.replace("/", "_") |
def convertHtml(text):
"""A few HTML encodings replacements.
&#39; to '
&quot; to "
"""
return text.replace('&#39;', "'").replace('&quot;', '"') |
def parse_globus_url(url):
"""Parse a Globus URL string of the format:
globus://<UUID Endpoint>:<Path>
globus://ddb59aef-6d04-11e5-ba46-22000b92c6ec:/share/godata/file1.txt
returns a dict of the format:
{
'endpoint': 'ddb59aef-6d04-11e5-ba46-22000b92c6ec'
'pa... |
def calcBotFinalReward(top_action, bot_aspect_action, bot_opinion_action, gold_labels, bot_bias = 0.):
"""
Final bottom reward, using tagging sequence matching.
"""
lenth = len(top_action)
r = [0. for j in range(len(bot_aspect_action))]
j = 0
for i in range(lenth):
if top_action[i] >... |
def format_if(value, format_kwargs):
"""Apply format args to value if value or return value as is."""
if not value:
return value
return value.format_map(format_kwargs) |
def current_data_indexes(data, two_columns_argument):
"""
Transform the columns argument to the indexes of data tuple.
Parameters
----------
data : tuple
A value returned by the get_data() function.
two_columns_argument : list
A list which contains two indexes of used columns - ... |
def gibberish(*args):
"""Concatenate strings in *args together."""
# Initialize an empty string: hodgepodge
hodgepodge=''
# Concatenate the strings in args
for word in args:
hodgepodge += word
# Return hodgepodge
return hodgepodge |
def _rstrip_underscored_part(string):
"""Remove part after rightmost underscore in string if such a part exists."""
underscore_ind = string.rfind('_')
if underscore_ind != -1:
return string[:underscore_ind]
return string |
def update_flag(key_press, current_flag, flags):
"""Handle key press from cv2.waitKey() for capturing frames
:param key_press: output from `cv2.waitKey()`
:param current_flag: value of 'flag' holding previous key press
:param flags: dictionary mapping key presses to class labels
:return: new flag v... |
def year_range(entry):
"""Show an interval of employment in years."""
val = ""
if entry.get("start_date") is None or entry["start_date"]["year"]["value"] is None:
val = "unknown"
else:
val = entry["start_date"]["year"]["value"]
val += "-"
if entry.get("end_date") is None or ent... |
def get_obj_value(data_obj, attr, default=None):
"""Get dict's key or object's attribute with given attr"""
if isinstance(data_obj, dict):
return data_obj.get(attr, default)
return getattr(data_obj, attr, default) |
def apply_downsampling(seq, step, filter_global=False, filter_local=False, **kwargs):
""" Apply Down Samplings
Args.
-----
- seq : list [e.g. np.ndarray(), pd.DataFrame]
- step : integer, Spaceing between values
Return.
-------
- lsit of donwsampled `seq`
"""
seq_list = []
... |
def _to(l):
"""To
Converts all addresses passed, whether strings or lists, into one singular
list
Arguments:
l (list(str|str[])): The list of addresses or lists of addresses
Returns:
list
"""
# Init the return list
lRet = []
# Go through each item in the list
for m in l:
# If we got a list
if is... |
def construct_yaml_fields(signatures, function_operation_id_root,
file_operation_id_root, server_root_url):
"""
Parse the signatures of functions to a dictionary that is used to generate yaml files.
f = {0: {'name': 'linear-regression',
'request_method': 'post',
... |
def get_item_properties(item, fields, mixed_case_fields=[]):
"""Return a tuple containing the item properties.
:param item: a single item resource (e.g. Server, Tenant, etc)
:param fields: tuple of strings with the desired field names
:param mixed_case_fields: tuple of field names to preserve case
... |
def map_loc_genes(gene_list):
"""Map gene names beginning with 'LOC'.
See https://www.biostars.org/p/129299/ : these are genes with no
published symbol, and thus have the format 'LOC' + Entrez ID.
"""
gene_map = {}
unmatched = []
for gene in gene_list:
if gene.startswith('LOC'):
... |
def flatten_tests(test_classes):
"""
>>> test_classes = {x: [x] for x in range(5)}
>>> flatten_tests(test_classes)
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> test_classes = {x: [x + 1, x + 2] for x in range(2)}
>>> flatten_tests(test_classes)
[(0, 1), (0, 2), (1, 2), (1, 3)]
"""
te... |
def get_end_time(op):
"""Return the end time string of the operation."""
return op.get('metadata', {}).get('endTime') |
def tablero_a_cadena(tablero):
"""
(str) -> str
convierte el tablero a una cadena
>>>tablero_a_cadena(tablero)
[
['t', 'k', 'a', 'q', 'r', 'a', 'k', 't'],
['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', '... |
def create_python_command(args):
"""Create python shell command with args"""
return "python {}".format(" ".join(args)) |
def SBATCH_Config(object):
"""Simple data type that holds a dict data member and has a to_str() method."""
settings = ["begin",
"constraint",
"cpus-per-task", # min. CPUs per task on one node
"error", # stderr ... |
def qualify(path: str) -> str:
"""Add the scheme to a file path, if required."""
if path.startswith("/"):
return f"file://{path}"
else:
return path |
def _canonical_machine_name(machine):
"""Handle the .comlab -> .cs DNS change, mapping old results to the new names."""
return machine.replace('.comlab.ox.ac.uk', '.cs.ox.ac.uk') |
def sahovnica_n(n_vrstic):
""" vrni string, ki bo narisal sahovnico v velikost n_vrstic"""
# BEGIN SOLUTION
result = ''
# END SOLUTION
return result |
def secToHHMMSS(seconds):
"""
Converts input seconds into the desired output display format.
Rounds to the nearest second.
"""
rndSec = int(seconds + 0.5) # rounded seconds
hrs = int(rndSec / 3600)
min = int((rndSec - hrs * 3600) / 60)
sec = rndSec - hrs * 3600 -... |
def clean_inputs(word):
"""
cleans inputs in case of blanks or all spaces
"""
invalid_tems = [None, ' ', '', '\t', '\n']
if word in invalid_tems:
return None
else:
return word |
def settings_outside_clinical_bounds(cir, isf, sbr):
"""
Identifies whether any of the settings are outside clinical bounds (based on medical advisory)
Parameters
----------
cir: float
carb to insulin ratio for the particular scenario
isf: float
insulin sensitivity factor for t... |
def conv_lin(a, b=1.0, c=0.0, inverse=False):
"""Simple linear transform
will I think store parameters against each sensor then they are handy
>>> conv_lin(4,2,3)
11
>>> conv_lin(11,2,3.0,True)
4.0
>>>"""
if inverse is False:
return a * b + c
else:
... |
def from_literal(tup):
"""Convert from simple literal form to the more uniform typestruct."""
def expand(vals):
return [from_literal(x) for x in vals]
def union(vals):
if not isinstance(vals, tuple):
vals = (vals,)
v = expand(vals)
return frozenset(v)
if not isinstance(tup, tuple):
... |
def _service_account_email(project_id, service_account_id):
"""Return full service account email."""
return '%s@%s.iam.gserviceaccount.com' % (service_account_id, project_id) |
def remove_subtitle(title):
"""Strip a book's subtitle (if it exists). For example, 'A Book: Why Not?' becomes 'A Book'."""
if ':' in title:
return title[:title.index(':')].strip()
else:
return title |
def overlap(start1, end1, start2, end2, tolerance=0):
"""Check that range (start1, end1) overlaps with (start2, end2)."""
# Taken from https://nedbatchelder.com/blog/201310/range_overlap_in_two_compares.html
return end1 + tolerance >= start2 and end2 + tolerance >= start1 |
def get_start_end(sequence, skiplist=['-','?']):
"""Return position of first and last character which is not in skiplist.
Skiplist defaults to ['-','?'])."""
length=len(sequence)
if length==0:
return None,None
end=length-1
while end>=0 and (sequence[end] in skiplist):
end-=1
... |
def rec_cmp_prereleases(one, two):
"""Recursive function that compares two version strings represented as lists
to determine which takes precedence. If it is the left argument ("one"), the
result will be a 1. If the righthand argument wins ("two"), the result will be
a 2. If the two are equivalent (... |
def strtobool(value):
"""
This method convert string to bool.
Return False for values of the keywords "false" "f" "no" "n" "off" "0" or 0.
Or, return True for values of the keywords "true" "t" "yes" "y" "on" "1" or 1.
Or, othres return None.
Args:
value : string value
Return:
Return False for va... |
def manual_sentence_spelling(x, spelling_dictionary):
"""
Applies spelling on an entire string, if x is a key of the spelling_dictionary.
:param x: (string) sentence to potentially be corrected
:param spelling_dictionary: correction map
:return: the sentence corrected
"""
if x in spelling_di... |
def _to_bytes(string):
"""
Convert string to bytes.
"""
if not isinstance(string, (str, bytes)): # pragma: no cover
string = str(string)
return string if isinstance(string, bytes) else string.encode('utf-8') |
def get_backend_properties_url(config, backend_type, hub=None):
"""
Util method to get backend properties url
"""
hub = config.get('hub', hub)
if hub:
return '/Network/{}/devices/{}/properties'.format(hub, backend_type)
return '/Backends/{}/properties'.format(backend_type) |
def get_mail_port(protocol):
"""
This returns the server port to use for POP retrieval of mails
:param protocol: The protocol to be used to fetch emails - IMAP or POP3
:type protocol: basestring
:return: Returns the correct port for either POP3 or POP3 over SSL
:rtype: int
"""
if protoco... |
def mask_list(mask):
"""Return the list of set bits in a mask as integers."""
set_bits = []
for position, bit in enumerate(reversed(bin(mask)[2:])):
if bit == "1":
set_bits.append(int("1{}".format("0" * position), base=2))
return set_bits |
def stock_list(listOfArt: list, listOfCat: list) -> str:
"""
You will be given a stocklist (e.g. : L) and a
list of categories in capital letters e.g :
M = {"A", "B", "C", "W"}
or
M = ["A", "B", "C", "W"] or ...
and your task is to find all the books of L with
codes belonging to... |
def get_title(file):
""" Returns a string containing the title for the given file.
Args:
file(dict): Describes the file.
Returns:
String representing the title.
"""
# Use the track title. As a fallback, use the display title.
title = file.get("track_and_facet_info", {}).get("tr... |
def make_attr_name(name):
"""Converts name to pep8_style
Upper case letters are replaced with their lower-case equivalent
optionally preceded by '_' if one of the following conditions is
met:
* it was preceded by a lower case letter
* it is preceded by an upper case letter and followed by... |
def template_alternate_precedence(trace, event_set):
"""
precedence(A, B) template indicates that event B
should occur only if event A has occurred before.
Alternate condition:
"events must alternate without repetitions of these events in between"
:param trace:
:param event_set... |
def ak_expected():
"""
Fixture to create example cosine coefficients
"""
return [6, -1] |
def ensure_list(value):
"""Wrap value in list if it is not one."""
if value is None:
return []
return value if isinstance(value, list) else [value] |
def find_by_id(object_id, items):
""" Find an object given its ID from a list of items """
for item in items:
if object_id == item["id"]:
return item
raise Exception(f"Item with {object_id} not found") |
def overall_accuracy_calc(TP, POP):
"""
Calculate overall accuracy.
:param TP: true positive
:type TP : dict
:param POP: population
:type POP:int
:return: overall_accuracy as float
"""
try:
overall_accuracy = sum(TP.values()) / POP
return overall_accuracy
except ... |
def check_letter(row, col, board):
"""
check cell in row and col to see if it's a head letter of a word
:param row: row starting from 0
:param col: col starting from 0
:param board: a list consists of 0 and 1 converted from original board
:return: head_value
0 not a head letter
... |
def merge(items1, items2):
"""Merge given lists of items, each assumed to already be in sorted order,
and return a new list containing all items in sorted order.
DONE: Running time: O(n), since the lists are iterated over and merged in linear time.
DONE: Memory usage: O(n), since an auxiliary list is cr... |
def _strip_to_integer(trigger):
"""Return only the integer part of a string."""
return int("".join([x for x in trigger if x.isdigit()])) |
def add_frame_div_parent(cell_info):
"""
Adds the frame a cells parent divides on to cell info.
Args:
cell_info (dict): dict that maps cells to cell info
Returns:
dict: cell info with added frame_div_parent
"""
new_info = cell_info.copy()
for info in new_info.values():
... |
def get_race_infos(results):
"""
Returns general information for the race
"""
race = {}
race["league_name"] = results["league_name"]
race["start_time"] = results["start_time"]
race["track_id"] = results["track"]["track_id"]
race["track_name"] = results["track"]["track_name"]
race["co... |
def subarray_slice(index, num_items):
"""
Returns a slice that selects for selecting a chunk out of an array
@param index: Which chunk to select
@param num_items: Number of items in a chunk
@return A slice for selecting index*num_items to (index+1)*num_items
"""
return slice(index * num_ite... |
def fno_to_na(fno):
"""Convert an fno to an NA.
Parameters
----------
fno : `float`
focal ratio
Returns
-------
`float`
NA. The NA of the system.
"""
return 1 / (2 * fno) |
def child_request_dict(ts_epoch):
"""A child request represented as a dictionary."""
return {
"system": "child_system",
"system_version": "1.0.0",
"instance_name": "default",
"namespace": "ns",
"command": "say",
"id": "58542eb571afd47ead90d25f",
"parameter... |
def _hyperparameters_to_cmd_args(hyperparameters):
"""
Converts our hyperparameters, in json format, into key-value pair suitable for passing to our training
algorithm.
"""
cmd_args_list = []
for key, value in hyperparameters.items():
cmd_args_list.append('--{}'.format(key))
cmd... |
def clean_text(text):
"""
Cleans words of newline character.
"""
cleaned_text = []
for line in text:
cleaned_word = line.replace('\n', '')
if len(line) >= 5:
cleaned_text.append(cleaned_word)
return cleaned_text |
def mel2hz(mel):
"""Convert a value in Mels to Hertz
:param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise.
:returns: a value in Hertz. If an array was passed in, an identical sized array is returned.
"""
return 700*(10**(mel/2595.0)-1) |
def get_module_name(name):
"""Gets the name according to the config parser."""
return name.split('.')[0] |
def position_similarity(el1, el2, seq1, seq2):
"""
Get the normalized inverted movement cost for for between `el1` and
`el2` on the `seq2` iterable.
The function is used to get a value describing how far two words are in a
phrase (as list, as in ``string.split(' ')`` or, in our case through
:fu... |
def _get_block_sizes_v2(resnet_size):
"""Retrieve the size of each block_layer in the ResNet model.
The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
Arg... |
def _unicode(s):
"""
A helper function for converting to Unicode
"""
if isinstance(s, str):
return s
elif isinstance(s, bytes):
return s.decode('utf-8')
else:
raise ValueError("Expected unicode or ascii string, got %s" % type(s)) |
def _validate_as_instance(item, target_type):
"""
Validates that the item is an instance of the target_type and if not,
checks whether the item is the
Parameters
----------
item : target_type
target_type : type
Returns
-------
target_type
the item as an instance of the ... |
def dict2str(data):
"""
Create a string with a whitespace and newline delimited text from a dictionary.
For example, this:
{'cpu': '1100', 'ram': '640', 'smp': 'auto'}
becomes:
cpu 1100
ram 640
smp auto
cpu 2200
ram 1024
"""
result = ''
for k in data:
if da... |
def restoreString(s, indices):
"""
:type s: str
:type indices: List[int]
:rtype: str
"""
shuffle_str = ""
for i in range(len(indices)):
shuffle_str += s[indices.index(i)]
return shuffle_str |
def check_instructors(instructors):
"""
'instructor' must be a non-empty comma-separated list of quoted
names, e.g. ['First name', 'Second name', ...']. Do not use 'TBD'
or other placeholders.
"""
# YAML automatically loads list-like strings as lists.
return isinstance(instructors, list) a... |
def occurrences(x, lst):
"""Count the number of occurrences of x in lst."""
return len(list(filter(lambda e: x == e, lst))) |
def is_symmetric(A):
"""Tells whether a matrix is a symmetric matrix or not.
Args
----
A (compulsory)
A matrix.
Returns
-------
bool
True if the matrix is a diagonal matrix, False otherwise.
"""
for i in range(len(A)):
for j in range(len(A[0]))... |
def getExtension(fname):
"""
Gets extension from the file name.
Returns without the dot (.)
"""
a = fname.rfind('.')
return fname[a+1:] |
def same_notebook_code(nb1, nb2):
"""
Return true of the code cells of notebook objects `nb1` and `nb2` are
the same.
"""
# Notebooks do not match of the number of cells differ
if len(nb1['cells']) != len(nb2['cells']):
return False
# Iterate over cells in nb1
for n in range(le... |
def calculate_pizzas_recursive(participants, n_pizza_types, pizza_types):
""" This function calculates the order list
for pizzas, for a given number of participants.
Recursive
See: https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
"""
# No participants left
if(n_pizza_t... |
def factors(number):
"""Give a list of all the facotrs of given natural number."""
if number > 1:
return [i for i in range(1, number) if number % i == 0]
elif number == 1:
return []
else:
raise ValueError("Requires a Natural number") |
def crop_list(timelist, min_len):
"""
Crop out items shorter than min len
"""
croped_list = []
for i in timelist:
# Don't keep items if start time shifted forward
# by min length, is greater than end time.
if i[0].shift(minutes=+min_len) <= i[1]:
croped_list.appen... |
def _num_requests_needed(num_repos, factor=2, wiggle_room=100):
"""
Helper function to estimate the minimum number of API requests needed
"""
return num_repos * factor + wiggle_room |
def count_bits(n):
"""
Write a function that takes an integer as input,
and returns the number of bits that are equal to one
in the binary representation of that number.
You can guarantee that input is non-negative.
"""
result = ""
f_num = f"{n:08b}"
for el in f_num:
if ... |
def escape(inp, char_pairs):
"""Escape reserved characters specified in the list of tuples `char_pairs`
Parameters
----------
inp : str
Input string
chair_pairs : list
List of tuples of (character, escape sequence for character)
Returns
-------
str
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.