content stringlengths 42 6.51k |
|---|
def extract_list_from_lines(lines, pattern):
""" Extract a list from lines if lines match with pattern.
:param lines: (list of str)
:param pattern: (str)
:returns: (list)
"""
my_list = list()
for line in lines:
columns = line.split(';')
if columns[0].strip() == pattern:
... |
def some(seq, func):
"""
Description
----------
Return True if some value in the sequence satisfies the predicate function.\n
Returns False otherwise.
Parameters
----------
seq : (list or tuple or set or dict) - sequence to iterate\n
func : callable - predicate function to apply eac... |
def parse_resolution(s, expected_length=None):
"""
Takes a string on the format '(WIDTH,HEIGHT,CHANNELS)' and
evaluates to a tuple with ints. Unlike literal_eval in ast,
this should be a bit more safe against unsanitized input.
It also accept strings with quote characters (' or ")... |
def _FindBigDeltas(revs_and_sizes, increase_threshold, decrease_threshold):
"""Filters revs_and_sizes for entries that grow/shrink too much."""
big_jumps = []
prev_size = revs_and_sizes[0][1]
for rev, size in revs_and_sizes:
delta = size - prev_size
prev_size = size
if delta > increase_threshold or ... |
def get_app_specific_information(json_list_of_transactions):
"""Function that extracts the application through which the venmo
transaction was made (ie iPhone app, desktop, etc) and stores
each type in a table in the venmo transactions database."""
apps = []
# Only extracting app information
... |
def dec_to_bin(decimal: int) -> int:
"""
Converts a decimal integer to binary
:param decimal: An integer
:return: A binary number
"""
remainder_str = ""
while decimal != 0:
remainder_str += str(decimal % 2)
decimal //= 2
return int(remainder_str[::-1]) |
def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function value at the mid-point of the interval.
f0: derivative val... |
def standard_number(input_num: float) -> int:
"""Get the standard number value.
In this project, the standard num is *100000000, and rounding to int.
Args:
input_num: The number you want to standard.
Returns:
The standard num.
"""
if input_num > 0:
return int(input_num... |
def filter_listkey_args(**kwargs):
"""
Filter pagination-related keyword arguments.
Parameters:
**kwargs: Arbitrary keyword arguments.
Returns:
dict: Keyword arguments relating to ListKey pagination.
"""
listkey_options = ['listkey_count', 'listkey_start']
listkey_args = {k... |
def msb(n):
"""! @brief Return the bit number of the highest set bit."""
ndx = 0
while ( 1 < n ):
n = ( n >> 1 )
ndx += 1
return ndx |
def change_default_type_if_none(default_value, new_type):
"""For GUI elements whose values come from a list, default can not be None"""
if default_value is None:
return new_type
else:
return default_value |
def uniquify(seq):
"""Remove duplicates from list preserving order."""
seen = set()
seen_add = seen.add
return type(seq)(x for x in seq if x not in seen and not seen_add(x)) |
def s3_path(bucket, prefix):
"""Returns a formatted S3 bucket output path"""
return f"s3://{bucket}/{prefix}" |
def rk2(y, f, t, h):
"""Runge-Kutta RK2 midpoint"""
k1 = f(t, y)
k2 = f(t + 0.5*h, y + 0.5*h*k1)
return y + h*k2 |
def escape_quotes(value):
"""
DTD files can use single or double quotes for identifying strings,
so " and ' are the safe bet that will work in both cases.
"""
value = value.replace('"', "\\"")
value = value.replace("'", "\\'")
return value |
def test_name(msg_name):
"""Generate the name of a serialization unit test given a message name"""
return "test_{}_serialization".format(msg_name) |
def max_val_of_gifts(board):
"""
:param board: gift val board
:return: max val of gifts
"""
if not board:
return 0
row = len(board)
col = len(board[0])
cache = [0] * col
for i in range(row):
for j in range(col):
if j == 0:
cache[j] = cache[... |
def count_sort(inpt_list, key):
""" This sorts a list by counting the number of occurances a given digt occurs,
Arguments:
inpt_list {list}
key {int}
list_range {int}
Returns:
[list]
"""
list_range = 9
count_list = [0]*(list_range + 1)
for i in range(len(... |
def get_user_replies_to_particular_skill(utterances, skill_name):
"""
Return user's responses to particular skill if it was active
Args:
utterances:
skill_name:
Returns:
list of string response
"""
result = []
for i, uttr in enumerate(utterances):
if uttr.get... |
def is_among(value, *possibilities):
"""
Ensure that the method that has been used for the request is one
of the expected ones (e.g., GET or POST).
"""
for possibility in possibilities:
if value == possibility:
return True
raise Exception('A different request value was encoun... |
def prepare_response(data):
"""
Transforms a string, Exception or tuple to consistently structured output.
"""
data = data.args if isinstance(data, Exception) else data
if isinstance(data, str):
detail = data
objects = []
else:
detail = str(data[0])
objects = data... |
def indent(s, n=4, notfirstline = False):
"""Indent string
>>> indent("apa\\nrapa\\nbapa", 4)
' apa\\n rapa\\n bapa'
>>> indent("apa\\nrapa\\nbapa", 4, notfirstline=True)
'apa\\n rapa\\n bapa'
"""
if notfirstline:
return ('\n' + n*' ').join(s.split('\n'))
else:
... |
def stringify(predictions):
"""
Arguments:
predictions: A list of tuple with class label and probability.
Returns:
A string version of the list
"""
prediction_str = ''
for label, score in predictions:
prediction_str+= f'{label}, ({score:.04f})\n'
return prediction_str |
def _ShouldParseLine(line):
"""Checks whether a line should be parsed."""
if not line or line.startswith("#"):
return False
return True |
def mod_inverse(x, n):
"""
Compute the inverse of x in the multiplicative
group of Z/nZ, i.e. the integer y such that
x * y = 1 mod N.
The algorithm uses the extended Euclidean
algorithm to find the inverse efficiently.
"""
a, b = n, x
ta, tb = 0, 1
while b != 0:
q = a / b
a, b = b, a % b... |
def wrap(wsgi_app, protect):
"""Wrap FLASK app for custom authentication."""
del protect
return wsgi_app |
def _cast_gfloat_to_native_backward(op, *grads):
"""Gradients for the CastFromGfloat op."""
return [grads[0], None] |
def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : dict
Keys: {'x1', 'x2', 'y1', 'y2'}
The (x1, y1) position is at the top left corner,
the (x2, y2) position is at the bottom right corner
bb2 : dict
... |
def SplitKmzPath(href_text):
"""Split the .kmz URL from the reference into the .kmz
Args:
href: any URL or pathname or '...foo.kmz/path-inside-kmz'
Returns:
(kmz_path, file_path): if href_text is a reference into a .kmz
(href_text, None): if href_text is a plain URL or pathname
"""
dot_kmz_slash =... |
def interval_intersect(int1, int2):
"""Given two two-long sequences representing closed intervals, return
their intersection. Input or output may be None, indicating an
empty interval.
"""
if int1 is not None and int2 is not None:
mi, ma = max(int1[0], int2[0]), min(int1[1], int2[1])
... |
def trans_char_to_bool(str_):
"""
Args:
str_: string
Returns:
bool
"""
result = False
if str_.lower() == "true":
result = True
return result |
def keys_volume_type_get(volume_type_id, **kwargs):
"""
Return extra specs of the specified volume type.
"""
url = "/types/{volume_type_id}/extra_specs".format(
volume_type_id=volume_type_id)
return url, {} |
def stern_brocot(predicate=lambda series: len(series) < 20):
"""\
Generates members of the stern-brocot series, in order, returning them when the predicate becomes false
>>> print('The first 10 values:',
stern_brocot(lambda series: len(series) < 10)[:10])
The first 10 values: [1, 1, 2, 1,... |
def estimate_responsivity(mis_MU, norm_MU):
"""from the estimated base intensities, we return onlu users which have zero base intensity for misinformation
and greater than zero base intensity for normal content. """
no_bad_intentions_ids = []
for id in range(len(mis_MU)):
if mis_MU[id] ==... |
def _pathDecode(pathString):
"""decodes a unicode string to a dart sequence (see _pathString)"""
result = []
for d in pathString:
d = ord(d)
if d > 0x080000:
d -= 0x100000
result.append(d)
return result |
def verify(word):
"""
Expect a word and return True if is valid or False otherwise.
Validate word on length and not starting or ending with punctuation.
"""
return all(
(
5 <= len(word) <= 10,
word[0].isalpha(),
word[-1].isalpha()
)
) |
def make_typeid(obj):
"""
Returns a type ID string from `obj`'s module and class names
by replacing '.' with '_'.
"""
typeid = '%s.%s' % (obj.__class__.__module__, obj.__class__.__name__)
return typeid.replace('.', '_') |
def create_search_criterion_by_header(header_name, header_value):
"""Return search criteria by header.
.. versionadded:: 0.4
"""
return 'HEADER {} {}'.format(header_name, header_value) |
def GetGuestPolicyRelativePath(parent, guest_policy):
"""Return the relative path of an osconfig guest policy."""
return '/'.join([parent, 'guestPolicies', guest_policy]) |
def fix(s):
"""Fixes a string by replacing _ with spaces and putting it in title case"""
return s.replace('_', ' ').title() |
def calculate_columns(sequence):
"""
Find all row names and the maximum column widths.
Args:
columns (dict): the keys are the column name and the value the max length.
Returns:
dict: column names (key) and widths (value).
"""
columns = {}
for row in sequence:
for k... |
def prod(seq):
"""
return the product of all numbers in seq
"""
p = 1
for a in seq:
p *= a
return p |
def all_except(mapping, *exclude):
"""Return a new mapping with all keys except `exclude`.
Keys must be hashable to be used with `set`.
"""
exclude = set(exclude)
return {k: v for k, v in mapping.items() if k not in exclude} |
def tm_move1(state, b1, dest):
"""
Generate subtasks to get b1 and put it at dest.
"""
return [('get', b1), ('put', b1, dest)] |
def remove_stopwords(stop_words, text):
"""Remove the occurrence of all stop_words provided in the list
Parameters
----------
stop_words : set
The set of words that should be removed
text : str
The text in which from the stop_words will be removed
Returns
-------
s... |
def main(args):
"""
:param: args containing command-line arguments.
:return: int containing desired exit status code.
"""
try:
print('hi from %s' % (__name__,))
except BaseException as e:
print('ERROR: %s' % (e,))
return 1
return 0 |
def checkQuantity(q):
"""
:param q: users entered quantity
Takes the quantity and checks if it meets the required specifications.
If it does then return true, if it doesnt then return false.
"""
if bool(0 < int(q) <= 100):
return True
else:
return False |
def skip_testing_during_training(task):
"""Filter to determine if we should be running test-time evaluation.
In cloth and bag tasks, we need `--disp` (at least with PyBullet 2.8.4),
and that causes problems if instantiating multiple `Environment`s, as in
standard testing. Furthermore, all 'Deformable Ravens' t... |
def rotate_list(alist):
"""Pop the last element of list out then put it into the first of list.
:param alist: A list that want to rotated.
:return alist: A rotated list.
"""
assert type(alist) == list
last = alist.pop()
alist.insert(0, last)
return alist |
def shape2d(a):
"""
a: a int or tuple/list of length 2
"""
if type(a) == int:
return [a, a]
if isinstance(a, (list, tuple)):
assert len(a) == 2
return list(a)
raise RuntimeError("Illegal shape: {}".format(a)) |
def getdate(year,month,day,hour,minute=None,second=None):
"""
Build an integer date from component input.
**`year`**: Year in 4-digit format.
**`month`**: Month in 2-digit format.
**`day`**: Day in 2-digit format.
**`hour`**: Hour in 2-digit format.
**`minute`**: Minute in 2-digit forma... |
def l3_unicast_group_id(ne_id):
"""
L3 Unicast Group Id
"""
return 0x20000000 + (ne_id & 0x0fffffff) |
def get_tool_index_sample_files( sample_files ):
"""Try to return the list of all appropriate tool data sample files included in the repository."""
tool_index_sample_files = []
for s in sample_files:
# The problem with this is that Galaxy does not follow a standard naming convention for file names.
... |
def get_color_matrix(pixels):
"""Function to get the colour codes (ANSI escape sequences) from RGB values of pixel."""
color_matrix = []
for row in pixels:
color_matrix_row = []
for p in row:
r = round(p[0] / 255)
g = round(p[1] / 255)
b = round(p[2] / 255... |
def questionDataQuery(problemName):
"""
#### itype: string (Question Name, formate: all lowercase and spaces replaced with '-')
#### rtype: json formated query
"""
Query = {
"operationName": "questionData",
"variables": {"titleSlug": problemName},
"query": """query question... |
def remove_dict_entry_by_value(dictionary, value):
"""Helper to remove an entry in a dictionary by its value instead of its key."""
return {k: v for k, v in dictionary.items() if v != dictionary.get(value)} |
def analyze_segmentation(seg_result):
"""
Parameters
----------
seg_result: the result of the segmentation is a list of tuples
each tuple contains:
* label in 'speech', 'music', 'noEnergy'
* start time of the segment
* end time of the se... |
def get_menu_def(update_available: bool, amiibo_loaded: bool):
"""
Creates menu definition for window
:param bool update_available: If update is available or not
:param bool amiibo_loaded: If amiibo has been loaded or not
:return: tuple of menu
"""
if amiibo_loaded:
file_tab = ['&Fi... |
def toggle_manual_weights_form(method):
""" Hide/show field based on other values """
# 0=override weights, 1=auto match
if method == 0:
return "visible"
return "hidden" |
def confopt_distunits(confstr):
"""Check and return a valid unit from metres or laps."""
if u'lap' in confstr.lower():
return u'laps'
else:
return u'metres' |
def predict_source_position_in_camera(cog_x, cog_y, disp_dx, disp_dy):
"""
Compute the source position in the camera frame
Parameters
----------
cog_x: float or `numpy.ndarray` - x coordinate of the center of gravity (hillas.x)
cog_y: float or `numpy.ndarray` - y coordinate of the center of gra... |
def filter_docs(docs, dic):
"""
Helper function for filtering documents if the word occurs in the dictionary
:param docs: list of list of int, the tokenized corpus
:param dic: list of int, the dictionary
:return: list of list of int, the content reduced corpus to the words in the dictionary
"""
... |
def push_number(i: int, sailfish_number: tuple) -> tuple:
"""
Add the number i to the first integer encounterd in nested tuples. A negative i is pushed from the tail end.
:param i: The number to add
:param sailfish_number: The sailfish number to add i to
:return: The new sailfish number
>>> pus... |
def assemble_mapping_arguments(arguments):
"""Assemble mapping arguments into string.
:param arguments: mapping arguments with values. Example:
{
'-v': {
'/host/dir': '/container/dir',
'/host/dir... |
def is_local_port_open(port):
"""
Args:
port (int):
Returns:
bool:
References:
http://stackoverflow.com/questions/7436801/identifying-listening-ports-using-python
CommandLine:
python -m utool.util_web is_local_port_open --show
Example:
>>> # DISABLE_DO... |
def merge_dict(a, b, path=None):
"""
Merge two dictionaries together. Do not overwrite duplicate keys.
:param a: The first dictionary
:type a: dict
:param b: The second dictionary
:type b: dict
:param path: Prepend optional path to the dict structure
:typ... |
def invert_dict (d):
"""
Parameters
----------
L : TYPE Dictionary
Swaps keys and values
Returns
-------
New dictionary with swapped values and keys
"""
new_d = {}
for k in d.keys():
new_d[d[k]] = k
return new_d |
def isChildUri(parentUri, childUri):
"""Return True, if childUri is a child of parentUri.
This function accounts for the fact that '/a/b/c' and 'a/b/c/' are
children of '/a/b' (and also of '/a/b/').
Note that '/a/b/cd' is NOT a child of 'a/b/c'.
"""
return parentUri and childUri and... |
def create_dist_list(dist: str, param1: str, param2: str) -> list:
""" Creates a list with a special syntax describing a distribution
Syntax: [identifier, param1, param2 (if necessary)]
"""
dist_list: list = []
if dist == 'fix':
dist_list = ["f", float(param1)]
elif dist == 'binary'... |
def class_year(klass):
"""Get just the year part of a class name, as <str>, padded to
2 digits.
"""
try:
k = int(klass[:2])
except:
k = int(klass[0])
return f'{k:02}' |
def _get_nodes_depth_first(all_nodes):
"""
Return all_nodes, placing parent nodes earlier in the list than their children.
"""
all_nodes = set(all_nodes)
node_parents = {node: node.getParent() for node in all_nodes}
result = []
def add_starting_at(node):
# Make sure the node's paren... |
def amountdiv(number, minnum, maxnum):
"""
Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
>... |
def reference_already_exists(access_references, new_reference):
"""Test if a given VBA reference already exists in the new database. Only needed if db created blank"""
for reference in access_references:
if reference.FullPath.lower() == new_reference.lower():
return True
return False |
def int32_to_octets(value):
""" Given an int or long, return a 4-byte array of 8-bit ints."""
return [int(value >> 24 & 0xFF), int(value >> 16 & 0xFF),
int(value >> 8 & 0xFF), int(value & 0xFF)] |
def dict_getSafe(dict, key):
"""Return:
key exists: value of dictionary
else: None
"""
if (not key in dict):
return None
return dict[key] |
def test_odd(value):
"""Return true if the variable is odd."""
return value % 2 == 1 |
def _extract_lsb_4fold(codon):
"""
This function returns a pair of bits from LSB of 4 fold synonymous
substitution codon.
:param codon: codon from which, message needs to be extracted.
:return: a pair of binary bits (string format) extracted from LSB of
given codon.
"""
if codon[-1] == '... |
def unique_prime_factors(n: int) -> set:
"""
Find unique prime factors of an integer.
Tests include sorting because only the set really matters,
not the order in which it is produced.
>>> sorted(set(unique_prime_factors(14)))
[2, 7]
>>> sorted(set(unique_prime_factors(644)))
[2, 7, 23]
... |
def tuple_to_dict(data, space):
"""Create a `orion.core.worker.trial.Trial` object from `data`.
Parameters
----------
data: tuple
A tuple representing a sample point from `space`.
space: `orion.algo.space.Space`
Definition of problem's domain.
Returns
-------
A diction... |
def parse_settings(line):
"""Parse a data message from the meteo station."""
parts = line.split(',')
msg_type = parts.pop(0)
data = dict()
for p in parts:
key, value = p.split('=')
data[key] = value
return msg_type, data |
def get_name(name):
"""
Blueprint names must be unique, and cannot contain dots.
This converts filenames to blueprint names.
e.g. vulnerable_app.views.basic => basic
:type name: str
"""
return name.split('.')[-1] |
def _nested_op(inputs, op): # pylint: disable=invalid-name
"""Helper: apply op over a list of arrays or nested arrays."""
# If input is a dictionary, apply to the values (ignore keys).
if isinstance(inputs, dict):
return _nested_op(list(inputs.values()), op)
# First the simple non-nested case.
if not isi... |
def getCompletedJobs(jobs):
"""
Gets all completed jobs
"""
completed_jobs = []
for job in jobs:
if 'result' in job:
completed_jobs.append(job)
return completed_jobs |
def length_greater_than_f(y, n):
"""Predicate determining if length of a string is less than n"""
return (len(y) > n) |
def flatten_param_tuples(param_tuples):
"""Flattens a nested list of tuples using unzipping."""
param_list = []
unzipped_tuples = zip(*param_tuples)
for i, unzipped in enumerate(unzipped_tuples):
unzipped = list(unzipped)
if isinstance(unzipped[0], tuple):
param_list.extend(f... |
def HistogramDistance(hist1, hist2):
"""Earth mover's distance.
http://en.wikipedia.org/wiki/Earth_mover's_distance
First, normalize the two histograms. Then, treat the two histograms as
piles of dirt, and calculate the cost of turning one pile into the other.
To do this, calculate the difference in one buc... |
def calc_average(some_list):
"""
Parameters
----------
some_list : list
This is a list of numeric values.
Returns
-------
avg : float
The average of the values in the numeric list some_list.
"""
avg = sum(some_list)/len(some_list)
return avg |
def sanitize_for_latex(text):
""" Sanitzes text for use within LaTeX. Escapes LaTeX special characters in
order to prevent errors.
"""
from functools import reduce
escape = '%_&~'
replacers = (lambda s: s.replace(e, r'\{}'.format(e)) for e in escape)
return reduce(lambda s, f: f(s), replacer... |
def _create_msg_string(val_add:str,msg_action:str):
"""
takes in validator address and msg action string
"""
msg_string=f"message.sender={val_add}&message.action={msg_action}"
return msg_string |
def _fqhostname(hostname=None,default=('localhost','127.0.0.1')):
""" Returns fully qualified (hostname, ip) for the given hostname.
If hostname is not given, the default name of the local host
is chosen.
Defaults to default in case an error occurs while trying to
determine the da... |
def BinsTriangleInequality(d1, d2, d3):
""" checks the triangle inequality for combinations
of distance bins.
the general triangle inequality is:
d1 + d2 >= d3
the conservative binned form of this is:
d1(upper) + d2(upper) >= d3(lower)
"""
if d1[1] + d2[1] < d3[0]:
return False
i... |
def __parse_header(request):
"""Returns parsed headers"""
headers_body = request.splitlines()
body_index = headers_body.index("")
headers = {}
for header in headers_body[1:body_index]:
key, value = header.split(": ")
headers[key] = value
try:
body = headers_body[body_ind... |
def is_even(num: int) -> bool:
"""Function to check if a number is even or not"""
return num % 2 == 0 |
def get_member_hp(checks, member_uuid, pool_uuid):
"""Helper function to find a members health in a given pool
:param checks list: https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Pool/#healthMonitor
:param member_uuid: server UUID we are looking for
:param pool_uuid: Connection p... |
def ensure_list(data, key1, key2=None):
"""The API is inconsitent in how empty responses are returned. This ensures that we always get an empty list."""
if key2 is None:
key2 = key1[:-1]
if isinstance(data[key1], list):
data[key1] = {}
data[key1][key2] = []
elif data[key1].get(k... |
def encode_label(label: str) -> int:
"""
Encodes a label into a number
If there is no label, the number is 0.
Othewise, the number is the index in the sequence:
```
A1, B1, C1, D1, E1, A2, B2, C2, ...
```
A, B, C, D, E are interpretted as A1, B1, C1, D1, E1, respectively.
"""
if not label:
return 0
# p... |
def intersection(L1, L2):
"""Function to calculate intersection between two lists.
"""
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx / D
y = Dy / D
return x,y
else:
return False |
def relu(x: float) -> float:
"""
:math:`f(x) =` x if x is greater than 0, else 0
(See `<https://en.wikipedia.org/wiki/Rectifier_(neural_networks)>`_ .)
Args:
x (float): input
Returns:
float : relu value
"""
return x if x > 0.0 else 0.0 |
def get_readgroups2samples_from_header(header):
"""Given an input BAM header dict, return a dict {readgroup: sample}.
...doctest:
>>> header = {'RG':[{'ID': 'myid', 'SM': 'mysample'}, {'ID': 'myid2', 'SM': 'mysample2'}]}
>>> d = get_readgroups2samples_from_header(header)
>>> d['myid']
... |
def is_not_empty(s): # if string is empty or not
"""
:param s: String
:return: Bool value given the string if empty will return True
"""
return bool(s and s.strip()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.