content
stringlengths 42
6.51k
|
---|
def get_biggest_product(adjacent_digits = 13):
"""Get the biggest product of n adjacent digits in the following number."""
number = "\
73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
number = number.replace(" ", "").replace("\n", "")
biggest_product = 0
for i in range(1, len(number) - adjacent_digits - 2):
current_product = 1
for j in range(i, i+adjacent_digits):
current_digit = number[j]
current_product *= int(current_digit)
if current_product > biggest_product:
biggest_product = current_product
return biggest_product
|
def get_mean_as_int_from_mean_plus_or_minus_stderr(input_string):
"""Convert something like '$37,343 ± $250' to 37343
This also works for medians."""
modified_string = input_string.replace("$","")
modified_string = modified_string.replace(",","")
values = modified_string.split()
return int(values[0])
|
def boolean(string):
"""
This returns True if the string is "True", False if "False",
raises an Error otherwise. This is case insensitive.
Args:
string (str): A string specifying a boolean
Returns:
bool: Whether the string is True or False.
"""
if string.lower() == 'true':
return True
elif string.lower() == 'false':
return False
else:
raise ValueError("Expected string to be True or False")
|
def parsepagerecord(record):
"""Split a division record into interesting parts.
:record: json object from the API
:returns: object containing the interestingparts
"""
parsed = {
'title': record['title'],
'date': record['date']['_value'],
'id': record['_about'].split('/')[-1],
'uin': record['uin']
}
return parsed
|
def _fmt_path(path):
"""Format the path for final display.
Parameters
----------
path : iterable of str
The path to the values that are not equal.
Returns
-------
fmtd : str
The formatted path to put into the error message.
"""
if not path:
return ''
return 'path: _' + ''.join(path)
|
def XOR(bools):
"""Logical Xor.
Result is True if there are an odd number of true items
and False if there are an even number of true items.
"""
# Return false if there are an even number of True results.
if len([x for x in bools if x is True]) % 2 == 0:
return False
return True
|
def is_property_rel(rel_type):
# type: (str) -> bool
"""Test for string indicating a property relationship
Arguments:
rel_type {str} -- relationship type
Returns:
bool -- relationship is a property
"""
return rel_type.endswith('-properties')
|
def cut_dict(d, length=100):
"""Removes dictionary entries according to the given length.
This method removes a number of entries, if needed, so that a
string representation would fit into the given length.
The intention of this method is to optimize truncation of string
representation for dictionaries where the exact precision is not
critically important. Otherwise, we'd always have to convert a dict
into a string first and then shrink it to a needed size which will
increase memory footprint and reduce performance in case of large
dictionaries (i.e. tens of thousands entries).
Note that the method, due to complexity of the algorithm, has some
non-zero precision which depends on exact keys and values placed into
the dict. So for some dicts their reduced string representations will
be only approximately equal to the given value (up to around several
chars difference).
:param d: A dictionary.
:param length: A length limiting the dictionary string representation.
:return: A dictionary which is a subset of the given dictionary.
"""
if not isinstance(d, dict):
raise ValueError("A dictionary is expected, got: %s" % type(d))
res = "{"
idx = 0
for key, value in d.items():
k = str(key)
v = str(value)
# Processing key.
new_len = len(k)
is_str = isinstance(key, str)
if is_str:
new_len += 2 # Account for the quotation marks
if 0 <= length <= new_len + len(res):
res += "'%s" % k if is_str else k
break
else:
res += "'%s'" % k if is_str else k
res += ": "
# Processing value.
new_len = len(v)
is_str = isinstance(value, str)
if is_str:
new_len += 2
if 0 <= length <= new_len + len(res):
res += "'%s" % v if is_str else v
break
else:
res += "'%s'" % v if is_str else v
res += ', ' if idx < len(d) - 1 else '}'
idx += 1
if 0 <= length <= len(res) and res[length - 1] != '}':
res = res[:length - 3] + '...'
return res
|
def get_mckey(scriptnum, fdict, fmt):
"""Figure out what our memcache key should be."""
vals = []
for key in fdict:
# Internal app controls should not be used on the memcache key
if not key.startswith("_"):
vals.append("%s:%s" % (key, fdict[key]))
return (
"/plotting/auto/plot/%s/%s.%s" % (
scriptnum, "::".join(vals), fmt)
).replace(" ", "")
|
def remove_line_comment(line: str) -> str:
"""Finds and erases Python style line comments, stripping any leading/trailing whitespace."""
split_pos = line.find("#")
if split_pos != -1:
clean_line = line[:split_pos]
else:
clean_line = line
return clean_line.strip()
|
def should_include_file_in_search(file_name, extensions, exclude_dirs):
""" Whether or not a filename matches a search criteria according to arguments.
Args:
file_name (str): A file path to check.
extensions (list): A list of file extensions file should match.
exclude_dirs (list): A list of directories to exclude from search.
Returns:
A boolean of whether or not file matches search criteria.
"""
return (exclude_dirs is None or not any(file_name.startswith(d) for d in exclude_dirs)) and \
any(file_name.endswith(e) for e in extensions)
|
def total_letters(words: list) -> int:
"""Counts the total number of letters in all words available
Args:
words (list): the words list
Returns:
int: the total number of letters in all words
"""
total = 0
# iterates through all words and counts all the letters
for word in words:
total += len(word)
return total
|
def format_date(date: str) -> str:
"""
Accepts an EBI json date string and formats it for Nextstrain
e.g. 20210100 -> 2021-01-XX
"""
if date is None: return "?"
date = str(date)
year = date[:4]
month = date[4:6].replace("00", "XX")
day = date[6:].replace("00", "XX")
return f"{year}-{month}-{day}"
|
def imageMetadata(dicomImageMetadata):
"""
Dictionary with all required metadata to construct a BIDS-Incremental, as
well as extra metadata extracted from the test DICOM image.
"""
meta = {'subject': '01', 'task': 'faces', 'suffix': 'bold', 'datatype':
'func', 'session': '01', 'run': 1}
meta.update(dicomImageMetadata) # DICOM
return meta
|
def getHash(s, length):
""" Return a hash from string s """
import hashlib
_hash = hashlib.md5()
_hash.update(s)
return _hash.hexdigest()[:length]
|
def sum_of_exponents(numbers, powers):
"""
Sums each number raised to the power in the same index powers
Ex: sum_of_exponents([2, 3, 4], [1, 2, 3]) = 2^1 + 3^2 + 4^3 = 75
"""
return sum(pow(number, power) for (number, power) in zip(numbers, powers))
|
def get_parent_map(pmx, bones):
"""
Arranges @bones into a dict of the form { @bone: [ancestors in @bones] }
"""
boneMap = { -1: [], 0: [] }
for bone in sorted(bones):
p = bone
while p not in boneMap: p = pmx.bones[p].parent_idx
if p not in [0,-1]: boneMap[bone] = boneMap[p] + [p]
else: boneMap[bone] = []
del boneMap[-1]
if 0 not in bones: del boneMap[0]
return boneMap
|
def get_factors(n: int) -> list:
"""Returns the factors of a given integer.
"""
return [i for i in range(1, n+1) if n % i == 0]
|
def compute_gain_profile(gain_zero, gain_tilting, freq):
""" compute_gain_profile evaluates the gain at the frequencies freq.
:param gain_zero: the gain at f=0 in dB. Scalar
:param gain_tilting: the gain tilt in dB/THz. Scalar
:param freq: the baseband frequencies at which the gain profile is computed in THz. Array
:return: gain: the gain profile in dB
"""
gain = gain_zero + gain_tilting * freq
return gain
|
def package_url(package):
"""Return fully-qualified URL to package on PyPI (JSON endpoint)."""
return u"http://pypi.python.org/pypi/%s/json" % package
|
def user_identity_check(user, password):
"""
Check if user is not null and have exact password as the given ones.
For now we just store the plain text password, do not need to hash it.
:param user: object that have username and password attribute.
:type user: models.UserModel
:param password: plaintext password string.
:type password: str
"""
if user is None:
return 0, {'return': {'error': 'User does not existed!'}}
if user.password != password:
return 0, {'return': {'error': 'Authentication failed!'}}
return 1,
|
def get_docker_host_mount_location(cluster_name: str) -> str:
"""Return host path that Docker mounts attach to."""
docker_mount_prefix = "/tmp/cls_tmp_mount/{cluster_name}"
return docker_mount_prefix.format(cluster_name=cluster_name)
|
def canonicalize_header(key):
"""Returns the canonicalized header name for the header name provided as an argument.
The canonicalized header name according to the HTTP RFC is Kebab-Camel-Case.
Keyword arguments:
key -- the name of the header
"""
bits = key.split('-')
for idx, b in enumerate(bits):
bits[idx] = b.capitalize()
return '-'.join(bits)
|
def echo(session, *args):
"""Prints a message"""
msg = ' '.join(args) if args else ''
print(msg)
return 0
|
def odd_or_even(number):
"""returns even if integer is even, odd if integer is odd"""
if type(number) is not int:
raise TypeError('Argument must be an integer.')
if number % 2 == 0:
return 'even'
else:
return 'odd'
|
def find_distance(x1, y1, x2, y2):
""" finds euclidean distance squared between points """
return (x1-x2)**2 + (y1-y2)**2
|
def apply_mask(mask, binary):
"""Apply a bitmask to a binary number"""
applied = []
for i, j in zip(mask, binary):
if i == 'X':
applied.append(j)
else:
applied.append(i)
return ''.join(applied)
|
def get_right_strip(chonk):
"""
Compute the right vertical strip of a 2D list.
"""
return [chonk[_i][-1] for _i in range(len(chonk))]
|
def f_beta(tp, fn, fp, beta):
"""Direct implementation of https://en.wikipedia.org/wiki/F1_score#Definition"""
return (1 + beta ** 2) * tp / ((1 + beta ** 2) * tp + beta ** 2 * fn + fp)
|
def query_prefix_transform(query_term):
"""str -> (str, bool)
return (query-term, is-prefix) tuple
"""
is_prefix = query_term.endswith('*')
query_term = query_term[:-1] if is_prefix else query_term
return (query_term, is_prefix)
|
def is_unique_n_lg(string: str) -> bool:
"""
We sort the string and take each neighbour. If they are equal, return False.
"""
start = 0
sorted_string = sorted(string)
while start + 1 < len(sorted_string):
if string[start] == string[start + 1]:
return False
start += 1
return True
|
def validate_blockchain(blockchain):
""" Validates the blockchain. """
is_valid = True
print("Validating the blockchain...")
for i in range(len(blockchain)):
if i == 0:
continue
else:
print(
f" Comparing block[{i}] ({blockchain[i]})",
f"first element ({blockchain[i][0]})",
)
print(f" and previous block[{i-1}]", f"({blockchain[i-1]})... ", end="")
if blockchain[i][0] == blockchain[i - 1]:
print("match")
is_valid = True
else:
print("mis-match")
is_valid = False
break
# # --- original attempt ---
# if len(blockchain) > 1:
# for i in range(1, len(blockchain)):
# print(
# f" Comparing block[{i - 1}] ({blockchain[i - 1]})",
# f"and block[{i}][0] ({blockchain[i]})... ",
# end="",
# )
# if blockchain[i - 1] == blockchain[i][0]:
# print("match")
# else:
# print("mis-match")
# # --- original attempt ---
# # --- second attempt ---
# i = 0
# for block in blockchain:
# if i == 0:
# i += 1
# continue
# else:
# print(f" Comparing block[{i}] ({block})", f"first element ({block[0]})")
# print(
# f" and previous block[{i-1}] ({blockchain[(i-1)]})... ", end="",
# )
# if block[0] == blockchain[(i - 1)]:
# print("match")
# is_valid = True
# else:
# print("mis-match")
# is_valid = False
# break
# i += 1
# # --- second attempt ---
return is_valid
|
def gtid_set_cardinality(gtid_set):
"""Determine the cardinality of the specified GTID set.
This function counts the number of elements in the specified GTID set.
gtid_set[in] target set of GTIDs to determine the cardinality.
Returns the number of elements of the specified GTID set.
"""
count = 0
uuid_sets = gtid_set.split(',')
for uuid_set in uuid_sets:
intervals = uuid_set.strip().split(':')[1:]
for interval in intervals:
try:
start_val, end_val = interval.split('-')
count = int(end_val) - int(start_val) + 1
except ValueError:
# Error raised for single values (not an interval).
count += 1
return count
|
def midiname2num(patch, rev_diva_midi_desc):
"""
converts param dict {param_name: value,...} to librenderman patch [(param no., value),..]
"""
return [(rev_diva_midi_desc[k], float(v)) for k,v in patch.items()]
|
def Arn(key):
"""Get the Arn attribute of the given template resource"""
return { 'Fn::GetAtt': [key, 'Arn']}
|
def simple_decorated_function(simple_arg, simple_kwargs='special string'):
"""I should see this simple docstring"""
# do stuff
return 'computed value'
|
def _mgSeqIdToTaxonId(seqId):
"""
Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId")
@param seqId: sequence id used in mg databases
@return: taxonId
@rtype: int
"""
return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[1])
|
def find_sub_list(sub_list, main_list):
"""Find starting and ending position of a sublist in a longer list.
Args:
sub_list (list): sublist
main_list (list): main longer list
Returns:
(int, int): start and end index in the list l. Returns None if sublist is not found in the main list.
"""
if len(sub_list) > len(main_list):
raise ValueError('len(sub_list) > len(main_list); should be len(sub_list) <= len(main_list)')
sll = len(sub_list)
for ind in (i for i, e in enumerate(main_list) if e == sub_list[0]):
if main_list[ind:ind+sll] == sub_list:
return ind, ind+sll-1
|
def is_valid_notification_config(config):
"""
Validate the notifications config structure
:param notifications: Dictionary with specific structure.
:return: True if input is a valid bucket notifications structure.
Raise :exc:`ValueError` otherwise.
"""
valid_events = (
"s3:ObjectAccessed:*",
"s3:ObjectAccessed:Get",
"s3:ObjectAccessed:Head",
"s3:ReducedRedundancyLostObject",
"s3:ObjectCreated:*",
"s3:ObjectCreated:Put",
"s3:ObjectCreated:Post",
"s3:ObjectCreated:Copy",
"s3:ObjectCreated:CompleteMultipartUpload",
"s3:ObjectRemoved:*",
"s3:ObjectRemoved:Delete",
"s3:ObjectRemoved:DeleteMarkerCreated",
)
def _check_filter_rules(rules):
for rule in rules:
if not (rule.get("Name") and rule.get("Value")):
msg = ("{} - a FilterRule dictionary must have 'Name' "
"and 'Value' keys")
raise ValueError(msg.format(rule))
if rule.get("Name") not in ["prefix", "suffix"]:
msg = ("{} - The 'Name' key in a filter rule must be "
"either 'prefix' or 'suffix'")
raise ValueError(msg.format(rule.get("Name")))
def _check_service_config(config):
# check keys are valid
for skey in config.keys():
if skey not in ("Id", "Arn", "Events", "Filter"):
msg = "{} is an invalid key for a service configuration item"
raise ValueError(msg.format(skey))
# check if "Id" key is present, it should be string or bytes.
if not isinstance(config.get("Id", ""), str):
raise ValueError("'Id' key must be a string")
# check for required keys
if not config.get("Arn"):
raise ValueError(
"Arn key in service config must be present and has to be "
"non-empty string",
)
events = config.get("Events", [])
if not isinstance(events, list):
raise ValueError(
"'Events' must be a list of strings in a service "
"configuration",
)
if not events:
raise ValueError(
"At least one event must be specified in a service config",
)
for event in events:
if event not in valid_events:
msg = "{} is not a valid event. Valid events are: {}"
raise ValueError(msg.format(event, valid_events))
if "Filter" not in config:
return
msg = ("{} - If a Filter key is given, it must be a "
"dictionary, the dictionary must have the key 'Key', "
"and its value must be an object, with a key named "
"'FilterRules' which must be a non-empty list.")
if (
not isinstance(config.get("Filter", {}), dict) or
not isinstance(config.get("Filter", {}).get("Key", {}), dict)
):
raise ValueError(msg.format(config["Filter"]))
rules = config.get(
"Filter", {}).get("Key", {}).get("FilterRules", [])
if not isinstance(rules, list) or not rules:
raise ValueError(msg.format(config["Filter"]))
_check_filter_rules(rules)
def _check_value(value, key):
# check if config values conform
# first check if value is a list
if not isinstance(value, list):
msg = ("The value for key '{}' in the notifications configuration "
"must be a list.")
raise ValueError(msg.format(key))
for sconfig in value:
_check_service_config(sconfig)
# check if config is a dict.
if not isinstance(config, dict):
raise TypeError("notifications configuration must be a dictionary")
if not config:
raise ValueError(
"notifications configuration may not be empty"
)
for key, value in config.items():
# check if key names are valid
if key not in (
"TopicConfigurations",
"QueueConfigurations",
"CloudFunctionConfigurations",
):
raise ValueError((
'{} is an invalid key '
'for notifications configuration').format(key))
_check_value(value, key)
return True
|
def parse_tag(tag):
"""
strips namespace declaration from xml tag string
Parameters
----------
tag : str
Returns
-------
formatted tag
"""
return tag[tag.find("}") + 1 :]
|
def to_cuda(*args):
"""
Move tensors to CUDA.
"""
return [None if x is None else x.cuda() for x in args]
|
def is_gregorian (year, month, day):
"""
"""
if year > 1582:
return True
elif year < 1582 :
return False
elif month > 10 :
return True
elif month < 10 :
return False
else :
return (day>=15)
|
def make_amrcolors(nlevels=4):
#-------------------------------
"""
Make lists of colors useful for distinguishing different patches when
plotting AMR results.
INPUT::
nlevels: maximum number of AMR levels expected.
OUTPUT::
(linecolors, bgcolors)
linecolors = list of nlevels colors for patch lines, contour lines
bgcolors = list of nlevels pale colors for patch background
"""
# For 4 or less levels:
linecolors = ['k', 'b', 'r', 'g']
# Set bgcolors to white, then light shades of blue, red, green:
bgcolors = ['#ffffff','#ddddff','#ffdddd','#ddffdd']
# Set bgcolors to light shades of yellow, blue, red, green:
#bgcolors = ['#ffffdd','#ddddff','#ffdddd','#ddffdd']
if nlevels > 4:
linecolors = 4*linecolors # now has length 16
bgcolors = 4*bgcolors
if nlevels <= 16:
linecolors = linecolors[:nlevels]
bgcolors = bgcolors[:nlevels]
else:
print("*** Warning, suggest nlevels <= 16")
return (linecolors, bgcolors)
|
def max_lookup_value(dict, key):
"""lookup in dictionary via key"""
if not dict: return None
value = max(dict.iteritems(), key=lambda d:d[1][key])[1][key]
return value
|
def determine(userChoice, computerChoice):
"""
This function takes in two arguments userChoice and computerChoice,
then determines and returns that who wins.
"""
if(userChoice == "Rock" and computerChoice == "Paper"):
return "computer"
elif(userChoice == "Rock" and computerChoice == "Scissors"):
return "user"
elif(userChoice == "Paper" and computerChoice == "Rock"):
return "user"
elif(userChoice == "Paper" and computerChoice == "Scissors"):
return "computer"
elif(userChoice == "Scissors" and computerChoice == "Paper"):
return "user"
elif(userChoice == "Scissors" and computerChoice == "Rock"):
return "computer"
else:
return "tie"
|
def flatTreeDictToList(root):
"""flatTreeDictToList(root)
This function is used to screen motif informations from old MDseqpos html results.
Input is a dict of mtree in MDseqpos.html, output is a flat list.
"""
result = []
if 'node' not in root.keys():
return []
if not root['node']:
return result
else:
result.append(root['node'])
for each in root['children']:
result.extend(flatTreeDictToList(each))
return result
|
def get_fib(position):
"""input: nonnegative int representing a position on the fibonacci sequence
output: fibonacci number corresponding to given position of the sequence
returns -1 for negative inputs
recursive function
"""
if position < 0:
return -1
if position == 0 or position == 1:
return position
else:
return get_fib(position - 1) + get_fib(position - 2)
|
def flatten_dict(nested_dict, sep='/'):
"""Flattens the nested dictionary.
For example, if the dictionary is {'outer1': {'inner1': 1, 'inner2': 2}}.
This will return {'/outer1/inner1': 1, '/outer1/inner2': 2}. With sep='/' this
will match how flax optim.ParamTreeTraversal flattens the keys, to allow for
easy filtering when using traversals. Requires the nested dictionaries
contain no cycles.
Args:
nested_dict: A nested dictionary.
sep: The separator to use when concatenating the dictionary strings.
Returns:
The flattened dictionary.
"""
# Base case at a leaf, in which case nested_dict is not a dict.
if not isinstance(nested_dict, dict):
return {}
return_dict = {}
for key in nested_dict:
flat_dict = flatten_dict(nested_dict[key], sep=sep)
if flat_dict:
for flat_key in flat_dict:
return_dict[sep + key + flat_key] = flat_dict[flat_key]
else: # nested_dict[key] is a leaf.
return_dict[sep + key] = nested_dict[key]
return return_dict
|
def getBounds(lvls_arr: list, n_lvl: float):
"""
A helper function to calculate the BN interpolation
@param lvls_arr: The corruption levels list
@param n_lvl: The current level to interpolate
@return: Returns the post and previous corruption levels
"""
lower = lvls_arr[0]
upper = lvls_arr[1]
for i, v in enumerate(lvls_arr[:-1]):
if n_lvl <= v:
break
lower = v
upper = lvls_arr[i + 1]
return lower, upper
|
def is_empty(value):
"""
Checks if a value is an empty string or None.
"""
if value is None or value == '':
return True
return False
|
def register_class(cls, register):
"""Add a class to register."""
register[cls.__name__] = cls
return register
|
def verbatim(s, delimiter='|'):
"""Return the string verbatim.
:param s:
:param delimiter:
:type s: str
:type delimiter: str
:return:
:rtype: str
"""
return r'\verb' + delimiter + s + delimiter
|
def set_cutoffs_permissiveEnds(edge_index, n_edges, strand):
""" Selects 3' and 5' difference cutoffs depending on the edge index and
strand. For internal edges, both cutoffs should be set to zero, but
more flexibility is allowed on the 3' and 5' ends.
Args:
edge_index: index we are at in the edge vector
tot_edges: total number of edges in the transcript
strand: strand that the edge is on.
"""
cutoff_5 = 0
cutoff_3 = 0
if edge_index == 0:
if strand == "+":
cutoff_5 = 100000
else:
cutoff_3 = 100000
if edge_index == n_edges-1:
if strand == "+":
cutoff_3 = 100000
else:
cutoff_5 = 100000
return cutoff_5, cutoff_3
|
def extraction(fullDic, subkeys):
"""Extracts a new dictionary that only contains the provided keys"""
subDic = {}
for subkey in subkeys:
subDic[subkey] = fullDic[subkey]
return subDic
|
def get_experiment_prefix(project_key, test_size, priority_queue=False):
"""
A convenient prefix to identify an experiment instance.
:param project_key: Projects under analysis.
:param test_size: Size of the test dataset.
:return: The prefix.
"""
return "_".join(project_key) + "_Test_" + str(test_size) + "_PRIQUEUE_" + str(priority_queue)
|
def get_sa_terminal_menu(burl, terminal):
""" xxx """
ret = ''
if terminal is None:
l_sa_terminal_tooltip = 'Launch Terminal'
l_sa_terminal = '<i class="fas fa-desktop" style="font-size: x-large;"></i>'
l_sa_terminal_menu = '<li class="nav-item d-none d-sm-block">'+\
'<a class="nav-link sa-navbar-text" href="'+\
burl +'terminal/" data-toggle="tooltip" data-placement="bottom" data-original-title="'+\
l_sa_terminal_tooltip +'">'+ l_sa_terminal +'</a></li>'
ret = l_sa_terminal_menu
return ret
|
def convert_path(path):
"""Convert to the path the server will accept.
Args:
path (str): Local file path.
e.g.:
"D:/work/render/19183793/max/d/Work/c05/112132P-embery.jpg"
Returns:
str: Path to the server.
e.g.:
"/D/work/render/19183793/max/d/Work/c05/112132P-embery.jpg"
"""
lower_path = path.replace('\\', '/')
if lower_path[1] == ":":
path_lower = lower_path.replace(":", "")
path_server = "/" + path_lower
else:
path_server = lower_path[1:]
return path_server
|
def coprime(a, b):
"""
coprime
:param a:
:param b:
:return:
"""
for i in range(2, min(a, b) + 1):
if a % i == 0 and b % i == 0:
return False
return True
|
def iterative_lcs(var1, var2):
"""
:param var1: variable
:param var2: 2nd variable to compare and finding common sequence
:return: return length of longest common subsequence
examples:
>>> iterative_lcs("abcd", "abxbxbc")
3
>>> iterative_lcs([1, 2, 4, 3], [1, 2, 3, 4])
3
"""
length1 = len(var1)
length2 = len(var2)
dp = [[0] * (length2 + 1) for _ in range(length1 + 1)]
for i in range(length1 + 1):
for j in range(length2 + 1):
if i == 0 or j == 0:
dp[i][j] = 0
elif var1[i - 1] == var2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])
return dp[length1][length2]
|
def boolean(value):
"""Parse the string "true" or "false" as a boolean (case insensitive).
Also accepts "1" and "0" as True/False (respectively). If
the input is from the request JSON body, the type is already a native
python boolean, and will be passed through without further parsing."""
if type(value) == bool:
return value
if not value:
raise ValueError("boolean type must be non-null")
value = value.lower()
if value in ('true', '1',):
return True
if value in ('false', '0',):
return False
raise ValueError("Invalid literal for boolean(): {}".format(value))
|
def _get_vals_wo_None(iter_of_vals):
""" Returns a list of values without Nones. """
return [x for x in iter_of_vals if x is not None]
|
def str2bool(val):
"""
Return True for 'True', False otherwise
:type val: str
:rtype: bool
"""
return val.lower() == 'true'
|
def quantile(x, p=0.50):
"""Returns the pth percentile value in x. Defaults to 50th percentile."""
# Eg x, 0.10 returns 10th percentile value.
pindex = int(p * len(x))
return sorted(x)[pindex]
|
def calculate_precision_recall_f1score(y_pred, y_true, entity_label=None):
""" Calculates precision recall and F1-score metrics.
Args:
y_pred (list(AnnotatedDocument)): The predictions of an NER
model in the form of a list of annotated documents.
y_true (list(AnnotatedDocument)): The ground truth set of
annotated documents.
entity_label (str, optional): The label of the entity for which
the scores are calculated. It defaults to None, which means
all annotated entities.
Returns:
(3-tuple(float)): (Precision, Recall, F1-score)
"""
# Flatten all annotations
all_y_pred_ann = []
all_y_true_ann = []
if entity_label is None:
for annotated_document in y_pred:
all_y_pred_ann.extend(annotated_document.annotations)
for annotated_document in y_true:
all_y_true_ann.extend(annotated_document.annotations)
else:
for annotated_document in y_pred:
all_y_pred_ann.extend([
annotation for annotation in annotated_document.annotations
if annotation.label == entity_label
])
for annotated_document in y_true:
all_y_true_ann.extend([
annotation for annotation in annotated_document.annotations
if annotation.label == entity_label
])
tp = 0.0
fp = 0.0
fn = 0.0
# Convert true annotations to a set in O(n) for quick lookup
all_y_true_ann_lookup = set(all_y_true_ann)
# True positives are predicted annotations that are confirmed by
# their existence in the ground truth dataset. False positives are
# predicted annotations that are not in the ground truth dataset.
for annotation in all_y_pred_ann:
if annotation in all_y_true_ann_lookup:
tp += 1.0
else:
fp += 1.0
# Convert predictions to a set in O(n) for quick lookup
all_y_pred_ann_lookup = set(all_y_pred_ann)
# False negatives are annotations in the ground truth dataset that
# were never predicted by the system.
for annotation in all_y_true_ann:
if annotation not in all_y_pred_ann_lookup:
fn += 1.0
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.
recall = tp / (tp + fn) if (tp + fn) > 0 else 0.
f1_score = (2 * precision * recall) / (precision + recall) if\
(precision + recall) > 0 else 0.
return (precision, recall, f1_score)
|
def S_Generation(PIN, lenMask) -> str:
"""
"""
S = bin(PIN)[2:]
n = len(S)
k = lenMask//n
return S*k + S[:lenMask - n*k]
|
def build_index(l, key):
"""Build an O(1) index of a list using key, only works if key is unique
"""
return dict((d[key], dict(d, index=index)) for index, d in enumerate(l))
|
def cmp_dicts(dict1, dict2):
"""
Returns True if dict2 has all the keys and matching values as dict1.
List values are converted to tuples before comparing.
"""
result = True
for key, v1 in dict1.items():
result, v2 = key in dict2, dict2.get(key)
if result:
v1, v2 = (tuple(x) if isinstance(x, list) else x for x in [v1, v2])
result = (v1 == v2)
if not result:
break # break for key, v1
return result
|
def quantity_column_split(string):
""" Quantity[100.4, "' Centimeters"^3/"Moles'"] to [100.4, " Centimeters"^3/"Moles"]
"""
values = string.split("[", 1)[1][:-1].split(",")
return(values)
|
def toBin3(v):
"""Return a string (little-endian) from a numeric value."""
return '%s%s%s' % (chr(v & 255), chr((v >> 8) & 255), chr((v >> 16) & 255))
|
def q_mult(a, b):
"""Multiply two quaternion."""
w = a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3]
i = a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2]
j = a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1]
k = a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0]
return [w, i, j, k]
|
def or_(*xs):
"""Returns the first truthy value among the arguments, or the final
argument if all values are falsy. If no arguments are provided,
False is returned.
"""
final = False
for x in xs:
if x:
return x
final = x
return final
|
def to_valid_key(name):
"""
convert name into a valid key name which contain only alphanumeric and underscores
"""
import re
valid_name = re.sub(r'[^\w\s]', '_', name)
return valid_name
|
def get_stream_digest_data(digest):
""" Process deployment digest for stream.
"""
try:
# Process deployment information for stream.
latitude = None
longitude = None
depth = None
water_depth = None
if digest and digest is not None:
latitude = digest['latitude']
longitude = digest['longitude']
depth = digest['depth']
water_depth = digest['waterDepth']
if latitude is not None:
latitude = round(latitude, 5)
if longitude is not None:
longitude = round(longitude, 5)
if depth is not None:
depth = round(depth, 5)
if water_depth is not None:
water_depth = round(water_depth, 5)
return depth, latitude, longitude, water_depth
except Exception as err:
message = str(err)
raise Exception(message)
|
def capValue(value, max=float('inf'), min=float('-inf')):
"""Clamp a value to a minimun and/or maximun value."""
if value > max:
return max
elif value < min:
return min
else:
return value
|
def _set_quality_risk_icon(risk):
"""
Function to find the index risk level icon for software quality risk.
:param float risk: the Software quality risk factor.
:return: _index
:rtype: int
"""
_index = 0
if risk == 1.0:
_index = 1
elif risk == 1.1:
_index = 2
return _index
|
def get_least_sig_bit(band):
"""Return the least significant bit in color value"""
mask = 0x1
last_bit = band & mask
return str(last_bit)
|
def code_point_of_unicode(unicode_entity, sep="-"):
"""Converts a given unicode entity to code point.
:param unicode_entity: The unicode entity to convert.
:type unicode_entity: str
:param sep: The separator. The result will be the list of all the converted characters joined with this separator.
:type sep: str
:returns: The converted string.
:rtype: str
"""
# Source: https://github.com/twitter/twemoji/blob/master/scripts/build.js#L571
result, current, p = [], 0, 0
for i in range(len(unicode_entity)):
current = ord(unicode_entity[i])
if p:
result.append("{a:02x}".format(a=0x10000 + ((p - 0xD800) << 10) + (current - 0xDC00)))
elif 0xD800 <= current <= 0xDBFF:
p = current
else:
result.append("{a:02x}".format(a=current))
return sep.join(result)
|
def _check_prop_requirements(sort_prop_dct, geo, freqs, sp_ene, locs):
""" Check that there is the correct data available for the desired
conformer sorting method.
"""
sort_prop = 'electronic'
if 'enthalpy' in sort_prop_dct:
if sort_prop_dct['enthalpy'] == 0:
sort_prop = 'ground'
elif 'entropy' in sort_prop_dct:
sort_prop = 'entropy'
elif 'gibbs' in sort_prop_dct:
sort_prop = 'gibbs'
if sort_prop in ['enthalpy', 'entropy', 'gibbs']:
if geo is None:
# ioprinter.warning_message('No geo found for ', locs)
sort_prop = None
if freqs is None:
# ioprinter.warning_message('No freqs found for ', locs)
sort_prop = None
if sp_ene is None:
# ioprinter.warning_message('No energy found for ', locs)
sort_prop = None
return sort_prop
|
def score_of(grade):
"""Computes numeric score given either a percentage of hybric score object
WARNING: currently ignore multipliers and lateness"""
if grade['kind'] == 'percentage':
return grade['ratio']
elif grade['kind'] == 'hybrid':
h = sum(_['ratio'] * _.get('weight',1) for _ in grade['human'])
t = sum(_.get('weight',1) for _ in grade['human'])
r = h/t
if grade.get('auto-weight', 0) > 0:
r *= 1-grade['auto-weight']
r += grade['auto-weight'] * grade['auto']
return r
|
def rgb_to_hex(r: int, g: int, b: int) -> str:
"""
Fungsi untuk mengubah tipe value warna RGB ke Hex.
Alur proses:
* Inisialisasi variabel `result` dengan string kosong
* Looping `x` untuk ketiga value dari input
* Cek apakah nilai x < 0
* Jika benar, maka nilai x = 0
* Jika salah, maka lanjutkan
* Cek apakah nilai x > 255
* Jika benar, maka nilai x = 255
* Jika salah, maka lanjutkan
* x > 0 dan x < 255
* maka x diformat menjadi 2 digit hex
* Tambahkan semua nilai x ke variabel `result`
* Kembalikan nilai `result`
Referensi format string:
* [f-strings](\
https://docs.python.org/3/reference/lexical_analysis.html#f-strings)
* [format string syntax](\
https://docs.python.org/3/library/string.html#format-string-syntax)
* [format specifier](\
https://docs.python.org/3/library/string.html#format-specification-mini-language)
>>> rgb_to_hex(0, 0, 0)
'000000'
>>> rgb_to_hex(1, 2, 3)
'010203'
>>> rgb_to_hex(255, 255, 255)
'FFFFFF'
>>> rgb_to_hex(-10, 255, 300)
'00FFFF'
>>> rgb_to_hex(150, 0, 180)
'9600B4'
"""
result = ""
for x in (r, g, b):
if x < 0:
x = 0
elif x > 255:
x = 255
# f-string specifier yang digunakan:
# '0' : padding '0' di depan string yang dihasilkan sesuai dengan width
# '2' : width atau panjang string yang dihasilkan
# 'X' : format int x menjadi hex yang telah di upper case
result += f"{x:02X}"
return result
|
def find_start_time(disc, positions, time, pos):
"""What button press time step would match this disc in
the open position?
"""
# Assume time is zero for now
return positions - ((disc + pos) % positions)
|
def harvest_oai_datacite3(xml_content):
"""Factory for Zenodo Record objects from ``oai_datacite3`` XML
Parameters
----------
xml_content : str
Content from the Zenodo harvesting URL endpoint for ``oai_datacite3``.
Returns
-------
records : list
Zenodo record objects derived from the `xml_content`.
"""
records = []
return records
|
def f_to_c(f):
"""
Convert fahrenheit to celcius
"""
return (f - 32.0) / 1.8
|
def bookmark_state(keyword):
"""Validation for ``bookmark-state``."""
return keyword in ('open', 'closed')
|
def genUsernamePassword(firstname: str, num: int):
"""
This function will return a username and password for a given user (username and password are considered as the same)
:param firstname: User's first name
:param num: User number
:return: User name for the user
"""
username = firstname.lower() + str(num)
if len(username) < 5:
username += '123'
return username
|
def _fileobj_to_fd(fileobj):
"""Return a file descriptor from a file object.
Parameters:
fileobj -- file object or file descriptor
Returns:
corresponding file descriptor
Raises:
ValueError if the object is invalid
"""
if isinstance(fileobj, int):
fd = fileobj
else:
try:
fd = int(fileobj.fileno())
except (AttributeError, TypeError, ValueError):
raise ValueError("Invalid file object: "
"{!r}".format(fileobj)) from None
if fd < 0:
raise ValueError("Invalid file descriptor: {}".format(fd))
return fd
|
def _allocate_expr_id_instance(name, exprmap):
""" Allocate a new free instance of a name
Args:
name: Existing name
exprmap: Map of existing expression names
Returns:
New id not in exprmap
"""
ndx = 1
name += "@"
nname = name + "1"
while nname in exprmap:
ndx += 1
nname = name + str(ndx)
return nname
|
def find_usable_exits(room, stuff):
"""
Given a room, and the player's stuff, find a list of exits that they can use right now.
That means the exits must not be hidden, and if they require a key, the player has it.
RETURNS
- a list of exits that are visible (not hidden) and don't require a key!
"""
usable = []
missing_key = []
for exit in room['exits']:
if exit.get("hidden", False):
continue
if "required_key" in exit:
if exit["required_key"] in stuff:
usable.append(exit)
continue
else:
missing_key.append(exit)
usable.append(exit)
continue
continue
usable.append(exit)
return usable, missing_key
|
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if val < 0 else 'green'
return 'color: %s' % color
|
def filter_DBsplit_option(opt):
"""We want -a by default, but if we see --no-a[ll], we will not add -a.
"""
flags = opt.split()
if '-x' not in opt:
flags.append('-x70') # daligner belches on any read < kmer length
return ' '.join(flags)
|
def gini(labels):
"""
Calculate the Gini value of the data set
:param labels: Category label for the dataset
:return gini_value: The Gini value of the data set
"""
data_count = {}
for label in labels:
if data_count.__contains__(label):
data_count[label] += 1
else:
data_count[label] = 1
n = len(labels)
if n == 0:
return 0
gini_value = 1
for key, value in data_count.items():
gini_value -= (value / n) ** 2
return gini_value
|
def _get_comm_key_send_recv(my_rank, my_gpu_idx, peer_rank, peer_gpu_idx):
"""Return a key given source and destination ranks for p2p tasks.
The p2p key is in the following form:
[min_rank]_[gpu_index]:[max_rank]_[gpu_index].
Args:
my_rank (int): the rank of the source process.
my_gpu_idx (int): the source gpu index on the process.
peer_rank (int): the rank of the destination process.
peer_gpu_idx (int): the destination gpu index on the process.
Returns:
comm_key (str): a string key to query the communication cache.
"""
if my_rank < peer_rank:
lower_key = str(my_rank) + "_" + str(my_gpu_idx)
higher_key = str(peer_rank) + "_" + str(peer_gpu_idx)
elif my_rank > peer_rank:
lower_key = str(peer_rank) + "_" + str(peer_gpu_idx)
higher_key = str(my_rank) + "_" + str(my_gpu_idx)
else:
raise RuntimeError(
"Send and recv happens on the same process. alpa.collective "
"does not support this case as of now. Alternatively, consider "
"doing GPU to GPU memcpy?")
comm_key = lower_key + ":" + higher_key
return comm_key
|
def getElectronState(radicalElectrons, spinMultiplicity):
"""
Return the electron state corresponding to the given number of radical
electrons `radicalElectrons` and spin multiplicity `spinMultiplicity`.
Raise a :class:`ValueError` if the electron state cannot be determined.
"""
electronState = ''
if radicalElectrons == 0:
electronState = '0'
elif radicalElectrons == 1:
electronState = '1'
elif radicalElectrons == 2 and spinMultiplicity == 1:
electronState = '2S'
elif radicalElectrons == 2 and spinMultiplicity == 3:
electronState = '2T'
elif radicalElectrons == 3:
electronState = '3'
elif radicalElectrons == 4:
electronState = '4'
else:
raise ValueError('Unable to determine electron state for {0:d} radical electrons with spin multiplicity of {1:d}.'.format(radicalElectrons, spinMultiplicity))
return electronState
|
def form_presentation(elastic_apartment):
"""
Fetch link to apartment presentation and add it to the end of project description
"""
main_text = getattr(elastic_apartment, "project_description", None)
link = getattr(elastic_apartment, "url", None)
if main_text or link:
return "\n".join(filter(None, [main_text, link]))
return None
|
def unicode_to_str(data):
""" Unicode to string conversion. """
if not isinstance(data, str):
return data.encode('utf-8')
return data
|
def invalid_fg_vsby(s, v):
"""Checks if visibility is inconsistent with FG"""
# NWSI 10-813, 1.2.6
if len(s) == 2 or s.startswith('FZ'):
if v > 0.6:
return True
elif s.startswith('MI'):
if v < 0.6:
return True
return False
|
def valid_csv(filename):
"""Validates that a file is actually a CSV"""
if filename.rsplit('.', 1)[1] == 'csv':
return True
else:
return False
|
def find_response_end_token(data):
"""Find token that indicates the response is over."""
for line in data.splitlines(True):
if line.startswith(('OK', 'ACK')) and line.endswith('\n'):
return True
return False
|
def process_elem_string(string):
"""Strips ion denotions from names e.g. "O2+" becomes "O"."""
elem = ""
for i, c in enumerate(string):
try:
int(c)
break
except:
elem += c
return elem
|
def _ImageFileForChroot(chroot):
"""Find the image file that should be associated with |chroot|.
This function does not check if the image exists; it simply returns the
filename that would be used.
Args:
chroot: Path to the chroot.
Returns:
Path to an image file that would be associated with chroot.
"""
return chroot.rstrip('/') + '.img'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.