content stringlengths 42 6.51k |
|---|
def pop_null(serialized_citation):
"""
Return the serialized_citation without null fields
:param serialized_citation: dict
:return: dict
"""
return {k: v for k, v in serialized_citation.items() if v} |
def count_sentences(text):
""" This function counts the number of sentences in a string of text
using period, semicolon, question mark and exclamation mark as
terminals.
"""
count = 0
terminals = '.;?!'
for char in text:
if char in terminals:
count = count + 1
... |
def _topological_sort(succ, reverse=False):
"""
Return a list of nodes (site names) in topologically sorted order.
"""
def dfs(site, visited):
if site in visited:
return
for s in succ[site]:
for node in dfs(s, visited):
yield node
visited.... |
def flatten_list(input_list):
"""Function used to flatten a list containing sublists. It does this by calling
itself recursively.
Args:
input_list (list): A list containing strings or other lists.
Returns:
list: The flattened list.
"""
flattened_list = []
for list_item in i... |
def _get_uri_suffix(uri):
"""
Returns the suffix (local name) of th uri
:Example:
>> _get_uri_suffix('http://example.org/test')
'test'
>> _get_uri_suffix('http://example.org/page#test2')
'test2'
"""
if '#' in uri:
return uri.rsplit('#', 1)[-1]
... |
def _getattr(obj, name, default):
"""Like getattr but return `default` if None or False.
By default, getattr(obj, name, default) returns default only if
attr does not exist, here, we return `default` even if attr evaluates to
None or False.
"""
value = getattr(obj, name, default)
if value:
... |
def binary_search(sorted_list, value, value_picker):
"""Executes a binary search on a sorted list.
Returns the index ind of the first element in the list whose value is <= than the given value.
or None if this element does not exist.
value_picker defines the value of the elements in sorted_list.
Ar... |
def contains(indices1, indices2):
"""Returns a boolean indicating whether indices1 contain indices2"""
if indices1[0] <= indices2[0] and indices1[1] >= indices2[1]:
return True
else:
return False |
def gravitationalForce(mass1, mass2, distance):
"""assumes mass1 is a number, representing the mass of an object, in kilograms
assumes mass2 is a number, representing the mass of another object, in kilograms
assumes distance is a number, representing the distance between the objects, in meters
"""
g... |
def replace_character_entities(xml_string):
"""replace standard XML character entities with hexadecimal replacements"""
char_map = {
b"&": b"&",
b">": b">",
b"<": b"<",
b""": b""",
}
for from_char, to_char in char_map.items():
... |
def _booleanise(value):
"""Try to booleanise something, return it unchanged if not possible"""
try:
if value.lower() in ['true', 'false']:
value = value.lower() == 'true'
except (AttributeError, TypeError):
pass
return value |
def linear_gradient(hexList, nColors):
"""Given a list of hexcode values, will return a list of length
nColors where the colors are linearly interpolated between the
(r, g, b) tuples that are given.
Example:
linear_gradient([(0, 0, 0), (255, 0, 0), (255, 255, 0)], 100)
"""
def _scale(start,... |
def function1(individual, position, height, width):
"""The function1 peak function to be used with scenario 1.
:math:`f(\mathbf{x}) = \\frac{h}{1 + w \sqrt{\sum_{i=1}^N (x_i - p_i)^2}}`
"""
value = 0.0
for x, p in zip(individual, position):
value += (x - p)**2
return height / (... |
def remove_common_suffix(ref_base, alt_base):
"""
For each haploid match, we simplify the reference base and alternative base and remove their common suffix characters.
"""
min_length = min(len(ref_base) - 1, min([len(item) - 1 for item in alt_base])) # keep at least one base
prefix = ref_base[::-... |
def _outer(a, b):
"""
Return the outer product/combination of two lists.
a is a multi- or one-dimensional list,
b is a one-dimensional list, tuple, NumPy array or scalar (new parameter)
Return: outer combination 'all'.
The function is to be called repeatedly::
all = _outer(all, p)
... |
def fromobject(thrift, tcls, obj):
"""Create thrift object with type `tcls` from a Python object.
"""
if isinstance(obj, tcls):
return obj
return globals().get(tcls.__name__, tcls)(thrift, obj) |
def isconst(name):
"""Is this the name of a const?"""
return name.startswith("const") |
def lum_filename(run, batch, source='frank', basename='xrb'):
"""Returns string for lum table filename
"""
return f'lum_{source}_{batch}_{basename}{run}.txt' |
def padl(l):
"""
Return amount of padding needed for a 4-byte multiple.
"""
return 4 * ((l + 3) // 4) - l |
def _get_id2lower(id2lower, item_id, item_obj):
"""Add the lower item IDs for one item object and the objects below them."""
if item_id in id2lower:
return id2lower[item_id]
lower_ids = set()
for lower_obj in item_obj.get_goterms_lower():
lower_id = lower_obj.item_id
lower_ids.ad... |
def rectCenter(rect):
"""Determine rectangle center.
Args:
rect: Bounding rectangle, expressed as tuples
``(xMin, yMin, xMax, yMax)``.
Returns:
A 2D tuple representing the point at the center of the rectangle.
"""
(xMin, yMin, xMax, yMax) = rect
return (xMin+xMax)/2... |
def episodes_length(dataset):
"""
Compute the length of each episode in the dataset.
Args:
dataset (list): the dataset to consider.
Returns:
A list of length of each episode in the dataset.
"""
lengths = list()
l = 0
for sample in dataset:
l += 1
if sam... |
def validate_length(length):
"""Check of if password length is valid.
password length is valid if it's either None or a positif int
"""
if length is None:
return True
if type(length) != int:
raise TypeError("password length must be of type int")
if length <= 0:
raise Val... |
def _slope(x, y):
"""
:type x: tuple[float, float]
:type y: tuple[float, float]
:rtype: float
"""
return (y[1] - x[1]) / (y[0] - x[0]) |
def get_next_step_name(module, current_step_number, response_retrieveP):
"""
Return the next step name.
:param AnsibleModule module: the ansible module
:param str current_step_number: the current step number
:param dict response_retrieveP: the response of the workflow API to \
retrieve the prope... |
def _get_server_id(servers, identity):
"""
Fetch and return server UUID by server name if found.
"""
for server in servers['items']:
if identity in (server['properties']['name'], server['id']):
return server['id']
return None |
def _firstResult(gen):
"""
Return the first element of a generator and exhaust it.
C{MethodicalMachine.upon}'s C{collector} argument takes a generator of
output results. If the generator is exhausted, the later outputs aren't
actually run.
@param gen: Generator to extract values from
@ret... |
def make_list(x, length=1):
"""Returns a list of length [length] where each elment is [x], or, if [x]
is a list of length [length], returns [x].
"""
if isinstance(x, list) and len(x) == length:
return x
elif isinstance(x, list) and len(x) == 1:
return x * length
elif isinstance(x... |
def get_ID (ID):
"""
input: "name, family, age, birth place"
output: ["setayesh", "pasandideh", 13, "tehran"]
"""
ID = ID.split()
ID[2] = int(ID[2])
return ID |
def applyF_filterG(L, f, g):
"""Mutates a list of integers
Mutates L such that, for each element i originally in L, L contains
i if g(f(i)) returns True, and no other elements
Decorators:
guenther.wasser
Args:
L ([list]): List of integer values
f ([function]): [description]
... |
def create_day_array(start, end):
"""Create an array of one-hour blocks from given start time and
end time. Returns an empty array if the start/end time was filled
as "----", otherwise splits the time given into one-hour objects
and returns the array of block objects.
"""
# Ensure input is vali... |
def load_config(field_spec, loader, **kwargs):
"""
Loads the config and any secondary configs into one object
:param field_spec: that should contain config
:param loader: system spec loader
:return: the full config
"""
if not isinstance(field_spec, dict):
return kwargs
config = ... |
def LoHighConvert(limIndex):
""" switch low to high"""
switcher = {
0 : 'Low',
1 : 'High'
}
return switcher.get(limIndex, 'Low') |
def is_sorted(t):
"""Takes a list, returns True if list sorted in ascending order, else False"""
t2 = sorted(t)
return t2 == t |
def make_code_inline(text: str) -> str:
"""Returns the text surrounded by `"""
return "`" + text + "`" |
def find(elements_list: list, match_pattern: str) -> list:
"""
Return indexes of a list that matches with pattern. Similar to MATLAB find function
"""
indexes = [i for i in range(len(elements_list)) if elements_list[i] == match_pattern]
return indexes |
def is_default_extra(extra: bytes) -> bool:
"""Checks if the tx_extra follows the standard format of:
0x01 <pubkey> 0x02 0x09 0x01 <encrypted_payment_id>
:param extra: Potential default extra bytes.
:type extra: bytes
:return: True if the passed in bytes are in the default tx_extra format
... |
def validation_to_text(validation):
"""
Return readable description of @validation dict.
"""
s = ""
if not validation['row_length_ok']:
if s: s+= "; "
s += "Row is incorrect length"
if validation['contains_example_data']:
if s: s+= "; "
s += "Row contains example ... |
def exp_mod(b, e, MOD):
"""docstring for exp_mod"""
if (e == 0):
return 1
if e == 1:
return b % MOD
rec = exp_mod(b, e >> 1, MOD)
return ((rec * rec * exp_mod(b, (e & 1), MOD)) % MOD) |
def parseBox(line):
"""
Take a line of the form "NxNxN" and parse it into a sorted tuple (length, width, height).
Keyword arguments:
line --- a string to be parsed as box specifications
"""
dimensions = sorted(map(int, line.split("x")))
return (dimensions[2], dimensions[1], dimensions[0]) |
def _jsnp_unescape(jsn_s):
"""
Parse and decode given encoded JSON Pointer expression, convert ~1 to
/ and ~0 to ~.
.. note:: JSON Pointer: http://tools.ietf.org/html/rfc6901
>>> _jsnp_unescape("/a~1b")
'/a/b'
>>> _jsnp_unescape("~1aaa~1~0bbb")
'/aaa/~bbb'
"""
return jsn_s.repl... |
def date_key(datekey):
"""
get YYYY-MM-DD from ISO string
:param datekey:
:return:
"""
if isinstance(datekey, list):
dkey = datekey[0][0:10]
return dkey
if isinstance(datekey, str):
dkey = datekey[0:10]
return dkey |
def dummy_function(first, second=0, third=2):
"""A dummy function for testing clize usage.
Args:
first (str):
The first argument.
second (int):
The second argument.
third (iris.cube.Cube):
The third argument
Returns:
(iris.cube.Cube)
... |
def abbreviate_segment(segment_name):
""" Abbreviate the segment name. For instance:
BABEL_OP2_202_10524_20131009_200043_inLine to BPL202-10524-20131009-200043-in
"""
if segment_name.endswith('inLine'):
stop_point = -4
elif segment_name.endswith('outLine'):
stop_point = -5
el... |
def decode_cstr(val: bytes) -> str:
"""Converts c_char_p stored in interface structures to a str.
Arguments:
val - Byte sequence to convert into str.
Returns:
str represented by 'val'
"""
return val.decode() if val else '' |
def flood(pos, tiles, maxsize=10000):
"""Flood fill from a given seed."""
seen = {pos}
todo = {pos}
size = 0
while todo and size < maxsize:
x, y = todo.pop()
for neighbour in ((x-1, y), (x+1, y), (x, y-1), (x, y+1)):
if neighbour not in seen and neighbour in tiles:
... |
def filter_repo_name(repo_name):
"""Remove the .git extension from the repo name."""
if repo_name is not None and repo_name.endswith(".git"):
return repo_name[: -len(".git")]
return repo_name |
def _merge(dst, src):
"""Merges src into dst, overwriting values if necessary."""
for key in src:
if key in dst and isinstance(dst[key], dict) and isinstance(src[key], dict):
_merge(dst[key], src[key])
else:
dst[key] = src[key]
return dst |
def getDetailLabel(origWeight, Label, num=True):
"""
Given original weight and label,
return more precise label specifying the original simulation type.
Args
----
origWeight: the original weight of the event
Label : the label of the event (can be {"b", "s"} or {0,1})
nu... |
def merge_clusters(inner_cluster, outer_cluster):
"""
Merge two clusters
param inner_cluster: The cluster that's inside another cluster
param outer_cluster: The cluster that's outside another cluster
"""
outer_cluster = outer_cluster + [
item for item in inner_cluster if item not in oute... |
def camara_calibration(mapa):
""" Calibrates the camara with the sum of the alignment parameters
a aligment parameter is: the result of the number of space units from the top multiplied
by the number of space units from the left of the map"""
intersections = []
for key, val in mapa.items():
... |
def create_select_values(mjpeg_info_dict):
"""
Creates the list of select options for camera drop down menus.
"""
camera_numbers = [str(x) for x in range(1,len(mjpeg_info_dict)+1)]
select_values = ['--']
select_values.extend(camera_numbers)
return select_values |
def normalize_pc_counter(dict_in):
"""
Normalize a dictionary by the sum of the total values. Meant to be used with the
net ql values from :obj:`decitala.hm.hm_utils`.
>>> d = {0: 0, 1: 0.375, 2: 0, 3: 0.25, 4: 0.375,
... 5: 0.375, 6: 0.375, 7: 0, 8: 0.75, 9: 0.25, 10: 0, 11: 0
... }
>>> for pc, norm_val in no... |
def apply_operators(obj, ops, op):
"""
Apply the list of operators ``ops`` to object ``obj``, substituting
``op`` for the generator.
"""
res = obj
for o in reversed(ops):
res = o.apply(res, op)
return res |
def first_index(target, it):
"""The first index in `it` where `target` appears; -1 if it is missing."""
for idx, elt in enumerate(it):
if elt == target:
return idx
return -1 |
def is_pom(item):
"""Checks if a item is a pom.xml"""
return "pom.xml" in item |
def ensure_bool(s):
"""Convert value into boolean following convention for strings
to recognize on,True,yes as True, off,False,no as False
"""
if isinstance(s, str):
if s.isdigit():
return bool(int(s))
sl = s.lower()
if sl in {'y', 'yes', 'true', 'on'}:
r... |
def breadcrumbs_li(links):
"""Returns HTML: an unordered list of URLs (no surrounding <ul> tags).
``links`` should be a iterable of tuples (URL, text).
"""
crumbs = ""
li_str = '<li><a href="{}">{}</a></li>'
li_str_last = '<li class="active"><span>{}</span></li>'
# Iterate over the list, exc... |
def _determine_quality(stderr_contents, stream_index):
"""
Determine whether the wavelet transform of JPEG2000 stream was lossless.
This is done by examining the line corresponding to the relevant stream and
determining whether it contains the string "lossless".
:stderr_contents: The stderr output... |
def make_dict_from_tree(element_tree):
"""Traverse the given XML element tree to convert it into a dictionary.
:param element_tree: An XML element tree
:type element_tree: xml.etree.ElementTree
:rtype: dict
"""
def internal_iter(tree, accum):
"""Recursively iterate through the elements... |
def compare_ratio(a, b, precision=0.05):
""" Compare decimal numbers up to a given precision. """
return abs(a-b) <= precision |
def format_access_error(_exc):
"""Format an access error."""
return (
'You do not have the appropriate permissions to run this command. '
'Contact your manager.'
) |
def is_iterable(obj):
""" Check if the object is iterable. """
has_iter = hasattr(obj, "__iter__")
has_get_item = hasattr(obj, "__getitem__")
return has_iter or has_get_item |
def check_sorted(nums):
"""
Determines if list is sorted.
"""
for i, val in enumerate(nums):
if i > 0 and val < nums[i - 1]:
return False
return True |
def saturn_rot_elements_at_epoch(T, d):
"""Calculate rotational elements for Saturn.
Parameters
----------
T: float
Interval from the standard epoch, in Julian centuries.
d: float
Interval in days from the standard epoch.
Returns
-------
ra, dec, W: tuple (float)
... |
def combine_multiple_lines(*args):
"""Combine Several Simulator Result
:param *args: several csv list
:return combine_lines: single csv line combined
"""
print('we got {} lines'.format(len(args)))
combine_lines = []
for arg in args:
combine_lines.extend(arg)
return com... |
def constant(step, total_train_steps, value=1.0):
"""Constant learning rate (multiplier).
Args:
step: a tf.Scalar
total_train_steps: a number
value: a number or tf.Scalar
Returns:
a tf.Scalar, the learning rate for the step.
"""
del step, total_train_steps
return value |
def update(host, service, action, **kwargs):
"""Enable/Disable nova service"""
if kwargs.get('disabled_reason') and action == 'disable':
url = '/os-services/disable-log-reason'
req = {"host": host, "binary": service, "disabled_reason": kwargs['disabled_reason']}
else:
url = '/os-services/%... |
def calc_intcode(codes, noun=None, verb=None):
"""
calculate intcode
"""
codes = codes.copy()
if noun:
codes[1] = noun
if verb:
codes[2] = verb
for idx in range(0, len(codes), 4):
try:
if codes[idx] == 99:
break
v1 = codes[cod... |
def runProcess(cmd, *args):
"""Run `cmd` (which is searched for in the executable path) with `args` and
return the exit status.
In general (unless you know what you're doing) use::
runProcess('program', filename)
rather than::
os.system('program %s' % filename)
because the latter will... |
def splitRPMFilename(filename):
"""
Pass in a standard style rpm fullname
Return a name, version, release, epoch, arch, e.g.::
foo-1.0-1.i386.rpm returns foo, 1.0, 1, i386
1:bar-9-123a.ia64.rpm returns bar, 9, 123a, 1, ia64
"""
if filename[-4:] == '.rpm':
filename = filenam... |
def _type_name(value):
"""
Returns a user-readable name for the type of an object
:param value:
A value to get the type name of
:return:
A unicode string of the object's type name
"""
cls = value.__class__
if cls.__module__ in set(['builtins', '__builtin__']):
retu... |
def find_selected_id_in_history(history, selected_frame, posx, posy):
"""
Find which one of our ids matches with the selected pedestrian to be tracked,
which was in posx and posy at the selected_frame.
:param history:
:param selected_frame:
:param posx:
:param posy:
:return:
"""
... |
def remove_special_characters(data):
"""
removes '\n', (' , space and ',)
"""
data = str(data)
data = data.replace("\\n","")
data = data.replace("\\t","")
data = data.replace("('","")
data = data.replace("',)","")
data = data.replace("\\r","")
return data |
def obj_to_dict(obj):
"""
Converts an :py:obj:`object` to a :py:obj:`dict` by taking the object's
properties and variables and their values and putting them into a dict.
Private and dunder (``__``) properties are ignored.
The use case for this is to enable passing of an object's data across
the... |
def remove_duplicates(nums):
"""
Remove the duplicates (more than twice) in the given sorted array in-place
:param nums: given array
:type nums: list[int]
:return: new length
:rtype: int
"""
if len(nums) <= 2:
return len(nums)
new_length = 1
for i in range(2, len(nums)):... |
def hth(results):
"""
Does the head-to-head ordering.
It works identical to the NFL Head-to-head sweep which is
applied to break a tie for the wild-card team. Basically it is
applicable only if one club has defeated each of the others or
if one club has lost to each of the others.
results attribute shou... |
def search_tag_hierarchy(name, tag_list):
"""Search a list of tags for any with the given name."""
result = []
for tag in tag_list:
if tag["tname"] == name:
result.extend([tag])
else:
if "tags" in tag:
result.extend(search_tag_hierarchy(name, tag["tags... |
def _header_dict(project_id, auth_token):
"""
Create a header dict from the project ID and auth token
"""
return {
"accept": "application/json",
"project": str(project_id),
"Authorization": "Bearer " + str(auth_token),
} |
def parse_geo(info):
"""Parse and return GSE IDs."""
gse_ids = []
if info:
tags = info.find_all('item', attrs={'name': "GSE"})
gse_ids = ["GSE" + tag.text for tag in tags]
return gse_ids |
def enable_auto_tray(on=0):
"""Esconder Automaticamente Icones Inativos na Bandeja
DESCRIPTION
Este ajuste controla se programas executando na bandeja devem ser
escondidos automaticamente quando estao inativos.
COMPATIBILITY
Windows XP
MODIFIED VALUES
Enab... |
def convert_boolean_to_int(param):
"""Convert the parameter of boolean to int.
@param param: parameter to be converted.
@return Parameter converted.
"""
if param is True:
return int(1)
elif param is False:
return int(0) |
def query_opt_params(opt_params, key):
""" Returns the provided key in optional parameters dictionayr.
Returns None if not found."""
return opt_params.get(key, None) |
def lb_to_int(loadbalance):
"""Returns the integer representation in VPP of a given load-balance strategy,
or -1 if 'lb' is not a valid string.
See src/vnet/bonding/bond.api and schema.yaml for valid pairs, although
bond.api defined more than we use in vppcfg."""
ret = {
"l2": 0,
"... |
def all_3_permutations(perm_list):
"""
Input :
- perm_list : tuple or list like ;
Output : list like : each possible permutations from perm_list parameters
"""
return [[i, j, k]
for i in range(perm_list[0] + 1)
for j in range(perm_list[1] + 1)
for k in... |
def getPicketFenceFakeLevelSequence(E0, aveD, numLevels):
"""
An evenly spaced set of fake resonances, separated by energy aveD. This gets the
level repulsion right, but otherwise it is so so wrong.
:param E0: first level of the sequence
:param aveD: average level spacing, assumed to be in same un... |
def determine_letter(current_score):
"""
Calculates the letter grade for a given score
:param current_score: the score to be evaluated
:return: the letter grade that score falls within
"""
if current_score >= 90:
return "A"
elif current_score >= 80:
return "B"
e... |
def parse_action(action):
"""parse the action and consider multiple name scenario.
name will also appear first.
"""
name = ' '.join(action[0:-2])
flight = action[-2]
state = action[-1]
return name, flight, state |
def find_relative(nominal_group, sentence, position, propo_rel_list):
"""
Function to find the position of the relative
:param nominal_group: the object of the relative
:param sentence: the sentence to search in
:param position: the nominal group position... |
def convert_translation(translation):
"""
Converts given translation into a valid translation to be used with tpDcc
NOTE: tpDcc uses Y up coordinate axes as the base reference axis
NOTE: 3ds Max works with Z up axis. We must do the conversion.
:param translation: list(float, float, float)
:retur... |
def right(dimension, position):
"""
Return the position on any board with the given dimension immediately to
the right of the given position.
- None is returned if the generated position is outside the boundaries of
a board with the given dimension.
ASSUMPTIONS
- T... |
def flatten_terms(terms):
"""
[
{ "simple_term": "A" },
{ "simple_term": "B" },
{ "simple_term": "C" }
]
to
["A", "B", "C"]
"""
return [list(i.values())[0] if isinstance(i, dict) else i for i in terms] |
def toNumber(a):
"""
Convert any input a to a number type
if can not convert, then return nan
"""
if isinstance(a, (int, float)):
return a
try:
return int(a)
except (ValueError, TypeError):
try:
return float(a)
except (ValueError, TypeError):
return float('nan') |
def find_executable(files, exts):
""" Try to find an executable in a tree structure. """
for file_ref in files:
for ext in exts:
if ext in file_ref.filename:
return file_ref.filename
# no executable found
return None |
def _handle_from_hex_to_string(handle):
"""Convert TC handle from hex to string
:param handle: (int) TC handle
:return: (string) handle formatted to string: 0xMMMMmmmm -> "M:m"
"""
minor = format(handle & 0xFFFF, 'x')
major = format((handle & 0xFFFF0000) >> 16, 'x')
return ':'.join([major, ... |
def convert_little_endian(string):
"""
>>> convert_little_endian('C0 00')
'00 C0'
"""
lst = string.split(" ")
lst.reverse()
return " ".join(lst) |
def is_square(positive_int):
"""
Quick function to find if a number is a perfect square root
Parameters
----------
positive_int : int
The number evaluated.
Returns
----------
bool : bool
If true, the number is a perfect square root.
"""
x = positive_int // 2
... |
def flatten_dict(dct, fields, *, rest_val=None, extras_action='raise',
field_set=None):
"""
>>> flatten_dict({'a': 1, 'b': 2}, ('a', 'b'))
[1, 2]
>>> flatten_dict({'a': 1, 'b': 2}, ('a', 'b', 'c'))
Traceback (most recent call last):
...
KeyError: 'c'
>>> flatten_di... |
def cleanSpikes(highPrice,lowPrice,closePrice):
""" Remove high and low prices significantly out of the normal range
Remove highest price if greater than 2x the second highest price
Remove lowest price if less than 1/2 the second lowest price
Input highPrice: List of high pric... |
def first(iterable, condition = lambda x: True):
"""
Returns the first item in the `iterable` that
satisfies the `condition`.
If the condition is not given, returns the first item of
the iterable.
Raises `StopIteration` if no item satysfing the condition is found.
>>> first( (1,2,3), condition=lambda x: x % 2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.