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':
retur... |
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_v... |
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_... |
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 ... |
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 i... |
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.
Arg... |
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:
... |
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(tok... |
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 GetCluste... |
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:
... |
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... |
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:
... |
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 ... |
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 give... |
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 valu... |
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'... |
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(... |
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 va... |
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... |
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:... |
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 (w... |
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["da... |
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:
... |
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 directio... |
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_... |
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],... |
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_nam... |
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... |
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
... |
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.ad... |
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".",... |
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:
... |
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... |
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'"').re... |
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 < e... |
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 col... |
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 bb... |
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 ... |
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,... |
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
th... |
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 mes... |
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 !=... |
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 F... |
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... |
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... |
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 ... |
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 th... |
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:
... |
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-----------
#----------... |
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 file... |
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, c... |
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 n... |
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... |
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... |
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 = rema... |
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 ... |
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 ch... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.