content stringlengths 42 6.51k |
|---|
def element_flatten(element):
"""Flatten the element into a single item if it's a single item list."""
# If there's only one result in the list, then return that single result.
if isinstance(element, list) and len(element) == 1:
return element[0]
else:
return element |
def get_data_dim(dataset):
"""
:param dataset: Name of dataset
:return: Number of dimensions in data
"""
if dataset == "SMAP":
return 25
elif dataset == "MSL":
return 55
elif str(dataset).startswith("machine"):
return 38
else:
raise ValueError("unknown dataset " + str(dataset)) |
def short_instance_profile(instance_profile=None):
"""
@type instance_profile: dict
"""
if instance_profile and instance_profile.get('Arn'):
return instance_profile.get('Arn') |
def format_flag(name):
"""Formats a flag given the name."""
return '--{}'.format(name.replace('_', '-')) |
def linear_search_recursive(array, item, index=0):
"""Incrementing index until item is found in the array recursively.
array: list
item: str
Best case running time: O(1) if the item is at the beginning of the array.
Worst case running time: O(n) if the item is last in the array.
"""
if index > (len(array) - 1):
return None
if item == array[index]:
return index
else:
return linear_search_recursive(array, item, index+1)
# once implemented, change linear_search to call linear_search_recursive
# to verify that your recursive implementation passes all tests |
def bin_from_float(number: float):
"""Return binary from float value.
>>> bin_from_float(446.15625)
0b110111110.00101
"""
integer = int(number)
fractional = abs(number) % 1
count = len(str(fractional)[2:])
binary = []
while (count > 0):
# print(number, integer, fractional)
fractional = fractional * 2
if fractional >= 1:
fractional = fractional - 1
binary.append('1')
else:
binary.append('0')
count -= 1
if binary:
return '{}.{}'.format(bin(integer), ''.join(binary))
return bin(integer) |
def diff_list(first, second):
"""Computes the difference between two input sets,
with the elements in the first set that are not in the second.
"""
second = set(second)
return [item for item in first if item not in second] |
def quote_path_component(text):
"""
Puts quotes around the path compoenents, and escapes any special characters.
"""
return "'" + text.replace("\\", "\\\\").replace("'", "\\'") + "'" |
def formatted(command):
"""Detects whether command is acceptable."""
if "official" in command:
return False
new = command.split()
if len(new) == 1:
return new[0] in [
"quit",
"options",
"adjourn",
"reload",
"redo_confidence",
"get_results",
]
elif len(new) == 3:
return new[0] in ["reset"]
elif len(new) == 2:
return new[0] in [
"confidence",
"min_trials",
"max_trials",
"min_time",
"max_time",
]
else:
return False |
def parse_sub_phase(raw):
"""Pass."""
parsed = {}
parsed["is_done"] = raw["status"] == 1
parsed["name"] = raw["name"]
parsed["progress"] = {}
for name, status in raw["additional_data"].items():
if status not in parsed["progress"]:
parsed["progress"][status] = []
parsed["progress"][status].append(name)
return parsed |
def fizz_buzz(current):
"""
Play fizz buzz
:param current: Number to check
:return: "Fizz" if current divisible by 3
"Buzz" if current divisible by 5
"Fizz Buzz" if current divisible by both 3 and 5
"""
if current % 3 == 0:
return "fizz"
elif current % 5 == 0:
return "buzz"
elif current % 15 == 0:
return "fizz buzz"
else:
return str(current) |
def truncate(
input_line: str) -> str:
"""
When a string is over 80 characters long, string is limited to 79
characters for readability in GUI window, An ellipsis (...) is added to
denote unseen text
"""
if len(input_line) >= 80:
input_line = input_line[0:79]
return input_line + "..."
else:
return input_line |
def get_id_from_stripe_data(data):
"""
Extract stripe id from stripe field data
"""
if isinstance(data, str):
# data like "sub_6lsC8pt7IcFpjA"
return data
elif data:
# data like {"id": sub_6lsC8pt7IcFpjA", ...}
return data.get("id")
else:
return None |
def detect_language(kernel_string):
"""attempt to detect language from the kernel_string"""
if "__global__" in kernel_string:
lang = "CUDA"
elif "__kernel" in kernel_string:
lang = "OpenCL"
else:
lang = "C"
return lang |
def bin(value: int, bits: int = 0) -> str:
"""Similar to built-in function bin(),
except negative values are represented in two's complement,
and the leading bit always indicates the sign (0 = positive, 1 = negative).
"""
length = value.bit_length()
if value < 0:
sign = 1
value = ~value ^ ((1 << length) - 1)
else:
sign = 0
digits = f"{value:0>{length}b}"
return f"0b{sign} {digits:{sign}>{bits}}" |
def calc_y(f, t):
"""Calc y from t.
:param f: the param of interp
:type f: dict
:param t: step of interp
:type t: int
:return: y corrdinate
:rtype: float
"""
return f['a_y'] + f['b_y'] * t + f['c_y'] * t * t + f['d_y'] * t * t * t |
def palindrome(word: str) -> bool:
"""
Check if a string is palindrome
:param word: the word to analyze
:return: True if the statement is verified, False otherwise
"""
i=0
while i < int((len(word)+1)/2):
if word[i] != word[-(i+1)]: return False
i+=1
return True |
def get_modified_columns(fields, fields_to_replace):
"""
This method updates the columns by adding prefix to each column if the column is being replaced and
joins it with other columns.
:param fields: list of fields of a particular table
:param fields_to_replace: dictionary of fields of a table which needs to be updated
:return: a string
"""
col_exprs = []
for field in fields:
if field in fields_to_replace:
col_expr = '{prefix}.concept_code as {name}'.format(prefix=fields_to_replace[field]['prefix'],
name=fields_to_replace[field]['name'])
else:
col_expr = field
col_exprs.append(col_expr)
cols = ', '.join(col_exprs)
return cols |
def calculate_spendings(queryResult):
"""
calculate_spendings(queryResult): Takes 1 argument for processing - queryResult
which is the query result from the display total function in the same file.
It parses the query result and turns it into a form suitable for display on the UI by the user.
"""
total_dict = {}
for row in queryResult:
# date,cat,money
s = row.split(",")
# cat
cat = s[1]
if cat in total_dict:
# round up to 2 decimal
total_dict[cat] = round(total_dict[cat] + float(s[2]), 2)
else:
total_dict[cat] = float(s[2])
total_text = ""
for key, value in total_dict.items():
total_text += str(key) + " $" + str(value) + "\n"
return total_text |
def get_result_sum(resultMap):
"""
Returns the corresponding entries of whether expressions should be summed or concatenated in a list.
:param resultMap:
:returns:
"""
return list(map(lambda row: row[3], resultMap)) |
def get_stochastic_depth_rate(init_rate, i, n):
"""Get drop connect rate for the ith block.
Args:
init_rate: `float` initial drop rate.
i: `int` order of the current block.
n: `int` total number of blocks.
Returns:
Drop rate of the ith block.
"""
if init_rate is not None:
if init_rate < 0 or init_rate > 1:
raise ValueError('Initial drop rate must be within 0 and 1.')
rate = init_rate * float(i) / n
else:
rate = None
return rate |
def verify_name(prior_name, inferred_name):
"""Verfies that the given/prior name matches with the inferred name.
"""
if prior_name is None:
prior_name = inferred_name
else:
assert prior_name == inferred_name, f"""given name {prior_name} does not mach with
inferred name {inferred_name}"""
return prior_name |
def format_date(value, format='%I:%M %m-%d-%Y'):
"""For use by Jinja to format dates on the frontend. Default format HH:MM M-D-YYYY"""
if value is None:
return ''
return value.strftime(format) |
def decodeIntLength(byte):
""" Extract the encoded size from an initial byte.
@return: The size, and the byte with the size removed (it is the first
byte of the value).
"""
# An inelegant implementation, but it's fast.
if byte >= 128:
return 1, byte & 0b1111111
elif byte >= 64:
return 2, byte & 0b111111
elif byte >= 32:
return 3, byte & 0b11111
elif byte >= 16:
return 4, byte & 0b1111
elif byte >= 8:
return 5, byte & 0b111
elif byte >= 4:
return 6, byte & 0b11
elif byte >= 2:
return 7, byte & 0b1
return 8, 0 |
def generate_primes(n: int):
"""Generate primes less than `n` (except 2) using the Sieve of Sundaram."""
half_m1 = int((n - 2) / 2)
sieve = [0] * (half_m1 + 1)
for outer in range(1, half_m1 + 1):
inner = outer
while outer + inner + 2 * outer * inner <= half_m1:
sieve[outer + inner + (2 * outer * inner)] = 1
inner += 1
return [2 * i + 1 for i in range(1, half_m1 + 1) if sieve[i] == 0] |
def __find_number_of_repeats(seq_before, seq, seq_after):
"""
Finds the number of repeats before or after a mutation.
:param seq_before: the genomic sequence before the mutation (str)
:param seq: the genomic sequence of the mutation (str)
:param seq_after: the sequence after the mutation (str)
:returns: number of repeats (int)
"""
tmp_seq = seq_after
k = 0
while tmp_seq[:len(seq)] == seq:
k += 1
tmp_seq = tmp_seq[len(seq):]
tmp_seq = seq_before[::-1]
seq = seq[::-1]
while tmp_seq[:len(seq)] == seq:
k += 1
tmp_seq = tmp_seq[len(seq):]
return k + 1 |
def need_to_escape(options):
""" Need escape string
Args:
options (dict): translation options
Returns:
boolean
"""
if 'escape' in options:
return options['escape']
return True |
def get_ugly(n: int) -> int:
"""
Get nth ugly number.
Parameters
-----------
Returns
---------
Notes
------
"""
if n <= 0:
return 0
uglies = [1] + [0] * (n-1)
nxt, u2, u3, u5 = 1, 0, 0, 0
while nxt < n:
minn = min(uglies[u2]*2, uglies[u3]*3, uglies[u5]*5)
uglies[nxt] = minn
while uglies[u2]*2 <= uglies[nxt]:
u2 += 1
while uglies[u3]*3 <= uglies[nxt]:
u3 += 1
while uglies[u5]*5 <= uglies[nxt]:
u5 += 1
print(u2, u3, u5)
nxt += 1
return uglies[-1] |
def find_available_path(from_list: list):
"""
Function to identify non empty items from nested list
Parameters
----------
from_list : list
Nested list containing None and not None entries.
Returns
-------
available_item_list: list
1D list
>>> relative_paths = ['spec.json', [None, None, None, [None, None, None, None], None, \
['directory2/directory22/spec.json', None, None, None, None]], ['directory1/spec.json', \
[None, None, None, None], None, None, [None, None, None, None], None, None]]
>>> find_available_path(relative_paths)
['spec.json', 'directory2/directory22/spec.json', 'directory1/spec.json']
"""
available_item_list = []
for item in from_list:
if isinstance(item, list):
ret_item = find_available_path(item)
if ret_item:
available_item_list.extend(ret_item)
elif isinstance(item, str):
available_item_list.append(item)
return available_item_list |
def get_partition_nodes(nodes_in_scheduler):
"""Get static nodes and dynamic nodes."""
static_nodes = []
dynamic_nodes = []
for node in nodes_in_scheduler:
if "-st-" in node:
static_nodes.append(node)
if "-dy-" in node:
dynamic_nodes.append(node)
return static_nodes, dynamic_nodes |
def lowercase(string):
"""Convert string into lower case.
Args:
string: String to convert.
Returns:
string: Lowercase case string.
"""
return str(string).lower() |
def get_person_uniqname(record, delimiter=','):
"""Spilt string and return uniqname by index position.
Parameters:
record (str): string to be split
delimiter (str): delimiter used to perform split
Returns:
str: uniqname
"""
return record.split(delimiter)[2] |
def parse_string (s):
"""Grab a string, stripping it of quotes; return string, length."""
if s[0] != '"':
string, delim, garbage = s.partition (" ")
return string.strip (), len (string) + 1
else:
try:
second_quote = s[1:].index ('"') + 1
except ValueError:
return s[1:], len (s)
else:
beyond = s[second_quote + 1:]
beyond_stripped = beyond.lstrip ()
extra_garbage = len (beyond) - len (beyond_stripped)
return s[1:second_quote], second_quote + 1 + extra_garbage |
def get_collection(collection, key, default=None):
"""
Retrieves a key from a collection, replacing None and unset values with the
default value. If default is None, an empty dictionary will be the
default.
If key is a list, it is treated as a key traversal.
This is useful for configs, where the configured value is often None,
but should be interpreted as an empty collection.
"""
if default is None:
default = {}
if isinstance(key, list):
out = collection
for k in key:
out = get_collection(out, k)
else:
out = collection.get(key, None)
return out if out is not None else default |
def parse_bool(value):
"""Parse string that represents a boolean value.
Arguments:
value (str): The value to parse.
Returns:
bool: True if the value is "on", "true", or "yes", False otherwise.
"""
return (value or '').lower() in ('on', 'true', 'yes') |
def ensure_tuple(tuple_or_mixed, *, cls=None):
"""
If it's not a tuple, let's make a tuple of one item.
Otherwise, not changed.
:param tuple_or_mixed: material to work on.
:param cls: type of the resulting tuple, or `tuple` if not provided.
:param length: provided by `_with_length_check` decorator, if specified, make sure that the tuple is of this
length (and raise a `TypeError` if not), otherwise, do nothing.
:return: tuple (or something of type `cls`, if provided)
"""
if cls is None:
cls = tuple
if isinstance(tuple_or_mixed, cls):
return tuple_or_mixed
if tuple_or_mixed is None:
return tuple.__new__(cls, ())
if isinstance(tuple_or_mixed, tuple):
return tuple.__new__(cls, tuple_or_mixed)
return tuple.__new__(cls, (tuple_or_mixed,)) |
def iter_to_string(it, format_spec, separator=", "):
"""Represents an iterable (list, tuple, etc.) as a formatted string.
Parameters
----------
it : Iterable
An iterable with numeric elements.
format_spec : str
Format specifier according to
https://docs.python.org/3/library/string.html#format-specification-mini-language
separator : str
String between items of the iterator.
Returns
-------
str
The iterable as formatted string.
"""
return separator.join([f"{format(elem, format_spec)}" for elem in it]) |
def _tofloat(obj):
"""Convert to float if object is a float string."""
if "inf" in obj.lower().strip():
return obj
try:
return int(obj)
except ValueError:
try:
return float(obj)
except ValueError:
return obj |
def get_2comp(val_int, val_size=16):
"""Get the 2's complement of Python int val_int
:param val_int: int value to apply 2's complement
:type val_int: int
:param val_size: bit size of int value (word = 16, long = 32) (optional)
:type val_size: int
:returns: 2's complement result
:rtype: int
"""
# test MSBit (1 for negative)
if (val_int&(1<<(val_size-1))):
# do complement
val_int = val_int - (1<<val_size)
return val_int |
def latex_criteria(value):
"""
Priority justification criteria in A4 latex PDF
"""
value = value.replace(' ', '\hspace*{0.5cm}').replace('\n', '\\newline')
return value |
def add_article(str_):
"""Appends the article 'the' to a string if necessary.
"""
if str_.istitle() or str_.find('the ') > -1:
str_ = str_
else:
str_ = 'the ' + str_
return str_ |
def cast_to_num(val):
"""Attempt to cast the given value to a float."""
try:
return float(val)
except ValueError:
return val |
def get_config_version(config_blob: dict):
"""
Get the version of a config file
"""
if "cfgpull" not in config_blob:
return 0
elif "version" not in config_blob["cfgpull"]:
return 0
return config_blob["cfgpull"]["version"] |
def parse_as_numeric(value, return_type=int):
"""
Try isolating converting to return type, if a ValueError Arises then return zero.
"""
try:
return return_type(value)
except ValueError:
return 0 |
def check_provided_metadata_dict(metadata, ktk_cube_dataset_ids):
"""
Check metadata dict provided by the user.
Parameters
----------
metadata: Optional[Dict[str, Dict[str, Any]]]
Optional metadata provided by the user.
ktk_cube_dataset_ids: Iterable[str]
ktk_cube_dataset_ids announced by the user.
Returns
-------
metadata: Dict[str, Dict[str, Any]]
Metadata provided by the user.
Raises
------
TypeError: If either the dict or one of the contained values has the wrong type.
ValueError: If a ktk_cube_dataset_id in the dict is not in ktk_cube_dataset_ids.
"""
if metadata is None:
metadata = {}
elif not isinstance(metadata, dict):
raise TypeError(
"Provided metadata should be a dict but is {}".format(
type(metadata).__name__
)
)
unknown_ids = set(metadata.keys()) - set(ktk_cube_dataset_ids)
if unknown_ids:
raise ValueError(
"Provided metadata for otherwise unspecified ktk_cube_dataset_ids: {}".format(
", ".join(sorted(unknown_ids))
)
)
# sorted iteration for deterministic error messages
for k in sorted(metadata.keys()):
v = metadata[k]
if not isinstance(v, dict):
raise TypeError(
"Provided metadata for dataset {} should be a dict but is {}".format(
k, type(v).__name__
)
)
return metadata |
def _name(ref):
"""Returns the username or email of a reference."""
return ref.get('username', ref.get('email')) |
def normScale( x, y ):
"""Scale to apply to an xy vector to normalize it, or 0 if it's a 0 vector"""
if x == 0 and y == 0:
return 0
else:
return 1.0 / pow( x*x + y*y, 0.5 ) |
def sqrt(x):
"""
Calculate the square root of argement x.
"""
# check that x is positive
if x<0:
print("Error: negative value supplied")
return -1
else:
print ("Here we go..")
#Initial guess for the square root.
z= x / 2.0
#continously improv the guess.
#adapted from https://tour.golang.org/flowcontrol
while abs(x-(z*z)) > 0.000001:
z= z- (z * z - x) / (2*z)
return z |
def get_media_from_object(tweet_obj):
"""Extract media from a tweet object
Args:
tweet_obj (dict): A dictionary that is the tweet object, extended_entities or extended_tweet
Returns:
list: list of medias that are extracted from the tweet.
"""
media_list = []
if "extended_entities" in tweet_obj.keys():
if "media" in tweet_obj["extended_entities"].keys():
for x in tweet_obj["extended_entities"]["media"]:
a = None
b = None
if "type" in x.keys():
a = x["type"]
if "expanded_url" in x.keys():
b = x["expanded_url"]
media_list.append((a, b))
return media_list |
def sumof(nn):
"""
sum values from 1 to nn
"""
sum = 0
while nn > 0:
sum = sum + nn
nn -= 1
return sum |
def _sanitize_text(text: str) -> str:
"""
note:
in rich-click, single newline (\n) will be removed, double newlines
(\n\n) will be preserved as one newline.
"""
return text.strip().replace('\n', '\n\n') |
def GetFrameworkPath(name):
"""Return path to the library in the framework."""
return '%s.framework/Versions/5/%s' % (name, name) |
def _compile_property_reference(prop):
"""Find the correct reference on the input feature"""
if prop == "$type":
return 'f.get("geometry").get("type")'
elif prop == "$id":
return 'f.get("id")'
return 'p.get("{}")'.format(prop) |
def get_os_url(url: str) -> str:
""" idiotic fix for windows (\ --> \\\\)
https://stackoverflow.com/questions/1347791/unicode-error-unicodeescape-codec-cant-decode-bytes-cannot-open-text-file"""
return url.replace('\\', '\\\\') |
def get_entities_bio(seq):
"""Gets entities from sequence.
note: BIO
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
seq = ['B-PER', 'I-PER', 'O', 'B-LOC', 'I-PER']
get_entity_bio(seq)
#output
[['PER', 0,1], ['LOC', 3, 3]]
"""
if any(isinstance(s, list) for s in seq):
seq = [item for sublist in seq for item in sublist + ["O"]]
chunks = []
chunk = [-1, -1, -1]
for indx, tag in enumerate(seq):
if tag.startswith("B-"):
if chunk[2] != -1:
chunks.append(chunk)
chunk = [-1, -1, -1]
chunk[1] = indx
chunk[0] = tag.split("-")[1]
chunk[2] = indx
if indx == len(seq) - 1:
chunks.append(chunk)
elif tag.startswith("I-") and chunk[1] != -1:
_type = tag.split("-")[1]
if _type == chunk[0]:
chunk[2] = indx # ['B-x', 'I-y', 'I-x'] -> [['x', 0, 2]]
if indx == len(seq) - 1:
chunks.append(chunk)
else:
if chunk[2] != -1:
chunks.append(chunk)
chunk = [-1, -1, -1]
return set([tuple(chunk) for chunk in chunks]) |
def _content_length(line):
"""Extract the content length from an input line."""
if line.startswith(b'Content-Length: '):
_, value = line.split(b'Content-Length: ')
value = value.strip()
try:
return int(value)
except ValueError:
raise ValueError("Invalid Content-Length header: {}".format(value))
return None |
def intersect(lists):
"""
Return the intersection of all lists in "lists".
"""
if len(lists) == 0: return lists
if len(lists) == 1: return lists[0]
finalList = set(lists[0])
for aList in lists[1:]:
finalList = finalList & set(aList)
return list(finalList) |
def get_halo_mass_key(mdef):
""" For the input mass definition,
return the string used to access halo table column
storing the halo mass.
For example, the function will return ``halo_mvir`` if passed the string ``vir``,
and will return ``halo_m200m`` if passed ``200m``, each of which correspond to the
Halotools convention for the column storing the halo mass in
`~halotools.sim_manager.CachedHaloCatalog` data tables.
Parameters
-----------
mdef: str
String specifying the halo mass definition, e.g., 'vir' or '200m'.
Returns
--------
mass_key : str
"""
return 'halo_m'+mdef |
def death_rate_ratio(age: int):
"""
Take into account age when calculating death probability. The 18-29 years old are the comparison group
Based on `https://www.cdc.gov/coronavirus/2019-ncov/covid-data/investigations-discovery/hospitalization-death-by-age.html`
:param age: age of the agent
"""
total = 13827
if 0 <= age < 5:
return 1 / total
elif 5 <= age < 18:
return 1 / total
elif 18 <= age < 30:
return 10 / total
elif 30 <= age < 40:
return 45 / total
elif 40 <= age < 50:
return 130 / total
elif 50 <= age < 65:
return 440 / total
elif 65 <= age < 75:
return 1300 / total
elif 75 <= age < 85:
return 3200 / total
elif age >= 85:
return 8700 / total |
def symbol_filename(name):
"""Adapt the name of a symbol to be suitable for use as a filename."""
return name.replace("::", "__") |
def KWW_modulus(x,logomega0, b, height):
"""1-d KWW: KWW(x, logomega0, b, height)"""
return height / ((1 - b) + (b / (1 + b)) * (b * (10**logomega0 / x) + (x / 10**logomega0)**b)) |
def gadgetMultipleFiles(rootName, fileIndex):
""" Returns the name of gadget file 'fileIndex' when a snapshot is saved in multiple binary files.
It takes 2 arguments: root name of the files and the file number whose name is requested (from 0 to GadgetHeader.num_files-1)."""
return rootName + "%i" % fileIndex |
def format_as_diagnostics(lines):
"""Format the lines as diagnostics output by prepending the diagnostic #.
This function makes no assumptions about the line endings.
"""
return ''.join(['# ' + line for line in lines]) |
def is_callable(var_or_fn):
"""Returns whether an object is callable or not."""
# Python 2.7 as well as Python 3.x with x > 2 support 'callable'.
# In between, callable was removed hence we need to do a more expansive check
if hasattr(var_or_fn, '__call__'):
return True
try:
return callable(var_or_fn)
except NameError:
return False |
def upper(text):
"""
Uppercases given text.
"""
return text.upper() |
def overlap(A, B):
"""Return the overlap (i.e. Jaccard index) of two sets
>>> overlap({1, 2, 3}, set())
0.0
>>> overlap({1, 2, 3}, {2, 5})
0.25
>>> overlap(set(), {1, 2, 3})
0.0
>>> overlap({1, 2, 3}, {1, 2, 3})
1.0
"""
return len(A.intersection(B)) / len(A.union(B)) |
def most_common(lst):
""" """
return max(set(lst), key=lst.count) |
def calculate_lux(r, g, b):
"""Calculate ambient light values"""
# This only uses RGB ... how can we integrate clear or calculate lux
# based exclusively on clear since this might be more reliable?
illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b)
return illuminance |
def is_structure_line(line):
"""Returns True if line is a structure line"""
return line.startswith('#=GC SS_cons ') |
def ami_quote_str(chars):
"""perform Amiga-like shell quoting with surrounding "..." quotes
an special chars quoted with asterisk *
"""
if chars == "":
return '""'
res = ['"']
for c in chars:
if c == "\n":
res.append("*N")
elif c == "\x1b": # ESCAPE
res.append("*E")
elif c == "*":
res.append("**")
elif c == '"':
res.append('*"')
else:
res.append(c)
res.append('"')
return "".join(res) |
def nrvocale(text):
"""Scrieti o functie care calculeaza cate vocale sunt intr-un string"""
count = 0
for c in text:
if c in ['a', 'e', 'i', 'o', 'u']:
count = count + 1
return count |
def check_answer(guess, a_followers, b_followers):
"""
Check the user guess to the actual followers of an account to verify if user's guess is correct
:param guess: user's guess
:param a_followers: number of followers of account a
:param b_followers: number of followers of account b
:return: if the user's guess is correct
"""
if a_followers > b_followers:
return guess == 'a'
else:
return guess == 'b' |
def verify_hr_info(in_dict):
"""
Verify the json contains the correct keys and data
{"patient_id": 1,
"heart_rate": 100}
"""
for key in ("patient_id", "heart_rate"):
if key not in in_dict.keys():
return "Key {} not found".format(key)
try:
integer = int(in_dict[key])
except ValueError:
return "Key {} is not integer".format(key)
return True |
def gcd_it(a: int, b: int) -> int:
"""iterative gcd
:param a:
:param b:
>>> from pupy.maths import gcd_it
>>> from pupy.maths import gcd_r
>>> gcd_it(1, 4) == gcd_r(1, 4)
True
>>> gcd_it(2, 6) == gcd_r(2, 6)
True
>>> gcd_it(3, 14) == gcd_r(3, 14)
True
>>> gcd_it(4, 300) == gcd_r(4, 300)
True
"""
while a:
a, b = b % a, a
return b |
def decode_subs(s, mapping):
"""
>>> decode_subs('hi there', [])
'hi there'
>>> decode_subs('g0SUB;there', [('hi ', 'g0SUB;')])
'hi there'
>>> decode_subs('g0SUB; theg1SUB;', [('hi', 'g0SUB;'), ('re', 'g1SUB;')])
'hi there'
"""
for tup in mapping:
s = s.replace(tup[1], tup[0])
return s |
def Linear(score, score_min, score_max, val_start, val_end):
"""Computes a value as a linear function of a score within given bounds.
This computes the linear growth/decay of a value based on a given score.
Roughly speaking:
ret = val_start + C * (score - score_min)
where
C = (val_end - val_start) / (score_max - score_min)
Note that score_min/max are used as lower/upper thresholds, determining the
range of scores that actually have impact on the returned value. Also note
that val_start/end may be arbitrarily related, for example it may be that
val_start > val_end, in which case the result will be a linearly decaying
function. The result is undefined (and may raise an exception) if
score_min >= score_max. Provided all arguments are integers, this guarantees
that all arithmetic operations, intermediate values, and returned result are
integers as well.
Args:
score: A number that determines the linear factor.
score_min: The lowest score to consider.
score_max: The highest score to consider.
val_start: The return value when score <= score_min.
val_end: The return value when score >= score_max.
Returns:
An integer value ranging between val_start and val_end.
"""
relative_score = max(min(score, score_max), score_min) - score_min
score_range = score_max - score_min
val_range = val_end - val_start
return val_start + ((val_range * relative_score) / score_range) |
def string_to_array(string, conversion=None):
""" Convert a string separated by spaces to an array, i.e.
a b c -> [a,b,c]
Parameters
----------
string : str
String to convert to an array
conversion : function, optional
Function to use to convert the string to an array
Returns
-------
array : list
List of items
"""
if isinstance(string, list):
return string
# Default: convert to list of ints
if not conversion:
conversion = int
parts = string.split(" ")
array = [conversion(i) for i in parts]
return array |
def splitlines(text):
"""Split text into lines."""
return text.splitlines() |
def jax_np_interp(x, xt, yt, indx_hi):
"""JAX-friendly implementation of np.interp.
Requires indx_hi to be precomputed, e.g., using np.searchsorted.
Parameters
----------
x : ndarray of shape (n, )
Abscissa values in the interpolation
xt : ndarray of shape (k, )
Lookup table for the abscissa
yt : ndarray of shape (k, )
Lookup table for the ordinates
Returns
-------
y : ndarray of shape (n, )
Result of linear interpolation
"""
indx_lo = indx_hi - 1
xt_lo = xt[indx_lo]
xt_hi = xt[indx_hi]
dx_tot = xt_hi - xt_lo
yt_lo = yt[indx_lo]
yt_hi = yt[indx_hi]
dy_tot = yt_hi - yt_lo
m = dy_tot / dx_tot
y = yt_lo + m * (x - xt_lo)
return y |
def get_year_for_first_weekday(weekday=0):
"""Get the year that starts on 'weekday', eg. Monday=0."""
import calendar
if weekday > 6:
raise ValueError("weekday must be between 0 and 6")
year = 2020
not_found = True
while not_found:
firstday = calendar.weekday(year, 1, 1)
if firstday == weekday and not calendar.isleap(year):
not_found = False
else:
year = year - 1
return year |
def solution(n):
"""Returns the largest prime factor of a given number n.
>>> solution(13195)
29
>>> solution(10)
5
>>> solution(17)
17
"""
prime = 1
i = 2
while i * i <= n:
while n % i == 0:
prime = i
n //= i
i += 1
if n > 1:
prime = n
return int(prime) |
def rectangles_contains_point(R, x, y):
"""Decides if at least one of the given rectangles contains a given point
either strictly or on its left or top border
"""
for x1, y1, x2, y2 in R:
if x1 <= x < x2 and y1 <= y < y2:
return True
return False |
def string_to_values(input_string):
"""Method that takes a string of '|'-delimited values and converts them to a list of values."""
value_list = []
for token in input_string.split('|'):
value_list.append(float(token))
return value_list |
def indent(yaml: str):
"""Add indents to yaml"""
lines = yaml.split("\n")
def prefix(line):
return " " if line.strip() else ""
lines = [prefix(line) + line for line in lines]
return "\n".join(lines) |
def class_as_descriptor(name):
"""Return the JVM descriptor for the class `name`"""
if not name.endswith(';'):
return 'L' + name + ';'
else:
return name |
def _construct_ws_obj_ver(wsid, objid, ver, is_public=False):
"""Test helper to create a ws_object_version vertex."""
return {
"_key": f"{wsid}:{objid}:{ver}",
"workspace_id": wsid,
"object_id": objid,
"version": ver,
"name": f"obj_name{objid}",
"hash": "xyz",
"size": 100,
"epoch": 0,
"deleted": False,
"is_public": is_public,
} |
def get_url(server: str):
"""Formats url based on given server
Args:
server: str, abbreviation of server
Return:
str: op.gg url with correct server
"""
if server == 'euw':
return 'https://euw.op.gg/summoner/userName='
elif server == 'na':
return 'https://na.op.gg/summoner/userName='
elif server == 'eune':
return 'https://eune.op.gg/summoner/userName='
elif server == 'kr':
return 'https://op.gg/summoner/userName='
return None |
def _decode_ctrl(key):
"""
Convert control codes ("\x01" - "\x1A") into ascii representation C-x
"""
assert len(key) == 1
if key == '\n':
return 'RET'
code = ord(key)
if not 0 < code <= 0x1A:
# Not control code
return key
letter = code + ord('a') - 1
return ("C-" + chr(letter)).replace("C-i", "TAB") |
def _parse_label(line: str) -> list:
"""Only parse the lables.
"""
s = line.strip().split()
if ':' in s[0]:
labels = []
else:
labels = s[0].split(',')
labels = [int(v) for v in labels]
labels = sorted(labels)
return labels |
def cross_idl(lon1, lon2, *lons):
"""
Return True if two longitude values define line crossing international date
line.
>>> cross_idl(-45, 45)
False
>>> cross_idl(-180, -179)
False
>>> cross_idl(180, 179)
False
>>> cross_idl(45, -45)
False
>>> cross_idl(0, 0)
False
>>> cross_idl(-170, 170)
True
>>> cross_idl(170, -170)
True
>>> cross_idl(-180, 180)
True
"""
lons = (lon1, lon2) + lons
l1, l2 = min(lons), max(lons)
# a line crosses the international date line if the end positions
# have different sign and they are more than 180 degrees longitude apart
return l1 * l2 < 0 and abs(l1 - l2) > 180 |
def f(x):
"""Assume x is an int > 0"""
ans = 0
#Loop that takes constant time
for i in range(1000):
ans += 1
print('Number of additions so far', ans)
#Loop that takes time x
for i in range(x):
ans += 1
print('Number of additions so far', ans)
#Nested loops take time x**2
for i in range(x):
for j in range(x):
ans += 1
ans += 1
print('Number of additions so far', ans)
return ans |
def askQuestion(nodes_list):
"""
Displays a question and gathers a response
:param nodes_list: a list of nodes to inquire about
:return: the value (1 for yes, 0 for no)
"""
out_str_begin = "Suppose that if you regained consciousness, you would have ALL below - "
out_str_end = " *Would you still want to receive life-sustaining care?"
# Add nodes to ask about.
for i in range(len(nodes_list)):
out_str_begin = out_str_begin + "*" + nodes_list[i][0] + nodes_list[i][1:] + "; "
out_str_begin = out_str_begin + out_str_end
return out_str_begin |
def spendscript(*data):
"""Take binary data as parameters and return a spend script containing that data"""
ret = []
for d in data:
assert type(d) is bytes, "There can only be data in spend scripts (no opcodes allowed)"
l = len(d)
if l == 0: # push empty value onto the stack
ret.append(bytes([0]))
elif l <= 0x4b:
ret.append(bytes([l])) # 1-75 bytes push # of bytes as the opcode
ret.append(d)
elif l < 256:
ret.append(bytes([76])) # PUSHDATA1
ret.append(bytes([l]))
ret.append(d)
elif l < 65536:
ret.append(bytes([77])) # PUSHDATA2
ret.append(bytes([l & 255, l >> 8])) # little endian
ret.append(d)
else: # bigger values won't fit on the stack anyway
assert 0, "cannot push %d bytes" % l
return b"".join(ret) |
def save_key(key: bytes, keyfile: str, *args):
"""Saves key to keyfile
Arguments:
key (bytes): key in bytes format
keyfile (str): name of the file to save to
Returns:
nothing
"""
with open(keyfile, "w") as kf:
kf.write(key.decode())
return "Success" |
def lexer_scan(extensions):
"""Scans extensions for ``lexer_rules`` and ``preprocessors``
attributes.
"""
lexer_rules = {}
preprocessors = []
postprocessors = []
for extension in extensions:
if hasattr(extension, "lexer_rules"):
lexer_rules.update(extension.lexer_rules)
if hasattr(extension, "preprocessors"):
preprocessors.extend(extension.preprocessors)
if hasattr(extension, "postprocessors"):
postprocessors.extend(extension.postprocessors)
return {
"lexer_rules": [lexer_rules[k] for k in sorted(lexer_rules.keys())],
"preprocessors": preprocessors,
"postprocessors": postprocessors,
} |
def _shift_header_up(
header_names, col_index, row_index=0, shift_val=0, found_first=False
):
"""Recursively shift headers up so that top level is not empty"""
rows = len(header_names)
if row_index < rows:
current_value = header_names[row_index][col_index]
if current_value == "" and not found_first:
shift_val += 1
else:
found_first = True
shift_val = _shift_header_up(
header_names, col_index, row_index + 1, shift_val, found_first
)
if shift_val <= row_index:
header_names[row_index - shift_val][col_index] = current_value
if row_index + shift_val >= rows:
header_names[row_index][col_index] = ""
return shift_val |
def filter_spouts(table, header):
""" filter to keep spouts """
spouts_info = []
for row in table:
if row[0] == 'spout':
spouts_info.append(row)
return spouts_info, header |
def fix_carets(expr):
"""Converts carets to exponent symbol in string"""
import re as _re
caret = _re.compile('[\\^]')
return caret.sub('**', expr) |
def vfs_construct_path(base_path, *path_components):
"""Mimics behavior of os.path.join on Posix machines."""
path = base_path
for component in path_components:
if component.startswith('/'):
path = component
elif path == '' or path.endswith('/'):
path += component
else:
path += '/%s' % component
return path |
def filter_key_blocks(blocks: dict) -> list:
"""Identify blocks that are keys in extracted key-value pairs."""
return [
k
for k, v in blocks.items()
if v["BlockType"] == "KEY_VALUE_SET" and "KEY" in v["EntityTypes"]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.