content stringlengths 42 6.51k |
|---|
def old_patch_description(pattern: str) -> str:
"""
Wrap the pattern to conform to the new commit queue patch description format.
Just add a start anchor. The format looks like:
<commit message>
:param pattern: The pattern to wrap.
:return: A pattern to match the old format for the patch desc... |
def shellQuote(value):
"""
Return the string value in a form that can safely be inserted into
a shell command.
"""
return "'%s'"%(value.replace("'", "'\"'\"'")) |
def euclide_gcd_algo(a, b):
"""Calculate (r, u, v) so that u * a + v * b = r = GCD(a, b)"""
(r, u, v, r2, u2, v2) = (a, 1, 0, b, 0, 1)
while r2 > 0:
q = r // r2
(r, u, v, r2, u2, v2) = (r2, u2, v2, r - q * r2, u - q * u2, v - q * v2)
return r, u, v |
def apply_hard_coded_changes(config, version):
"""
Unfortunately, some changes made between config version are too complex
to implement using the versioning dict to make it worth while. Best to
hard code changes like this for each version and update the config as
needed.
@param config Diction... |
def ped_lines(request):
"""Get the lines for a case"""
case_lines = [
"#Family ID Individual ID Paternal ID Maternal ID Sex Phenotype",
"643594 ADM1059A1 0 0 1 1",
"643594 ADM1059A2 ADM1059A1 ADM1059A3 1 2",
"643594 ADM1059A3 0 0 2 1",
]
return case_lines |
def VG_pressureh(h, theta_r, theta_s, a, n):
""" Water retention function :math:`theta(h)`
Soil water retention function as described by
:cite:`VanGenuchten1980`.
Parameters
----------
h : `float`
Soil water potential :math:`\\left(length\\right)`.
theta_r : `float`
Residua... |
def tmle_unit_bounds(y, mini, maxi):
"""Bounding for continuous outcomes for TMLE.
Parameters
----------
y : array
Observed outcome values
mini : float
Lower bound to apply
maxi : float
Upper bound to apply
Returns
-------
array
Bounded outcomes
... |
def dict_values_convert_to_float(dict_to_convert):
"""Simple converting dict values from string to float.
:param dict_to_convert: dict from csv file with string values.
"""
return {key: float(value) for key, value in dict_to_convert.items()} |
def create_unique_col_names(col_names):
"""
Given a list/array of column names, make each unique by appending
an integer to the end.
Returns: list (each element being a str)
"""
i = 0
cols_unique = []
for col in col_names:
col_unique = f"{col}_{i}"
cols_unique.append(col... |
def slugify(elements, connector):
"""
Get a string with all the elements connected by connector
:param elements: a sequence of elements
:param connector: a single character serves as a connector between elements
:return: the connected string
"""
return connector.join([str(x) for x in sorted(... |
def _limitSize(message_list, char_limit=450):
"""Returns a list of strings within a certain character length.
Args:
* message_list (List[str]) - The message to truncate as a list
of lines (without line endings).
"""
hint = ('**The complete output can be'
' found at the bottom of the presu... |
def pascal_triangle(n):
"""Computes N rows of Pascal's Triangle"""
pascal = [[1]]
for _ in range(n - 1):
pascal += [[1] + [pascal[-1][i] + pascal[-1][i + 1]
for i in range(len(pascal[-1]) - 1)] + [1]]
return pascal if n > 0 else [] |
def valid_role(role):
"""
Args:
role (str): name of a role
Returns:
Bool: True if the role is not administrative
"""
return role not in [
'userAdminAnyDatabase',
'dbAdminAnyDatabase'
'dbAdmin',
'dbOwner',
'userAdmin',
'clusterAdmin',
... |
def split_opts(seq):
"""Splits a name from its list of options."""
parts = seq.split('::')
name, opts = parts[0], dict()
for x in map(lambda x: x.split(':'), parts[1:]):
for y in x:
try:
opt, val = y.split('=')
except ValueError:
opt, val =... |
def kernel_sort(kernel: dict, values):
"""
Sort the elements of the kernel passed in in ascending order.
:param kernel: the kernel of the problem
:type kernel: dict
:param values: the values of variable in the kernel
:return: The variables sorted occording to their values
:rtype: list
"... |
def echo(message):
"""
Echos a message back to the client, splitting off
a leading "ECHO ".
"""
_, msg = message.split(' ', 1)
return msg |
def time_based(t, eta_init, last_eta, d = 0.01):
"""Time-based learning rate with decay d."""
return last_eta/(1+d*t) |
def RoundFloat(Float: float, Precision: int) -> str:
""" Rounds the Float to the given Precision and returns It as string. """
return f"{Float:.{Precision}f}" |
def unique_seq(seq):
"""
Deduplicate sequence and reserve elements order.
:param seq:
:return:
"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] |
def clamp_number(num, a, b):
"""
Clamps num within the inclusive range specified by the boundary values a and b.
If num falls within the range, return itself. Otherwise, return the nearest number in the range.
"""
return max(min(num, max(a, b)), min(a, b)) |
def float_or_none(string):
""" Returns float number iff string represents one, else return None. TESTS OK 2020-10-24. """
try:
return float(string)
except (ValueError, TypeError):
return None |
def convert_tz_offset_to_tz_seconds(
tz_offset
):
"""Convert timezone offset to seconds.
Args:
tz_offset:
Returns:
"""
int_offset = int(tz_offset)
int_hours = int(int_offset / 100)
int_minutes = int(int_offset % 100)
return (int_hours * 3600) + (int_minutes * 60) |
def wrap_command_str(in_str, max_width, indent):
"""Commands ending with semicolon are split with a carriage return after
semicolon. Each command is split as necessary to not overrun the end
of the line by splitting before an option.
"""
max_width = max_width - indent
# split commands a... |
def decode_text (text):
"""Decodes a string from HTML."""
output = text
output = output.replace('\\n', '\n')
output = output.replace('\s', '\\')
output = output.replace('<', '<')
output = output.replace('>', '>')
output = output.replace('"', '"')
return output |
def cut(deck, N):
"""cut N cards"""
newdeck = deck[N:] + deck[:N]
return newdeck |
def parse_price(price: float) -> float:
"""Parse price."""
if price <= 0:
raise ValueError("Price should be positve")
return price |
def valid(circuit_string, param):
""" checks validity of parameters
Parameters
----------
circuit_string : string
string defining the circuit
param : list
list of parameter values
Returns
-------
valid : boolean
Notes
-----
All parameters are considered va... |
def glsl_file_type_value(op):
"""Gets file type value for given file type."""
if op == "vertex":
return 0
elif op == "geometry":
return 1
elif op == "fragment":
return 2
raise RuntimeError("unknown GLSL file type: %s" % (op)) |
def filter_classes(classes, included_namespaces=(), included_ontologies=()):
"""Filter out classes whos namespace is not in `included_namespaces`
or whos ontology name is not in one of the ontologies in
`included_ontologies`.
`classes` should be a sequence of classes.
"""
filtered = set(classes... |
def check_max_drawdown(
initial_balance: float, current_balance: float, max_drawdown: float
) -> bool:
"""
check if the loss exceed the max given drawdown
"""
percentage = 0.01
max_drawdown_percentage = max_drawdown * percentage
is_in_drawdown = False
if current_balance < (initi... |
def mul_or_none(a, b):
"""Return the element wise multiplicative of the inputs.
If either input is None, we return None.
Args:
a: A tensor input.
b: Another tensor input with the same type as a.
Returns:
None if either input is None. Otherwise returns a * b.
"""
if a is None or b is None:
... |
def none_to_empty(val):
"""Convert None to empty string.
Necessary for fields that are required POST but have no logical value.
"""
if val is None:
return ""
return val |
def breakCentroidTie(attribute_variants, min_dist_indices):
"""
Finds centroid when there are multiple values w/ min avg distance
(e.g. any dupe cluster of 2) right now this selects the first among a set of
ties, but can be modified to break ties in strings by selecting the longest string
"""
... |
def remove_dupes(items):
"""
make sure no item appears twice in list
i.e. filter for any duplicates
"""
clean = []
for i in items:
if not i in clean:
clean.append(i)
return clean |
def separate_callback_data(data):
"""Separa i dati in entrata"""
return [i for i in data.split(";")] |
def process_opts(player, player_opts):
"""Add data to the options to make them human readable."""
results = []
for opt in player_opts:
res = list(opt)
if opt[0] == "ATTACK":
# Get move name
res.append(player.game_state.gamestate["active"].moves[opt[1]]["name"])
... |
def _is_numeric(x):
"""Return true if x is a numeric value, return false else
Parameters
----------
x : str
string to test whether something is or not a number
Returns
-------
bool
whether something is or not a number
"""
try:
float(x)
except Exception:
... |
def start_worker(scopeURL: str) -> dict:
"""
Parameters
----------
scopeURL: str
"""
return {"method": "ServiceWorker.startWorker", "params": {"scopeURL": scopeURL}} |
def get_well_name(well_id, plate_dims):
"""Function that maps well numerical id to name (label)
Parameters
----------
well_id : int
well id on plate eg: 234
plate_dims : np array
dimensions of plate
Returns
-------
index : str
coordinate label of the well, eg: 'B10'... |
def parse_object(response, infotype):
"""Parse the results of an OBJECT command"""
if infotype in ("idletime", "refcount"):
return int(response) if response else None
return response |
def is_number(value: str) -> int:
""""
Determines the number type for the property value
:return 0 for text, 1 for float, 2 for integer
"""
try:
float_number = float(value)
except ValueError:
return 0
else:
if float_number.is_integer():
return 2
re... |
def namelist(names):
"""
Function which returns a new list with proper formatting between names.
:param names: an array containing hashes of names
:return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand.
"""
list... |
def listMountpoint(rc,output,outerr,parseParamList,Logger):
"""
Return target volume of a mount point
"""
mountpoint=""
return mountpoint |
def _iter_tolist(x):
"""Transforms recursively a list of iterables into a list of list."""
if hasattr(x, '__iter__'):
return list(map(_iter_tolist, x))
else:
return x |
def is_uuid(uuid):
"""
Check if value is a proper uuid
:param uuid: string to check
:return: bool
"""
import re
UUID_PATTERN = re.compile(r'^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}$', re.IGNORECASE)
if UUID_PATTERN.match(uuid):
return True
return False |
def get_res(output: bytes) -> bytes:
"""Support function to get the 64-bit signed response (RES) from OUT2, the
output of 3GPP f2 function.
:param output: OUT2
:returns: OUT2[64] .. OUT2[127]
"""
lower_edge = 8 # = ceil(64/8)
upper_edge = 16 # = ceil(127/8)
return output[lower_edge:up... |
def CALL(parent, r):
"""Call a function of certain module"""
if len(r) >= 2:
split = parent.robot._split_module(r[0])
return parent.robot.callModule(split[1], split[2], split[0], r[1], r[2:])
return '' |
def _env(env):
"""Parse multiline KEY=VALUE string into dict."""
return dict((key.strip(), val)
for line in env.strip().splitlines()
for key, _, val in [line.partition('=')]) |
def as_phar(frag_id, points):
"""Return pharmacophore in \*.phar format.
See `align-it <http://silicos-it.be.s3-website-eu-west-1.amazonaws.com/software/align-it/1.0.4/align-it.html#format>`_ for format description.
Args:
frag_id (str): Fragment identifier
points (list): List of points whe... |
def get_header_info(headers):
"""
gets crucial header info such as how many requests left and when it resets
"""
try:
return int(headers['X-RateLimit-Remaining']), int(headers['X-RateLimit-Reset'])
except KeyError:
return None, None |
def _get_int(p_str):
"""Convert 2 hex chars into a 1 byte int.
a3 --> 163
"""
l_int = 0
try:
l_int = int(p_str, 16)
except:
l_int = 0
return l_int |
def determine_pubmed_xml_type(xmlstr):
""" Returns string "type" of pubmed article XML based on presence of expected strings.
Possible returns:
'article'
'book'
'unknown'
:param xmlstr: xml in any data type (str, bytes, unicode...)
:return typestring: (str)
:rtype: str
... |
def splitevery(s, n):
"""splits a string every num chars and return the list"""
return [s[x:x+n] for x in range(0,len(s), n)] |
def compress(lhs_label, rhs_label):
"""Combine two labels where the rhs replaces the lhs. If the rhs is
empty, assume the lhs takes precedent."""
if not rhs_label:
return lhs_label
label = list(lhs_label)
label.extend([None]*len(rhs_label))
label = label[:len(rhs_label)]
for i in r... |
def get_midpoint(point_a, point_b):
"""Finds the midpoint of two points.
Args:
point_a: Tuple (x, y) point.
point_b: Tuple (x, y) point.
Returns:
Tuple of (x, y) midpoint.
"""
x1, y1 = point_a
x2, y2 = point_b
return (x1 + x2) / 2, (y1 + y2) / 2 |
def is_iterable(obj):
"""Check if `obj` is iterable."""
try:
iter(obj)
except TypeError:
return False
else:
return True |
def get_linked_info(issue):
"""
for the given issue, if "[Dd]uplicates: <org>/<repo>#XXX
exists in PR body, returns the parsed org/repo/number
Else return None
"""
body = issue["body"].lower()
if "\nduplicates" in body:
_, url_string = body.split("\nduplicates ")
next_newlin... |
def ceil(value):
"""
Rounds a number upward to its nearest integer
Arguments
---------
value: number to be rounded upward
"""
return -int(-value//1) |
def match_subject(subject, check):
"""Check if `check` does match the `subject`
:param dict|object subject:
:param dict|object check:
:return bool:
"""
if check is None:
return True
if isinstance(subject, dict) and isinstance(check, dict):
for key, value in check.items():
... |
def pos_func(val):
"""
Force positive values only
"""
value = max(val, 0)
return value |
def secuenced_words(txt):
"""
Function identifies the three words most
often repeated as a group, regardless of
the words order in the group
"""
word_list = txt.split()
collector = dict()
for idx in range(1, len(word_list)-1):
item = frozenset([word_list[idx-1], wor... |
def is_iterable(obj):
"""Return true if the object is iterable."""
try:
_ = iter(obj)
except Exception: # pylint: disable=broad-except
return False
return True |
def int_to_bin(i, w, lend=False):
"""
Converts integer to binary tuple.
Parameters
----------
i : int
Integer to convert.
w : int
Width of conversion
lend : bool
Endianness of returned tuple, helpful for iterating.
Returns
-------
tuple of bo... |
def get_direct_prop(obj, fields):
""" Gets a model property of an object """
# shouldn't happen, but whatever
if len(fields) == 0:
return obj
# if we have a single field to get
elif len(fields) == 1:
field = fields[0]
# we may have a display getter
try:
... |
def merge_relevancies(a, b):
"""
The second element of the returned tuple is True
iff the relevancies are compatible and can be merged.
Two relevancies are incompatible if one of them is a
"strong" one, i.e. either "harmful" or "vital", and
the other is "weak" and has the opposite sign ("relevan... |
def strip_extra_char(s):
"""
Return a processed string stripped of return characters
"""
return s.strip('\n') |
def fix_name(basename):
"""Fixes illegitimate basename, deprecated."""
if len(basename) < 3:
return '{}0{}'.format(*basename)
return basename |
def part2(data):
"""Find the product of trees hit in 5 runs at different slopes."""
terrain = data.splitlines()
product = 1
for dc, dr in [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]:
column, trees = dc, 0
for row in range(dr, len(terrain), dr):
line = terrain[row]
tr... |
def hexToTuple(hex_colour):
"""
Convert hex #RRGGBB to an (R, G, B) tuple
"""
hex_colour = hex_colour.strip()
if hex_colour[0] == '#':
hex_colour = hex_colour[1:]
if len(hex_colour) != 6:
raise ValueError("input #%s is not in #RRGGBB format" % hex_colour)
(rs, gs, bs) = hex_c... |
def getClassfromFileName(fname):
"""
Get a class name from the filename. Assume that the filename
is formed from the classname + EvHist.csv, strip any directory
names and then return the class preface in what is left.
"""
if '/' in fname:
fileName = fname[fname.rindex('/')+1:]
else:... |
def look_for_card_in_collections(cardname, collections, cardset = None):
"""
"""
resultset = None
for collection in collections:
resultset = collection.look_for_card(cardname, cardset, resultset)
return(resultset) |
def read_from_downstream(boundary, data):
""" This functions reads data from the raw downstream channel, and pulls out messages based on
the specified boundary.
:param boundary: boundary used in message
:param data: current data in the downchannel stream
:return: (new_data, data) new_dat... |
def minkowski_distance(x, y, p=2):
"""
Calculates the minkowski distance between two points.
:param x: the first point
:param y: the second point
:param p: the order of the minkowski algorithm. If *p=1* it is equal
to the manhatten distance, if *p=2* it is equal to the euclidian
dis... |
def list_to_csv(lst):
"""
Convert list to string separated by comma
:param lst: Python list
:return: string
"""
return '"' + '","'.join(lst) + '"' |
def tryConvertToNumeric(value):
"""Convert str to float or int. Returns what should be expected, t.y.:
if str is float, int will fail and float will be returned;
if str is int, float and int will succeed, returns int;
if any of these fail, returns value"""
floatVal = None
intVal = None
... |
def to_float(str):
"""
This function tries to convert a string into a float.
:param str: a string
:return: a float or None
"""
try:
return float(str)
except:
return None |
def strip_white_space(value: str) -> str:
"""Strip whitespace from form input."""
if not value:
return value
return value.strip() |
def mock_oauth2(pem):
"""Mock OAuth2 params for the mock app"""
mock_params = dict(
server="FOO",
issuers=["https://login.elixir-czech.org/oidc/"],
userinfo="mock_oidc_server", # Where to send access token to view user data (permissions, statuses, ...)
audience=["audience"],
... |
def _fix_base64_padding(data: bytes) -> bytes:
"""Extend the base64 padding until it's correct. This is needed for some
forms of URL-safe base64 which do not include padding.
"""
missing_padding = len(data) % 4
if missing_padding:
data += b'=' * (4 - missing_padding)
return data |
def select_pivot_column(z):
"""
Pick one variable that increases the objective
"""
for i, zi in enumerate(z):
if zi > 0:
return i + 1
else:
return None |
def GetPides(mali, id1, ids, first_res, last_res):
"""calculate pid between sequence id1 and all others in ids."""
result = []
sequence1 = mali[id1][first_res:last_res]
for id2 in ids:
sequence2 = mali[id2][first_res:last_res]
# calculate percent identity - gaps treated as separate ch... |
def escape_strings(escapist: str) -> str:
"""Escapes strings as required for ultisnips snippets
Escapes instances of \\, `, {, }, $
Parameters
----------
escapist: str
A string to apply string replacement on
Returns
-------
str
The input string with all defined replace... |
def _recurse_binary_exponentiation(num, power):
"""
Recursively calculate num**power quickly (via binary exponentiation).
Helper function. We did parameter checks before so that we don't have to
do them inside every recursive call.
"""
if power == 1:
return num
num_squared = n... |
def recursive_combat( decks ):
"""
Plays recursive combat game based on the additional rules defined in
Part 2.
"""
history = set()
rounds = 1
while all( [ len(deck)!=0 for deck in decks ] ):
current_decks = ( ','.join( str(card) for card in decks[0] ),
','.... |
def _lat_heimisphere(latitude):
"""Return the hemisphere (N, S or '' for 0) for the given latitude."""
if latitude > 0:
hemisphere = ' N'
elif latitude < 0:
hemisphere = ' S'
else:
hemisphere = ''
return hemisphere |
def PageNotFound(e): # pylint: disable=unused-argument
"""Return a custom 404 error."""
return 'Sorry, Nothing at this URL.', 404 |
def add_prefix(prefix, name):
"""Adds prefix to name."""
return "/".join((prefix, name)) |
def update_entity_list(entity_list, solution_found, normalized_text, solution_label_matches_entity):
""" Put the correct candidate in the first position of the candidates list."""
updated_list, entity_perfect_matches = list(), list()
correct = entity_list[solution_found]
del entity_list[solu... |
def cleanup_header(lines_text):
"""
This function cleans up some lines of text contained in a list of strings.
:param lines_text: lines of text
:return: header of the file "cleaner"
Example:
>>> cleanup_header(['# hello',"\t,# ciao"])
['hello', 'ciao']
"""
lines_text = [s.replace("#... |
def sphere(individual):
"""Sphere test objective function.
"""
return sum(x**2 for x in individual) |
def is_parent_of(page1, page2):
"""
Determines whether a given page is the parent of another page
Example:
{% if page|is_parent_of:feincms_page %} ... {% endif %}
"""
if page1 is None:
return False
return (page1.tree_id == page2.tree_id and
page1.lft < page2.lft a... |
def gen_Command(drone_id, state):
"""Create a command entity."""
command = {
"@type": "Command",
"DroneID": drone_id,
"State": state
}
return command |
def str_recurse(features):
"""
Helper function to recursively convert "base elements" to strings while leaving datastructures intact
:param features: item or collection of items to convert to strings
:return: string representation of features where datastructures are preserved
"""
if type(featur... |
def to_int(num):
"""
Converts 'num' to int representation in string
or to "None" in case of None.
"""
if num is None:
return "None"
return "{:.0f}".format(num) |
def to_points(string):
""" Turn e.g. '#.#\n..#\n' into a set of (x,y) points. """
points = set()
lines = string.strip().split('\n')
_n_rows = len(lines)
_n_cols = len(lines[0])
for row in range(_n_rows):
for column in range(_n_cols):
if lines[row][column] == '#':
... |
def angle_difference( theta_1, theta_2 ):
"""
Returns the absolute difference between two angles
@param theta_1 - first angle [degrees]
@param theta_2 - second angle [degrees]
"""
if not isinstance( theta_1, float):
raise TypeError("theta_1 not {}, it's {}".format(float, type(theta_1)))... |
def round_list(float_list):
"""Rounds a list of floats and returns a list of integers."""
return [round(i) for i in float_list] |
def header(ntasks, nlifetimes, lifetimes) -> str:
"""The global-fit input file header
"""
lines = []
lines.append("Global fit input file")
lines.append(f"Number of tasks = {ntasks}")
lines.append(f"Global variables = {nlifetimes}")
for i in range(len(lifetimes)):
lines.append(f"t{i}"... |
def expanded_shape(*shapes, side='left'):
"""Expand input shapes according to broadcasting rules
Parameters
----------
*shapes : sequence[int]
Input shapes
side : {'left', 'right'}, default='left'
Side to add singleton dimensions.
Returns
-------
shape : tuple[int]
... |
def lazy_begin(*bodys):
"""Racket-like begin: run bodys in sequence, return the last return value.
Lazy; each body must be a thunk (0-argument function), to delay its evaluation
until begin() runs.
f = lambda x: lazy_begin(lambda: print("hi"),
lambda: 42*x)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.