content
stringlengths 42
6.51k
|
---|
def combinations(n: int, r : int):
"""Gives the number of possibilities of n objects chosen r times, order matters"""
product = 1
for i in range(n - r + 1, n + 1):
product *= i
for x in range(2, r+1):
product /= x
return product
|
def detect_encrypted_resource(resource):
"""Detect if resource is encrypted with GnuPG
Determining factors:
a) The resource is ascii-armored text
b) The resource is binary data starting with 0x8502"""
try:
# Read file like
line = resource.read(50)
resource.seek(0)
except AttributeError:
# Read str like
line = resource[:50]
if line.startswith(b"-----BEGIN PGP"):
return True
elif line.startswith(b'\x85\x02'):
return True
else:
return False
|
def _no_pending_stacks(stacks):
"""If there are any stacks not in a steady state, don't cache"""
for stack in stacks:
status = stack['stack_status']
if '_COMPLETE' not in status and '_FAILED' not in status:
return False
return True
|
def interval_idx(x, xi):
"""
Given a grid of points xi (sorted smallest to largest) find in
which interval the point x sits. Returns i, where x \in [ xi[i],xi[i+1] ].
Raise ValueError if x is not inside the grid.
"""
assert x >= xi[0] and x <= xi[-1], ValueError(
'x=%g not in [%g,%g]' % (x, xi[0], xi[-1])
)
for i in range(len(xi) - 1):
if xi[i] <= x and x <= xi[i + 1]:
return i
|
def _get_bucket_and_file_names(event: dict):
"""
Get bucket and file name from s3 trigger event to download transaction source data file.
"""
bucket_name = event['Records'][0]['s3']['bucket']['name']
file_key = event['Records'][0]['s3']['object']['key']
return bucket_name, file_key
|
def dump_section(bank_number, separator="\n\n"):
"""
Returns a str of a section header for the asm file.
"""
output = "SECTION \""
if bank_number in [0, "0"]:
output += "bank0\",HOME"
else:
output += "bank"
output += bank_number
output += "\",DATA,BANK[$"
output += bank_number
output += "]"
output += separator
return output
|
def is_cross_host(mpi_nodes, edge):
"""
Return true if the supplied edge is a cross-host edge according to the
mpi nodes supplied.
"""
out_node_key = edge[0][0]
in_node_key = edge[0][1]
return mpi_nodes[out_node_key]["host"] != mpi_nodes[in_node_key]["host"]
|
def upper_bound(l, k):
"""
>>> upper_bound([1, 2, 2, 3, 4], 2)
3
>>> upper_bound([1, 2, 2, 3, 4], 5)
-1
:param l:
:param k:
:return:
"""
if l[-1] <= k:
return -1
i = len(l) // 2
start, end = 0, len(l) - 1
while start < end:
if l[i] > k:
end = i
else:
start = i + 1
i = start + (end - start) // 2
return i
|
def convert_environment_id_string_to_int(
environment_id: str
) -> int:
"""
Converting the string that describes the environment id into an int which needed for the http request
:param environment_id: one of the environment_id options
:return: environment_id represented by an int
"""
try:
environment_id_options = {
"300: Linux Ubuntu 16.04": 300,
"200: Android (static analysis)": 200,
"160: Windows 10": 160,
"110: Windows 7": 110,
"100: Windows 7": 100,
"64-bit": 64,
"32-bit": 32,
}
return environment_id_options[environment_id]
except Exception:
raise Exception('Invalid environment id option')
|
def get_usergraph_feature_names(osn_name):
"""
Returns a set of the names of the user graph engineered features.
:param osn_name: The name of the dataset (i.e. reddit, slashdot, barrapunto)
:return: names: The set of feature names.
"""
names = set()
####################################################################################################################
# Add user graph features.
####################################################################################################################
names.update(["user_graph_user_count",
"user_graph_hirsch_index",
"user_graph_randic_index",
"user_graph_outdegree_entropy",
"user_graph_outdegree_normalized_entropy",
"user_graph_indegree_entropy",
"user_graph_indegree_normalized_entropy"])
return names
|
def subsets(n):
"""
Returns all possible subsets of the set (0, 1, ..., n-1) except the
empty set, listed in reversed lexicographical order according to binary
representation, so that the case of the fourth root is treated last.
Examples
========
>>> from sympy.simplify.sqrtdenest import subsets
>>> subsets(2)
[[1, 0], [0, 1], [1, 1]]
"""
if n == 1:
a = [[1]]
elif n == 2:
a = [[1, 0], [0, 1], [1, 1]]
elif n == 3:
a = [[1, 0, 0], [0, 1, 0], [1, 1, 0],
[0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]
else:
b = subsets(n-1)
a0 = [x+[0] for x in b]
a1 = [x+[1] for x in b]
a = a0 + [[0]*(n-1) + [1]] + a1
return a
|
def parse_file_to_bucket_and_filename(file_path):
"""Divides file path to bucket name and file name"""
path_parts = file_path.split("//")
if len(path_parts) >= 2:
main_part = path_parts[1]
if "/" in main_part:
divide_index = main_part.index("/")
bucket_name = main_part[:divide_index]
file_name = main_part[divide_index + 1 - len(main_part):]
return bucket_name, file_name
return "", ""
|
def down(state):
"""move blank space down on the board and return new state."""
new_state = state[:]
index = new_state.index(0)
if index not in [6, 7, 8]:
temp = new_state[index + 3]
new_state[index + 3] = new_state[index]
new_state[index] = temp
return new_state
else:
return None
|
def _check(rule1, rule2):
"""
introduction: Verify the correctness of the YYC rules.
:param rule1: Correspondence between base and binary data (RULE 1).
:param rule2: Conversion rule between base and binary data based on support base and current base (RULE 2).
:return: Check result.
"""
for index in range(len(rule1)):
if rule1[index] != 0 and rule1[index] != 1:
return False
if sum(rule1) != 2:
return False
if rule1[0] == rule1[1]:
same = [0, 1, 2, 3]
elif rule1[0] == rule1[2]:
same = [0, 2, 1, 3]
else:
same = [0, 3, 1, 2]
for row in range(len(rule2)):
if rule2[row][same[0]] + rule2[row][same[1]] != 1 or rule2[row][same[0]] * rule2[row][same[1]] != 0:
return False
if rule2[row][same[2]] + rule2[row][same[3]] != 1 or rule2[row][same[2]] * rule2[row][same[3]] != 0:
return False
return True
|
def decode_dict(d):
"""Decode dict."""
result = {}
for key, value in d.items():
if isinstance(key, bytes):
key = key.decode()
if isinstance(value, bytes):
value = value.decode()
elif isinstance(value, dict):
value = decode_dict(value)
result.update({key: value})
return result
|
def get_office_result(office):
"""SQL query to read office results from database
Args:
office (integer): office id to get results of
candidate (integer): candidate id to get results of
"""
sql = """
SELECT office_id, candidate_id, COUNT(candidate_id) AS result
FROM votes
WHERE office_id=%s
GROUP BY office_id, candidate_id
ORDER BY result DESC;
"""
query = sql, (office,)
return query
|
def is_list(value):
"""Check if a value is a list"""
return isinstance(value, list)
|
def gf_mult(a, b, m):
"""Galois Field multiplication of a by b, modulo m.
Just like arithmetic multiplication, except that additions and
subtractions are replaced by XOR.
"""
res = 0
while b != 0:
if b & 1:
res ^= a
a <<= 1
b >>= 1
if a >= 256:
a ^= m
return res
|
def deg_plato_to_gravity(deg_plato):
"""Convert degrees Plato to specific gravity.
Parameters
----------
deg_plato : float
Degrees Plato, like 13.5
Returns
-------
sg : float
Specific gravity, like 1.053
"""
return 1. + (deg_plato / 250.)
|
def unescape(s):
"""
Revert escaped characters back to their special version.
For example, \\n => newline and \\t => tab
"""
return s.replace('\\n', '\n').replace('\\t', '\t').replace('\\r', '\r')
|
def form_line(ltokens=[], rtokens=[]):
"""Form line."""
if not isinstance(ltokens, (list, tuple)):
return str(ltokens) + ';'
ltext = ' '.join(map(str, ltokens))
rtext = ' '.join(map(str, rtokens))
if len(rtokens) > 0:
return '{ltext} = {rtext};'.format(ltext=ltext, rtext=rtext)
else:
return '{ltext};'.format(ltext=ltext)
|
def get_days_in_month(year, month):
"""
Returns the number of days in the month of a specific year
:param int year: the year of the month
:param int month: the number of the month
:return:
:rtype: int
"""
from calendar import monthrange
return monthrange(year, month)[1]
|
def health():
"""Our instance health. If queue is too long or we use too much mem,
return 500. Monitor might reboot us for this."""
is_bad_state = False
msg = "Ok"
import resource
stats = resource.getrusage(resource.RUSAGE_SELF)
mem = stats.ru_maxrss
if mem > 1024**3:
is_bad_state = True
msg = "Over memory " + str(mem) + ">" + str(1024**3)
if is_bad_state:
return msg, 500
return msg, 200
|
def read_sealevel_pressure(pressure, altitude_m=0.0):
"""Calculates the pressure at sealevel when given a
known altitude in meters. Returns a value in Pascals."""
p0 = pressure / pow(1.0 - altitude_m/44330.0, 5.255)
return p0
|
def get_provenance_record(ancestor_files, caption, statistics,
domains, plot_type='geo'):
"""Get Provenance record."""
record = {
'caption': caption,
'statistics': statistics,
'domains': domains,
'plot_type': plot_type,
'themes': ['atmDyn', 'monsoon', 'EC'],
'authors': [
'weigel_katja',
],
'references': [
'li17natcc',
],
'ancestors': ancestor_files,
}
return record
|
def black_invariant(text, chars=None):
"""Remove characters that may be changed when reformatting the text with black"""
if chars is None:
chars = [' ', '\t', '\n', ',', "'", '"', '(', ')', '\\']
for char in chars:
text = text.replace(char, '')
return text
|
def camelcase(string):
"""Convert snake casing where present to camel casing"""
return ''.join(word.capitalize() for word in string.split('_'))
|
def fib_list(n):
"""[summary]
This algorithm computes the n-th fibbonacci number
very quick. approximate O(n)
The algorithm use dynamic programming.
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a positive integer'
list_results = [0, 1]
for i in range(2, n+1):
list_results.append(list_results[i-1] + list_results[i-2])
return list_results[n]
|
def isAbundant(x):
"""Returns whether or not the given number x is abundant.
A number is considered to be abundant if the sum of its factors
(aside from the number) is greater than the number itself.
Example: 12 is abundant since 1+2+3+4+6 = 16 > 12.
However, a number like 15, where the sum of the factors.
is 1 + 3 + 5 = 9 is not abundant.
"""
# your code here
Abundant = False
sum = 0
for i in range(1, x):
if(x % i == 0):
sum += i
if (sum > x):
Abundant = True
else:
Abundant = False
return Abundant
|
def tupletupleint(items):
"""A tuple containing x- and y- slice tuples from a string or tuple"""
if isinstance(items, str):
for s in " ()[]":
items = items.replace(s, "")
# we have a string representation of the slices
x1, x2, y1, y2 = items.split(",")
out = ((int(float(x1)), int(float(x2))),
(int(float(y1)), int(float(y2))))
else:
(x1, x2), (y1, y2) = items
out = ((int(float(x1)), int(float(x2))),
(int(float(y1)), int(float(y2))))
return out
|
def Elastic(m1, m2, v1, v2):
"""Returns a tuple of the velocities resulting from a perfectly
elastic collision between masses m1 traveling at v1 and m2
traveling at v2. This simultaneously conserves momentum and energy."""
vp2 = ((m2 * v2) + (m1 * ((2.0 * v1) - v2))) / (m1 + m2)
vp1 = vp2 + v2 - v1
return vp1, vp2
|
def function_path(func):
"""
This will return the path to the calling function
:param func:
:return:
"""
if getattr(func, 'func_code', None):
return func.func_code.co_filename.replace('\\', '/')
else:
return func.__code__.co_filename.replace('\\', '/')
|
def _guess_header(info):
"""Add the first group to get report with some factor"""
value = "group"
if "metadata" in info:
if info["metadata"]:
return ",".join(map(str, info["metadata"].keys()))
return value
|
def dehexify(data):
"""
A URL and Hexadecimal Decoding Library.
Credit: Larry Dewey
"""
hexen = {
'\x1c': ',', # Replacing Device Control 1 with a comma.
'\x11': ',', # Replacing Device Control 2 with a new line.
'\x12': '\n', # Space
'\x22': '"', # Double Quotes
'\x23': '#', # Number Symbol
'\x27': '\'', # Single Quote
'\x28': '(', # Open Parenthesis
'\x29': ')', # Close Parenthesis
'\x2b': '+', # Plus Symbol
'\x2d': '-', # Hyphen Symbol
'\x2e': '.', # Period, dot, or full stop.
'\x2f': '/', # Forward Slash or divide symbol.
'\x7c': '|', # Vertical bar or pipe.
}
uri = {
'%11': ',', # Replacing Device Control 1 with a comma.
'%12': '\n', # Replacing Device Control 2 with a new line.
'%20': ' ', # Space
'%22': '"', # Double Quotes
'%23': '#', # Number Symbol
'%27': '\'', # Single Quote
'%28': '(', # Open Parenthesis
'%29': ')', # Close Parenthesis
'%2B': '+', # Plus Symbol
'%2D': '-', # Hyphen Symbol
'%2E': '.', # Period, dot, or full stop.
'%2F': '/', # Forward Slash or divide symbol.
'%3A': ':', # Colon
'%7C': '|', # Vertical bar or pipe.
}
for (enc, dec) in hexen.items():
data = data.replace(enc, dec)
for (enc, dec) in uri.items():
data = data.replace(enc, dec)
return data
|
def is_zero_depth_field(name):
"""
Checks if a field name has one dot in it.
For example, BuildingCode.Value
"""
if name.find('.') != -1 and name.find('.') == name.rfind('.'):
return True
return False
|
def cpu_usage_for_process(results, process):
"""
Calculate the CPU percentage for a process running in a particular
scenario.
:param results: Results to extract values from.
:param process: Process name to calculate CPU usage for.
"""
process_results = [
r for r in results if r['metric']['type'] == 'cputime' and
r['process'] == process
]
cpu_values = sum(r['value'] for r in process_results)
wallclock_values = sum(r['wallclock'] for r in process_results)
if wallclock_values > 0:
return float(cpu_values) / wallclock_values
return None
|
def parse_balanced_delimiters(_input, _d_left, _d_right, _text_qualifier):
"""Removes all balanced delimiters. Handles multiple levels and ignores those contained within text delimiters."""
# Depth is deep into recursion we are
_depth = 0
# Balance is a list of all balanced delimiters
_balanced = []
# Cleared is a string without the balanced delimiters
_cleared = ""
# If in text mode all delimiters are ignored, since they are in text. Also, _text delimiters are escaped.
_text_mode = False
# Start- and end positions refers to start and end of balanced delimiters.
_start_pos = None
# End pos implicitly also mean start of "clean" area.
_clear_start_pos = 0
for _curr_idx in range(len(_input)):
_curr_char = _input[_curr_idx]
if _curr_char == _text_qualifier:
_text_mode = not _text_mode
elif not _text_mode:
if _curr_char == _d_left:
if _depth == 0:
_start_pos = _curr_idx
_cleared += _input[_clear_start_pos:_curr_idx]
_clear_start_pos = None
_depth += 1
elif _curr_char == _d_right:
_depth -= 1
if _start_pos and _depth == 0 and _start_pos < _curr_idx:
_balanced.append(_input[_start_pos + 1:_curr_idx])
_start_pos = None
_clear_start_pos = _curr_idx + 1
if _cleared == "":
return _balanced, _input
else:
return _balanced, _cleared
|
def _sched_malformed_err(msg=None):
"""
Returns an error message if the schedule is malformed
"""
msg = msg if msg else 'schedule malformed'
help_msg = "<br><br>Enter a schedule like <i>r1(x)w1(y)r2(y)r1(z)</i>"
return msg+help_msg
|
def var_to_int(var):
"""
Convert a variable name (such as "t5") to an integer (in this case 5).
Variables like "Amat(iq,D1_RA)" should never show up here.
"""
return int(var[1:])
|
def object_name(object):
"""Convert Python object to string"""
if hasattr(object, "__name__"):
return object.__name__
else:
return repr(object)
|
def count_deck(deck: dict) -> int:
"""Count the number of remaining cards in the deck."""
total = 0
for card, card_item in deck.items():
total += card_item['count']
return total
|
def calculate_streak(streak, operation):
"""
Params:
streak: current user's streak
operation: 1 if bet hits, -1 if bet doesn't hit
If streak is positive and bet hits it will increment streak
If streak is negative and bet hits it will assign it 1
If streak is positive and bet misses it will assign it -1
If streak is negative and bet misses it will decrement streak
"""
return operation if (streak * operation) < 0 else (streak + operation)
|
def firehose_alerts_bucket(config):
"""Get the bucket name to be used for historical alert retention
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
string: The bucket name to be used for historical alert retention
"""
# The default name is <prefix>-streamalerts but can be overridden
# The alerts firehose is not optional, so this should always return a value
return config['global']['infrastructure'].get('alerts_firehose', {}).get(
'bucket_name',
'{}-streamalerts'.format(config['global']['account']['prefix'])
)
|
def last_in_array(array, operation = None):
"""Return the last element in an array.
I think this is just [-1]
"""
if len(array) == 0:
return None
return array[-1]
|
def service_proxy_settings(service_proxy_settings):
"""Expect credentials to be passed in headers"""
service_proxy_settings.update({"credentials_location": "headers"})
return service_proxy_settings
|
def ground_truth_to_word(ground_truth, char_vector):
"""
Return the word string based on the input ground_truth
"""
try:
return ''.join([char_vector[i] for i in ground_truth if i != -1])
except Exception as ex:
print(ground_truth)
print(ex)
input()
|
def reverse_mapping(mapping):
"""
For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True
"""
keys, values = zip(*mapping.items())
return dict(zip(values, keys))
|
def clean_file(f, config):
"""Remove AWS @-based region specification from file.
Tools such as Toil use us-east-1 bucket lookup, then pick region
from boto.
"""
approach, rest = f.split("://")
bucket_region, key = rest.split("/", 1)
if bucket_region.find("@") > 0:
bucket, region = bucket_region.split("@")
else:
bucket = bucket_region
if config.get("input_type") in ["http", "https"]:
return "https://s3.amazonaws.com/%s/%s" % (bucket, key)
else:
return "%s://%s/%s" % (approach, bucket, key)
|
def display_attributes(attributes: dict) -> str:
"""
This function read a dictionary with attributes and returns a string displaying the attributes it gives.
A template: {armor} {health} {mana} {strength} {agility}
If any are missing, we don't add them
"""
attributes_to_print = [f'{attr.replace("bonus_", "")}: {val}' for attr, val in attributes.items() if val]
return ", ".join(attributes_to_print)
|
def _merge(a, b, path=None):
"""merges b into a"""
if path is None:
path = []
for key, bv in b.items():
if key in a:
av = a[key]
nested_path = path + [key]
if isinstance(av, dict) and isinstance(bv, dict):
_merge(av, bv, nested_path)
continue
a[key] = bv
return a
|
def _recursive_parameter_structure(default_parameters):
"""
Convert a set of parameters into the data types used to represent them.
Returned result has the same structure as the parameters.
"""
# Recurse through the parameter data structure.
if isinstance(default_parameters, dict):
return {key: _recursive_parameter_structure(value)
for key, value in default_parameters.items()}
elif isinstance(default_parameters, tuple):
return tuple(_recursive_parameter_structure(value)
for value in default_parameters)
# Determine data type of each entry in parameter data structure.
elif isinstance(default_parameters, float):
return float
elif isinstance(default_parameters, int):
return int
raise TypeError('Unaccepted type in experiment parameters: type "%s".'%(type(default_parameters).__name__))
|
def transforms_fields_uktrade(record, table_config, contexts):
"""
Transform data export fields to match those of the UKTrade Zendesk API.
"""
service = next(
field for field in record["custom_fields"] if field["id"] == 31281329
)
if "requester" in record:
org = record['organization']
return {
**record,
"submitter_id": record["submitter"]["id"],
"requester_id": record["requester"]["id"],
"assignee_id": record.get("assignee")["id"]
if record.get("assignee")
else None,
"group_id": record.get("group")["id"] if record.get("group") else None,
"collaborator_ids": [
collaborator["id"] for collaborator in record["collaborator"]
],
"organization_id": org['id'] if isinstance(org, dict) else org,
"service": service["value"],
"solved_at": record["metric_set"]["solved_at"],
"full_resolution_time_in_minutes": record["metric_set"][
"full_resolution_time_in_minutes"
]["calendar"],
}
return {**record, "service": service["value"]}
|
def infer_prop_name(name):
"""Return inferred property name from pandas column name."""
return name.strip(' "').rsplit('(', 1)[0].rsplit(
'[', 1)[0].strip().replace(' ', '_')
|
def cmyk_to_luminance(r, g, b, a):
"""
takes a RGB color and returns it grayscale value. See
http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
for more information
"""
if (r, g, b) == (0, 0, 0):
return a
return (0.299 * r + 0.587 * g + 0.114 * b) * a / 255
|
def ensure_timed_append_if_cardinality_one(
config,
extra_config,
app_type,
app_path,
):
"""
Automatically sets the "TIMED_APPEND" App Configuration variable automatically to "TRUE" if
the "append" option is enabled and the cardinality parameter (if given) is set to "one".
:param config: Configuration dictionary (the one that gets exported to local.settings.json).
:param extra_config: Dictionary configuring the additional options passed by user in generator_config.json.
:param app_type: Application type.
:param app_path: Path to the output folder for the Function App.
:return: The local.settings.json dictionary currently being formed.
"""
if extra_config["append"].lower() == "true" \
and "cardinality" in extra_config and extra_config["cardinality"].lower() == "one":
config["Values"]["TIMED_APPEND"] = "TRUE"
return config
|
def validate_tag(key, value):
"""Validate a tag.
Keys must be less than 128 chars and values must be less than 256 chars.
"""
# Note, parse_sql does not include a keys if the value is an empty string
# (e.g. 'key=&test=a'), and thus technically we should not get strings
# which have zero length.
klen = len(key)
vlen = len(value)
return klen > 0 and klen < 256 and vlen > 0 and vlen < 256
|
def convert_str_to_mac_address(hex_mac):
"""Just add colons in the right places."""
hex_pairs = [hex_mac[(x*2):((x+1)*2)] for x in range(6)]
mac = "{0}:{1}:{2}:{3}:{4}:{5}".format(*hex_pairs)
return mac
|
def pad_sequences(sequences, pad_func, maxlen = None):
"""
Similar to keras.preprocessing.sequence.pad_sequence but using Sample as higher level
abstraction.
pad_func is a pad class generator.
"""
ret = []
# Determine the maxlen
max_value = max(map(len, sequences))
if maxlen is None:
maxlen = max_value
# Pad / truncate (done this way to deal with np.array)
for sequence in sequences:
cur_seq = list(sequence[:maxlen])
cur_seq.extend([pad_func()] * (maxlen - len(sequence)))
ret.append(cur_seq)
return ret
|
def H(path):
"""Head of path (the first name) or Empty."""
vec = [e for e in path.split('/') if e]
return vec[0] if vec else ''
|
def uv76_to_uv60(u76, v76): # CIE1976 to CIE1960
""" convert CIE1976 u'v' to CIE1960 uv coordinates
:param u76: u' value (CIE1976)
:param v76: v' value (CIE1976)
:return: CIE1960 u, v """
v60 = (2 * v76) / 3
return u76, v60
|
def formalize_switch(switch, s):
"""
Create single entry for a switch in topology.json
"""
entry= {
"mac": "08:00:00:00:01:"+str(s),
"runtime_json": "./build/"+switch+"P4runtime.json"
}
return entry
|
def compare_lists(list1: list, list2: list):
"""Returns the diff of the two lists.
Returns
-------
- (added, removed)
``added`` is a list of elements that are in ``list2`` but not in ``list1``.
``removed`` is a list of elements that are in ``list1`` but not in ``list2``.
"""
added = []
removed = []
for elem in list1:
if elem not in list2:
removed.append(elem)
for elem in list2:
if elem not in list1:
added.append(elem)
return (added, removed)
|
def matrices_params(n_samples):
"""Generate matrices benchmarking parameters.
Parameters
----------
n_samples : int
Number of samples to be used.
Returns
-------
_ : list.
List of params.
"""
manifold = "Matrices"
manifold_args = [(3, 3), (5, 5)]
module = "geomstats.geometry.matrices"
def matrices_metric_params():
params = []
metric = "MatricesMetric"
metric_args = manifold_args
kwargs = {}
common = manifold, module, metric, n_samples, kwargs
for manifold_arg, metric_arg in zip(manifold_args, metric_args):
params += [common + (manifold_arg, metric_arg)]
return params
return matrices_metric_params()
|
def index(seq):
"""
Build an index for a sequence of items. Assumes
that the items in the sequence are unique.
@param seq the sequence to index
@returns a dictionary from item to position in the sequence
"""
return dict((k,v) for (v,k) in enumerate(seq))
|
def _whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
|
def _func(l):
"""Convert a list to a pretty text."""
return '{' + ", ".join([f"'{x}'" for x in l]) + '}'
|
def binEntryBytes(binStr):
"""Convert a sequence of whitespace separated tokens
each containing no more than 8 0's and 1's to a list of bytes.
Raise Exception if illegal.
"""
bytes = []
for i, token in enumerate(binStr.split()):
if len(token) > 8:
raise Exception("Token {} is more than 8 bits: {}".format(i+1,token))
bytes.append(int(token, 2)) # should be OK if only01(binStr) run first
return bytes
|
def exception_to_ec2code(ex):
"""Helper to extract EC2 error code from exception.
For other than EC2 exceptions (those without ec2_code attribute),
use exception name.
"""
if hasattr(ex, 'ec2_code'):
code = ex.ec2_code
else:
code = type(ex).__name__
return code
|
def RemoveDuplicate(Sortedlist):
"""Removes duplicates from a sorted list"""
_Newlist=[]
if not Sortedlist:
return(_Newlist)
else:
iterable=(x for x in Sortedlist)
prev=None
for element in iterable:
if (element == prev):
pass
else:
_Newlist.append(element)
prev=element
return(_Newlist);
|
def shiftCoordsForHeight(s):
"""
Shift with height s
origin = 0,0
"""
coords = (
( # path
(s/2,s), (0,s*4/9), (s*4/15,s*4/9), (s*4/15,0),
(s*11/15,0), (s*11/15,s*4/9), (s,s*4/9),
),
)
return coords
|
def get_words_from_string(input_):
"""This splits a string into individual words separated by empty spaces or punctuation
"""
return input_.split()
|
def get_value_for_key_from_json(key, data_structure):
"""
Given a data_structure return the *first* value of the key from the first dict
example:
data_structure: [ { "id": 1, "name": "name1" }, { "id": 2, "name": "name2"} ]
key: "id"
return 1
:param key: key of a dict of which to return the value
:param data_structure: python data_structure
:return: value of key in first dict found
"""
if type(data_structure) == list:
for v in data_structure:
# print("recursively searching %s" % str(v))
r = get_value_for_key_from_json(key, v)
if r is not None:
return r
return None
elif type(data_structure) == dict:
if key in data_structure:
return data_structure[key]
else:
for k in data_structure:
v = data_structure[k]
# print("recursively searching %s" % str(v))
r = get_value_for_key_from_json(key, v)
if r is not None:
return r
return None
|
def hash_to_test():
"""
Easy way to create test data for hash to test.
:var string text_test: holds test text
:var string text_format: holds format for test text
:var string hash_text: holds test hash
:return: test data array that contains text, format of text, hash.
"""
text_test = 'hello'
text_format = 'utf-8'
hash_test = '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
element_id = 'id_text'
return text_test, text_format, hash_test, element_id
|
def count_nests(nest_spec):
"""
count the nests in nest_spec, return 0 if nest_spec is none
"""
def count_each_nest(spec, count):
if isinstance(spec, dict):
return count + sum([count_each_nest(alt, count) for alt in spec['alternatives']])
else:
return 1
return count_each_nest(nest_spec, 0) if nest_spec is not None else 0
|
def read_error_line(l):
"""
Reads line?
"""
print('_read_error_line -> line>', l)
name, values = l.split(' ', 1)
print('_read_error_line -> name>', name)
print('_read_error_line -> values>', values)
name = name.strip(': ').strip()
values = values.strip(': ').strip()
v, error = values.split(" +/- ")
return name, float(v), float(error)
|
def model_function(X, a, b, c):
"""
- the analytical expression for the model that aims at describing the experimental data
- the X argument is an array of tuples of the form X=[,...,(xi_1,xi_2),...]
"""
nw1, nw2, I = X
f = a * pow(I, 2) * (nw1 + 0.5) + b * I * (nw2 + 0.5) + c
return f
|
def getfmt(n,dtype ="d"):
"""
Generates the binary format n dtype
defualts to double
@param n: number of particles
@param dtype: data type
returns the format string used to decode the binary data
"""
fmt = ""
fmt += dtype
for i in range(n):
fmt += dtype
return fmt
|
def make_physical_params_sweep_fname(tag: str, param_str: str):
"""Return a filename for noiseless parameter sweeps inputs.
Args:
tag: Some identifier string for this simulation result.
"""
return f"physical_parameter_sweep_{tag}_{param_str}.npy"
|
def matching(a, b):
"""
Totals the number of matching characters between two strings
Parameters
----------
a: str
b: str
Returns
-------
int
"""
comp = zip(a, b)
diff = abs(len(a)-len(b))
m = sum(1 for x,y in comp if x == y)
return m - diff
|
def anal_q(data_dict):
""" Try and get the CCSDT(Q) energy """
try:
q_dict = data_dict["ccsdtq"]
q_energy = q_dict["ccsdt(q) energy"] - q_dict["ccsdt energy"]
except KeyError:
q_energy = 0.
return q_energy
|
def get_drop_connect_rate(init_rate, block_num, total_blocks):
"""Get drop connect rate for the ith block."""
if init_rate is not None:
return init_rate * float(block_num) / total_blocks
else:
return None
|
def get_round_scaled_dsize(dsize, scale):
"""
Returns an integer size and scale that best approximates
the floating point scale on the original size
Args:
dsize (tuple): original width height
scale (float or tuple): desired floating point scale factor
"""
try:
sx, sy = scale
except TypeError:
sx = sy = scale
w, h = dsize
new_w = int(round(w * sx))
new_h = int(round(h * sy))
new_scale = new_w / w, new_h / h
new_dsize = (new_w, new_h)
return new_dsize, new_scale
|
def get_guest_flag(flags):
"""
This is get flag index list
:param flags:
:return: flag index list in GUEST_FLAGS
"""
err_dic = {}
flag_str = ''
for flag in flags:
if flags.count(flag) >= 2:
return (err_dic, flag)
for i in range(len(flags)):
if i == 0:
if len(flags) == 1:
# get the guest flag 0UL
if flags[0] == '0UL':
return (err_dic, flags[0])
flag_str = "{0}".format(flags[0])
else:
flag_str = "({0}".format(flags[0])
else:
# flags lenght already minus 1
if i == len(flags) - 1:
flag_str = flag_str + " | {0})".format(flags[i])
else:
flag_str = flag_str + " | {0}".format(flags[i])
return (err_dic, flag_str)
|
def _is_package_init(path):
"""Check whether a file path refers to a __init__.py or __init__.pyc file.
Params:
-------
path: str
File path.
Return:
-------
bool:
Whether the file path refers to a pacvkage init file.
"""
return path.lower().endswith('__init__.py') or path.lower().endswith('__init__.pyc')
|
def calc_bitmasks_ARGB_color(bdR: int, bdG: int, bdB: int, bdA: int):
"""Calculates the appropriate bitmasks for a color stored in ARGB format."""
redMask = 0
greenMask = 0
blueMask = 0
alphaMask = 0
if bdA > 0:
for _ in range(bdA):
alphaMask = (alphaMask << 1) + 1
alphaMask = alphaMask << (bdR + bdG + bdB)
for _ in range(bdR):
redMask = (redMask << 1) + 1
redMask = redMask << (bdG + bdB)
greenMask = 0
for _ in range(bdG):
greenMask = (greenMask << 1) + 1
greenMask = greenMask << (bdB)
blueMask = 0
for _ in range(bdB):
blueMask = (blueMask << 1) + 1
masks = [redMask, greenMask, blueMask, alphaMask]
return masks
|
def read_kwargs_from_dict(input_dict, type_dict):
""" Reads, from an input dictionary, a set of keyword arguments.
This function is useful to gather optional arguments for a function call
from a greater, more complete, input dictionary. For this purpose,
keys that are not found at input_dict are simply ignored.
The desired keywords mus be the keys of type_dict, whose values
must be the type cast callable. None can be passed as a type cast
for no conversion.
Parameters
------
input_dict : dict
Dictionary with the input keywords. Can contain more than the
necessary keywords.
type_dict : dict
Dictionary with the desired names as keys and their type casts
as values. Type can be None for no conversion.
"""
kwargs = dict()
for key, cast in type_dict.items():
try:
if cast is None:
kwargs[key] = input_dict[key]
else:
kwargs[key] = cast(input_dict[key])
except KeyError:
pass
return kwargs
|
def f(a, b):
"""Function with an integer range containing the other."""
return -(a + b)
|
def regexp_versions(versions_string):
"""Converts the list of versions from the bulletin data into a regexp"""
if len(versions_string) == 0:
return ''
versions = versions_string.replace('and', ',').replace(' ', '').replace('.', '\\.').split(',')
regexp = ''
for version in versions:
dots = version.count('.')
if dots == 2:
regexp += ('(' + version + ')|')
elif dots == 1:
regexp += ('(' + version + '\\.[0-9])|')
elif dots == 0:
regexp += ('(' + version + '\\.[0-9]\\.[0-9])|')
else:
raise ValueError('Invalid version string provided')
return regexp[:-1]
|
def member_id_validation(input_id):
"""
function used to check if the input member id is valid
"""
if len(input_id) != 4:
# if the id input is not 4 digits
return 1
elif input_id.isdigit():
# if the input id is a number
return 0
else:
# if not a number
return 2
|
def micro(S, C, T):
"""
Computes micro-average over @elems
"""
S, C, T = sum(S.values()), sum(C.values()), sum(T.values())
P = C/S if S > 0. else 0.
R = C/T if T > 0. else 0.
F1 = 2 * P * R /(P + R) if C > 0. else 0.
return P, R, F1
|
def parse_optimization_method(lr_method):
"""
Parse optimization method parameters.
"""
if "-" in lr_method:
lr_method_name = lr_method[:lr_method.find('-')]
lr_method_parameters = {}
for x in lr_method[lr_method.find('-') + 1:].split('-'):
split = x.split('_')
assert len(split) == 2
lr_method_parameters[split[0]] = float(split[1])
else:
lr_method_name = lr_method
lr_method_parameters = {}
return lr_method_name, lr_method_parameters
|
def strip_docstring(docstring):
"""Return contents of docstring."""
docstring = docstring.strip()
quote_types = ["'''", '"""', "'", '"']
for quote in quote_types:
if docstring.startswith(quote) and docstring.endswith(quote):
return docstring.split(quote, 1)[1].rsplit(quote, 1)[0].strip()
raise ValueError('We only handle strings that start with quotes')
|
def _change_dict_key(the_dict, old_key, new_key, default=None):
"""
Changes a dictionary key name from old_key to new_key.
If old_key doesn't exist the value of new_key becomes and empty dictionary
(or the value of `default`, if set).
"""
if default is None:
default = dict()
v = the_dict.get(old_key, default)
if new_key not in the_dict:
the_dict[new_key] = v
if old_key in the_dict:
del the_dict[old_key]
return the_dict
|
def x0_mult(guess, slip):
"""
Compute x0_mult element-wise
Arguments:
guess (np.array)
slip (np.array)
"""
return slip*(1.0+guess)/(1.0+slip)
|
def left_of_center(box, im_w):
"""
return -1 if left of center, 1 otherwise.
"""
(left, right, top, bot) = box
center_image = im_w / 2
if abs(left - center_image) > abs(right - center_image):
return -1
return 1
|
def sanitize_text(text: str) -> str:
"""Sanitizes and removes all useless characters from the text, returns sanitized text string"""
alphanum_text = ""
for letter in list(text):
if letter.isalnum() or letter == " " or letter in "!?.,:;\'\"&()$%#@~":
alphanum_text += letter
return alphanum_text
|
def cal_percents(count_list):
"""A,C,G,T, depth"""
depth = float(count_list[0])
if depth > 0:
count_list.append(str(100*(int(count_list[1])/depth))) # perA
count_list.append(str(100*(int(count_list[2])/depth))) # perC
count_list.append(str(100*(int(count_list[3])/depth))) # perG
count_list.append(str(100*(int(count_list[4])/depth))) # perT
else:
# div by zero error
count_list.append('0.0')
count_list.append('0.0')
count_list.append('0.0')
count_list.append('0.0')
return count_list
|
def change_dict_value(dictionary, old_value, new_value):
"""
Change a certain value from a dictionary.
Parameters
----------
dictionary : dict
Input dictionary.
old_value : str, NoneType, bool
The value to be changed.
new_value : str, NoneType, bool
Replace value.
Returns
-------
dict
"""
for key, value in dictionary.items():
if value == old_value:
dictionary[key] = new_value
return dictionary
|
def findComplement_v4(num: int) -> int:
"""The lLeetCode solutions runner judges this to be the fastest of all four."""
return num ^ max(1, 2 ** (num).bit_length() - 1)
|
def get_origin(type_annotation):
""" Backport of python 3.8's get_origin. e.g. get_origin(Tuple[str, int]) is Tuple
:param type_annotation: A type annotation, e.g Tuple[str, int]
:return: The base type, e.g. Tuple
"""
is_generic_annotation = hasattr(type_annotation, '__origin__') and type_annotation.__origin__ is not None
return type_annotation.__origin__ if is_generic_annotation else type_annotation
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.