content stringlengths 42 6.51k |
|---|
def get_next_match_pick_first_available(population):
""" Decides next two player indexes who will play against each other next, iterating over the list
and picking the very first available"""
p1 = None
for player in population:
if player.available:
if p1 is not None:
... |
def set_privacy(annotations, key, is_private=True, value_types=['longAnnos', 'doubleAnnos', 'stringAnnos']):
"""
Set privacy of individual annotations, where annotations are in the format used by Synapse
SubmissionStatus objects. See the `Annotations documentation <http://rest.synapse.org/org/sagebionetwork... |
def median(arr):
"""
Calculate the median of all the values in a list
:param arr: The list of values
:type arr: list
:return: The median of all the numbers
:rtype: float
"""
arr.sort()
n = len(arr)
mid = int(n / 2)
return arr[mid] |
def adaptMetricsInterval(metrics, interval):
"""Transforms the selected metrics and the time interval (daily, weekly, etc.) into a understandable metrics
Parameters:
-----------
metrics : str list
list of cumulatives selected metrics
interval : str
time intervall (daily, wee... |
def ramsey_sequence(length, target):
"""
Generate a gate sequence to measure dephasing time in a two-qubit chip.
Parameters
----------
length : int
Number of Identity gates.
target : str
Which qubit is measured. Options: "left" or "right"
Returns
-------
list
... |
def pipeline(ticker, years):
"""Converts user input to appropriate types"""
ticker = str(ticker)
years = int(years)
return ticker, years |
def DivideAndCeil(dividend, divisor):
"""Returns ceil(dividend / divisor).
Takes care to avoid the pitfalls of floating point arithmetic that could
otherwise yield the wrong result for large numbers.
Args:
dividend: Dividend for the operation.
divisor: Divisor for the operation.
Returns:
Quotie... |
def merge_dicts(src, dest):
"""Merge to dictionaries and return a new dictionary
"""
ndict = dict(src)
ndict.update(dest)
return ndict |
def construct_dict_from_source(fields, source):
"""
Construct a new dict from a source dict and catch all KeyErrors, using predefined functions to extract desired
values from a source dictionary.
:param fields: Dictionary with fields in the the target dict as keys and functions to extract their de... |
def _value_is_array(value):
"""Check if a parameter value is an array.
Parameters
----------
value : str
Parameter value as a string.
Returns
-------
bool
``True`` if the value is an array. Otherwise, ``False``.
"""
return "," in value |
def _character_to_symbol(character):
""" converts a single character to the mathematic symbol, does not apply all tex formatting """
if character == "T":
return r"v_{\theta}"
elif character == "W":
return r"v_{z}"
elif character == "R":
return r"v_{r}"
elif character == "U":
... |
def get_distinct_edge(edge_array):
"""
Return Distinct edges from edge array of multiple graphs
>>> sorted(get_distinct_edge(edge_array))
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
"""
distinct_edge = set()
for row in edge_array:
for item in row:
distinct_edge.add(... |
def login_allowed(user):
"""
@user_passes_test decorator to check whether the user is allowed to access the application or not.
We do not want to allow non-UserBackend users to access the application
(because we need the LDAP entry for the shares etc.) so we check that here.
"""
if user is None... |
def _format_print(string, prefix=""):
"""Inserts the given prefix at the beginning of each line"""
if prefix:
string = prefix + ("\n" + prefix).join(string.splitlines())
return string |
def nice_pair(pair):
"""Make a nice string representation of a pair of numbers.
If the numbers are equal, just return the number, otherwise return the pair
with a dash between them, indicating the range.
"""
start, end = pair
if start == end:
return "%d" % start
else:
... |
def float_to_htk_int(string):
""" Converts a string representing a floating point number to an
integer (time in 100ns units)...
"""
return int(round(float(string)*10000000)) |
def hexStr2Bytes(hexStr: str) -> bytes:
"""
Convert an hexadecimal string in bytes
:param hexStr: The hexadecimal string
:type hexStr: str
:return: The bytes of the hexadecimal string
:rtype: bytes
"""
return bytes.fromhex(hexStr) |
def get_new_hw(h, w, size, max_size):
"""Get new hw."""
scale = size * 1.0 / min(h, w)
if h < w:
newh, neww = size, scale * w
else:
newh, neww = scale * h, size
if max(newh, neww) > max_size:
scale = max_size * 1.0 / max(newh, neww)
newh = newh * scale
neww = neww * scale
neww = int(neww... |
def bubblesort_core(x):
"""
sort x by bubblesort. also, keep track of assignments and
conditionals.
"""
assignments = 0
conditionals = 0
# in X steps...
for step in range(len(x)):
# for each of the first X-step element pairs...
for i in range(len(x)-1-step):
#... |
def Gt(field, value):
"""
A criterion used to search for a field greater than a certain value. For example
* search for TLP > 2
* search for customFields.cvss > 4.5
* search for date > now
Arguments:
field (value): field name
value (Any): field value
Returns:
dict:... |
def getindex(ndim, ind, strides):
"""Convert multi-dimensional index to the position in the flat list."""
ret = 0
for i in range(ndim):
ret += strides[i] * ind[i]
return ret |
def zakharov(ind):
"""Zakharov function defined as:
$$ f(x) = \sum_{i=1}^n x_i^2 + (\sum_{i=1}^n 0.5 i x_i)^2 + (\sum_{i=1}^n 0.5 i x_i)^4$$
with a search domain of $-5 < x_i < 10, 1 \leq i \leq n$.
The global minimum is at $f(x_1, ..., x_n) = f(0, ..., 0) = 0.
"""
return sum((x**2. for x in in... |
def get_flowcell_name_from_desc(description_dict, user_run_name):
"""
Get the flowcell name from the description
Parameters
----------
description_dict: dict
A parsed dictionary created from the description from the fastq record
user_run_name: str
The user run name that we have b... |
def parse_details_url(record):
"""
> Site URLs can be similarly constructed from some Services,
> such as https://waterdata.usgs.gov/nwis/uv/?site_no=14113000, when
> ServCode = "NWISDV" and location = "NWISDV:14113000"
Ref: https://github.com/WikiWatershed/model-my-watershed/issues/1931
"""
... |
def rough_calibration(pis, mission):
"""
Parameters
----------
pis: float or array of floats
PI channels in data
mission: str
Mission name
Returns
-------
energies : float or array of floats
Energy values
Examples
--------
>>> rough_calibration(0, '... |
def roundToMultiple(x, y):
"""Return the largest multiple of y < x
Args:
x (int): the number to round
y (int): the multiplier
Returns:
int: largest multiple of y <= x
"""
r = (x + int(y / 2)) & ~(y - 1)
if r > x:
... |
def _is_c2d_topic(split_topic_str):
"""
Topics for c2d message are of the following format:
devices/<deviceId>/messages/devicebound
:param split_topic_str: The already split received topic string
"""
if "messages/devicebound" in split_topic_str and len(split_topic_str) > 4:
return True
... |
def get_sql_result_as_dict_list(res):
"""Returns the result set as a list of dicts
Args:
res: (object): The sql result set
Returns:
A list of dicts
"""
if not res:
return []
col_names = res.get_column_names()
rows = res.fetch_all()
dict_list = [... |
def binHits(hitMap):
"""
return map of assignments to list of reads
"""
hits = {}
for (read, hit) in hitMap.items():
if isinstance(hit, list):
for h in hit:
hits.setdefault(h, []).append(read)
else:
hits.setdefault(hit, []).append(read)
re... |
def _value_checker(index_input):
"""Helper function to input check the main index functions"""
if index_input == "": # empty string, default index
return "default"
try:
return float(index_input)
except ValueError:
return False |
def prepare_commands(commands):
"""converts commands to Eapi formatted dicts"""
formatted = []
for command in commands:
answer = command.answer or ""
command = command.cmd.strip()
formatted.append({"cmd": command, "input": answer})
return formatted |
def lerp(a, b, t):
""" Returns the linear interpolation between a and b at time t between 0.0-1.0.
For example: lerp(100, 200, 0.5) => 150.
"""
if t < 0.0:
return a
if t > 1.0:
return b
return a + (b - a) * t |
def getbool(value, default=None,
truevalues=set((True, 1, '1', 't', 'true', 'True')),
falsevalues=set((False, 0, '0', 'f', 'false', 'False'))):
"""Convert a given value to True, False, or a default value.
If the given value is in the given truevalues, True is returned.
If the ... |
def sorted_by_key(x, i, reverse=False):
"""sort by key"""
# Sort by distance
def key(element):
return element[i]
return sorted(x, key=key, reverse=reverse) |
def longest_positive_sequence(the_list):
"""
Function that given a list, it returns the longest number of positive numbers.
If it returns 3, then there exists 3 consecutive positive numbers.
@param the_list: an array of integers
@complexity: best-case and worst-case is O(N) where N is the length of the list
... |
def _fingerprint(row):
"""Generate a string-based fingerprint to characterize row diversity."""
return ''.join(map(lambda x: str(type(x)), row)) |
def remove_html_tags(text):
"""Remove html tags from a string"""
import re
# make semi colon after list element
text = text.replace('</li>', ";")
# clean other tags
clean = re.compile('<.*?>')
return re.sub(clean, ' ', text) |
def size_increment(added_content, deleted_content):
"""
:param added_content: content added to wiki by an user
:param deleted_content: content deleted from wiki by an user
:return: ratio of added to deleted content
useful to identify deletion vandalism, where a vandal can remove data in large amount... |
def _gen_table_cols(col_ids):
"""Generate Dash table columns in the expected format.
:param col_ids: list of columns; must be in format <table-alias.name>,
like "s.serial_number", as in the SQL select statement
-- except for derived column values which must literally
... |
def deep_len(lst):
"""Returns the deep length of the list.
>>> deep_len([1, 2, 3]) # normal list
3
>>> x = [1, [2, 3], 4] # deep list
>>> deep_len(x)
4
>>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
>>> deep_len(x)
6
"""
"*** YOUR CODE HERE ***"
if type(lst) != li... |
def run_is_big_enough(s, e, bankend):
"""Check whether a run is big enough to consider.
A run of $FF or $00 is OK if it's 32 bytes or longer, or if it's
10 bytes or longer and touches the reset vectors.
"""
if e - s >= 32:
return True
if s <= bankend - 15 and e >= bankend - 6:
return True
... |
def get_connected_devices(device, data):
"""Get all devices that are connected to a device in a certain state."""
result = []
if device not in data:
return result
for interface in data[device]:
if "device" in data[device][interface]:
result.append(data[device][interface]["... |
def group_name_to_team_name(group_name):
"""Return the team name corresponding to Keycloak's `group_name`."""
if group_name.startswith("TEAM-"):
return group_name[len("TEAM-") :]
return group_name |
def typify(tokens):
"""
Returns a dictionary of unique types with their frequencies.
:param tokens:a list of tokens
:type tokens:list
:return:a dictionary of unique types with their frequencies.
:rtype:dict
"""
temp_types = {}
for word in tokens:
if word not in temp_types.keys():
temp_types[word] = 1
el... |
def _prepare_dict_inputs(inputs, tensor_info_map):
"""Converts inputs to a dict of inputs and checks extra/missing args.
Args:
inputs: inputs fed to Module.__call__().
tensor_info_map: A map from string to `tensor_info.ParsedTensorInfo`
describing the signature inputs.
Returns:
A dict of value... |
def list_set_bits(r, expected_length):
"""Return list of positions of bits set to one in given data.
This method is used to read e.g. violated zones. They are marked by ones
on respective bit positions - as per Satel manual.
"""
set_bit_numbers = []
bit_index = 0x1
assert (len(r) == expecte... |
def remove_plural_words (dictionary, lang):
"""
`remove_plural_words()` removes from the dictionary every word that is already in the dictionary in singular form.
* **dictionary** (*list*) : the input dictionary (while processing)
* **lang** (*str*) : the language used to follow plural rules (only... |
def ValueNameFromTraceAndChartName(trace_name, chart_name=None):
"""Mangles a trace name plus optional chart name into a standard string.
A value might just be a bareword name, e.g. numPixels. In that case, its
chart may be None.
But, a value might also be intended for display with other values, in which
ca... |
def f_beta(precision, recall, beta = 1):
"""
Get F_beta score from precision and recall.
"""
beta = float(beta) # Make sure that results are in float
return (1 + pow(beta, 2)) * (precision * recall) / ((pow(beta, 2) * precision) + recall) |
def split(number, portion=0.9):
"""
splitting a data set into train and val set
:param number: Int / number of samples in dataset
:param portion: Float / percentile of samples that go into train set
:return: list of Int / numbers indicating samples needed in train and val set according to portion
... |
def xp_calculation(length: int):
"""
Calculate the XP for the given message length
:param length:
:return:
"""
if length <= 10:
xp = 0.1
elif 10 < length <= 200:
xp = ((length / 200) * 2.5) + 0.5
elif 200 < length <= 400:
xp = 2.5
elif 400 < length <= 600:
... |
def to_one_dimensional_array(iterator):
"""convert a reader to one dimensional array"""
array = []
for i in iterator:
if type(i) == list:
array += i
else:
array.append(i)
return array |
def floor_lg(n: int) -> int:
"""Return floor(log_2(n)) for a positive integer `n`"""
assert n > 0
r = 0
t = 1
while 2 * t <= n:
t = 2 * t
r = r + 1
return r |
def get_command_from_state(state):
"""
This method gets appropriate command name for the state specified. It
returns the command name for the specified state.
:param state: The state for which the respective command name is required.
"""
command = None
if state == 'present':
command ... |
def transform(data, ops=None):
""" transform """
if ops is None:
ops = []
for op in ops:
data = op(data)
if data is None:
return None
return data |
def db_to_lin(db):
"""
Convert gain in dB to linear.
"""
return 10.0**(db/20.0) |
def validate_port_number(port_number):
"""Check if the port number is within range.
:param int port_number: The port number to check.
:return: True if the port number is valid; false if not.
:rtype: bool
:raises ValueError: if the port number is invalid.
"""
if port_number not in range(0,... |
def serial_to_ring(x: int) -> int:
"""Convert serialized chamber id to ring."""
return ((x >> 6) & 0x00000003) + 1 |
def collect_functions(functions, r=None):
"""Return functions for next values of latches.
@param functions: `dict` as returned by `make_functions`
"""
if r is None:
r = dict()
r.update(
(var, d['function'])
for var, d in functions.items())
return r |
def merge_lines(lines, start, join=" "):
"""Gets a single continuous string from a sequence of lines.
:param list lines: The lines to merge.
:param int start: The start point in each record.
:param str join: The string to join on.
:rtype: ``str``"""
string = join.join([line[start:].strip() for... |
def cvtHH(hhstr, pos=0):
""" Convert HH hex [sub]string value into integer.
Parameters:
hhstr - HH [sub]string
format: "....HH...."
pos - starting position in string.
default: 0 (start of string)
Return Value:
Returns converted integer va... |
def add_device_info(mappings, session):
"""
Adds the informations about the device for each mapping.
- If the mapping is related to a device, gives the device id.
- If it is common space, takes the id 0
- ! Not used here ! If it is part of a "memory hole", id is -1
Input :
... |
def perimeterTriangle(side1: float, side2: float, base: float) -> float:
"""Finds perimeter of triangle"""
perimeter: float = side1 + base + side2
return perimeter |
def pixellate(resolution_x=320, resolution_y=240):
"""
A sharp pixellation filter.
Author: SolarLune
Date Updated: 6/6/11
resolution_x = target resolution on the X axis. Defaults to 320.
resolution_y = target resolution on the Y axis. Defaults to 240.
A larger X-axis resolution would equa... |
def incident_related_resource_data_to_xsoar_format(resource_data, incident_id):
"""
Convert the incident relation from the raw to XSOAR format.
:param resource_data: (dict) The related resource raw data.
:param incident_id: The incident id.
"""
properties = resource_data.get('properties', {})
... |
def clean_word(word):
"""Cleans word from chars that are not allowed
Arguments:
word {string} -- the word to be cleaned
"""
return word.replace('\n', '').replace('=', '').replace('(', '').replace(')', '') \
.replace('"', '') .replace(',', '').replace('.', '') |
def is_good(entry):
"""
Good entries on a bropage have more upvotes than downvotes.
"""
try:
return entry["up"] >= entry["down"]
except:
return True |
def binary_search(arr, key):
"""
Searches for the key in a list and returns the position of the key in the array.
If the key can not be found in the list, raise a ValueError
Will keep shifting the middle point for as long as the middle value is not equal to the search key
If, the search key is less ... |
def validate_ansible_playbook(response_dict):
"""
Validate if ansible playbook ran OK. Returns:
success = Bool
"""
if (
"FAILED" in response_dict["ansible_output"]
or "ERROR" in response_dict["ansible_output"]
or "WARNING" in response_dict["ansible_output"]
):
suc... |
def unique_match_from_list(list):
"""
Check the list for a potential pattern match
@param list : a list of potential matching groups
@rtype : return the string representation of the unique value that matched, or nothing if nothing matched
"""
result = ''
for item in lis... |
def strip_shacl_prefix(url: str) -> str:
"""Strip the shacl prefix and return value of the url.
Args:
url (str): String with shacl prefix.
Returns:
str: String after removing shacl prefix..
"""
term = str(url)
return term[27:] |
def parse_updates(updates_string):
""" Parses updates string in a report and returns a sanitized version
"""
updates = []
ulist = updates_string.split()
while ulist:
updates.append('{0!s} {1!s} {2!s}\n'.format(ulist[0],
ulist[1],
... |
def value_of_card(card: str):
"""Determine the scoring value of a card.
:param card: str - given card.
:return: int - value of a given card. See below for values.
1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10
2. 'A' (ace card) = 1
3. '2' - '10' = numerical value.
"""
i... |
def check_brack_o(count):
"""
Help funktion for balance brackets
"""
if count > 0:
print("No match")
return 0
return 1 |
def is_virtual_column(col_id):
"""
Returns whether col_id is of a special column that does not get communicated outside of the
sandbox. Lookup maps are an example.
"""
return col_id.startswith('#') |
def like_rnncell(cell):
"""Checks that a given object is an RNNCell by using duck typing."""
conditions = [hasattr(cell, "output_size"), hasattr(cell, "state_size"),
hasattr(cell, "zero_state"), callable(cell)]
return all(conditions) |
def check_abs_diff(x0: float, x1: float, tol: float = 3) -> bool:
"""
Check absolute difference between two numbers.
This will test if the absolute difference between two numbers is
within a certain tolerance.
Parameters
----------
x0, x1: float
the numbers to difference
tol: f... |
def levenshtein_dynamic(s1: str, s2: str) -> int:
"""Return the minimum edit distance between strings s1 and s2.
This function implements the Levenshtein distance algorithm using Dynamic Programming.
Note: This function is not required by the levenshtein automaton, but I felt it that
it could be useful... |
def escape(s):
"""Replace special characters '&', "'", '<', '>' and '"' by XML entities."""
s = s.replace("&", "&") # Must be done first!
s = s.replace("'", "'")
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
return s |
def fuzzy_match_simple(pattern, instring):
"""Return True if each character in pattern is found in order in instring.
:param pattern: the pattern to be matched
:type pattern: ``str``
:param instring: the containing string to search against
:type instring: ``str``
:return: True if there is a ma... |
def to_tuple(param, low=None):
"""Converts a parameter to a tuple."""
if isinstance(param, (list, tuple)):
return tuple(param)
elif param is not None:
if low is None:
return -param, param
return (low, param) if low < param else (param, low)
else:
return param |
def variable_id(printer, ast):
"""Prints "varName [= initData]"."""
var_name_str = ast["varName"]
array_decl_str = ''.join(map(lambda decl: f'[{printer.ast_to_string(decl)}]', ast["arrayDecl"]))
init_data_str = f' = {printer.ast_to_string(ast["initData"])}' if ast.get("initData") else ''
return f'{v... |
def _is_from_logout(request):
"""
Returns whether the request has come from logout action to see if
'is_from_logout' attribute is present.
"""
return getattr(request, 'is_from_logout', False) |
def normalize_spaces(s):
"""replace any sequence of whitespace
characters with a single space"""
return ' '.join(s.split()) |
def parseNeighbors_rank(urls):
"""Parses a urls pair string into urls pair."""
parts = urls.split(',')
res=float(float(parts[2])/float(parts[3]))
return parts[1], res |
def load_model(known_loaders, outname, **kwargs):
"""If `model_type` is given, use it to load an addon model and construct that OW use default
:param known_loaders: Map of baseline functions to load the model, typically a static factory method
:param outname The model name to load
:param kwargs: Anythi... |
def get_P_X_past_cond_X(past_symbol_counts, number_of_symbols):
"""
Compute P(X_past | X), the probability of the past activity conditioned
on the response X using the plug-in estimator.
"""
P_X_past_cond_X = [{}, {}]
for response in [0, 1]:
for symbol in past_symbol_counts[response... |
def change_app_header(uri, headers, body):
""" Add Accept header for preview features of Github apps API """
headers["Accept"] = "application/vnd.github.machine-man-preview+json"
return uri, headers, body |
def translate(old, translation_table):
"""Returns a new dictionary with keys based on translation_table."""
result = dict()
for field, val in old.items():
if field in translation_table:
result[translation_table[field]] = val
else:
result[field] = val
return result |
def is_sequence(arg):
"""Check if an object is iterable (you can loop over it) and not a string."""
return not hasattr(arg, "strip") and hasattr(arg, "__iter__") |
def get_foot_point(point, line_p1, line_p2):
"""
@point, line_p1, line_p2 : [x, y, z]
"""
x0 = point[0]
y0 = point[1]
# z0 = point[2]
x1 = line_p1[0]
y1 = line_p1[1]
# z1 = line_p1[2]
x2 = line_p2[0]
y2 = line_p2[1]
# z2 = line_p2[2]
assert not (x1 == x2 and y1 == y... |
def pmr_corr(vlos, r, d):
"""
Correction on radial proper motion due to apparent contraction/expansion
of the cluster.
Parameters
----------
vlos : float
Line of sight velocity, in km/s.
r : array_like, float
Projected radius, in degrees.
d : float
Cluster distan... |
def if_(if_func, func, arg):
"""Whether to apply a function or not
"""
if if_func(arg):
return func(arg)
return arg |
def offsets_transform(row_offset, col_offset, transform):
"""Calculating new geotransform for each segment boxboundary"""
new_geotransform = [
transform[0] + (col_offset * transform[1]),
transform[1],
0.0,
transform[3] + (row_offset * transform[5]),
0.0,
t... |
def _normalize_typos(typos, replacement_rules):
"""
Applies all character replacement rules to the typos and returns a new
dictionary of typos of all non-empty elements from normalized 'typos'.
"""
if len(replacement_rules) > 0:
typos_new = dict()
for key, values i... |
def dfs_category_dictionary(categories, categories_df, parentId, count):
"""
dfs predefined predefined hierarchical categories.
:param categories: each topic's predefined hierarchical categories.
:param categories_df: dataframe stroes data
:param parentId: id of parent categories
:param count: ... |
def stringify_keys(d):
# taken from https://stackoverflow.com/a/51051641
"""Convert a dict's keys to strings if they are not."""
keys = list(d.keys())
for key in keys:
# check inner dict
if isinstance(d[key], dict):
value = stringify_keys(d[key])
else:
va... |
def classify(s, data_set, suffixes=None):
"""
Return True or some classification string value that evaluates to True if
the data in string s is not junk. Return False if the data in string s is
classified as 'junk' or uninteresting.
"""
if not s:
return False
s = s.lower().strip('/')... |
def intersection(list_to_intersect):
""" Helper method to intersect lists
"""
lst0 = list_to_intersect[0]
for lst1 in list_to_intersect[1:]:
lst0 = [value for value in lst0 if value in lst1]
return lst0 |
def print_error(message):
""" returns a message to be printed in red """
return '\033[31m{}\033[0m'.format(str(message)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.