content
stringlengths 42
6.51k
|
---|
def stag_density_ratio(M, gamma):
"""Stagnation density / static density ratio.
Arguments:
M (scalar): Mach number [units: dimensionless].
gamma (scalar): Heat capacity ratio [units: dimensionless].
Returns:
scalar: the stagnation density ratio :math:`\\rho_0 / \\rho` [units: dimensionless].
"""
return (1 + (gamma - 1) / 2 * M**2)**(1 / (gamma - 1))
|
def reverse(string):
"""
>>> reverse('Robin')
'niboR'
"""
if len(string) < 2:
return string
else:
return reverse(string[1:]) + string[0]
|
def vflip(anns, size):
"""
Vertically flip the bounding boxes of the given PIL Image.
Parameters
----------
anns : ``List[Dict]``
Sequences of annotation of objects, containing `bbox` of [l, t, w, h].
size : ``Sequence[int]``
Size of the original image.
"""
w, h = size
new_anns = []
for ann in anns:
bbox = list(ann['bbox'])
bbox[1] = h - (bbox[1] + bbox[3])
new_anns.append({**ann, "bbox": bbox})
return new_anns
|
def follows(trace, distance=1):
"""Returns a mapping (aka. dict) from pairs of activities to frequency.
A pair (a, b) is part of the mapping if activity b directly follows activity a,
in any of the traces.
Parameters
----------
distance: int
Distance two activities have to be appart to be counted in the mapping.
"""
if not isinstance(trace, tuple):
raise ValueError("Trace has to be a tuple of activities.")
if not float(distance).is_integer():
raise ValueError("Distance has to be an integer.")
if not distance >= 1:
raise ValueError("Distance has to be greater or equal to 1.")
pairs = dict()
for i in range(len(trace) - distance):
ai = trace[i]
aj = trace[i + distance]
if (ai, aj) not in pairs:
pairs[(ai, aj)] = 0
pairs[(ai, aj)] += 1
return pairs
|
def clean_and_split(input_val, split_by_char=',', enclosure_char='{|}|[|]', strip_chars='"',
also_remove_single_inv_comma=False):
"""
Returns a dictionary of split columns
Used for amenities and host verifications within get_cleaned_listings()
:params input_val array:
:params split_by_char string:
:params enclosure_char string:
:params strip_char string:
:params also_remove_single_inv_comma boolean(optional):
:returns dictionary of split columns
"""
# Split columns by characters
input_val = input_val.strip()
input_val = input_val.strip(enclosure_char)
input_val = input_val.split(split_by_char)
# Remove the apostrophe for host_verifications
if also_remove_single_inv_comma is True:
input_val = [item.strip().strip(strip_chars).strip("'").strip() for item in input_val]
else:
input_val = [item.strip().strip(strip_chars).strip() for item in input_val]
# Assemble dictionary
output_dict = {}
for item in input_val:
output_dict[item] = 1
return output_dict
|
def normalize(iter):
"""
Normally takes the output of `extrapolate` and makes a dictionary suitable
for applying to a connector.
"""
rd = {}
for (k, v) in iter:
sd = rd
for sk in k[:len(k)-1]:
sd = sd.setdefault(sk, {})
sd[k[-1]] = v
return rd
|
def _version_for_config(version, config):
"""Returns the version string for retrieving a framework version's specific config."""
if "version_aliases" in config:
if version in config["version_aliases"].keys():
return config["version_aliases"][version]
return version
|
def tick(text: str):
"""Add '`' to text"""
return f"`{text}`"
|
def splitSecondLevelEntry(name):
"""Split second-level entry and return (first, second) pair.
If name is not a second level entry then (None, name) is returned.
"""
xs = None
if name.count('::') > 1 and ' ' in name:
xs = name.split(' ', 1)
elif '#' in name:
xs = name.split('#', 1)
elif '::' in name:
xs = name.rsplit('::', 1)
if xs:
return xs
return (None, name)
|
def handle_same_string(str1, alist):
""" if a string already exist in a list, add a number to it """
if str1 in alist:
for i in range(1, 1000):
str1_ = str1 + ' (%i)' % i
if str1_ not in alist:
return str1_
else:
return str1
|
def remove_unrelated_domains(subdomains, domains):
"""
This function removes from the entire set hostnames found, the ones who
do not end with the target provided domain name.
So if in the list of domains we have example.com and our target/scope
is example.it, then example.com will be removed because falls out of the
scope.
Args:
domains -- the list of input target domains
Returns:
subdomains -- the set of subomains strictly respecting the scope
"""
subdomains = [s for s in subdomains if s.endswith(tuple(domains))]
return subdomains
|
def have_txt_extension(l):
"""Check if .txt extension is present"""
if ".txt" in str(l):
return 1
else:
return 0
|
def int_to_bits(i:int):
"""Take an integer as input and return the bits written version."""
return "{:0{}b}".format(i,i.bit_length())
|
def make_sequence(elements):
"""
Ensure that elements is a type of sequence, otherwise
it converts it to a list with only one element.
"""
if isinstance(elements, (list, set, tuple)):
return elements
elif elements is None:
return []
else:
return [elements]
|
def calculate_alphabet_from_order(ORDER):
"""
Generates aplhabet from order
"""
LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ALPHABET = ""
for CHAR in ORDER:
if CHAR.islower():
ALPHABET = "%s%s" % (ALPHABET, LOWERCASE)
elif CHAR.isupper():
ALPHABET = "%s%s" % (ALPHABET, UPPERCASE)
else:
try:
int(CHAR)
ALPHABET = "%s%s" % (ALPHABET, "0123456789")
except TypeError:
pass
return ALPHABET
|
def amax(lst):
"""
return max value by deviation from 0
:param lst iterable: list of values to find max in
:returns: max value by deviation from 0
"""
return max([abs(x) for x in lst])
|
def is_templated(module):
"""Returns an indication where a particular module is templated
"""
if "attr" not in module:
return False
elif module["attr"] in ["templated"]:
return True
else:
return False
|
def is_list(value):
"""Checks if value is a list"""
return isinstance(value, list)
|
def median(subarr, k):
"""
Return the median of the subarray based on the value ok "k"
"""
even_k = (k % 2 == 0)
if even_k:
right = k / 2
left = right - 1
return (subarr[left] + subarr[right]) / 2
else:
id = k // 2
return subarr[id]
|
def generate_sol_patterns(patterns, ngrams):
"""A method to generate SOL patterns given the textual patterns and ngrams.
Parameters
----------
patterns : type List
Textual Patterns
ngrams : type List of tuples
NGrams
Returns
-------
type List
Returns SOL Patterns
"""
pos_patterns = []
for pattern_index, pattern in enumerate(patterns):
words = pattern.split(" ")
line = []
pos_line = []
for word_index, word in enumerate(words):
if word.startswith("CHEMICAL_") or word.startswith("DISEASE_") or word.startswith("GENE_"):
line.append("<ENTITY>")
#pos_line.append("<ENTITY>")
else:
line.append(word)
#pos_line.append(post[pattern_index][word_index])
line = ' '.join(line)
times = 0
for string, suport in ngrams:
if string in line:
if times <= 4:
line = line.replace(" "+string+" ", " $ $ $ ")
times += 1
else:
break
words = line.split(" ")
assert len(words) == len(pattern.split(" "))
for i in range(len(words)):
if words[i] != "$" and words[i] != "<ENTITY>" :
words[i] = "*"
toks = pattern.split(" ")
for i in range(len(words)):
if words[i] == "<ENTITY>" or words[i] == "$":
pos_line.append(toks[i])
elif words[i]!=words[i-1]:
pos_line.append("*")
strpos = ' '.join(pos_line)
pos_patterns.append(strpos)
return pos_patterns
|
def incrementdefault(obj: dict, key, default: int = 0) -> int:
"""Increments value stored in the `obj` under `key`.
Returns the incremented value.
If value with specified key does not exist, then initializes it with
`default` and then increments it.
"""
val = obj.setdefault(key, default) + 1
obj[key] = val
return val
|
def dict_to_parameter_list(d):
"""
:type d: dict
:rtype: list[dict]
"""
return [{u'name': k, u'value': v} for k, v in d.items()]
|
def find_recipes_2(pattern):
"""
Calculate the number of recipes in the sequence before the given pattern appears.
:param pattern: the pattern to identify
:return: the number of recipes to the left of the pattern
>>> find_recipes_2('51589')
9
>>> find_recipes_2('01245')
5
>>> find_recipes_2('92510')
18
>>> find_recipes_2('59414')
2018
"""
# Make rounds into a list of digits.
pattern_len = len(pattern)
digits = [int(i) for i in pattern]
last_digits = []
recipes = [3, 7]
elf1 = 0
elf2 = 1
looking = True
while looking:
new_recipe = recipes[elf1] + recipes[elf2]
for i in str(new_recipe):
if len(last_digits) == pattern_len:
last_digits.pop(0)
recipes.append(int(i))
last_digits.append(int(i))
# We have to check here as it could appear in the middle of adding new recipes.
# In fact, in my case, it does.
if last_digits == digits:
looking = False
break
elf1 = (elf1 + recipes[elf1] + 1) % len(recipes)
elf2 = (elf2 + recipes[elf2] + 1) % len(recipes)
return len(recipes) - len(digits)
|
def is_serialised(serialised):
"""
Detects whether a ``bytes`` object represents an integer.
:param serialised: A ``bytes`` instance which must be identified as being an
integer or not.
:return: ``True`` if the ``bytes`` likely represent an integer, or ``False``
if they do not.
"""
first_byte = True
for byte in serialised:
if not (byte >= b"0"[0] and byte <= b"9"[0]) and not (first_byte and byte == b"-"[0]): #Minus is allowed for first byte, as negative sign.
return False #Not a byte representing a digit.
first_byte = False
return not first_byte
|
def get_valid_crop_size(crop_size, upscale_factor):
""" If we upscale by upscale_factor, then hr_image needs to be
dividable by upscale_factor to have a valid lr_image. """
return crop_size - (crop_size % upscale_factor)
|
def generate_resp_obj(content_type, responses):
"""
Generate response object
"""
resp_obj = {
"type": "object",
"properties": dict(),
"additionalProperties": False,
}
for resp_key, resp_val in responses.items():
if 'content' in responses[resp_key] and (
'schema' in resp_val['content'][content_type]
):
resp_obj['properties'][resp_key] = resp_val[
'content'][content_type]['schema']
else:
resp_obj['properties'][resp_key] = resp_val
return resp_obj
|
def open_time(km, brevet_distance):
"""
input:
km
brevet_distance is one of the standered distances
200,300,400,600,1000
retun:
Opening time in minutes
"""
## brevet_dict[brevet_distance]=[max_time,min_speed]
brevet_max = {200:353, 300:540,400:728,600:1128,1000:1985}
if km ==0:
return 0
elif km >= brevet_distance:
return brevet_max[brevet_distance]
elif km < 200:
return round((km/34)*60)
elif km <400:
return round((200/34+(km-200)/32)*60)
elif km <600:
return round((200/34+200/32+(km-400)/30)*60)
elif km <1000:
return round((200/34+200/32+200/30+200+(km-600)*60))
|
def starts_with_triple(string):
"""Return True if the string starts with triple single/double quotes."""
return (string.strip().startswith('"""') or
string.strip().startswith("'''"))
|
def reverse_transformation(text):
"""
Reverses a given string so that the first character becomes the last one
"""
return text[::-1]
|
def getRelativeFreePlaceIndexForCoordinate(freePlaceMap, x, y):
"""
Returns the Index in the FreePlaceValueArray in witch the given Coordinate is in
:param freePlaceMap: The FreePlaceMap to check on
:param x: The X Coordinate to Check for
:param y: The Y Coordinate to Check for
:return: The found Index or None if not Found
"""
if freePlaceMap is None or len(freePlaceMap) < y or len(freePlaceMap[0]) < x or x < 0 or y < 0:
return None
# Check current Cell
if freePlaceMap[y][x] != -1:
return freePlaceMap[y][x] - 1
# Check Left Cell
elif x > 0 and freePlaceMap[y][x - 1] != -1:
return freePlaceMap[y][x - 1] - 1
# Check Right Cell
elif x < len(freePlaceMap[0]) - 1 and freePlaceMap[y][x + 1] != -1:
return freePlaceMap[y][x + 1] - 1
# Check Cell Underneath
elif y > 0 and freePlaceMap[y - 1][x] != -1:
return freePlaceMap[y - 1][x] - 1
# Check Upper Cell
elif y < len(freePlaceMap) - 1 and freePlaceMap[y + 1][x] != -1:
return freePlaceMap[y + 1][x] - 1
return None
|
def ok(n):
""" Successful import of ``n`` records
:param int n: number of records which should have been imported
"""
return n, 0, 0, 0
|
def model_snowaccumulation(tsmax = 0.0,
tmax = 0.0,
trmax = 0.0,
precip = 0.0):
"""
- Name: SnowAccumulation -Version: 1.0, -Time step: 1
- Description:
* Title: snowfall accumulation calculation
* Author: STICS
* Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002
* Institution: INRA
* Abstract: It simulates the depth of snow cover and recalculate weather data
- inputs:
* name: tsmax
** description : maximum daily air temperature (tmax) below which all precipitation is assumed to be snow
** inputtype : parameter
** parametercategory : constant
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 1000
** unit : degC
** uri :
* name: tmax
** description : current maximum air temperature
** inputtype : variable
** variablecategory : auxiliary
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 5000.0
** unit : degC
** uri :
* name: trmax
** description : tmax above which all precipitation is assumed to be rain
** inputtype : parameter
** parametercategory : constant
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 5000.0
** unit : degC
** uri :
* name: precip
** description : current precipitation
** inputtype : variable
** variablecategory : auxiliary
** datatype : DOUBLE
** default : 0.0
** min : 0.0
** max : 5000.0
** unit : mmW
** uri :
- outputs:
* name: Snowaccu
** description : snowfall accumulation
** variablecategory : rate
** datatype : DOUBLE
** min : 0.0
** max : 500.0
** unit : mmW/d
** uri :
"""
fs = 0.0
if tmax < tsmax:
fs = 1.0
if tmax >= tsmax and tmax <= trmax:
fs = (trmax - tmax) / (trmax - tsmax)
Snowaccu = fs * precip
return Snowaccu
|
def get_useful_fields(repos, repo_count):
"""Selects the useful fields from the repos
Arguments:
repos {list} -- the list of repos to be cleaned
repo_count {int} -- the number of repos
Returns:
{dict} -- the standard output format for the program
"""
filtered_repos = []
for repo in repos:
filtered_repos.append({
"name": repo["name"],
"language": repo["language"],
"stars": repo["stargazers_count"],
"forks": repo["forks_count"],
"issues": repo["open_issues_count"]
})
return {
"Number of repositories": repo_count,
"Repositories": filtered_repos
}
|
def similar(x,y):
"""
function that checks for the similarity between the words of
two strings.
:param x: first string
:param y: second string
:return: returns a float number which is the result of the
division of the length of the intersection between the two strings'
words by the length of their union.
"""
result = ''
x_list = x.split() # convert string to a list for parsing
x_list = [word.lower() for word in x_list] # transform all words to lowercase
x_list = list(set(x_list)) # list of of words that appear at least one in x_list
y_list = y.split() # convert string to a list for parsing
y_list = [word.lower() for word in y_list] # transform all words to lowercase
y_list = list(set(y_list)) # list of words that appear at least one in y_list
intersection = [word for word in x_list if word in y_list] # obtain the common words between x_list and y_list
union = list(set(x_list).union(y_list)) # words that appear in both lists as well as their common ones
result = float(len(intersection) / len(union) ) # find the coefficient of their similarity
return result
|
def power_set(arr):
""" 8.4 Power Set: Write a method to return all subsets of a set. """
if len(arr) == 0:
return [ [] ] # only the empty set
head, tail = arr[0], arr[1:]
tail_subsets = power_set(tail)
head_subsets = []
for sub in tail_subsets:
new_sub = sub[:]
new_sub.append(head)
head_subsets.append(new_sub)
return tail_subsets + head_subsets
|
def inverse_a_mod_p(a, p):
"""
Use the Bezout law to calculate the inverse of e to the modulus of phi.
"""
s, t, sn, tn, r = 1, 0, 0, 1, 1
while r != 0:
q = p // a
r = p - q * a
st, tt = sn * (-q) + s, tn * (-q) + t
s, t = sn, tn
sn, tn = st, tt
p = a
a = r
return t
|
def validateDSType(dsType):
"""
>>> validateDSType('counter')
'COUNTER'
>>> validateDSType('ford prefect')
Traceback (most recent call last):
ValueError: A data source type must be one of the following: GAUGE COUNTER DERIVE ABSOLUTE COMPUTE
"""
dsType = dsType.upper()
valid = ['GAUGE', 'COUNTER', 'DERIVE', 'ABSOLUTE', 'COMPUTE']
if dsType in valid:
return dsType
else:
valid = ' '.join(valid)
raise ValueError('A data source type must be one of the ' + 'following: %s' % valid)
|
def indent_string_block(s, indent=2):
"""
Indents all the lines of s by indent number of spaces
"""
indent_str = ' ' * indent
return indent_str + s.replace('\n', '\n' + indent_str)
|
def has_function_call(instructions):
"""
A function to determine whether the instruction contain any calls to any functions.
:param instructions: The instructions to check for function calls
:return: Whether the instructions contain any calls to any functions as a boolean value
"""
for line in instructions:
for each in line:
if type(each) == str:
return True
return False
|
def parse_args(args:dict):
"""Parse arguments passed to a graphql query name or nodes and returns a string of arguments
Args:
dict (list):
The arguments you want passed to your node or query name. An example for retrieving balances is:
{"cryptocurrency":"bitcoin"}
Returns:
A string of comma-separated arguments key-value pairs as in the graphql standard like (cryptocurrency: bitcoin, status:open)
"""
parsed_args = args.items()
arg_pairs = []
for pair in parsed_args:
arg_pairs.append("{}:{}".format(pair[0],pair[1]))
return ",".join(arg_pairs)
|
def group_32(s):
"""Convert from 8-bit bytes to 5-bit array of integers"""
result = []
unused_bits = 0
current = 0
for c in s:
unused_bits += 8
current = (current << 8) + c
while unused_bits > 5:
unused_bits -= 5
result.append(current >> unused_bits)
mask = (1 << unused_bits) - 1
current &= mask
result.append(current << (5 - unused_bits))
return result
|
def _stacktrace_end(stacktrace, size):
""" Gets the last `size` bytes of the stacktrace """
stacktrace_length = len(stacktrace)
if stacktrace_length <= size:
return stacktrace
return stacktrace[:-(stacktrace_length-size)]
|
def emails_parse(emails_dict):
"""
Parse the output of ``SESConnection.list_verified_emails()`` and get
a list of emails.
"""
return sorted([email for email in emails_dict['VerifiedEmailAddresses']])
|
def gql_api_keys(fragment):
"""
Return the GraphQL assets query
"""
return f'''
query($where: ApiKeyWhere!, $first: PageSize!, $skip: Int!) {{
data: apiKeys(where: $where, skip: $skip, first: $first) {{
{fragment}
}}
}}
'''
|
def _sliceString(s,vec):
"""Slice string s at integer inds in vec"""
return ''.join([s[i] for i in vec])
|
def _is_within_rect(xy, p1, p2):
""" If xy is withing rectangle defined by p1, p2
"""
for i in range(2):
if p1[i] <= xy[i] <= p2[i] or p2[i] <= xy[i] <= p1[i]:
continue
else:
return False
return True
|
def get_chunks(labels):
"""
It supports IOB2 or IOBES tagging scheme.
You may also want to try https://github.com/sighsmile/conlleval.
"""
chunks = []
start_idx,end_idx = 0,0
for idx in range(1,len(labels)-1):
chunkStart, chunkEnd = False,False
if labels[idx-1] not in ('O', '<pad>', '<unk>', '<s>', '</s>', '<STOP>', '<START>'):
prevTag, prevType = labels[idx-1][:1], labels[idx-1][2:]
else:
prevTag, prevType = 'O', 'O'
if labels[idx] not in ('O', '<pad>', '<unk>', '<s>', '</s>', '<STOP>', '<START>'):
Tag, Type = labels[idx][:1], labels[idx][2:]
else:
Tag, Type = 'O', 'O'
if labels[idx+1] not in ('O', '<pad>', '<unk>', '<s>', '</s>', '<STOP>', '<START>'):
nextTag, nextType = labels[idx+1][:1], labels[idx+1][2:]
else:
nextTag, nextType = 'O', 'O'
if Tag == 'B' or Tag == 'S' or (prevTag, Tag) in {('O', 'I'), ('O', 'E'), ('E', 'I'), ('E', 'E'), ('S', 'I'), ('S', 'E')}:
chunkStart = True
if Tag != 'O' and prevType != Type:
chunkStart = True
if Tag == 'E' or Tag == 'S' or (Tag, nextTag) in {('B', 'B'), ('B', 'O'), ('B', 'S'), ('I', 'B'), ('I', 'O'), ('I', 'S')}:
chunkEnd = True
if Tag != 'O' and Type != nextType:
chunkEnd = True
if chunkStart:
start_idx = idx
if chunkEnd:
end_idx = idx
chunks.append((start_idx,end_idx,Type))
start_idx,end_idx = 0,0
return chunks
|
def bytecount(numbytes):
"""Convert byte count to display string as bytes, KB, MB or GB.
1st parameter = # bytes (may be negative)
Returns a short string version, such as '17 bytes' or '47.6 GB'
"""
retval = "-" if numbytes < 0 else "" # leading '-' for negative values
absvalue = abs(numbytes)
if absvalue < 1024:
retval = retval + format(absvalue, ".0f") + " bytes"
elif 1024 <= absvalue < 1024 * 100:
retval = retval + format(absvalue / 1024, "0.1f") + " KB"
elif 1024 * 100 <= absvalue < 1024 * 1024:
retval = retval + format(absvalue / 1024, ".0f") + " KB"
elif 1024 * 1024 <= absvalue < 1024 * 1024 * 100:
retval = retval + format(absvalue / (1024 * 1024), "0.1f") + " MB"
elif 1024 * 1024 * 100 <= absvalue < 1024 * 1024 * 1024:
retval = retval + format(absvalue / (1024 * 1024), ".0f") + " MB"
else:
retval = retval + format(absvalue / (1024 * 1024 * 1024), ",.1f") + " GB"
return retval
|
def parse_isomer_spin(spin):
"""Parses nubase style spin information
returns dictionary {value, extrapolated} """
result = {}
result['extrapolated'] = True if spin.count('#') > 0 else False
if result['extrapolated']:
spin = spin.replace('#', ' ')
result['value'] = spin[0:8].strip()
result['T'] = spin[8:].strip('T= ')
return result
|
def _extract_defines_from_option_list(lst):
"""Extracts preprocessor defines from a list of -D strings."""
defines = []
for item in lst:
if item.startswith("-D"):
defines.append(item[2:])
return defines
|
def rule_lift(f11, f10, f01, f00):
"""
Computes the lift for a rule `a -> b` based on the contingency table.
params:
f11 = count a and b appearing together
f10 = count of a appearing without b
f01 = count of b appearing without a
f00 = count of neither a nor b appearing
returns:
float ranging from zero to infinity where 1 implies independence, greater
than 1 implies positive association, less than 1 implies negative association
"""
N = f11 + f10 + f01 + f00
zero = 1e-10
supp_ab = f11 / N
supp_a = f10 / N
supp_b = f01 / N
return supp_ab / ((supp_a * supp_b) + zero)
|
def isiter(obj):
"""Checks whether given object is iterable."""
return obj is not None and hasattr(obj, '__iter__')
|
def canon_nexiq(msg):
"""
Format is:
13:48:06.1133090 - RX - 172 254 137 4 212 128 194 137
"""
m = msg.strip().split(" ")[4:]
newmsg = [int(x) for x in m]
# print(newmsg)
return newmsg
|
def _get_options(opts, with_keyty_valty):
"""Returns a triple of the options: a key field type, a value
field type, and a flag of needs of output generation."""
if ((not with_keyty_valty) and (("key" in opts) or ("value" in opts))):
raise Exception("Bad option: key= or value= not allowed")
keyty = opts.get("key", "opaque")
valty = opts.get("value", "opaque")
mkkvo = opts.get("output", True)
return (keyty, valty, mkkvo)
|
def invert_dict(front_dict):
""" Take a dict of key->values and return values->[keys] """
back_dict = { value : [] for value in front_dict.values() }
for key, value in front_dict.items():
back_dict[value].append(key)
return back_dict
|
def _determine_fields(fields, radars):
""" Determine which field should be mapped to the grid. """
if fields is None:
fields = set(radars[0].fields.keys())
for radar in radars[1:]:
fields = fields.intersection(radar.fields.keys())
fields = list(fields)
return fields
|
def tupleSearch(findme, haystack):
"""Partial search of list of tuples.
The "findme" argument is a tuple and this will find matches in "haystack"
which is a list of tuples of the same size as "findme". An empty string as
an item in "findme" is used as a wildcard for that item when searching
"haystack".
"""
match = []
for words in haystack:
testmatch = []
for i, j in zip(findme, words):
if not i:
testmatch.append(True)
continue
if i == j:
testmatch.append(True)
continue
testmatch.append(False)
if all(testmatch):
match.append(words)
return match
|
def dict_merge(source, destination):
"""dest wins"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
dict_merge(value, node)
else:
destination[key] = value
return destination
|
def filterClusterByDis(data, cut):
"""
Filter inter-ligation clusters by distances
"""
for key in data:
nr = []
for r in data[key]["records"]:
d = (r[4] + r[5]) / 2 - (r[1] + r[2]) / 2
if d >= cut:
nr.append(r)
data[key]["records"] = nr
return data
|
def parser_multiplex_buffer_utilisation_Descriptor(data,i,length,end):
"""\
parser_multiplex_buffer_utilisation_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "multiplex_buffer_utilisation", "contents" : unparsed_descriptor_contents }
(Defined in ISO 13818-1 specification)
"""
return { "type" : "multiplex_buffer_utilisation", "contents" : data[i+2:end] }
|
def levenshtein_distance(a, b):
"""Return the Levenshtein edit distance between two strings *a* and *b*."""
if a == b:
return 0
if len(a) < len(b):
a, b = b, a
if not a:
return len(b)
previous_row = range(len(b) + 1)
for i, column1 in enumerate(a):
current_row = [i + 1]
for j, column2 in enumerate(b):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (column1 != column2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
|
def preorder_traversal_iterative(root):
"""
Return the preorder traversal of nodes' values.
- Worst Time complexity: O(n)
- Worst Space complexity: O(n)
:param root: root node of given binary tree
:type root: TreeNode or None
:return: preorder traversal of nodes' values
:rtype: list[int]
"""
# basic case
if root is None:
return []
# use stack to traverse
result = []
stack = [root]
while len(stack) != 0:
root = stack.pop()
result.append(root.val)
if root.right is not None:
stack.append(root.right)
if root.left is not None:
stack.append(root.left)
return result
|
def normalize_framework(framework: str) -> str:
"""Normalize framework strings by lowering case."""
return framework.lower()
|
def hex_str_to_bytes(str_hex: str) -> bytes:
"""Convert hex string to bytes."""
str_hex = str_hex.lower()
if str_hex.startswith("0x"):
str_hex = str_hex[2:]
if len(str_hex) & 1:
str_hex = "0" + str_hex
return bytes.fromhex(str_hex)
|
def group_text(text, n=5):
"""Groups the given text into n-letter groups separated by spaces."""
return ' '.join(''.join(text[i:i+n]) for i in range(0, len(text), n))
|
def normalize_knot_vector(knot_vector, decimals=18):
""" Normalizes the input knot vector to [0, 1] domain.
:param knot_vector: knot vector to be normalized
:type knot_vector: list, tuple
:param decimals: rounding number
:type decimals: int
:return: normalized knot vector
:rtype: list
"""
try:
if knot_vector is None or len(knot_vector) == 0:
raise ValueError("Input knot vector cannot be empty")
except TypeError as e:
print("An error occurred: {}".format(e.args[-1]))
raise TypeError("Knot vector must be a list or tuple")
except Exception:
raise
first_knot = float(knot_vector[0])
last_knot = float(knot_vector[-1])
denominator = last_knot - first_knot
knot_vector_out = [float(("{:." + str(decimals) + "f}").format((float(kv) - first_knot) / denominator))
for kv in knot_vector]
return knot_vector_out
|
def add_items(inventory, items):
"""Add or increment items in inventory using elements from the items `list`.
:param inventory: dict - dictionary of existing inventory.
:param items: list - list of items to update the inventory with.
:return: dict - the inventory updated with the new items.
"""
for item in items:
inventory.setdefault(item, 0)
inventory[item] += 1
return inventory
|
def normaliseSum(*args):
"""Returns a list of all the arguments, so that they add up to 1
Args:
*args: A variable number of arguments
Returns:
(list): list of all the arguments that all add up to 1
"""
# convert the arguments to a list, so we can operate on it
args = list(args)
# calculate the sum of the list
s = sum(args)
# this if statement is important, because dividing by 0 is bad!
if s != 0:
# return a list on numbers divided by the sum
return [float(x) / s for x in args]
# return a list of 0s if the sum is 0
return [0.0 for x in args]
|
def _merge_and_count_split_inv(left, right):
"""Return merged, sorted array and number of split inversions."""
max_left, max_right = len(left), len(right)
if max_left == 0 or max_right == 0:
return left + right, 0
merged = []
inv_count = 0
i = j = 0
while i < max_left and j < max_right:
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
# Count inversions
inv_count += max_left - i
while i < max_left:
merged.append(left[i])
i += 1
while j < max_right:
merged.append(right[j])
j += 1
return merged, inv_count
|
def ispoweroftwo(n):
"""Return True if n is power of two."""
if n<=0:
return False
else:
return n & (n-1) == 0
|
def capitalize_correct(phrase):
"""
Capitalizes words in a string, avoiding possessives being capitalized
"""
phrase = phrase.strip()
return " ".join(w.capitalize() for w in phrase.split())
|
def crc32_combine(crc1, crc2, len2):
"""Explanation algorithm: http://stackoverflow.com/a/23126768/654160
crc32(crc32(0, seq1, len1), seq2, len2) == crc32_combine(
crc32(0, seq1, len1), crc32(0, seq2, len2), len2)"""
# degenerate case (also disallow negative lengths)
if len2 <= 0:
return crc1
# put operator for one zero bit in odd
# CRC-32 polynomial, 1, 2, 4, 8, ..., 1073741824
odd = [0xedb88320] + [1 << i for i in range(0, 31)]
even = [0] * 32
def matrix_times(matrix, vector):
number_sum = 0
matrix_index = 0
while vector != 0:
if vector & 1:
number_sum ^= matrix[matrix_index]
vector = vector >> 1 & 0x7FFFFFFF
matrix_index += 1
return number_sum
# put operator for two zero bits in even - gf2_matrix_square(even, odd)
even[:] = [matrix_times(odd, odd[n]) for n in range(0, 32)]
# put operator for four zero bits in odd
odd[:] = [matrix_times(even, even[n]) for n in range(0, 32)]
# apply len2 zeros to crc1 (first square will put the operator for one
# zero byte, eight zero bits, in even)
while len2 != 0:
# apply zeros operator for this bit of len2
even[:] = [matrix_times(odd, odd[n]) for n in range(0, 32)]
if len2 & 1:
crc1 = matrix_times(even, crc1)
len2 >>= 1
# if no more bits set, then done
if len2 == 0:
break
# another iteration of the loop with odd and even swapped
odd[:] = [matrix_times(even, even[n]) for n in range(0, 32)]
if len2 & 1:
crc1 = matrix_times(odd, crc1)
len2 >>= 1
# if no more bits set, then done
# return combined crc
crc1 ^= crc2
return crc1
|
def get_frequency_band(wavelength: float) -> str:
"""
Frequency bands in the microwave range are designated by letters. This
standard is the IEEE radar bands.
Parameter:
==========
wavelength: float
Wavelength in cm.
Returns:
========
band: str
Radar frequency band designation.
"""
# name, freq min, freq max
ieee_freq_band_ghz = [
("L", 1, 2),
("S", 2, 4),
("C", 4, 8),
("X", 8, 12),
("Ku", 12, 18),
("K", 18, 27),
("Ka", 27, 40),
("V", 40, 75),
("W", 75, 110),
]
ghz = 1e-9 * 300_000_000 / (wavelength * 1e-2)
for band, fmin, fmax in ieee_freq_band_ghz:
if ghz >= fmin and ghz <= fmax:
return band
# Freq band not found.
raise ValueError("Invalid radar wavelength. Is the wavelength in cm?")
|
def _check_repo_contents(contents_list: list, contents_ext: str):
"""Returns the list of files in a repo that match the requested extension.
Args:
contents_list (list): a list of repository content dictionaries from API.
contents_ext (str): an extension to limit results.
Returns:
list: a subset of the input list containing only matches extensions.
"""
# Loop over the input 'contents_list' dicitonaries.
for content_dict in contents_list:
# If file has an extension matching contents_ext, return True.
if content_dict['name'].endswith(contents_ext):
return True
# If didn't find any matches, return False.
return False
|
def get_pins(line):
""" Extract the pin names from the vector line """
line = line.replace('{','')
line = line.replace(')','')
line = line.replace('(','')
bits = line.split(',')
return [s.strip() for s in bits[1:]]
|
def has_relative_protocol(uri):
"""Return True if URI has relative protocol '//' """
start = uri[:2]
if start == '//':
return True
return False
|
def crop_resize(src, target, right=0, bottom=70):
"""rescale image to 300dpi"""
cropargs = '-{}-{}'.format(right,bottom)
return ['convert', src, '-crop' , cropargs, '-resize', '150%', target]
|
def find_ole_header(fi, data, offset, output):
"""
Used by guess_multibyte_xor_keys()
"""
i = 0
pos = 0
found = 0
length = len(data)
while i < length:
pos = data.find("".join(['\xd0', '\xcf', '\x11', '\xe0', '\xa1', '\xb1', '\x1a', '\xe1']), i)
if pos == -1:
break
else:
output += "OLE2 Compound Document header found at offset %s.\n" % hex(offset + pos)
fi.setBookmark(offset + pos, 8, hex(offset + pos) + " OLE2 Compound Document", "#c8ffff")
i = pos + 8
found += 1
return (found, output)
|
def extract_ontology_id_from_iri(url: str) -> str:
"""
Get the ontology short term from iri string
:param url: iri of ontology
:return: short term of ontology
"""
if type(url) is not str:
raise TypeError("The method only take str as its input")
if url.find('/') > -1:
elmts = url.split('/')
return elmts[-1]
else:
return url
|
def remove_url(tweet):
"""
Removes '<url>' tag from a tweet.
INPUT:
tweet: original tweet as a string
OUTPUT:
tweet with <url> tags removed
"""
return tweet.replace('<url>', '')
|
def dz_any1D(hbot,zeta,hc,dCs,N):
""" same as dz_anyND but assume entries are flat arrays of same shape (fancy addressing,
staggered access) or scalar. Just compute the product
"""
return (zeta + hbot)*(hc/N+dCs*hbot)/(hc + hbot)
|
def poly_eval(P,x):
"""
Evaluate the polynomial P at x
"""
out = 0
e = 1
for coef in P:
out += coef*e
e *= x
return out
|
def serialize_columns(columns):
"""
Return the headers and frames resulting
from serializing a list of Column
Parameters
----------
columns : list
list of Columns to serialize
Returns
-------
headers : list
list of header metadata for each Column
frames : list
list of frames
"""
headers = []
frames = []
if len(columns) > 0:
header_columns = [c.serialize() for c in columns]
headers, column_frames = zip(*header_columns)
for f in column_frames:
frames.extend(f)
return headers, frames
|
def split(text):
"""Split an annotation file by sentence. Each sentence's annotation should
be a single string."""
return text.strip().split('\n')[1:-1]
|
def getJobMetricDimensions(job):
"""
Store metrics in the same format as Cloudwatch in case we want to use
Cloudwatch as a metrics store later
:param job: JSON job data struture from dynamodb
"""
ret = {}
dimensions = []
filters = {}
job_dim= {}
job_dim['Name'] = 'jobId'
job_dim['Value'] = job['id']
dimensions.append(job_dim)
filters['jobId'] = job['id']
filters['account'] = job['queue'].split(':')[4]
filters['region'] = job['queue'].split(':')[3]
queue_dim = {}
queue_dim['Name'] = 'queue'
queue_dim['Value'] = job['queue']
dimensions.append(queue_dim)
filters['queue'] = job['queue']
filters['queueName'] = job['queue'].split('/')[1]
for key in job['userMetadata']:
value = job['userMetadata'][key]
dimension = {}
dimension['Name'] = key
dimension['Value'] = value
dimensions.append(dimension)
filters[key] = value
# doing this so we can index dyanmo records by filters - dynamo needs a
# top level objects as index keys. No nesting.
if key not in job:
job[key] = value
ret['dimensions'] = dimensions
ret['filters'] = filters
return ret
|
def guess_max_depth(map_or_seq):
"""HACK A DID ACK - please delete me when cleaning up."""
if isinstance(map_or_seq, dict):
return 1 + max(map(guess_max_depth, map_or_seq.values()), default=0)
elif isinstance(map_or_seq, list):
return 1 + max(map(guess_max_depth, map_or_seq[0].values()), default=0)
return 0
|
def round_up_next_multiple(x, mult):
"""Round integer `x` up to the next possible multiple of `mult`."""
rem = x % mult
if rem > 0:
return x - rem + mult
else:
return x
|
def _weight_table(dat):
"""
Return weight table.
"""
table = {}
# weight tables
for item in dat:
if dat[item] not in table:
table[dat[item]] = [(item, 1.0)]
else:
old = table[dat[item]]
new = []
for old_item in old:
new.append((old_item[0], 1.0 / (len(old) + 1.0)))
new.append((item, 1.0 / (len(old) + 1.0)))
table[dat[item]] = new
return table
|
def istag(arg):
"""Return true if the argument starts with a dash ('-') and is not a number
Parameters
----------
arg : str
Returns
-------
bool
"""
return arg.startswith('-') and len(arg) > 1 and arg[1] not in '0123456789'
|
def dir(object: object=None) -> object:
"""dir."""
return object.__dir__()
|
def get_available_moves(board_state):
"""
Return an array of board positions/indices that contain "None".
Input:
board_state:
(0,1,0,None,None,None,None,None,None)
a tuple of the board's state
Output:
an array of board positions/indices of possible moves:
[3,4,5,6,7,8]
"""
possible_moves = []
for i, board_position in enumerate(board_state):
if board_position == None:
possible_moves.append(i)
return possible_moves
|
def get_tag_type(tagtype, pairs):
"""
Given a list of (word,tag) pairs, return a list of words which are tagged as nouns/verbs/etc
The tagtype could be 'NN', 'JJ', 'VB', etc
"""
return [w for (w, tag) in pairs if tag.startswith(tagtype)]
|
def is_same_behavior_id_str(behavior_id_str_1, behavior_id_str_2):
"""Checks if the two behavior ID strings are the same (e.g. 'fd' vs. 'fd_r' should return
True).
Args:
behavior_id_str_1: Behavior ID as a string.
behavior_id_str_2: Behavior ID as a string.
"""
return behavior_id_str_1.startswith(behavior_id_str_2) or behavior_id_str_2.startswith(behavior_id_str_1)
|
def business_rule_3(amount: int, account: int, use_br: bool, threshold: int) -> bool:
"""
Account sends transactions with combined total value >= threshold within a day. Only works for scatter-gather.
:param amount: transaction value
:param account: number of involved accounts
:param use_br: whether to use this br
:param threshold: the threshold
:return: True when the laundering was successful, false when it is caught
"""
if not use_br:
return True
if amount * (account - 2) < threshold:
return True
else:
return False
|
def iyr_valid(passport):
""" Check that iyr is valid
iyr (Issue Year) - four digits; at least 2010 and at most 2020.
:param passport: passport
:return: boolean
"""
return len(passport['iyr']) == 4 and 2010 <= int(passport['iyr']) <= 2020
|
def headers(mime, length):
"""Returns a list of HTTP headers given the MIME type and the length of the
content, in bytes (in integer or sting format)."""
return [('Content-Type', mime),
('Content-Length', str(length))]
|
def extract_element(item_list, index):
"""
Safely extract indexed xpath element
"""
if index < len(item_list):
return item_list[index].extract()
else:
return ""
|
def _GetArmVersion(arch):
"""Returns arm_version for the GN build with the given architecture."""
if arch == 'armeabi':
return 6
elif arch == 'armeabi-v7a':
return 7
elif arch in ['arm64-v8a', 'x86', 'x86_64']:
return None
else:
raise Exception('Unknown arch: ' + arch)
|
def has_blank_ids(idlist):
"""
Search the list for empty ID fields and return true/false accordingly.
"""
return not(all(k for k in idlist))
|
def coords_add(coords0, coords1):
""" Add two coordinates """
return tuple([x0 + x1 for x0, x1 in zip(coords0, coords1)])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.