content
stringlengths 42
6.51k
|
---|
def partition(array):
""" partition split array in half """
return [array[len(array)//2:], array[:len(array)//2]]
|
def OR(a, b):
"""
Returns a single character '0' or '1'
representing the logical OR of bit a and bit b (which are each '0' or '1')
>>> OR('0', '0')
'0'
>>> OR('0', '1')
'1'
>>> OR('1', '0')
'1'
>>> OR('1', '1')
'1'
"""
if a == '0' and b == '0':
return '0'
return '1'
|
def is_x12_data(input_data: str) -> bool:
"""
Returns True if the input data appears to be a X12 message.
:param input_data: Input data to evaluate
:return: True if the input data is a x12 message, otherwise False
"""
return input_data.startswith("ISA") if input_data else False
|
def get_multiples(multiplier, count):
"""Return [0, 1*multiplier, 2*multiplier, ...]."""
return [i * multiplier for i in range(count)]
|
def sum3(n):
"""
sum of n numbers - expression
n - unsigned
"""
m = n+1
return (m*(m-1))/2
|
def update_position(coord, velocity, delta_time, max_z, spatial_res):
"""
Accepts 3D coord, 3D velcoity vectors, and the timestep. Returns new coordinate position.
:param coord:
:param velocity:
:param delta_time:
:return:
"""
x, y, z = coord[0], coord[1], coord[2]
x_vel, y_vel, z_vel = velocity[0], velocity[1], velocity[2]
change_x, change_y, change_z = (x_vel * delta_time), (y_vel * delta_time), (z_vel * delta_time)
new_x, new_y, new_z = (x + change_x), (y + change_y), (z + change_z)
if new_z < max_z:
new_coord = (new_x, new_y, new_z)
distance_travelled = ((new_x - x), (new_y - y), (new_z - z))
else:
new_coord = (new_x, new_y, max_z)
distance_travelled = (0, 0, 0)
return new_coord, distance_travelled
|
def build_dict(arg):
"""
Helper function to the Evaluator.to_property_di_graph() method that
packages the dictionaries returned by the "associate" family of
functions and then supplies the master dict (one_dict) to the Vertex
obj as kwargs.
"""
# helper function to the Evaluator.to_property_di_graph() method that
# packages the dictionaries returned by the "associate_" family of
# functions and then supplies the master dict (one_dict) to the Vertex
# obj as **kwargs
one_dict = {}
for ar in arg:
one_dict.update(ar)
return one_dict
|
def admin_actions(context):
"""
Track the number of times the action field has been rendered on the page,
so we know which value to use.
"""
context['action_index'] = context.get('action_index', -1) + 1
return context
|
def sanitize_build(build):
"""
Takes a build name and processes it for tagging
:param build: String - Name of build - (full/slim)
:return: String - Name of processed build - (""/-slim)
"""
if build == "full":
return ""
elif build == "slim":
return "-" + build
|
def eval(predicted):
"""
Evaluates the predicted chunk accuracy
:param predicted:
:return:
"""
word_cnt = 0
correct = 0
for sentence in predicted:
for row in sentence:
word_cnt += 1
if row['chunk'] == row['pchunk']:
correct += 1
return correct / word_cnt
|
def compute(x, y):
"""The problem sets the parameters as integers in the range 0-100.
We'll raise an exception if we receive a type other than int, or if the value
of that int is not in the right range"""
if type(x) != int or type(y) != int:
raise TypeError('The types of both arguments must be ints')
if x < 0 or x > 100 or y < 0 or y > 100:
raise ValueError('The value of each argument must be in the range 0-100')
return x+y
|
def int_to_hex(number):
"""Convert an int into a hex string."""
# number.to_bytes((number.bit_length() + 7) // 8, byteorder='big')
hex_string = '%x' % number
return hex_string
|
def SeparateFlagArgs(args):
"""Splits a list of args into those for Flags and those for Fire.
If an isolated '--' arg is not present in the arg list, then all of the args
are for Fire. If there is an isolated '--', then the args after the final '--'
are flag args, and the rest of the args are fire args.
Args:
args: The list of arguments received by the Fire command.
Returns:
A tuple with the Fire args (a list), followed by the Flag args (a list).
"""
if '--' in args:
separator_index = len(args) - 1 - args[::-1].index('--') # index of last --
flag_args = args[separator_index + 1:]
args = args[:separator_index]
return args, flag_args
return args, []
|
def extract_tags(data, keys):
"""Helper function to extract tags out of data dict."""
tags = dict()
for key in keys:
try:
tags[key] = data.pop(key)
except KeyError:
# Skip optional tags
pass
return tags
|
def convert_enum_list_to_delimited_string(enumlist, delimiter=','):
"""
Converts a list of enums into a delimited string using the enum values
E.g., [PlayerActionEnum.FLYBALL, PlayerActionEnum.HOMERUN, PlayerActionEnum.WALK] = 'FLYBALL,HOMERUN,WALK'
:param enumlist:
:param delimiter:
:return:
"""
return delimiter.join([listitem.value for listitem in enumlist])
|
def create_vocab(data):
"""
Creating a corpus of all the tokens used
"""
tokenized_corpus = [] # Let us put the tokenized corpus in a list
for sentence in data:
tokenized_sentence = []
for token in sentence.split(' '): # simplest split is
tokenized_sentence.append(token)
tokenized_corpus.append(tokenized_sentence)
# Create single list of all vocabulary
vocabulary = [] # Let us put all the tokens (mostly words) appearing in the vocabulary in a list
for sentence in tokenized_corpus:
for token in sentence:
if token not in vocabulary:
if True:
vocabulary.append(token)
return vocabulary, tokenized_corpus
|
def _shellquote(s):
"""
http://stackoverflow.com/questions/35817/how-to-escape-os-system-calls-in-python
"""
return "'" + s.replace("'", "'\\''") + "'"
|
def get_ssh_info(**output_dict):
"""
Get the SSH status of each node
"""
out_dict = {}
response_json = output_dict['GetClusterSshInfo']
if 'result' not in response_json.keys():
if 'xPermissionDenied' in response_json['error']['message']:
print("No data returned from GetClusterSshInfo.\n"
"Permission denied, is the account a cluster admin?\n")
out_dict['Access Denied'] = 'Verify login credentials'
elif 'xUnknownAPIMethod' in response_json['error']['message']:
print("Incorrect API version, SSH requires at least 10.3")
out_dict['Unknown API'] = 'Verify API version 10.3 or above called'
else:
api_error = response_json['error']
print("Error returned:\n{}".format(api_error))
api_error_name = api_error['name']
api_error_message = api_error['message']
out_dict[api_error_name] = api_error_message
hdr1 = 'SSH status'
hdr2 = 'Response'
return hdr1, hdr2, out_dict
else:
cls_status = response_json['result']['enabled']
out_dict['Cluster'] = cls_status
for node in response_json['result']['nodes']:
node_id = str(node['nodeID'])
ssh_state = node['enabled']
out_dict[node_id] = ssh_state
hdr1 = "Node ID"
hdr2 = "SSH status"
return hdr1, hdr2, out_dict
|
def get_rest_url_private(account_id: int) -> str:
"""
Builds a private REST URL
:param account_id: account ID
:return: a complete private REST URL
"""
return f"https://ascendex.com/{account_id}/api/pro/v1/websocket-for-hummingbot-liq-mining"
|
def get_bowtie2_index_files(base_index_name):
""" This function returns a list of all of the files necessary for a Bowtie2 index
that was created with the given base_index_name.
Args:
base_index_name (string): the path and base name used to create the bowtie2 index
Returns:
list of strings: the paths to all of the files expected for a Bowtie2 index
based on the provided index_name
"""
bowtie_extensions = ['.1.bt2', '.2.bt2', '.3.bt2', '.4.bt2', '.rev.1.bt2', '.rev.2.bt2']
bowtie_files = ['{}{}'.format(base_index_name, bowtie_extension)
for bowtie_extension in bowtie_extensions]
return bowtie_files
|
def current_workspace(workspace=None):
"""Sets/Gets the current AML workspace used all accross code.
Args:
workspace (azureml.core.Workspace): any given workspace
Returns:
azureml.core.Workspace: current (last) workspace given to current_workspace()
"""
global CURRENT_AML_WORKSPACE
if workspace:
CURRENT_AML_WORKSPACE = workspace
if not CURRENT_AML_WORKSPACE:
raise Exception(
"You need to initialize current_workspace() with an AML workspace"
)
return CURRENT_AML_WORKSPACE
|
def nonempty(str):
""":nonempty: Any text. Returns '(none)' if the string is empty."""
return str or "(none)"
|
def name_normalize(name):
"""
Replaces "/" characters with "-" to
"""
if name is None:
return name
return name.replace("/", "-")
|
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
if not k:
return 1
else:
output = n
while k != 1:
output = output * (n - 1)
n = n - 1
k -= 1
return output
|
def infinite_check(graph_array, distance):
"""Runs the Bellman-Ford algorithm to look for infinite loops."""
## Check for negative-weight cycles:
## For each node_1:
for node_1, edges in enumerate(graph_array):
## For each node_2:
for node_2, edge in enumerate(edges):
## If distance[node_1] + graph_array[node_1][node_2]
## < distance[node_2]:
if distance[node_1] + edge < distance[node_2]:
return True
return False
|
def is_ok(func, prompt, blank='', clearline=False):
"""Prompt the user for yes/no and returns True/False
Arguments:
prompt -- Prompt for the user
blank -- If True, a blank response will return True, ditto for False, the default ''
will not accept blank responses and ask until the user gives an appropriate
response
Returns:
True if user accepts, False if user does not"""
while True:
ok = func(prompt).lower().strip()
if len(ok) > 0:
if ok[0] == 'y' or ok[0] == 't' or ok[0] == '1': # yes, true, 1
return True
elif ok[0] == 'n' or ok[0] == 'f' or ok[0] == '0': # no, false, 0
return False
else:
if blank is True:
return True
elif blank is False:
return False
|
def prepare_qualification(qual: str) -> dict:
"""
Prepares a qualification object from an expression string.
Examples:
location in US,CA,GB
location not_in US-CA,US-MA
hits_approved > 500
percent_approved > 95
:param qual: a qualification in format 'qual_id operator value'
:return:
"""
_QUAL_IDS = {
"location": '00000000000000000071',
"hits_approved": '00000000000000000040',
"percent_approved": '000000000000000000L0'
}
_COMPARATORS = {
">": "GreaterThan",
"=": "GreaterThan",
"<": "LessThan",
"in": "In",
"not_in": "NotIn",
}
parts = qual.split(' ')
if len(parts) != 3 or parts[1] not in _COMPARATORS:
raise ValueError("Invalid qualification specifier: {}".format(qual))
qual_id, comparator, value = parts
if qual_id == "location":
assert comparator in ["in", "not_in"], f"When using a location qualification, use 'in' or 'not_in'. Got {qual}."
locations = value.split(",")
value = []
for location in locations:
parts = location.split("-", 1)
if len(parts) == 1:
value.append({"Country": parts[0]})
else:
value.append({"Country": parts[0], "Subdivision": parts[1]})
return {
"QualificationTypeId": _QUAL_IDS.get(qual_id, qual_id),
"Comparator": _COMPARATORS[comparator],
"LocaleValues": value,
}
else:
return {
"QualificationTypeId": _QUAL_IDS.get(qual_id, qual_id),
"Comparator": _COMPARATORS[comparator],
"IntegerValues": [int(value)],
}
|
def build_complement(dna):
"""
:param dna: dna string
:return ans : the complement strand of dna
"""
ans = ''
for base in dna:
if base == 'A':
ans += 'T'
elif base == 'T':
ans += 'A'
elif base == 'C':
ans += 'G'
elif base == 'G':
ans += 'C'
return ans
|
def bisect_left(data, target, lo, hi):
"""
Given a sorted array, returns the insertion position of target
If the value is already present, the insertion post is to the left of all of them
>>> bisect_left([1,1,2,3,4,5], 1, 0, 6)
0
>>> bisect_left([1,1,2,3,4,5], 6, 0, 6)
6
>>> bisect_left([1,1,2,3,4,5], 0, 0, 6)
0
"""
while lo < hi:
mid = (lo+hi)/2
if data[mid] < target:
lo = mid+1
else:
hi = mid
return lo
|
def _is_range_format_valid(format_string: str) -> bool:
"""
Return 'True' if a string represents a valid range definition and 'False' otherwise.
Parameters
----------
format_string:
String that should be checked.
Returns
-------
bool:
'True' if the passed string is a valid range definition, 'False' otherwise
"""
if "~" in format_string:
if len(format_string.split("~")) != 2:
return False
format_string = format_string.replace("~", "")
return format_string.isalnum() or format_string == ""
return format_string.isalnum()
|
def is_monotonic(a,b,c):
"""
Determines if the three input numbers are in sequence, either low-to-high
or high-to-low (with ties acceptable).
Parameters
----------
a : float
b : float
c : float
Returns
----------
boolean
"""
# if b is equal to either a or c then the sequence is monotonic
if b == a:
return True
elif b == c:
return True
# otherwise, a and c must be on different sides of b
elif (a > b) != (c > b):
return True
else:
return False
|
def _kw_extract(kw,dict):
""" if keys from dict occur in kw, pop them """
for key,value in dict.items():
dict[key]=kw.pop(key,value)
return kw,dict
|
def remove_prefix(state_dict, prefix):
"""Old style model is stored with all names of parameters share common prefix 'module."""
def f(x):
return x.split(prefix, 1)[-1] if x.startswith(prefix) else x
return {f(key): value for key, value in state_dict.items()}
|
def get_revisions(page):
"""Extract the revisions of a page.
Args:
page: a string
Returns:
a list of strings
"""
start_string = " <revision>\n"
end_string = " </revision>\n"
ret = []
current_pos = 0
while True:
start_pos = page.find(start_string, current_pos)
if start_pos == -1:
break
end_pos = page.find(end_string, start_pos)
assert end_pos != -1
ret.append(page[start_pos + len(start_string):end_pos])
current_pos = end_pos + len(end_string)
return ret
|
def check_len(wt: str, off: str) -> int:
"""Verify the lengths of guide and off target match returning the length
Args:
wt: the guide type guide sequence
off: the off target sequence
Returns:
(int): the length of the data
"""
wtl = len(wt)
offl = len(off)
assert (wtl == offl), "The lengths wt and off differ: wt = {}, off = {}".format(str(wtl), str(offl))
return wtl
|
def get_concert_info(event, location):
"""Get additional information for each event for the markers' info window"""
concert = {}
concert["venue"] = event['_embedded']['venues'][0]['name']
concert["location"] = location
concert["city"] = event['_embedded']['venues'][0]['city']['name']
concert["date"] = event['dates']['start']['localDate']
concert["link"] = event["url"]
return concert
|
def isGreaterOrEqual(a, b):
"""Compare the two options and choose best permutation"""
ab = str(a) + str(b)
ba = str(b) + str(a)
if ab > ba:
return a
else:
return b
|
def calculateEffective (trgtable, totalrecorded):
"""
input: trgtable{hltpath:[l1seed, hltprescale, l1prescale]}, totalrecorded (float)
output:{hltpath, recorded}
"""
#print 'inputtrgtable', trgtable
result = {}
for hltpath, data in trgtable.items():
if len (data) == 3:
result[hltpath] = totalrecorded/ (data[1]*data[2])
else:
result[hltpath] = 0.0
return result
|
def IJK(nx, ny, nz, i, j, k):
"""
Translate a three dimensional point to
a one dimensional list
Parameters
nx: No. of total gridpoints in x direction (int)
ny: No. of total gridpoints in y direction (int)
nz: No. of total gridpoints in z direction (int)
i: Specific gridpoint in x direction (int)
j: Specific gridpoint in y direction (int)
k: Specific gridpoint in z direction (int)
Returns
value: The one dimensional value matching the
three dimensional point
"""
value = (k*nx*ny + j*nx + i)
return value
|
def cleanString(s):
""" takes in a string s and return a string with no punctuation and no upper-case letters"""
s = s.lower()
import string
for p in "?.!,'": # looping over punctuation
s = s.replace(p,'') # replacing punctuation with space
return s
|
def _MakeOptional(property_dict, test_key):
"""Iterates through all key/value pairs in the property dictionary. If the "test_key" function
returns True for a particular property key, then makes that property optional. Returns the
updated property dict.
"""
for key, value in property_dict.items():
if test_key(key):
property_dict[key]['required'] = False
return property_dict
|
def is_typed_dict(type_or_hint) -> bool:
"""
returns whether the type or hint is a TypedDict
"""
return issubclass(type_or_hint, dict) and hasattr(type_or_hint, "__annotations__")
|
def sorted_values(x):
"""Returns the sorted values of a dictionary as a list."""
return [x[k] for k in sorted(x)]
|
def adjustEdges(height, width, point):
"""
This handles the edge cases if the box's bounds are outside the image range based on current pixel.
:param height: Height of the image.
:param width: Width of the image.
:param point: The current point.
:return:
"""
newPoint = [point[0], point[1]]
if point[0] >= height:
newPoint[0] = height - 1
if point[1] >= width:
newPoint[1] = width - 1
return tuple(newPoint)
|
def resource_wrapper(data):
"""Wrap the data with the resource wrapper used by CAI.
Args:
data (dict): The resource data.
Returns:
dict: Resource data wrapped by a resource wrapper.
"""
return {
'version': 'v1',
'discovery_document_uri': None,
'discovery_name': None,
'resource_url': None,
'parent': None,
'data': data
}
|
def parse_sql_condition(cohort_ids, where_condition=False):
""" Parse the sql condition to insert in another sql statement.
"""
return f"""{"WHERE" if where_condition else "AND"} id IN {cohort_ids}""" \
if cohort_ids else ""
|
def getPath(bucketName, key):
"""
Args:
bucketName: the name of the s3 bucket
key: S3 object key within a bucket, i.e. the path
Returns:
The path of the s3 object
"""
return f's3://{bucketName}/{key}'
|
def invert(ref_filters):
"""Inverts reference query filters for a faster look-up time downstream."""
inv_filters = {}
for key, value in ref_filters.items():
try:
# From {"cats_ok": {"url_key": "pets_cat", "value": 1, "attr": "cats are ok - purrr"},}
# To {"cats are ok - purrr": {"cats_ok": "true"},}
inv_filters[value["attr"]] = {key: "true"}
except KeyError:
# For filters with multiple values.
# From {'auto_bodytype': ['bus', 'convertible', ... ],}
# To {'bus': 'auto_bodytype', 'convertible': 'auto_bodytype', ... ,}
if isinstance(value, dict):
inv_filters.update({child_value: key for child_value in value})
return inv_filters
|
def cubic_bezier(start, end, ctrl1, ctrl2, nv):
"""
Create bezier curve between start and end points
:param start: start anchor point
:param end: end anchor point
:param ctrl1: control point 1
:param ctrl2: control point 2
:param nv: number of points should be created between start and end
:return: list of smoothed points
"""
result = [start]
for i in range(nv - 1):
t = float(i) / (nv - 1)
tc = 1.0 - t
t0 = tc * tc * tc
t1 = 3.0 * tc * tc * t
t2 = 3.0 * tc * t * t
t3 = t * t * t
tsum = t0 + t1 + t2 + t3
x = (t0 * start[0] + t1 * ctrl1[0] + t2 * ctrl2[0] + t3 * end[0]) / tsum
y = (t0 * start[1] + t1 * ctrl1[1] + t2 * ctrl2[1] + t3 * end[1]) / tsum
result.append((x, y))
result.append(end)
return result
|
def bfs(graph: list, start: int):
"""
Here 'graph' represents the adjacency list
of the graph, and 'start' represents the
node from which to start
"""
visited, queue = set(), [start]
while (queue):
vertex = queue.pop(0)
if (vertex not in visited):
visited.add(vertex)
queue.extend(graph[vertex] - visited)
return visited
|
def _hostname_matches(cert_pattern, actual_hostname):
"""
:type cert_pattern: `bytes`
:type actual_hostname: `bytes`
:return: `True` if *cert_pattern* matches *actual_hostname*, else `False`.
:rtype: `bool`
"""
if b"*" in cert_pattern:
cert_head, cert_tail = cert_pattern.split(b".", 1)
actual_head, actual_tail = actual_hostname.split(b".", 1)
if cert_tail != actual_tail:
return False
# No patterns for IDNA
if actual_head.startswith(b"xn--"):
return False
return cert_head == b"*" or cert_head == actual_head
else:
return cert_pattern == actual_hostname
|
def ipow(a,b):
"""
returns pow(a,b) for integers
constructed in terms of lower arithmetic to be compatible
with cost calculations
"""
# quick special cases
if b == 0:
return 1
if a == 0:
return 0
if a == 1:
return 1
if a == -1:
if (b%2) == 1:
return -1
return 1
if b < 0:
raise ValueError('ipow not defined for negative exponent and |base|>1')
val = 1
while True:
b,bit = divmod(b,2)
if bit:
val = val*a # no *= to allow cost calculation
if b == 0:
break
a = a*a # no *= to allow cost calculation
return val
|
def first_upper_case(words):
"""
Set First character of each word to UPPER case.
"""
return [w.capitalize() for w in words]
|
def nodes_per_dai(tree, context):
"""Return the ratio of the number of nodes to the number of original DAIs.
@rtype: dict
@return: dictionary with one key ('') and the target number as a value
"""
return {'': len(tree) / float(len(context['da']))}
|
def init_time(p, **kwargs):
"""Initialize time data."""
time_data = {
'times': [p['parse']],
'slots': p['slots'],
}
time_data.update(**kwargs)
return time_data
|
def crystal(ele):
"""
Tell me the name of element.
I will tell you its crystal structure and recorded lattice parameter.
"""
if ele in ('Cu', 'cu'):
lat_a = 3.597 # unit is A
lat_b = lat_a
lat_c = lat_a
cryst_structure = 'FCC' # the name of crystal structure
if ele in ('Ni', 'ni'):
lat_a = 3.520 # unit is A
lat_b = lat_a
lat_c = lat_a
cryst_structure = 'FCC' # the name of crystal structure
if ele in ('Si', 'si'):
lat_a = 5.431 # unit is A
lat_b = lat_a
lat_c = lat_a
cryst_structure = 'Diamond_Cubic' # the name of crystal structure
if ele in ('Mo', 'mo'):
lat_a = 3.147 # unit is A
lat_b = lat_a
lat_c = lat_a
cryst_structure = 'BCC' # the name of crystal structure
if ele in ('Ti', 'ti'):
lat_a = 2.951 # unit is A
lat_b = lat_a
lat_c = 4.684
cryst_structure = 'HCP' # the name of crystal structure
if ele in ('Al', 'al'):
lat_a = 4.046 # unit is A
lat_b = lat_a
lat_c = lat_a
cryst_structure = 'FCC' # the name of crystal structure
#print("The structure of {} is {}, and lattice parameter is {}.".format(ele, cs, str(a)))
else:
lat_a = 0
lat_b = lat_a
lat_c = lat_a
cryst_structure = 'nope'
print("Our database is so small. It is time to add more element!")
return cryst_structure, lat_a, lat_b, lat_c
|
def language_probabilities(word, models):
"""Return a list of probabilities for word in each model"""
probabilities = list(map(lambda model: model.find_word_probability(word)[0], models))
return probabilities
|
def convert(value, _type):
"""
Convert instances of textx types to python types.
"""
return {
'BOOL' : lambda x: x == '1' or x.lower() == 'true',
'INT' : lambda x: int(x),
'FLOAT' : lambda x: float(x),
'STRING': lambda x: x[1:-1].replace(r'\"', r'"').replace(r"\'", "'"),
}.get(_type, lambda x: x)(value)
|
def distance(x, y, i, j):
""" get eculidien distance """
return ((x - i) ** 2 + (y - j) ** 2)
|
def directions(startxy, endxy):
""" Returns 0, 90, 180 or 270
:rtype : integer
:return: degrees !!counter clockwise!!
"""
startX, startY = startxy[0], startxy[1]
endX, endY = endxy[0], endxy[1]
if startX < endX:
return 270
elif startX > endX:
return 90
elif startY < endY:
return 180
else:
return 0
|
def convertStringToList(string):
"""
Really simply converts a string to a list
"""
theList = []
for x in range(0, len(string)):
theList.append(string[x])
return theList
|
def find_pivot_column(last_row):
"""
locate the most negative entry in the last row excluding the last column
"""
m = 0
column_index = -1
for i, entry in enumerate(last_row):
if entry < 0:
if entry < m:
m = entry
column_index = i
return column_index
|
def get_bigger_bbox(bbox1, bbox2):
"""
:param bbox1:
:param bbox2:
:return:
Assumption: One bounding box is contained inside another
"""
min_x_1 = min([x for x, y in bbox1])
min_y_1 = min([y for x, y in bbox1])
max_x_1 = max([x for x, y in bbox1])
max_y_1 = max([y for x, y in bbox1])
min_x_2 = min([x for x, y in bbox2])
min_y_2 = min([y for x, y in bbox2])
max_x_2 = max([x for x, y in bbox2])
max_y_2 = max([y for x, y in bbox2])
if min_x_1 < min_x_2 or min_y_1 < min_y_2:
return bbox1
if max_x_2 < max_x_1 or max_y_2 < max_y_1:
return bbox1
return bbox2
|
def is_str(var):
"""Returns True, if int"""
return isinstance(var, str)
|
def response_generator(intent, tags, tokens):
"""
response_generator - function to generate response (searching in this version)
Inputs:
- intent : str
Intent
- tags : list
List of tags
- tokens : list
List of tokens
Outputs:
- _: dict
Dictionary of Intent and Entities
"""
entities = {}
for idx in range(len(tags)):
if tags[idx] != 'o':
tag = tags[idx][2:]
if not tag in entities:
entities[tag] = [tokens[idx]]
else:
entities[tag].append(tokens[idx])
return {'Intent' : intent, 'Entities' : entities}
|
def sort_by_last(txt):
"""Sort string txt by each word's last character."""
return " ".join(sorted(
[word for word in txt.split(' ')],
key=lambda x: x[-1].lower()
))
|
def deep_dict_merge(from_file: dict, from_env: dict):
"""
Iterative DFS to merge 2 dicts with nested dict
a = {'a', {'j': 2, 'b': 1}, c: 1, e: 4}
b = {'a': {'k': 4, 'b': 12}, d: 2, e: 5}
{'a':{'j': 2, 'k': 4, 'b': 12}, c: 1, d: 2, e: 5}
"""
conf_data = {}
stack = [(conf_data, from_file, from_env)]
while stack:
conf, dict1, dict2 = stack.pop()
for key in dict1:
if isinstance(dict1[key], dict) and isinstance(dict2.get(key), dict):
conf[key] = {}
stack.append((conf[key], dict1[key], dict2[key]))
continue
# dict2 is overwriting dict1
conf[key] = dict2.get(key, dict1[key])
for key, val in dict2.items():
conf.setdefault(key, val)
return conf_data
|
def translate(term, locale=None, strict=False):
"""This function allows you to retrieve the global translation of a
term from the translation database using the current locale.
Args:
term (str): The term to look up.
locale (str): Which locale to translate against. Useful when
there are multiple locales defined for a single term. If
omitted, the function attempts to use the current locale (as
defined by the client, session, or Designer). Optional.
strict (bool): If False, the function will return the passed
term (param 1) if it could not find a defined translation
for the locale: meaning, if you pass a term that hasn't been
configured, the function will just send the term back to
you. If True, then the function will return a None when it
fails to find a defined translation. Default is False.
Optional.
Returns:
str: The translated term.
"""
print(term, locale, strict)
return term
|
def avg_words_per_sent(sent_count, word_count):
"""return the average number of words per sentence"""
result = word_count/sent_count
return result
|
def string_to_int(string, keyspace_chars):
""" Turn a string into a positive integer. """
output = 0
for char in string:
output = output * len(keyspace_chars) + keyspace_chars.index(char)
return output
|
def check_headers(headers):
"""Return True if the headers have the required keys.
Parameters
----------
headers : dict
should contains 'content-type' and 'x-mailerlite-apikey'
Returns
-------
valid_headers : bool
True if it is valid
error_msg : str
the error message if there is any problem
"""
valid_headers = True
error_msg = ''
if not headers:
error_msg = "Empty headers. Please enter a valid one"
valid_headers = False
return valid_headers, error_msg
if not isinstance(headers, dict):
error_msg = "headers should be a dictionnary"
valid_headers = False
return valid_headers, error_msg
if ('content-type' not in headers or
'x-mailerlite-apikey' not in headers):
error_msg = "headers should be a dictionnary and it contains "
error_msg += "'content-type' and 'x-mailerlite-apikey' as keys"
valid_headers = False
return valid_headers, error_msg
return valid_headers, error_msg
|
def get_ring_size(
x_ring_size: int,
y_ring_size: int,
) -> int:
"""Get the ring_size of apply an operation on two values
Args:
x_ring_size (int): the ring size of op1
y_ring_size (int): the ring size of op2
Returns:
The ring size of the result
"""
if x_ring_size != y_ring_size:
raise ValueError(
"Expected the same ring size for x and y ({x_ring_size} vs {y_ring_size})"
)
return x_ring_size
|
def is_excluded(value):
"""Validate if field 300 should be excluded."""
exclude = [
"mul. p",
"mult p",
"mult. p",
"mult. p.",
"mult. p",
"multi p",
"multi pages",
]
if not value or value.strip().lower() in exclude:
return True
return False
|
def _clean_lines(lines):
"""removes comment lines and concatenates include files"""
lines2 = []
for line in lines:
line2 = line.strip().split('**', 1)[0]
#print(line2)
if line2:
if 'include' in line2.lower():
sline = line2.split(',')
assert len(sline) == 2, sline
assert '=' in sline[1], sline
sline2 = sline[1].split('=')
assert len(sline2) == 2, sline2
base, inc_filename = sline2
base = base.strip()
inc_filename = inc_filename.strip()
assert base.lower() == 'input', 'base=%r' % base.lower()
with open(inc_filename, 'r') as inc_file:
inc_lines = inc_file.readlines()
inc_lines = _clean_lines(inc_lines)
lines2 += inc_lines
continue
lines2.append(line)
return lines2
|
def ordered_unique(seq):
"""
Return unique items in a sequence seq preserving the original order.
"""
if not seq:
return []
uniques = []
for item in seq:
if item in uniques:
continue
uniques.append(item)
return uniques
|
def kepler_parabolic(B):
"""
Computes the time of flight since perigee passage at particular eccentric
anomaly for paraboliparabolic orbit.
Parameters
----------
B: float
Parabolic anomaly.
Returns
-------
Mp: float
Parabolic mean motion
"""
Mp = B + (1 / 3) * B ** 3
return Mp
|
def adjustList (theList):
"""Copies thelist, modifies values to range 0 to 100.
Designed to handle integer values. Will convert floats.
:param theList: List of any values of no specified range
:type theList: list
:return: List of values with a max. of 100 and min. of 0
:rtype: list
:raise ValueError: Supports only numerical values (integers).
"""
adjustedList = []
for i in range(len(theList)):
if theList[i] > 100:
adjustedList.append(100)
elif theList[i] < 0:
adjustedList.append(0)
else:
adjustedList.append(theList[i])
return adjustedList
|
def _make_yaml_key(s):
"""
Turn an environment variable into a yaml key
Keys in YAML files are generally lower case and use dashes instead of
underscores. This isn't a universal rule, though, so we'll have to
either change the keys to conform to this, or have some way of indicating
this from the environment.
"""
return s.lower().replace("_", "-")
|
def checkuuidsyntax(uuidtxt):
""" Check syntax of the UUID, utility function
"""
score = 0
if uuidtxt != None:
if len(uuidtxt) < 10:
score = 0
elif uuidtxt.find("{") > -1 or uuidtxt.find("}") > -1 or uuidtxt.lower() != uuidtxt:
score = 1
else:
score = 2
return score
|
def partition(arr, start, end):
"""Moving elements to left and right to pivot to make sure arr[pi] is at the right position
Input:
- arr: array to be sorted
- start: start position/index
- end: end position/index
Return: pi"""
# ----_small-----start--------------------end-----------
#----------------a[i]-------small---------a[i]----end--
#----------------a[i]-------end(pivot)----a[i]---------
# Return _small = positiion of Pivot = new position of end value
_pi = arr[end] #pivot as last element
_small = start - 1 # smaller index indicator (=0 at the start)
for i in range(start, end):
# run a loop for a whole array
if arr[i] <= _pi:
# Increase the index (room) for smaller value
_small = _small+1
# moving smaller values to the left by swapping
arr[_small], arr[i] = arr[i], arr[_small]
# Finally, moving elemet with pivot value (last one) to the middle (end of smaller)
_small = _small+1
arr[_small], arr[end] = arr[end], arr[_small]
# return value
return _small
|
def GetFileExtension(file_path):
"""Given foo/bar/baz.pb.gz, returns '.pb.gz'."""
# Get the filename only because the directory names can contain "." like
# "v8.browsing".
filename = file_path.split('/')[-1]
first_dot_index = filename.find('.')
if first_dot_index == -1:
return ''
else:
return filename[first_dot_index:]
|
def first_element_or_none(element_list):
"""
Return the first element or None from an lxml selector result.
:param element_list: lxml selector result
:return:
"""
if element_list:
return element_list[0]
return
|
def char2int(char):
"""
Convert character to integer.
"""
if char >= 'a' and char <= 'z':
return ord(char) - ord('a')
elif char == ' ':
return 26
return None
|
def get_keys_from_val(dic, val):
"""Get all keys from a value in a dictionnary"""
toreturn = list()
for key in dic:
if dic[key] == val:
toreturn.append(key)
return toreturn
|
def extract_data_from_query(query):
"""
query: a string.
return: a dictionary.
"""
result = {}
if query is '':
return result
list_of_queries = query.split('&')
for q in list_of_queries:
splitted = q.split('=')
result[splitted[0]] = splitted[1]
return result
|
def cr_strip(text):
"""
Args:
Returns:
Raises:
"""
text = text.replace("\n", "")
text = text.replace("\r", "")
return text
|
def _filter_none_values(d: dict):
"""
Filter out the key-value pairs with `None` as value.
Arguments:
d
dictionary
Returns:
filtered dictionary.
"""
return {key: value for (key, value) in d.items() if value is not None}
|
def mmd0_decode(data):
"""return data read from file (short - MMD0 - format) as note event information
"""
note_number = data[0] & 0x3F
instr_hi = (data[0] & 0xC0) >> 2
instr_lo = data[1] >> 4
instr_number = instr_hi + instr_lo
command = data[1] & 0x0F
return note_number, instr_number, command, data[2]
|
def wrap_url(s, l):
"""Wrap a URL string"""
parts = s.split('/')
if len(parts) == 1:
return parts[0]
else:
i = 0
lines = []
for j in range(i, len(parts) + 1):
tv = '/'.join(parts[i:j])
nv = '/'.join(parts[i:j + 1])
if len(nv) > l or nv == tv:
i = j
lines.append(tv)
return '/\n'.join(lines)
|
def myround(x, base=5):
"""Custom rounding for histogram."""
return int(base * round(float(x) / base))
|
def _get_mailpiece_image(row):
"""Get mailpiece image url."""
try:
return row.find('img', {'class': 'mailpieceIMG'}).get('src')
except AttributeError:
return None
|
def replaceTill(s, anchor, base):
"""Replaces the beginning of this string (until anchor) with base"""
n = s.index(anchor)
return base + s[n:]
|
def parse_bool(string: str) -> bool:
"""Parses strings into bools accounting for the many different text representations of bools
that can be used
"""
if string.lower() in ["t", "true", "1"]:
return True
elif string.lower() in ["f", "false", "0"]:
return False
else:
raise ValueError("{} is not a valid boolean string".format(string))
|
def _rfc822_escape(header):
"""Return a version of the string escaped for inclusion in an
RFC-822 header, by ensuring there are 8 spaces space after each newline.
"""
lines = header.split('\n')
header = ('\n' + 8 * ' ').join(lines)
return header
|
def chunk_data(lst, n):
""" Chunk the data into lists to k fold cv"""
increment = len(lst) / float(n)
last = 0
index = 1
results = []
while last < len(lst):
idx = int(round(increment * index))
results.append(lst[last:idx])
last = idx
index += 1
return results
|
def get_polymer_template(text: str) -> str:
"""
Gets the polymer template sequence from the first
line of `text`.
"""
return text.strip().splitlines()[0]
|
def mode(lyst):
"""Returns the mode of a list of numbers."""
# Obtain the set of unique numbers and their
# frequencies, saving these associations in
# a dictionary
theDictionary = {}
for number in lyst:
freq = theDictionary.get(number, None)
if freq == None:
# number entered for the first time
theDictionary[number] = 1
else:
# number already seen, increment its freq
theDictionary[number] = freq + 1
# Find the mode by obtaining the maximum freq
# in the dictionary and determining its key
if len(theDictionary) == 0:
return 0
else:
theMaximum = max(theDictionary.values())
for key in theDictionary:
if theDictionary[key] == theMaximum:
return key
|
def gcd_steps(a, b):
""" Return the number of steps needed to calculate GCD(a, b)."""
# GCD(a, b) = GCD(b, a mod b).
steps = 0
while b != 0:
steps += 1
# Calculate the remainder.
remainder = a % b
# Calculate GCD(b, remainder).
a = b
b = remainder
# GCD(a, 0) is a.
#return a
return steps
|
def annotate_code(path, code, coverage):
"""Annotate lines of code with line numbers and coverage status."""
return [{ # line_num is 0-based, line numbers are 1-based
'num': line_num+1,
'status': str(coverage.lookup(path, line_num+1)).lower(),
'code': line
} for (line_num, line) in enumerate(code.splitlines())]
|
def HealthCheckName(deployment):
"""Returns the name of the health check.
A consistent name is required to define references and dependencies.
Assumes that only one health check will be used for the entire deployment.
Args:
deployment: the name of this deployment.
Returns:
The name of the health check.
"""
return "{}-health-check".format(deployment)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.