content
stringlengths 42
6.51k
|
|---|
def inherit_docstrings(cls):
"""Inherit docstrings from parent class"""
from inspect import getmembers, isfunction
for name, func in getmembers(cls, isfunction):
if func.__doc__: continue
for parent in cls.__mro__[1:]:
if hasattr(parent, name):
func.__doc__ = getattr(parent, name).__doc__
return cls
|
def tokenize(s):
""" Converts a string to list of tokens. """
return s.replace('(', ' ( ').replace(')', ' ) ').split()
|
def sanitize_command_options(options):
"""
Sanitizes command options.
"""
multiples = [
'badges',
'exclude_badges',
]
for option in multiples:
if options.get(option):
value = options[option]
if value:
options[option] = [v for v in value.split(' ') if v]
return options
|
def checkBuildingType(line):
"""Checks if the building type is a house, or if the item is being bought or sold"""
if " is buying " in line:
return "buy"
elif " is selling " in line:
return "sell"
else:
return "house"
|
def convertToBase10(numList, base):
"""
Parses numList and returns the total base 10 value in the list.
"""
negative = False
# If numList contains a negative, then remove it...
# and indicate it is negative so the algorithm can continue.
if numList[0] == '-':
numList.remove('-')
negative = True
numList = numList[::-1]
if negative:
for i in range(len(numList)):
numList[i] *= -1
numList[i] *= (base ** i)
else:
for i in range(len(numList)):
numList[i] *= base ** i
return sum(numList)
|
def get_tree_leaf(element, branch):
"""
Return the nested leaf element corresponding to all dictionnary keys in
branch from element
"""
if isinstance(element, dict) and len(branch) > 0:
return get_tree_leaf(element[branch[0]], branch[1:])
else:
return element
|
def nifty_power_of_ten(num):
"""Return 10^n: 10^n > num; 10^(n-1) <= num."""
result = 10
while result <= num:
result *= 10
return result
|
def get_proxy_column_names(protected_columns, noise_param, noise_index=''):
"""Gets proxy column names."""
return [
'PROXY' + noise_index + '_' + '%0.2f_' % noise_param + column_name
for column_name in protected_columns
]
|
def _wrap_metric(metric_name: str) -> str:
"""Put a newline on "::" for metric names.
Args:
metric_name: metric name.
Returns: wrapped metric name.
"""
if "::" in metric_name:
return "<br>".join(metric_name.split("::"))
else:
return metric_name
|
def getattr_call(obj, attr_name, *args, **vargs):
"""
Call the getter for the attribute `attr_name` of `obj`.
If the attribute is a property, pass ``*args`` and ``**kwargs`` to the getter (`fget`); otherwise, ignore them.
"""
try:
return getattr(type(obj),attr_name).fget(obj,*args,**vargs)
except AttributeError:
return getattr(obj,attr_name)
|
def readFile(fileName):
"""Read all file lines to a list and rstrips the ending"""
try:
with open(fileName) as fd:
content = fd.readlines()
content = [x.rstrip() for x in content]
return content
except IOError:
# File does not exist
return []
|
def create_table_sql(flds2keep, table):
"""
Arguments:
- `flds`:
- `table`:
"""
fld_names = ["[{}]".format(x) for x in flds2keep]
fld_list = ", ".join(fld_names)
sql = "create table tmp as select {} from [{}];".format(fld_list, table)
return sql
|
def reduce_multiline(string):
"""
reduces a multiline string to a single line of text.
args:
string: the text to reduce
"""
string = str(string)
return " ".join([item.strip()
for item in string.split("\n")
if item.strip()])
|
def _check_if_contr_in_dict(consecutive, sent, contractions):
"""
Args:
- consecutive = a list of consecutive indices at which sent contains
contractions.
- sent = a (word, pos_tag) list, whereby the words make up a sentence.
- contractions = the contractions dictionary.
Returns:
- the list of possible expansions.
Raises:
- ValueError if the contractions have questionable capitalization,
which will not be reproduced upon expansion since that would be too
cumbersome.
"""
# combine all the words that are expanded, i.e. one word
# before the first apostrophe until the last one with an
# apostrophe
contr = [word_pos[0] for word_pos
in sent[consecutive[0]:consecutive[-1]+1]]
# if the expanded string is one of the known contractions,
# extract the suggested expansions.
# Note that however many expansions there are, expanded is a list!
if ''.join(contr) in contractions:
expanded = contractions[''.join(contr)]
# the dictionary only contains non-capitalized replacements,
# check for capitalization
elif ''.join(contr).lower() in contractions:
if ''.join(contr)[0].isupper() or ''.join(contr)[1].isupper():
# capitalize the replacement in this case
expanded = [a.capitalize() for a in
contractions[''.join(contr).lower()]]
else:
raise ValueError("Weird capitalization error! Please use standard "
"english grammar.")
else:
# if the replacement is unknown skip to the next one
return None, contr
return expanded, contr
|
def artf_in_scan(scan, width, img_x_min, img_x_max, verbose=False):
"""return precise artefact angle and distance for lidar & camera combination"""
if scan is None:
return 0, 0
# the scan is already in mm, so angle is modified to int deg*100, ready to send
x_min, x_max = img_x_min, img_x_max
angular_resolution = len(scan) / 270
mid_index = len(scan) // 2
camera_fov_deg = 60
deg_max = camera_fov_deg * (width / 2 - x_min) / width # small value on the left corresponds to positive angle
deg_min = camera_fov_deg * (width / 2 - x_max) / width
tolerance = int(5 * angular_resolution) # in paritular the valve is detected with offset
left_index = mid_index + int(deg_min * angular_resolution) - tolerance
right_index = mid_index + int(deg_max * angular_resolution) + tolerance
# if verbose:
# print('SubSelection', deg_min, deg_max, left_index, right_index, scan[left_index:right_index])
tmp = [x if x > 0 else 100000 for x in scan]
dist_mm = min(tmp[left_index:right_index])
index = left_index + tmp[left_index:right_index].index(dist_mm)
deg_100th = int(((index / angular_resolution) - 135) * 100)
return deg_100th, dist_mm
|
def number_to_base(n, base):
"""Function to convert any base-10 integer to base-N."""
if base < 2:
raise ValueError('Base cannot be less than 2.')
if n < 0:
sign = -1
n *= sign
elif n == 0:
return [0]
else:
sign = 1
digits = []
while n:
digits.append(sign * int(n % base))
n //= base
return digits[::-1]
|
def count_paths_recursive(graph, node_val, target):
"""A more conventional recursive function (not a recursive generator)"""
if node_val >= target:
return 1
total = 0
for next_node in graph[node_val]:
total += count_paths_recursive(graph, next_node, target)
return total
|
def compare_server_id(x,y):
"""Comparison function for use with builtin 'sorted'. Sorts the server serverId
in numeric order."""
ccard_x = int(x['serverId'].split('/')[0])
ccard_y = int(y['serverId'].split('/')[0])
return ccard_x - ccard_y
|
def fail_message(user, msg, groups):
"""
The message to be displayed to the user when they fail the LDAP validation
Override this method if you want your own custom message
Args:
user (str): The user ID that was used for the LDAP search
msg (errbot.backends.base.Message): The message from the bot that triggered the LDAP lookup
groups (list): The list og group(s) in which the user was searched
Returns:
str: The formatted failure message
"""
return f"Sorry, ```{user}``` is not permitted to execute the command ```{msg}``` as you are not a member of ```{','.join(groups)}```"
|
def _extract_git_revision(prerelease):
"""Extracts the git revision from the prerelease identifier.
This is assumed to be the last `.` separated component.
"""
return prerelease.split(".")[-1]
|
def human_check(string):
"""
The API is actually terribly unreliable at providing information on
whether an entity is human or corporate. What is consistent is that
companies are provided in UPPER CASE and humans provided in the format
"SURNAME, Othernames". This takes advantage of this to identify if a
record is human.
"""
for i in string:
if i.islower():
return "Individual"
return "Corporate"
|
def get_source_name(module_type, name, prefix_override, suffix,
alternative_suffix):
"""Generate source file name by type."""
if (module_type == 'lib'
or module_type == 'lib64') and not prefix_override:
if not name.startswith('lib'):
name = 'lib' + name
alias = ''
if module_type == 'java_library' and alternative_suffix:
alias = '%s%s' % (name, alternative_suffix)
if suffix:
name = '%s%s' % (name, suffix)
if module_type == 'none':
name = ''
return name, alias
|
def GetSyslogConfMultiHomedHeaderString(WorkspaceID):
"""
Return the header for the multi-homed section from an rsyslog conf file
"""
return '# OMS Syslog collection for workspace ' + WorkspaceID
|
def row(row_no) -> slice:
"""Returns slice object for appropriate row.
Note: Can this be memoised? Would it help in any way?
"""
start = 0 + row_no * 9
stop = 9 + row_no * 9
return slice(start, stop)
|
def add_commas(number):
"""1234567890 ---> 1,234,567,890"""
return "{:,}".format(number)
|
def sanitize_branch_name(branch_name: str) -> str:
"""
replace potentially problematic characters in provided string, a branch name
e.g. copr says:
Name must contain only letters, digits, underscores, dashes and dots.
"""
# https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string
offenders = "!@#$%^&*()+={[}]|\\'\":;<,>/?~`"
for o in offenders:
branch_name = branch_name.replace(o, "-")
return branch_name
|
def key_for_issues(issue):
"""Generate a string search key for a Jira issues."""
return u' '.join([
issue['key'],
issue['summary']])
|
def list_diff(list_a, list_b):
"""
Return the items from list_b that differ from list_a
"""
result = []
for item in list_b:
if item not in list_a:
result.append(item)
return result
|
def selection_sort(nums_array: list) -> list:
"""
Selection Sort Algorithm
:param nums_array: list
:return nums_array: list
"""
for i in range(len(nums_array)):
min_index = i
for j in range(i + 1, len(nums_array)):
if nums_array[j] < nums_array[min_index]:
min_index = j
if min_index != i:
temp = nums_array[i]
nums_array[i] = nums_array[min_index]
nums_array[min_index] = temp
return nums_array
|
def merge_dict(data, *override):
"""
Merges any number of dictionaries together, and returns a single dictionary
Usage::
>>> util.merge_dict({"foo": "bar"}, {1: 2}, {"Tx": "erpa"})
{1: 2, 'foo': 'bar', 'Tx': 'erpa'}
"""
result = {}
for current_dict in (data,) + override:
result.update(current_dict)
return result
|
def is_prime(x):
"""Given a number x, returns True if it is prime; otherwise returns False"""
num_factors = 0
if type(x) != int:
return False
for n in range(2,x+1):
if x%n == 0:
num_factors +=1
if num_factors == 1:
return True
return False
|
def fuel_requirement(module_mass):
"""
Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module,
take its mass, divide by three, round down, and subtract 2.
:param module_mass:
:return: fuel_requirement
"""
return module_mass // 3 - 2
|
def cumulative_sum(array):
"""Write a function that takes a list of numbers and returns the cumulative sum; that
is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For
example, the cumulative sum of [1, 2, 3] is [1, 3, 6]."""
res = []
val = 0
for elem in array:
val += elem
res.append(val)
return res
|
def grow(string, start, end):
"""
starts with a 0 or 1 length palindrome and try to grow bigger
"""
while (start > 0 and end < len(string)
and string[start - 1].upper() == string[end].upper()):
start -= 1;
end += 1
return (start, end)
|
def xyzs2xyzfile(xyzs, filename=None, basename=None, title_line=''):
"""
For a list of xyzs in the form e.g [[C, 0.0, 0.0, 0.0], ...] convert create a standard .xyz file
:param xyzs: List of xyzs
:param filename: Name of the generated xyz file
:param basename: Name of the generated xyz file without the file extension
:param title_line: String to print on the title line of an xyz file
:return: The filename
"""
if basename:
filename = basename + '.xyz'
if filename is None:
return 1
if filename.endswith('.xyz'):
with open(filename, 'w') as xyz_file:
if xyzs:
print(len(xyzs), '\n', title_line, sep='', file=xyz_file)
else:
return 1
[print('{:<3}{:^10.5f}{:^10.5f}{:^10.5f}'.format(*line), file=xyz_file) for line in xyzs]
return filename
|
def countName(dictname):
"""Return the underlying key used for access to the number of items
in the dictlist named dictname.
"""
return (dictname,"N")
|
def IsInRangeInclusive(a, low, high):
"""
Return True if 'a' in 'low' <= a >= 'high'
"""
return (a >= low and a <= high)
|
def combinatrix(combos):
""" pass """
dias_visualizacion= [
#Lunes,Martes,mierc,jueves,viernes,sabado
1 ,2 ,3 ,4 ,5 ,6, #8-9
7 ,8 ,9 ,10 ,11 ,12,
13 ,14 ,15 ,16 ,17 ,18,
19 ,20 ,21 ,22 ,23 ,24,#11-12
25 ,26 ,27 ,28 ,29 ,30,
31 ,32 ,33 ,34 ,35 ,36,
37 ,38 ,39 ,40 ,41 ,42,#14-15
43 ,44 ,45 ,46 ,47 ,48,
49 ,50 ,51 ,52 ,53 ,54,
55 ,56 ,57 ,58 ,59 ,60,#17-18
61 ,62 ,63 ,64 ,65 ,66,
67 ,68 ,69 ,70 ,71 ,72,
73 ,74 ,75 ,76 ,77 ,78,#20-21
79 ,80 ,81 ,82 ,83 ,84,
]
pass
return dias_visualizacion
|
def __color(mode, string, color):
"""
mode escape sequence code for background or foreground color
string string to be formatted
color used color
"""
if isinstance(color, int):
escape = "\x1b[{0}8:5:{1}m".format(mode, color)
elif isinstance(color, tuple):
r, g, b = color
escape = "\x1b[{0}8;2;{1};{2};{3}m".format(mode, r, g, b)
elif isinstance(color, str):
if not color.startswith('#'):
try:
color = int(color)
return __color(mode, string, int(color))
except ValueError:
return string
r = int(color[1:3], 16)
g = int(color[3:5], 16)
b = int(color[5:7], 16)
escape = "\x1b[{0}8;2;{1};{2};{3}m".format(mode, r, g, b)
else:
return string
return escape + string.replace("\x1b[0m", '') + "\x1b[0m"
|
def _func_worker_ranks(workers):
"""
Builds a dictionary of { (worker_address, worker_port) : worker_rank }
"""
return dict(list(zip(workers, range(len(workers)))))
|
def mapToRightLanguageCode(languageField, languageIsoCodesDictionary):
""" map the language codes to the right ISO 639 3 letter codes.
"""
if languageField in languageIsoCodesDictionary:
langIso = languageIsoCodesDictionary[languageField]
else:
langIso = languageField
langIso = langIso.rstrip()
return langIso
|
def sizeof(num, suffix='B'):
""" Utility method to convert a file size in bytes to a human-readable format
Args:
num (int): Number of bytes
suffix (str): Suffix for 'bytes'
Returns:
str: The formatted file size as a string, eg. ``1.21 GB``
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Y', suffix)
|
def tuple_get(string, count=None):
"""
Parse a tuple string like "(1024;768)" and return strings of the elements
"""
if not string:
return None
string = string.strip()
assert string.startswith("(") and string.endswith(")")
string = string[1:-1]
res = [x.strip() for x in string.split(";")]
if count is not None: # be strict
assert len(res) == count
return res
|
def _are_scopes_sufficient(authorized_scopes, sufficient_scopes):
"""Check if a list of authorized scopes satisfies any set of sufficient scopes.
Args:
authorized_scopes: a list of strings, return value from oauth.get_authorized_scopes
sufficient_scopes: a set of sets of strings, return value from _process_scopes
"""
for sufficient_scope_set in sufficient_scopes:
if sufficient_scope_set.issubset(authorized_scopes):
return True
return False
|
def subplot_shape(size):
"""
Get the most square shape for the plot axes values.
If only one factor, increase size and allow for empty slots.
"""
facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0]
# re-calc for prime numbers larger than 3 to get better shape
while len(facts) == 1:
size += 1
facts = [[i, size//i] for i in range(1, int(size**0.5) + 1) if size % i == 0]
sum_facts = [sum(i) for i in facts]
smallest = min(sum_facts)
shape = facts[sum_facts.index(smallest)]
return shape
|
def permissions_string(permissions, known_permissions):
"""Return a comma separated string of permission changes.
:param permissions: A list of strings, or ``None``. These strings can
exclusively contain ``+`` or ``-`` prefixes, or contain no prefixes at
all. When prefixed, the resulting string will simply be the joining of
these inputs. When not prefixed, all permissions are considered to be
additions, and all permissions in the ``known_permissions`` set that
aren't provided are considered to be removals. When None, the result is
``+all``.
:param known_permissions: A set of strings representing the available
permissions.
"""
to_set = []
if permissions is None:
to_set = ['+all']
else:
to_set = ['-all']
omitted = sorted(known_permissions - set(permissions))
to_set.extend('-{}'.format(x) for x in omitted)
to_set.extend('+{}'.format(x) for x in permissions)
return ','.join(to_set)
|
def func_ab(a=2, b=3):
"""func.
Parameters
----------
a, b: int, optional
Returns
-------
None, None
a, b: int
None, None, None, None
"""
return None, None, a, b, None, None, None, None
|
def IsImageVersionStringComposerV1(image_version):
"""Checks if string composer-X.Y.Z-airflow-A.B.C is Composer v1 version."""
return (not image_version or image_version.startswith('composer-1.') or
image_version.startswith('composer-latest'))
|
def update_position(xc, yc, vxc, vyc, tstep):
"""Returns the new position after a time step"""
xc = xc+vxc*tstep
yc = yc+vyc*tstep
return xc, yc
|
def binary_search(array, query, key=lambda a: a, start=0, end=-1):
"""Python's 'in' keyword performs a linear search on arrays.
Given the circumstances of storing sorted arrays, it's better
for Nyx to use a binary search.
Arguments:
key - filter for objects in the array
start - 0-indexed starting marker on the array to search
end - exclusive ending marker on the array to search
"""
if array is None or len(array) == 0:
return None
# elif len(array) == 1:
# return key(array[0]) == query and array[0] or None
if end == -1:
end = len(array)
elif start >= end:
return None
# print(start, "and", end)
mid = int(start + (end - start) / 2)
# print(mid)
# mid = int(len(array) / 2)
compare_to = key(array[mid]) # Applies lambda to array items.
if query < compare_to:
return binary_search(array, query, key, start, mid)
elif query > compare_to:
return binary_search(array, query, key, mid + 1, end)
else:
return array[mid]
|
def convert_params_to_string(params: dict) -> str:
""" Create a string representation of parameters in PBC format
"""
return '\n'.join(['%s %s' % (key, value) for (key, value) in params.items()])
|
def device_id(obj):
"""Get the device ID
Parameters
----------
obj : dict
A grow or data "object"
Returns
-------
id : str
Device id
"""
return obj['device_id']
|
def pick(seq, func, maxobj=None):
"""Picks the object obj where func(obj) has the highest value."""
maxscore = None
for obj in seq:
score = func(obj)
if maxscore is None or maxscore < score:
(maxscore, maxobj) = (score, obj)
return maxobj
|
def ensure_prefix(string, prefix):
"""Ensure, that a string is prefixed by another string."""
if string[:len(prefix)] == prefix:
return string
return prefix + string
|
def points_to_list(points):
"""Make array of dictionaries as a list.
Args:
points: array of dictionaries - [{'x': x_coord, 'y': y_coord}].
Returns:
list: points as a list.
"""
points_list = []
for point in points:
points_list.append([int(point['x']), int(point['y'])])
return points_list
|
def fpow0(x, n):
"""
Perform recursive fast exponentiation by squaring.
:param x: the base number
:param n: the target power value, an integer
:return: x to the power of n
"""
if n < 0:
return fpow0(1 / x, -n)
if n == 0:
return 1
if x == 0:
return 0
assert n == int(n), "n must be an integer"
return fpow0(x * x, n // 2) if n % 2 == 0 else x * fpow0(x * x, n // 2)
|
def _matrix(n, m, value=None):
"""Utility function to create n x m matrix of a given value"""
el = value if callable(value) else lambda i, j: value
matrix = []
for i in range(n):
row = []
matrix.append(row)
for j in range(m):
row.append(el(i, j))
return matrix
|
def _default_axis_names(n_dims):
"""Name of each axis.
Parameters
----------
n_dims : int
Number of spatial dimensions.
Returns
-------
tuple of str
Name of each axis.
Examples
--------
>>> from landlab.grid.base import _default_axis_names
>>> _default_axis_names(1)
('x',)
>>> _default_axis_names(2)
('y', 'x')
>>> _default_axis_names(3)
('z', 'y', 'x')
"""
_DEFAULT_NAMES = ('z', 'y', 'x')
return _DEFAULT_NAMES[- n_dims:]
|
def create_notify_payload(host, nt, usn, location=None, al=None, max_age=None, extra_fields=None):
"""
Create a NOTIFY packet using the given parameters.
Returns a bytes object containing a valid NOTIFY request.
The NOTIFY request is different between IETF SSDP and UPnP SSDP.
In IETF, the 'location' and 'al' fields serve the same purpose, and can be
provided together (if so, they should point to the same location) or not at
all.
In UPnP, the 'location' field MUST be provided, and 'al' is ignored.
Sending both 'location' and 'al' is the more widely supported option. It
does not, however, mean that all SSDP implementations would accept a packet
with both. Therefore the option to send just one of these fields (or none at
all) is supported.
If in doubt, send both. If your notifications go ignored, opt to not send 'al'.
:param host: The address (IP + port) that the NOTIFY will be sent about. This is usually a multicast address.
:type host: str
:param nt: Notification type. Indicates which device is sending the notification.
:type nt: str
:param usn: Unique identifier for the service. Usually this will be composed of a UUID or any other universal identifier.
:type usn: str
:param location: A URL for more information about the service. This parameter is only valid when sending a UPnP SSDP packet, not IETF.
:type location: str
:param al: Similar to 'location', but only supported on IETF SSDP, not UPnP.
:type al: str
:param max_age: Amount of time in seconds that the NOTIFY packet should be cached by clients receiving it. In UPnP, this header is required.
:type max_age: int
:param extra_fields: Extra header fields to send. UPnP SSDP section 1.1.3 allows for extra vendor-specific fields to be sent in the NOTIFY packet. According to the spec, the field names MUST be in the format of `token`.`domain-name`, for example `myheader.philips.com`. SSDPy, however, does not check this. Normally, headers should be in ASCII - but this function does not enforce that.
:return: A bytes object containing the generated NOTIFY payload.
"""
if max_age is not None and not isinstance(max_age, int):
raise ValueError("max_age must by of type: int")
data = (
"NOTIFY * HTTP/1.1\r\n"
"HOST:{}\r\n"
"NT:{}\r\n"
"NTS:ssdp:alive\r\n"
"USN:{}\r\n"
).format(host, nt, usn)
if location is not None:
data += "LOCATION:{}\r\n".format(location)
if al is not None:
data += "AL:{}\r\n".format(al)
if max_age is not None:
data += "Cache-Control:max-age={}\r\n".format(max_age)
if extra_fields is not None:
for field, value in extra_fields.items():
data += "{}:{}\r\n".format(field, value)
data += "\r\n"
return data.encode("utf-8")
|
def get_cell_from_label(label):
""" get cell name from the label (cell_name is in parenthesis)
it
"""
cell_name = label.split("(")[1].split(")")[0]
if cell_name.startswith("loopback"):
cell_name = "_".join(cell_name.split("_")[1:])
return cell_name
|
def parse_time_params(age_birth, age_death):
"""
Converts simple statements of the age at which an agent is born and the
age at which he dies with certaintiy into the parameters that HARK needs
for figuring out the timing of the model.
Parameters
----------
age_birth : int
Age at which the agent enters the model, e.g., 21.
age_death : int
Age at which the agent dies with certainty, e.g., 100.
Returns
-------
dict
Dictionary with parameters "T_cycle" and "T_age" which HARK expects
and which map to the birth and death ages specified by the user.
"""
# T_cycle is the number of non-terminal periods in the agent's problem
T_cycle = age_death - age_birth
# T_age is the age at which the agents are killed with certainty in
# simulations (at the end of the T_age-th period)
T_age = age_death - age_birth + 1
return {"T_cycle": T_cycle, "T_age": T_age}
|
def flexdefault(arg):
"""Convert string argument to a slice."""
# We want four cases for indexing: None, int, list of ints, slices.
# Use [] as default, so 'in' can be used.
if isinstance(arg, str):
arg = eval('np.s_['+arg+']')
return [arg] if isinstance(arg, int) else arg
|
def work_strategy1(l, Ve, Vr, Vf, wf, wr):
"""
a function that returns the work done by a swimmer if they choose to escape
from a rip current via strategy 1
"""
W1 = ((Ve+Vr)**3)*((l-wf)/Ve) # Calculates work for section swimming in rip channel
W2 = ((Ve+Vf)**3)*(wf/Ve) # Calculates work for section swimming in feeder channel
if l - wf < 0: #Limits Starting distance offshore to be further than the feeder width
return -1
else:
return W1 + W2 # Returns total value of work done for Strategy 1
|
def update(context, uri=None):
"""
*musicpd.org, music database section:*
``update [URI]``
Updates the music database: find new files, remove deleted files,
update modified files.
``URI`` is a particular directory or song/file to update. If you do
not specify it, everything is updated.
Prints ``updating_db: JOBID`` where ``JOBID`` is a positive number
identifying the update job. You can read the current job id in the
``status`` response.
"""
return {"updating_db": 0}
|
def to_upper_snake_case(s: str) -> str:
"""Converts a string from a MixedCaseString to a UPPER_SNAKE_CASE_STRING."""
s = s.upper()
r = ''
for i in range(0, len(s)):
r += s[i] if s[i].isalnum() else '_'
return r
|
def to_internal_byte_order(rpc_byte_order):
"""
Returns a given RPC byte order hash (bytes) to the format expected by
Bitcoin primitives (blocks, transactions, etc.)
"""
return rpc_byte_order[::-1]
|
def text_card_generator(card_details):
"""
Stub card generator monkeypatched into the flight module for testing
boarding card printing
:param card_details: Boarding card details
"""
return "\n".join(card_details.values())
|
def generate_freq_list(d): # dict
"""
Generate a frequency list from a dictionary
"""
total = sum(d.values())
freq_list = sorted(d.items(), key=lambda x: x[1], reverse=True)
return [(index+1, key, value, round(value/total, 2)) for index, (key, value) in enumerate(freq_list)]
|
def format_pydantic_error_message(msg):
"""Format pydantic's error message field."""
# Replace shorthand "str" with "string".
msg = msg.replace("str type expected", "string type expected")
return msg
|
def bubble_sort(array):
"""
Input : list of values
Note :
Compares neighbouring elements and sortes them. Loops through the list multiple times until list is sorted.
Returns : sorted list of values
"""
is_sorted = False
while not is_sorted:
is_sorted = True
for i in range(len(array)-1):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
is_sorted = False
return array
|
def sample_fib(x):
"""Calculate fibonacci numbers."""
if x == 0 or x == 1:
return 1
return sample_fib(x - 1) + sample_fib(x - 2)
|
def get_email_value(operation_definition):
"""Assuming format like: { GetUserByEmail(email: "someemail") { ... } }"""
text_after_email = operation_definition.split('email:')[1]
unquoted_tokens = text_after_email.split('"')
return unquoted_tokens[1]
|
def eager(x):
"""Force eager evaluation of a Thunk, and turn a Tuple into a dict eagerly.
This forces that there are no unbound variables at parsing time (as opposed
to later when the variables may be accessed).
Only eagerly evaluates one level.
"""
if not hasattr(x, 'items'):
# The Thunk has been evaluated already, so that was easy :)
return x
return dict(x.items())
|
def flatten(captions_list):
""" Flatten all the captions into a single list """
caption_list = [
caption for captions in captions_list for caption in captions
]
return caption_list
|
def isIsomorphic(s,t):
"""
Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving
the order of characters. No two characters may map to the same character, but a character
may map to itself.
"""
if len(set(s)) != len(set(t)):
return False
result = {}
for i in range(len(s)):
if s[i] not in result:
result[s[i]] = t[i]
elif result[s[i]] != t[i]:
return False
return True
|
def shorten(name: str):
"""Oryza_sativa -> osat"""
split = name.lower().split("_")
return split[0][0] + split[1][:3]
|
def two_level_to_single_level_dict(two_level_dict):
"""
Converts a two-level dictionary to a single level dictionary
dict[meeting][speaker] --> dict[speaker]
"""
assert isinstance((next(iter(two_level_dict.values()))), dict)
single_level_dict = {}
for _, value1 in two_level_dict.items():
for key2, value2 in value1.items():
if key2 not in single_level_dict.keys():
single_level_dict[key2] = []
if isinstance(value2, list):
single_level_dict[key2].extend(value2)
else:
single_level_dict[key2].append(value2)
return single_level_dict
|
def flatten(lst):
"""Returns a flattened version of lst.
>>> flatten([1, 2, 3]) # normal list
[1, 2, 3]
>>> x = [1, [2, 3], 4] # deep list
>>> flatten(x)
[1, 2, 3, 4]
>>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
>>> flatten(x)
[1, 1, 1, 1, 1, 1]
"""
new_list = []
for i in lst:
if type(i) == list:
new_list += flatten(i)
else:
new_list.append(i)
return new_list
|
def euclids_formula(m, n):
"""
"""
assert type(m) is int, ""
assert type(n) is int, ""
a = m*m - n*n
b = 2*m*n
c = m*m + n*n
return (min(a, b), max(a, b), c)
|
def mergesort(_list):
""" merge sort works by recursively spliting a list down to a
binary comparison and then sorting smaller values to the left
"""
if not isinstance(_list, list):
raise TypeError
# Need a recursive function that splits a list
# in half until a list of length n has n lists of 1 unit
if len(_list) > 1:
half = len(_list)//2
left_half = _list[:half]
right_half = _list[half:]
mergesort(left_half)
mergesort(right_half)
# once down to the last split, the left list is compared to the right list and the lower value is appended to newList.
# this runs recursively until the list is fully rebuilt
# we need to keep track of three counters
i = 0 # index of left side
j = 0 # index of right side
k = 0 # index of _list
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
_list[k] = left_half[i]
i += 1
else:
_list[k] = right_half[j]
j += 1
k += 1
# when left or right is no longer present the following continue the sort
while i < len(left_half):
_list[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
_list[k] = right_half[j]
j += 1
k += 1
return _list
|
def bbox_to_extent(bbox):
"""Helper function to reorder a list of coordinates from [W,S,E,N] to [W,E,S,N]
args:
bbox (list[float]): list (or tuple) or coordinates in the order of [W,S,E,N]
returns:
extent (tuple[float]): tuple of coordinates in the order of [W,E,S,N]
"""
return (bbox[0], bbox[2], bbox[1], bbox[3])
|
def format_special_results(special_results=[]):
""" Takes special_results, which is a list of dictionaries,
returns a list of election years. Round odd years up to even.
Example: [2008, 2000]
"""
senate_specials = []
for result in special_results:
# Round odd years up to even years
result["election_year"] = result["election_year"] + (
result["election_year"] % 2
)
senate_specials.append(result.get("election_year", None))
return senate_specials
|
def scenicToWebotsPosition(pos, y=0):
"""Convert a Scenic position to a Webots position."""
x, z = pos
return [x, y, -z]
|
def make_time_bc(constraints, bc_terminal):
"""
Makes free or fixed final time boundary conditions.
:param constraints: List of constraints.
:param bc_terminal: Terminal boundary condition.
:return: New terminal boundary condition.
"""
time_constraints = constraints.get('independent', [])
if len(time_constraints) > 0:
return bc_terminal+['tf - 1']
else:
# Add free final time boundary condition
return bc_terminal+['_H - 0']
|
def _align_chunks(chunks, alignment):
"""Compute a new chunking scheme where chunk boundaries are aligned.
`chunks` must be a dask chunks specification in normalised form.
`alignment` is a dictionary mapping axes to an alignment factor. The return
value is a new chunking scheme where all chunk sizes, except possibly the
last on each axis, is a multiple of that alignment.
The implementation tries to minimize the cost of rechunking to the new
scheme, while also minimising the number of chunks. Within each existing
chunk, the first and last alignment boundaries are split along (which may
be a no-op where the start/end of the chunk is already aligned).
"""
out = list(chunks)
for axis, align in alignment.items():
sizes = []
in_pos = 0 # Sum of all processed incoming sizes
out_pos = 0 # Sum of generated sizes
for c in chunks[axis]:
in_end = in_pos + c
low = (in_pos + align - 1) // align * align # first aligned point
if low > out_pos and low <= in_end:
sizes.append(low - out_pos)
out_pos = low
high = in_end // align * align # last aligned point
if high > out_pos and high >= in_pos:
sizes.append(high - out_pos)
out_pos = high
in_pos = in_end
# May be a final unaligned piece
if out_pos < in_pos:
sizes.append(in_pos - out_pos)
out[axis] = tuple(sizes)
return tuple(out)
|
def get_first_defined(data, keys, default_value=None):
"""
Get the first defined key in data.
:param data:
:type data:
:param keys:
:type keys:
:param default_value:
:type default_value:
:return:
:rtype:
"""
for key in keys:
if key in data:
return data[key]
return default_value
|
def hamming_distance(s1, s2):
"""
https://en.wikipedia.org/wiki/Hamming_distance#Algorithm_example
Return the Hamming distance between equal-length sequences
"""
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
s1 = ''.join("{0:08b}".format(ord(c)) for c in s1)
s2 = ''.join("{0:08b}".format(ord(c)) for c in s2)
return sum(el1 != el2 for el1, el2 in zip(s1, s2))
|
def dhcp_option119(fqdn):
"""Convert a FQDN to an hex-encoded DHCP option 119 (DNS search domain list, RFC 3397).
>>> dhcp_option119("tx1.blade-group.net")
'037478310b626c6164652d67726f7570036e657400'
"""
result = ""
for component in fqdn.split("."):
result += "{:02x}{}".format(len(component), component.encode('ascii').hex())
result += "00"
return result
|
def test_quadruple_args_in_call(x):
"""Test that duplicated arguments still cause no problem even if
there are four of them."""
def g(a, b, c, d):
return a * b * c * d
return g(x, x, x, x)
|
def get_kahan_queue_id(output: list):
"""
obtains the kahan queue id from the output of the qsub command
:param output list with all the output lines from kahan server
"""
return output[0] if len(output) > 0 and output[0].isdigit() else None
|
def _cmpTop(a, b, what='top 250 rank'):
"""Compare function used to sort top 250/bottom 10 rank."""
av = int(a[1].get(what))
bv = int(b[1].get(what))
if av == bv:
return 0
return (-1, 1)[av > bv]
|
def sstrip(s, suffix):
"""Suffix strip
>>> sstrip('foo.oof', '.oof')
'foo'
>>> sstrip('baroof', '.oof')
'baroof'
"""
i = - len(suffix)
if s[i:] == suffix:
return s[:i]
return s
|
def is_folder(url):
"""
Checks whether a url points to a folder with resources
"""
if 'mod/folder/' in url:
return True
else:
return False
|
def generate_checks(container, address, check_ports):
"""Generates the check dictionary to pass to consul of the form {'checks': []}"""
checks = {}
checks['checks'] = []
for p in check_ports:
checks['checks'].append(
{'id': '{}-port{}'.format(container, p),
'name': 'Check TCP port {}'.format(p),
'tcp': '{}:{}'.format(address, p),
'Interval': '30s',
'timeout': '4s'})
return checks
|
def get_data_shapes_resize(masks):
"""Generating data shapes with img resizing for tensorflow datasets depending on if we need to load the masks or not
outputs:
data shapes with masks = output data shapes for (images, ground truth boxes, ground truth labels, masks, mask id labels)
data shapes without masks = output data shapes for (images, ground truth boxes, ground truth labels)
"""
if masks:
return ([None, None, None], [None, None], [None, ], [None, None, None], [None, ])
else:
return ([None, None, None], [None, None], [None,])
|
def check_index_file_type(file_name: str) -> str:
"""
Get the index file type based on the extension of given `file_name`
:param file_name: index file name
:return: file type
"""
if file_name.endswith(".fa.gz"):
return "fasta"
elif file_name.endswith(".json.gz"):
return "json"
else:
return "bowtie2"
|
def head(_b, _x):
"""Determine the number of leading b's in vector x.
Parameters
----------
b: int
Integer for counting at head of vector.
x: array
Vector of integers.
Returns
-------
head: int
Number of leading b's in x.
"""
# Initialize counter
_head = 0
# Iterate through values in vector
for i in _x:
if i == _b:
_head += 1
else:
break
return _head
|
def _get_space(space):
"""Verify requested colorspace is valid."""
space = space.lower()
if space in ('hpluv', 'hsluv'):
space = space[:3]
if space not in ('rgb', 'hsv', 'hpl', 'hsl', 'hcl'):
raise ValueError(f'Unknown colorspace {space!r}.')
return space
|
def _make_list(obj):
"""Returns list corresponding to or containing obj, depending on type."""
if isinstance(obj, list):
return obj
elif isinstance(obj, tuple):
return list(obj)
else:
return [obj]
|
def _tags_to_dict(s):
""" "k1=v1,k2=v2" --> { "k1": "v1", "k2": "v2" } """
return dict(map(lambda kv: kv.split('='), s.split(",")))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.