content
stringlengths 42
6.51k
|
---|
def move_over_floors(instructions):
"""Moves over floors up and down by given instructions
:param instructions: string of '(' (up) and ')' (down) characters
:return: floor: number of floor where we stop
basement_enter: number of first instruction where we entered negative values
"""
floor = 0
i = 0
basement_enter = 0
for char in instructions:
i += 1
if char == '(':
floor += 1
elif char == ')':
floor -= 1
if floor < 0 and basement_enter == 0:
basement_enter = i
return floor, basement_enter
|
def make_task_key(x, y):
"""
Creates a key from the coordinates of a given task.
The key is used to identify the tasks within a dictionary
:param x: x coordinate
:param y: y coordinate
:return: the created key
"""
key = (x, y)
return key
|
def maximumBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value below n.
Example:
.. code-block:: none
&target=maximumBelow(system.interface.eth*.packetsSent,1000)
This would only display interfaces which sent less than 1000 packets/min.
"""
result = []
for series in seriesList:
if max(series) <= n:
result.append(series)
return result
|
def get_sentence_entities(beg, end, annotations):
"""Get annotation for each individual sentence and adjust indices to start from 0 for each sentence.
Args:
beg (int): begin index of sentence in text
end (int): end index of sentence in text
annotation (dictionary): annotation dictionary (result of calling annotation_to_dict)
Returns:
dictionary: entities
"""
entities = {}
for k, v in annotations['entities'].items():
if v['beg'] >= beg and v['end'] <= end + 1:
entities[k] = {
'label': v['label'],
'beg': v['beg'] - beg,
'end': v['end'] - beg,
'string': v['string']
}
elif v['beg'] <= end and v['end'] > end:
print(RuntimeWarning("Annotation span stretches over more than one sentence according to the sentence split: {} and {}".format(k, v)))
entities[k] = {
'label': v['label'],
'beg': v['beg'] - beg,
'end': end - 1 - beg,
'string': v['string'][:v['end']-end-1]
}
elif v['beg'] <= beg and v['end'] >= beg:
print(RuntimeWarning("Annotation span stretches over more than one sentence, ingoring the second part!"))
#print(annotations)
entities = {k: v for k, v in sorted(entities.items(), key=lambda item: item[1]['beg'])}
for idx, (k, v) in enumerate(entities.items()):
v['idx'] = idx
return entities
|
def calc_max_length(dictionary):
"""
:param dictionary: an object of set, indicates all of the keywords. e.g
:return: the max length of keyword
"""
max_length = 1
for _ in dictionary:
if len(_) > max_length:
max_length = len(_)
return max_length
|
def determine_triggers(triggers, add_triggers, use_triggers):
"""Determine set of effective triggers.
:param triggers: list of configured triggers.
:type triggers: List[str]
:param add_triggers: additional triggers.
:type add_triggers: List[str]
:param use_triggers: triggers shall be applied.
:type use_triggers: bool
:return: list of effective triggers.
:rtype: List[str]
"""
if use_triggers:
triggers_ = triggers
triggers_.extend(add_triggers)
else:
triggers_ = []
return triggers_
|
def _write_string_to_hex(string_to_write: str) -> str:
""" Write any string to hex.
As mentioned above, numbers get padded because all numbers are a fixed size in keytabs.
However, strings are super free-form, like principals and realms. They're not constrained to a fixed size ever, and
so instead all string fields will also end up encoding their length before them in the keytab. So there's no need
for any input other than the string itself to this function.
"""
return string_to_write.encode().hex()
|
def login_user_block(username, ssh_keys, create_password=True):
"""
Helper function for creating Server.login_user blocks.
(see: https://www.upcloud.com/api/8-servers/#create-server)
"""
block = {
'create_password': 'yes' if create_password is True else 'no',
'ssh_keys': {
'ssh_key': ssh_keys
}
}
if username:
block['username'] = username
return block
|
def transparent(value, function, *args, **kwargs):
"""
Invoke ``function`` with ``value`` and other arguments, return ``value``.
Use this to add a function to a callback chain without disrupting the
value of the callback chain::
d = defer.succeed(42)
d.addCallback(transparent, print)
d.addCallback(lambda x: x == 42)
"""
function(value, *args, **kwargs)
return value
|
def map_nested_attrs(nested_dict, split_attr_name, query_data):
"""
A function that can be called recursively to map attributes from related
entities to the associated data
:param nested_dict: Dictionary to insert data into
:type nested_dict: :class:`dict`
:param split_attr_name: List of parts to an attribute name, that have been split
by "."
:type split_attr_name: :class:`list`
:param query_data: Data to be added to the dictionary
:type query_data: :class:`str` or :class:`str`
:return: Dictionary to be added to the result dictionary
"""
# Popping LHS of related attribute name to see if it's an attribute name or part
# of a path to a related entity
attr_name_pop = split_attr_name.pop(0)
# Related attribute name, ready to insert data into dictionary
if len(split_attr_name) == 0:
# at role, so put data in
nested_dict[attr_name_pop] = query_data
# Part of the path for related entity, need to recurse to get to attribute name
else:
nested_dict[attr_name_pop] = {}
map_nested_attrs(nested_dict[attr_name_pop], split_attr_name, query_data)
return nested_dict
|
def alpha(algorithm_period_return, treasury_period_return,
benchmark_period_returns, beta):
"""
http://en.wikipedia.org/wiki/Alpha_(investment)
Args:
algorithm_period_return (float):
Return percentage from algorithm period.
treasury_period_return (float):
Return percentage for treasury period.
benchmark_period_return (float):
Return percentage for benchmark period.
beta (float):
beta value for the same period as all other values
Returns:
float. The alpha of the algorithm.
"""
return algorithm_period_return - \
(treasury_period_return + beta *
(benchmark_period_returns - treasury_period_return))
|
def dicts_equal(lhs, rhs):
"""
Check dicts' equality.
"""
if len(lhs.keys()) != len(rhs.keys()):
return False
for key, val in rhs.items():
val_ref = lhs.get(key, None)
if val != val_ref:
return False
return True
|
def change_angle_origin(angles, max_positive_angle):
"""
Angles in DICOM are all positive values, but there is typically no mechanical continuity in across 180 degrees
:param angles: angles to be converted
:type angles list
:param max_positive_angle: the maximum positive angle, angles greater than this will be shifted to negative angles
:return: list of the same angles, but none exceed the max
:rtype: list
"""
if len(angles) == 1:
if angles[0] > max_positive_angle:
return [angles[0] - 360]
else:
return angles
new_angles = []
for angle in angles:
if angle > max_positive_angle:
new_angles.append(angle - 360)
elif angle == max_positive_angle:
if angle == angles[0] and angles[1] > max_positive_angle:
new_angles.append(angle - 360)
elif angle == angles[-1] and angles[-2] > max_positive_angle:
new_angles.append(angle - 360)
else:
new_angles.append(angle)
else:
new_angles.append(angle)
return new_angles
|
def patch_attributes(new_attrs, obj):
"""Updates attribute values.
Ignored if new_attrs is None
"""
if new_attrs:
if obj.attributes is None:
obj.attributes = new_attrs
else:
for attr_name in new_attrs:
obj.attributes[attr_name] = new_attrs[attr_name]
return obj
|
def islambda(v):
""" Checks if v is a lambda function """
LAMBDA = lambda:0
return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
|
def business_logic(product_id, sku_id):
"""Example of service."""
if product_id == 'Secure Firewall' and sku_id == 'Ingress network traffic':
return 1 + 1
if product_id == 'Secure Firewall' and sku_id == 'Egress network traffic':
return 1 * 1
return 0
|
def compareVersions(verA, verB):
"""Given two versions formatted as 'major.minor.build' (i.e. 2.0.1), compares
A to B and returns B if B is larger than A, else returns None
A version is larger if stepping down from major -> build results in a larger
difference.
Ex:
1.0.1 > 1.0.0
2.2.1 > 1.0.5
2.2.1 > 2.1.3
Args:
verA (str): Version A, what we compare Version B against
verB (str): Version B, what we compare to Version A and return if it
is larger than A.
Returns:
str: verB if verB is larger than verA, or None if verB is equal or smaller
"""
aParts = verA.split('.')
bParts = verB.split('.')
for i in range(3):
diff = int(bParts[i]) - int(aParts[i])
if diff == 0:
continue
elif diff > 0:
return verB
else:
return None
return None
|
def typeFullName(o):
"""This function takes any user defined object or class of any type and
returns a string absolute identifier of the provided type.
Args:
o (Any): object of any type to be inspected
Returns:
str: The full dotted path of the provided type
"""
module = o.__class__.__module__
if module is None or module == str.__class__.__module__:
return o.__class__.__name__ # Avoid reporting __builtin__
else:
return module + '.' + o.__class__.__name__
|
def scale(pix, pixMax, floatMin, floatMax):
""" scale takes in
pix, the CURRENT pixel column (or row)
pixMax, the total # of pixel columns
floatMin, the min floating-point value
floatMax, the max floating-point value
scale returns the floating-point value that
corresponds to pix
"""
return (pix / pixMax) * (floatMax - floatMin) + floatMin
|
def escape_dot_syntax(key):
"""
Take a table name and check for dot syntax. Escape
the table name properly with quotes; this currently
only supports the MySQL syntax, but will hopefully
be abstracted away soon.
"""
dot_index = key.find('.')
if(dot_index == -1):
if not(key.startswith('`')):
key = '`%s`' % key
else:
if not(key.endswith('`')):
key = key.replace('.', '.`') + '`'
return key
|
def enpunycode(domain: str) -> str:
"""
convert utf8 domain to punycode
"""
result = []
for _ in domain.split("."):
try:
_.encode("ascii")
result.append(_)
except UnicodeEncodeError:
result.append("xn--" + _.encode("punycode").decode("ascii"))
return ".".join(result)
|
def even_fibonacci(n):
"""Return the sum of even elements of the fibonacci series"""
fibo = [1, 1]
even = 0
if n < 2 or n > 2_000_000:
return 0
while n > 2:
n -= 1
f = sum(fibo)
if f % 2 == 0:
even += f
fibo = [fibo[-1], f]
return even
|
def determin_meetw(meetw_processes, sample_processes, repeat_cutoff=2):
"""Determine meetwaarde and meetwaarde herhaling (reapeat) based on list of processes and repeat cutoff."""
meetw = 'N'
meetw_herh = 'N'
for process in meetw_processes:
if process in sample_processes:
if len(sample_processes[process]) >= repeat_cutoff:
meetw = 'N'
meetw_herh = 'J'
break
else:
meetw = 'J'
return meetw, meetw_herh
|
def gen_fov_chan_names(num_fovs, num_chans, return_imgs=False, use_delimiter=False):
"""Generate fov and channel names
Names have the format 'fov0', 'fov1', ..., 'fovN' for fovs and 'chan0', 'chan1', ...,
'chanM' for channels.
Args:
num_fovs (int):
Number of fov names to create
num_chans (int):
Number of channel names to create
return_imgs (bool):
Return 'chanK.tiff' as well if True. Default is False
use_delimiter (bool):
Appends '_otherinfo' to the first fov. Useful for testing fov id extraction from
filenames. Default is False
Returns:
tuple (list, list) or (list, list, list):
If return_imgs is False, only fov and channel names are returned
If return_imgs is True, image names will also be returned
"""
fovs = [f'fov{i}' for i in range(num_fovs)]
if use_delimiter:
fovs[0] = f'{fovs[0]}_otherinfo'
chans = [f'chan{i}' for i in range(num_chans)]
if return_imgs:
imgs = [f'{chan}.tiff' for chan in chans]
return fovs, chans, imgs
else:
return fovs, chans
|
def calc_lithostat(z,p=2700.0,g=9.80665):
"""
Lithostatic stress according to Pylith's definition of g=9.80665
"""
litho = p*g*z
print('%.3e' % litho)
return litho
|
def labels():
"""
Returns a dict with relevant labels as keys and their index as value.
"""
labels = {"car": 7, "bus": 6, "motorcycle": 14, "bicycle": 2, "person": 15}
return labels
|
def _unique(seq):
"""Return unique elements of ``seq`` in order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
def mean(*args):
"""
Calculates the mean of a list of numbers
:param args: List of numbers
:return: The mean of a list of numbers
"""
index = 0
sum_index = 0
for i in args:
index += 1
sum_index += float(i)
return (sum_index / index) if index != 0 else "Division by zero"
|
def chao1_var_bias_corrected(singles, doubles):
"""Calculates chao1 variance, bias-corrected.
From EstimateS manual, equation 6.
"""
s, d = float(singles), float(doubles)
return s*(s-1)/(2*(d+1)) + (s*(2*s-1)**2)/(4*(d+1)**2) + \
(s**2 * d * (s-1)**2)/(4*(d+1)**4)
|
def any(list):
"""Is any of the elements of the list true?"""
for x in list:
if x: return True
return False
|
def ByteToHex( byteStr ):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
# Uses list comprehension which is a fractionally faster implementation than
# the alternative, more readable, implementation below
#
# hex = []
# for aChar in byteStr:
# hex.append( "%02X " % ord( aChar ) )
#
# return ''.join( hex ).strip()
return ''.join( [ "%02X" % ord( x ) for x in byteStr ] ).strip()
|
def validate_recoveryoption_name(recoveryoption_name):
"""
Validate Name for RecoveryOption
Property: RecoveryOption.Name
"""
VALID_RECOVERYOPTION_NAME = (
"admin_only",
"verified_email",
"verified_phone_number",
)
if recoveryoption_name not in VALID_RECOVERYOPTION_NAME:
raise ValueError(
"RecoveryOption Name must be one of: %s"
% ", ".join(VALID_RECOVERYOPTION_NAME)
)
return recoveryoption_name
|
def find_kaprecar_numbers(p, q):
"""
:type p: int
:type q: int
:rtype: list[int]
"""
kaprecar_numbers = list()
for i in range(p, q + 1):
square = str(i ** 2)
l_piece = square[:len(square) // 2] if len(square) > 1 else "0"
r_piece = square[len(l_piece):] if len(square) > 1 else square
if int(l_piece) + int(r_piece) == i:
kaprecar_numbers.append(i)
return kaprecar_numbers
|
def b128_decode(data):
""" Performs the MSB base-128 decoding of a given value. Used to decode variable integers (varints) from the LevelDB.
The code is a port from the Bitcoin Core C++ source. Notice that the code is not exactly the same since the original
one reads directly from the LevelDB.
The decoding is used to decode Satoshi amounts stored in the Bitcoin LevelDB (chainstate). After decoding, values
are decompressed using txout_decompress.
The decoding can be also used to decode block height values stored in the LevelDB. In his case, values are not
compressed.
Original code can be found in:
https://github.com/bitcoin/bitcoin/blob/v0.13.2/src/serialize.h#L360#L372
Examples and further explanation can be found in b128_encode function.
:param data: The base-128 encoded value to be decoded.
:type data: hex str
:return: The decoded value
:rtype: int
"""
n = 0
i = 0
while True:
d = int(data[2 * i:2 * i + 2], 16)
n = n << 7 | d & 0x7F
if d & 0x80:
n += 1
i += 1
else:
return n
|
def remove_parentheses(inv, replace_with=''):
"""
function used to remove/replace top-level matching parenthesis from a string
:param inv: input string
:param replace_with: string to replace matching parenthesis with
:return: input string without first set of matching parentheses
"""
k = 0
lp = ''
out = ''
for c in inv:
# go one level deep
if c == '(':
k += 1
lp = c
# go one level up
elif c == ')':
k -= 1
lp += c
if k == 0:
out += replace_with
# zero depth: add character to output string
elif k == 0:
out += c
return out
|
def valid_cluster_name(name):
"""
Return valid qsub ID by removing semicolons, converting
them into underscores.
"""
name = name.replace(';', '_')
return name
|
def count_true_args(*args):
"""Count number of list of arguments that evaluate True"""
count = 0
for arg in args:
if (arg):
count += 1
return(count)
|
def format_message(message: str) -> str:
"""Formats the Message to remove redundant Spaces and Newline chars"""
msg_l = message.split(" ")
new = []
for x in msg_l:
if "\n" in x:
x = x.replace("\n", "")
new.append(x) if not len(x) == 0 else None
elif len(x) != 0:
new.append(x)
return " ".join(new)
|
def get_initial_cholcovs_index_tuples(n_mixtures, factors):
"""Index tuples for initial_cov.
Args:
n_mixtures (int): Number of elements in the mixture distribution of the factors.
factors (list): The latent factors of the model
Returns:
ind_tups (list)
"""
ind_tups = []
for emf in range(n_mixtures):
for row, factor1 in enumerate(factors):
for col, factor2 in enumerate(factors):
if col <= row:
ind_tups.append(
(
"initial_cholcovs",
0,
f"mixture_{emf}",
f"{factor1}-{factor2}",
)
)
return ind_tups
|
def convert_arrays_to_dict(speciesNames,moleFractions):
"""
Converts two vectors, one containing species names and
one containing mole fractions, into a species dictionary
"""
d = {}
assert len(speciesNames) == len(moleFractions)
for name, amt in zip(speciesNames,moleFractions):
if amt > 0.0:
d[name] = amt
return d
|
def parse_ref(ref):
"""
Convenience method that removes the "#/definitions/" prefix from the
reference name to a REST definition.
"""
ref = ref.replace('#/definitions/', '')
ref = ref.replace('#/x-stream-definitions/', '')
# Workaround for nested messages that the Swagger generator doesn't know
# where to place.
if ref.startswith('PendingChannelsResponse'):
ref = 'lnrpc' + ref
return ref
|
def Dot(v1,v2):
""" Returns the Dot product between two vectors:
**Arguments**:
- two vectors (sequences of bit ids)
**Returns**: an integer
**Notes**
- the vectors must be sorted
- duplicate bit IDs are counted more than once
>>> Dot( (1,2,3,4,10), (2,4,6) )
2
Here's how duplicates are handled:
>>> Dot( (1,2,2,3,4), (2,2,4,5,6) )
5
>>> Dot( (1,2,2,3,4), (2,4,5,6) )
2
>>> Dot( (1,2,2,3,4), (5,6) )
0
>>> Dot( (), (5,6) )
0
"""
res = 0
nV1 = len(v1)
nV2 = len(v2)
i = 0
j = 0
while i<nV1:
v1Val = v1[i]
v1Count = 1
i+=1
while i<nV1 and v1[i]==v1Val:
v1Count += 1
i+=1
while j<nV2 and v2[j]<v1Val:
j+=1
if j < nV2 and v2[j]==v1Val:
v2Val = v2[j]
v2Count = 1
j+=1
while j<nV2 and v2[j]==v1Val:
v2Count+=1
j+=1
commonCount=min(v1Count,v2Count)
res += commonCount*commonCount
elif j>=nV2:
break
return res
|
def _zfill(v, l = 5):
"""zfill a string by padding 0s to the left of the string till it is the link
specified by l.
"""
return "0" * (l - len(v)) + v
|
def swap_bits(x, j, k):
"""
Question 5.2: Swap bits in a number
"""
if (x >> j) & 1 != (x >> k) & 1:
mask = (1 << j) | (1 << k)
x ^= mask
return x
|
def blend_exclusion(cb: float, cs: float) -> float:
"""Blend mode 'exclusion'."""
return cb + cs - 2 * cb * cs
|
def dayAbbrevFormat(day: int) -> str:
"""
Formats a (0-6) weekday number as an abbreviated week day name, according to the current locale.
For example: dayAbbrevFormat(0) -> "Sun".
"""
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
return days[day % 7]
|
def do_truncate(s, length=255, killwords=False, end='...'):
"""
Return a truncated copy of the string. The length is specified
with the first parameter which defaults to ``255``. If the second
parameter is ``true`` the filter will cut the text at length. Otherwise
it will try to save the last word. If the text was in fact
truncated it will append an ellipsis sign (``"..."``). If you want a
different ellipsis sign than ``"..."`` you can specify it using the
third parameter.
.. sourcecode jinja::
{{ mytext|truncate(300, false, '»') }}
truncate mytext to 300 chars, don't split up words, use a
right pointing double arrow as ellipsis sign.
"""
if len(s) <= length:
return s
elif killwords:
return s[:length] + end
words = s.split(' ')
result = []
m = 0
for word in words:
m += len(word) + 1
if m > length:
break
result.append(word)
result.append(end)
return u' '.join(result)
|
def substr_in_list(sub,list,fetch=False):
"""Returns the first string containing the substring if fetch = True. Otherwise it returns a bool that evalutes to true if the substring is present in any string in the list"""
for s in list:
if sub in s:
if fetch:
return s
return True
if fetch:
return ''
return False
|
def to_bytes(something, encoding='utf8') -> bytes:
"""
cast string to bytes() like object, but for python2 support it's bytearray copy
"""
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something, bytearray):
return bytes(something)
else:
raise TypeError("Not a string or bytes like object")
|
def fac(num):
"""fac: Returns an array of factors for the given number
Args:
num (int): number to list factors for
Returns:
array: factors of num
"""
output = []
# Creates inlist for output
for x in range(1, num + 1):
# Loop with variable x
if num % x == 0 and not num % x in output:
# Tests if x goes into num and if x is already in output
output.append(x)
return output
|
def determine_num_ranges(N, max_n):
"""Calculates the number of scatters given max_n from N.
To increase the speed of the LIONESS analysis, we use split the expression
matrix and operate on smaller subsets (e.g. like a map-reduce).
To limit the number of samples in a given shard, we specify `max_n`.
Given that `max_n`, we get the number of shards we will need to make
Args:
N (int): total N of samples / observations
max_n (int): maximum number of samples for a single shard
Returns:
int: total number of windows
"""
d = int(N / max_n)
# edge case where max_n > N.
# We need at least one shard
if d == 0:
return 1
return d
|
def get_nested_dict_key(nested_dict):
"""Get all keys of nested dict
Parameters
----------
nested_dict : dict
Nested dictionary
Return
------
all_nested_keys : list
Key of nested dict
"""
all_nested_keys = []
for entry in nested_dict:
for value in nested_dict[entry].keys():
all_nested_keys.append(value)
return all_nested_keys
|
def valid_urgency():
"""Returns a list of valid urgency levels, all lowercase.
:return: A list of valid urgency levels.
:rtype: list[str]
"""
return ["Immediate", "Expected", "Future", "Past", "Unknown"]
|
def diamond_db_name(config):
"""Generate filtered diamond database name."""
name = "reference_proteomes"
parts = ["diamond", name]
return ".".join(parts)
|
def normal_hostname(hostname: str):
"""Convert ansible hostname to normal format"""
return hostname.replace("_", "-")
|
def _str_to_unit(string):
"""
translates to the string representation of the `astropy.units`
quantity from the Vizier format for the unit.
Parameters
----------
string : str
`s`, `m` or `d`
Returns
-------
string equivalent of the corresponding `astropy` unit.
"""
str_to_unit = {
's': 'arcsec',
'm': 'arcmin',
'd': 'degree'
}
return str_to_unit[string]
|
def merge(large_array, small_array):
"""
Merges 2 given arrays (large and small indicate length) by
combining them in ascending order and returning the one big array.
"""
merged = []
small_index = 0
large_index = 0
merging = True
while merging:
if large_index + 1 > len(large_array):
merged += small_array[small_index:]
merging = False
elif small_index + 1 > len(small_array):
merged += large_array[large_index:]
merging = False
elif large_array[large_index] > small_array[small_index]:
merged.append(small_array[small_index])
small_index += 1
else:
merged.append(large_array[large_index])
large_index += 1
return merged
|
def list2dict(infos):
"""We want a mapping name: char/service for convenience, not a list."""
info_dict = {}
for info in infos:
info_dict[info["Name"]] = info
del info["Name"]
return info_dict
|
def tohlist(s):
"""
convert sofa string to list of hexa
"""
sl= s.replace('[','').split(']')
hlist=list()
for h in sl:
if len(h)!=0 :
hlist.append(map(int,h.split(',')))
return hlist
|
def _cast(value):
"""
Attempt to convert ``value`` to an ``int`` or ``float``. If unable, return
the value unchanged.
"""
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
return value
|
def _positive(value):
""" Validate positive key value. """
return isinstance(value, int) and value > 0
|
def generate_dictionary(**kwargs):
""" Silly function #2 """
dictionary = {}
for entry in kwargs:
dictionary[entry] = kwargs[entry]
return dictionary
|
def get_id(repo):
"""
:param str repo: the url to the compressed file contained the google id
:return the google drive id of the file to be downloaded
:rtype str
"""
start_id_index = repo.index("d/") + 2
end_id_index = repo.index("/view")
return repo[start_id_index:end_id_index]
|
def cve_harvest(text):
"""
looks for anything with 'CVE' inside a text and returns a list of it
"""
array = []
#look inside split by whitespace
for word in text.split():
if 'CVE' in word:
array.append(word)
return array
|
def get_filename(file: str):
"""returns image file name"""
return file.split("\\")[-1]
|
def ishl7(line):
"""Determines whether a *line* looks like an HL7 message.
This method only does a cursory check and does not fully
validate the message.
:rtype: bool
"""
## Prevent issues if the line is empty
return line.strip().startswith('MSH') if line else False
|
def max_in_sliding_window(array, window_width):
"""
:param array: numbers
:param window_width:sliding window size
:return: all max number
"""
if not array or window_width < 1:
return None
max_i = []
res = []
for i in range(len(array)):
while max_i and array[i] >= array[max_i[-1]]:
max_i.pop()
max_i.append(i)
while max_i and i - max_i[0] >= window_width:
max_i.pop(0)
if window_width - 1 <= i:
res.append(array[max_i[0]])
return res
|
def finn_flest(antall):
"""
Finner og returnerer hvilken terningverdi som
forekommer flest ganger
"""
return max(antall, key = antall.count)
|
def remove_quotes(s):
"""
Where a string starts and ends with a quote, remove the quote
"""
if len(s) > 1 and s[0] == s[-1] and s[0] in ['"', "'"]:
return s[1:-1]
return s
|
def calculate_code_lines_count(code: str) -> int:
""" Calculate number of code lines. """
if isinstance(code, str):
return len(code.split('\n'))
return 0
|
def removeElt(items, i):
"""
non-destructively remove the element at index i from a list;
returns a copy; if the result is a list of length 1, just return
the element
"""
result = items[:i] + items[i+1:]
if len(result) == 1:
return result[0]
else:
return result
|
def is_odd(n):
"""Returns True if n is odd, and False if n is even.
Assumes integer.
"""
return bool(n & 1)
|
def flatten(v):
"""
Flatten a list of lists/tuples
"""
return [x for y in v for x in y]
|
def split_iativer(version_str):
"""Split an IATIver-format version number into numeric representations of its components.
Args:
version_str (string): An IATIver-format string.
Returns:
list of int: A list containing numeric representations of the Integer and Decimal components.
"""
integer_component = int(version_str.split('.')[0])
decimal_component = int(version_str.split('.')[1])
return [integer_component, decimal_component]
|
def read_table_header_left(table):
"""
Read a table whit header in first column.
@param table Matrix format
@return dict Dictionary with header as key
"""
data = {}
for row in table:
data[row[0]] = row[1:]
return data
|
def alpha(m_med, m_f):
"""Convenience function that implements part of the spin-1 width formula.
:param m_med: mediator mass
:type m_med: float
:param m_f: fermion mass
:type m_f: float
"""
return 1 + 2 * m_f**2 / m_med**2
|
def _convert_display_size(size):
"""
Convert filesize into human-readable size using unit suffixes
"""
unit_gigabyte = 1024 * 1024 * 1024.0
unit_megabyte = 1024 * 1024.0
unit_kilobyte = 1024.0
if size > unit_gigabyte:
return "{:.2f} GB".format(
size / unit_gigabyte)
elif size > unit_megabyte:
return "{:.2f} MB".format(
size / unit_megabyte)
elif size > unit_kilobyte:
return "{:.1f} KB".format(
size / unit_kilobyte)
return "{0} bytes".format(size)
|
def sciNot(x):
"""Returns scientific notation of x value"""
return '%.2E' % x
|
def bool_option(s):
"""
Command-line option str which must resolve to [true|false]
"""
s = s.lower()
if s=='true':
return True
elif s=='false':
return False
else:
raise TypeError
|
def appn(s1, s2):
"""Append two strings, adding a space between them if either is nonempty.
Args:
s1 (str): The first string
s2 (str): The second string
Returns:
str: The two strings concatenated and separated by a space.
"""
if not s1: return s2
elif not s2: return s1
else: return s1 + " " + s2
|
def find_scaling_factor(tile_num):
""" For a given number of tiles composing the EPU atlas, determine the number of basis vector lengths span from the center of the image to an edge.
PARAMETERS
tile_num = int(), number of tiles of which the atlas is composed
RETURNS
scaling_factor = float()
"""
if tile_num <= 9:
return 1.5
elif tile_num <= 25:
return 2.5
elif tile_num <= 49:
return 3.5
elif tile_num <= 81:
return 4.5
elif tile_num <= 121:
return 5.5
elif tile_num <= 169:
return 6.5
else:
return print("ERROR :: Unexpected number of tiles for atlas (%s)!" % tile_num)
|
def calc_insert_point(source, body, part):
""" Calculates start of line of "part. Usefull for identation."""
if len(body) >= part:
startOffset = body[part].start
ret = startOffset
while source[ret] != '\n':
ret -= 1
newline = ret
ret += 1
while source[ret] == ' ':
ret += 1
return ret-newline-1
else:
return 4
|
def serial_to_station(x: int) -> int:
"""Convert serialized chamber id to station."""
return ((x >> 8) & 0x00000003) + 1
|
def none_to_zero(x):
"""Return 0 if value is None"""
if x is None:
return 0
return x
|
def make_cybox_object_list(objects):
"""
Makes an object list out of cybox objects to put in a cybox container
"""
cybox_objects = {}
for i in range(len(objects)):
cybox_objects[str(i)] = objects[i]
return cybox_objects
|
def Underline(string):
"""Returns string wrapped in escape codes representing underlines."""
return '\x1F%s\x0F' % string
|
def bubbleSort(unsort: list) -> list:
"""bubble sort"""
arr = unsort.copy()
last = len(arr) - 1
for i in range(0, last):
for j in range(0, last - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j] # swap
return arr
|
def DES3500(v):
"""
DES-3500-series
:param v:
:return:
"""
return v["platform"].startswith("DES-35")
|
def stellar_radius(M, logg):
"""Calculate stellar radius given mass and logg"""
if not isinstance(M, (int, float)):
raise TypeError('Mass must be int or float. {} type given'.format(type(M)))
if not isinstance(logg, (int, float)):
raise TypeError('logg must be int or float. {} type given'.format(type(logg)))
if M < 0:
raise ValueError('Only positive stellar masses allowed.')
M = float(M)
return M/(10**(logg-4.44))
|
def allowed_file_history(filename: str) -> bool:
"""Check whether the type is allowed for a file history file.
:param filename: name of the file
:return: True or False
"""
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ['json']
|
def round_channels(channels, divisor=8):
"""
Round weighted channel number (make divisible operation).
Parameters:
----------
channels : int or float
Original number of channels.
divisor : int, default 8
Alignment value.
Returns
-------
int
Weighted number of channels.
"""
rounded_channels = max(
int(channels + divisor / 2.0) // divisor * divisor, divisor)
if float(rounded_channels) < 0.9 * channels:
rounded_channels += divisor
return rounded_channels
|
def to_fully_staffed_matrix_3(d):
"""
Parameters
----------
d : dict<object, object>
Returns
-------
dict<object, object>
"""
for key, val in d.items():
d[val] = key
return d
|
def process_gene_line(gene_line):
"""Parse gene line."""
# contain [gene_id]=[intersected_chain_id] blocks
# remove "gene" and "", get (gene. chain) tuples
# is not necessary really
data = [(x.split("=")[1], x.split("=")[0]) for x in gene_line[1:-1]]
chain = data[0][0] # chain is equal everywhere
genes = [x[1] for x in data]
return chain, genes
|
def getList(start,end):
"""
Strictly Ymd format no spaces or slashes
"""
import datetime
start = datetime.datetime.strptime(str(start),'%Y%m%d')
end = datetime.datetime.strptime(str(end),'%Y%m%d')
dateList = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days + 1)]
sList = [datetime.datetime.strftime(x,'%Y%m%d') for x in dateList]
return sList
|
def rchop(s, sub):
"""
Remove `sub` from the end of `s`.
"""
return s[:-len(sub)] if s.endswith(sub) else s
|
def stripTrailingNL(s):
"""If s ends with a newline, drop it; else return s intact"""
return s[:-1] if s.endswith('\n') else s
|
def check_conditions(line, category, method, thresh=0.3):
"""Check conditions of our or m3d txt file"""
check = False
assert category in ['pedestrian', 'cyclist', 'all']
if category == 'all':
category = ['pedestrian', 'person_sitting', 'cyclist']
if method == 'gt':
if line.split()[0].lower() in category:
check = True
else:
conf = float(line[15])
if line[0].lower() in category and conf >= thresh:
check = True
return check
|
def p_assist(assist):
"""
String of assist operator
:param assist: assist operator
:return: lowercase assist operator
"""
return str(assist).lower()
|
def action(maximize, total_util, payoffs):
"""
>>> action(True, 0.9, [1.1, 0, 1, 0.4])
0
>>> action(True, 1.1, [1.1, 0, 1, 0.4])
1
>>> action(False, 0.9, [1.1, 0, 1, 0.4])
0.9
"""
if maximize:
return int(total_util > payoffs[2])
else:
return total_util
|
def big_l_prime_array(p, n):
""" Compile L' array (Gusfield theorem 2.2.2) using p and N array.
L'[i] = largest index j less than n such that N[j] = |P[i:]| """
lp = [0] * len(p)
for j in range(len(p)-1):
i = len(p) - n[j]
if i < len(p):
lp[i] = j + 1
return lp
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.