content stringlengths 42 6.51k |
|---|
def area(a):
"""
Returns the area of a rectangle.
"""
if a is None: return 0
(x, y, w, h) = a
return w * h |
def corsikaConfigFileName(arrayName, site, primary, zenith, viewCone, label=None):
"""
Corsika config file name.
Parameters
----------
arrayName: str
Array name.
site: str
Paranal or LaPalma.
primary: str
Primary particle (e.g gamma, proton etc).
zenith: float
Zenith angle (deg).
viewCone: list of float
View cone limits (len = 2).
label: str
Instance label.
Returns
-------
str
File name.
"""
isDiffuse = viewCone[0] != 0 or viewCone[1] != 0
name = "corsika-config_{}_{}_{}".format(site, arrayName, primary)
name += "_za{:d}-{:d}".format(int(zenith[0]), int(zenith[1]))
name += (
"_cone{:d}-{:d}".format(int(viewCone[0]), int(viewCone[1])) if isDiffuse else ""
)
name += "_{}".format(label) if label is not None else ""
name += ".input"
return name |
def split_ado(string):
"""
a replacement for re
:param string: any string
:return: alpha, digit, other parts in a list
"""
prev_chr_type = None
acc = ""
parts = []
for c in string:
if c.isalpha():
cur_chr_type = "alpha"
elif c.isdigit():
cur_chr_type = "digit"
else:
cur_chr_type = "other"
if prev_chr_type is None:
acc = c
elif prev_chr_type == cur_chr_type:
acc += c
else:
parts.append(acc)
acc = c
prev_chr_type = cur_chr_type
parts.append(acc)
return parts |
def binary_mask_to_str(m):
"""
Given an iterable or list of 1s and 0s representing a mask, this returns
a string mask with '+'s and '-'s.
"""
m = list(map(lambda x: "-" if x == 0 else "+", m))
return "".join(m) |
def mnist_model_preprocess(image):
"""Processing which should be combined with model for adv eval."""
return 2. * image - 1. |
def preprocessText(text):
"""
This script parses text and removes stop words
"""
# Remove unwanted characters
unwanted_chars = set(["@", "+", '/', "'", '"', '\\', '', '\\n', '\n',
'?', '#', '%', '$', '&', ';', '!', ';', ':', "*", "_", "="])
for char in unwanted_chars:
text = text.replace(char, '')
# Convert all text into lowercase
text = text.lower()
return text |
def inpath(entry, pathvar):
"""Check if entry is in pathvar. pathvar is a string of the form
`entry1:entry2:entry3`."""
return entry in set(pathvar.split(':')) |
def arg_list(items, prefix=''):
"""Process a list or string of arguments into a string containing them
Used so users can pass arguments as a string or list in the configuration file.
:param items:
:param prefix:
:return:
"""
if not items:
return ''
list_of_items = items.split(' ') if isinstance(items, str) else items
if list_of_items == ['']:
return ''
list_of_items = [prefix + i for i in list_of_items]
return ' '.join(filter(None, list_of_items)) |
def card_remover(decklist, card):
"""
Given a decklist and a card name, returns the decklist with the card removed.
Parameters:
decklist: list of str
A decklist represented by a list of strings of card names.
card: str
The card to be removed from the decklist
:return:
list of str
Returns the same decklist, minus the card that was removed, as a list
of strings
"""
return [x for x in decklist if x != card] |
def my_str(in_str):
"""Convert a given string to tex-able output string.
"""
out_str = in_str.replace("_", "\\textunderscore ")
return out_str |
def count(generator):
"""Count the number of items in the stream."""
counter = 0
for _ in generator:
counter += 1
return counter |
def gen_all_party_key(all_party):
"""
Join all party as party key
:param all_party:
"role": {
"guest": [9999],
"host": [10000],
"arbiter": [10000]
}
:return:
"""
if not all_party:
all_party_key = 'all'
elif isinstance(all_party, dict):
sorted_role_name = sorted(all_party.keys())
all_party_key = '#'.join([
('%s-%s' % (
role_name,
'_'.join([str(p) for p in sorted(set(all_party[role_name]))]))
)
for role_name in sorted_role_name])
else:
all_party_key = None
return all_party_key |
def _merge_dicts(d, *args, **kw):
"""Merge two or more dictionaries into a new dictionary object.
"""
new_d = d.copy()
for dic in args:
new_d.update(dic)
new_d.update(kw)
return new_d |
def get_time_in_video(total_frames, frame_rate, curr_frame):
"""Calculate current time of video"""
# return (total_frames * frame_rate) / curr_frame
return curr_frame / frame_rate |
def strip_dav_path(path):
"""Removes the leading "remote.php/webdav" path from the given path.
:param str path: path containing the remote DAV path "remote.php/webdav"
:return: path stripped of the remote DAV path
:rtype: str
"""
if 'remote.php/webdav' in path:
return path.split('remote.php/webdav')[1]
return path |
def botobool(obj):
""" returns boto results compatible value """
return u'false' if not bool(obj) else u'true' |
def filterv(fn, *colls):
"""A greedy version of filter."""
return list(filter(fn, *colls)) |
def dicts_equal(lhs, rhs):
"""
>>> dicts_equal({}, {})
True
>>> dicts_equal({}, {'a': 1})
False
>>> d0 = {'a': 1}; dicts_equal(d0, d0)
True
>>> d1 = {'a': [1, 2, 3]}; dicts_equal(d1, d1)
True
>>> dicts_equal(d0, d1)
False
"""
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 get_num(x: str) -> int:
""" Extracts all digits from incomig string """
return int(''.join(ele for ele in x if ele.isdigit())) |
def _select_encoding(consumes, form=False):
"""
Given an OpenAPI 'consumes' list, return a single 'encoding' for CoreAPI.
"""
if form:
preference = [
'multipart/form-data',
'application/x-www-form-urlencoded',
'application/json'
]
else:
preference = [
'application/json',
'multipart/form-data',
'application/x-www-form-urlencoded',
'application/octet-stream'
]
if not consumes:
return preference[0]
for media_type in preference:
if media_type in consumes:
return media_type
return consumes[0] |
def str_to_int(exp):
"""
Convert a string to an integer.
The method is primitive, using a simple hash based on the
ordinal value of the characters and their position in the string.
Parameters
----------
exp : str
The string expression to convert to an int.
Returns
-------
sum : int
An integer that is likely (though not extremely so) to be unique
within the scope of the program.
"""
sum_ = 0
for i, character in enumerate(exp):
sum_ += i + ord(character) + i * ord(character)
return sum_ |
def convert_to_dict(obj):
"""Converts a OpenAIObject back to a regular dict.
Nested OpenAIObjects are also converted back to regular dicts.
:param obj: The OpenAIObject to convert.
:returns: The OpenAIObject as a dict.
"""
if isinstance(obj, list):
return [convert_to_dict(i) for i in obj]
# This works by virtue of the fact that OpenAIObjects _are_ dicts. The dict
# comprehension returns a regular dict and recursively applies the
# conversion to each value.
elif isinstance(obj, dict):
return {k: convert_to_dict(v) for k, v in obj.items()}
else:
return obj |
def xenon1t_detector_renamer(input):
"""Function: xenon1t_detector_renamer
"""
if input.get("detector") == 'muon_veto':
input['detector'] = 'mv'
return input |
def envelope(value, minval, maxval):
"""Adjust `value` to be within min/max bounds."""
return min(max(value, minval), maxval) |
def is_c_func(func):
"""Return True if given function object was implemented in C,
via a C extension or as a builtin.
>>> is_c_func(repr)
True
>>> import sys
>>> is_c_func(sys.exit)
True
>>> import doctest
>>> is_c_func(doctest.testmod)
False
"""
return not hasattr(func, 'func_code') |
def say_hello_something(config, http_context):
"""
"Hello <something>" using slug
Usage:
$ export XSESSION=`curl -s -k -X POST --data '{"username":"<user>", "password":"<password>"}' https://localhost:2345/login | sed -E "s/^.+\"([a-f0-9]+)\".+$/\1/"`
$ curl -s -k -H "X-Session:$XSESSION" "https://localhost:2345/hello/toto" | python -m json.tool
{
"content": "Hello toto"
}
""" # noqa
return {"content": "Hello %s" % (http_context['urlvars'][0])} |
def format_test_id(test_id) -> str:
"""Format numeric to 0-padded string"""
test_str = str(test_id)
test_str = '0'*(5-len(test_str)) + test_str
return test_str |
def gmof(x, sigma):
"""
Geman-McClure error function
"""
x_squared = x ** 2
sigma_squared = sigma ** 2
return (sigma_squared * x_squared) / (sigma_squared + x_squared) |
def get_bib_ident(cite_data):
"""Return the best identifier (ISBN, DOI, PMID, PMCID, or URL)"""
data = cite_data["data"]
return data.get(
"isbn", data.get("pmcid", data.get("pmid", data.get("doi", data.get("url"))))
) |
def change_zp(flux, zp, new_zp):
"""Converts flux units given a new zero-point.
**Note:** this assumes that the new zero-point is in the same magnitude system as the current one.
Parameters
----------
flux : float or array
Fluxes.
zp : float or array
Current zero-point for the given fluxes.
new_zp : float or array
New zero-point to convert the flux units.
Returns
-------
new_flux : float or array
Fluxes with with a new zero-point.
"""
new_flux = flux*10**( -0.4*(zp - new_zp) )
return new_flux |
def accumulate(combiner, base, n, term):
"""Return the result of combining the first n terms in a sequence and base.
The terms to be combined are term(1), term(2), ..., term(n). combiner is a
two-argument commutative, associative function.
>>> accumulate(add, 0, 5, identity) # 0 + 1 + 2 + 3 + 4 + 5
15
>>> accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5
26
>>> accumulate(add, 11, 0, identity) # 11
11
>>> accumulate(add, 11, 3, square) # 11 + 1^2 + 2^2 + 3^2
25
>>> accumulate(mul, 2, 3, square) # 2 * 1^2 * 2^2 * 3^2
72
"""
total, k = base, 1
while k <= n:
total, k = combiner(total, term(k)), k + 1
return total |
def decolumnify(columns):
"""Takes ['afkpuz', 'bglqv', 'chrmw', 'dinsx', 'ejoty']
and outputs abcdefghijklmnopqrstuvwxyz
"""
comp = ''
keyword_length = len(columns)
for row_num in range(len(columns[0])):
for column_num in range(keyword_length):
try:
comp += columns[column_num][row_num]
except IndexError:
pass
return(comp) |
def parse_target_from_json(one_target, command_line_list):
"""parse the targets out of the json file struct
Parameters
----------
one_target: dict
dictionary with all target's details
command_line_list: list
list to update with target parameters
"""
target_kind, *sub_type = [
one_target[key] if key == "kind" else (key, one_target[key]) for key in one_target
]
internal_dict = {}
if sub_type:
sub_target_type = sub_type[0][0]
target_value = sub_type[0][1]
internal_dict[f"target_{target_kind}_{sub_target_type}"] = target_value
command_line_list.append(internal_dict)
return target_kind |
def init_parameters(parameter):
"""Auxiliary function to set the parameter dictionary
Parameters
----------
parameter: dict
See the above function initTemplates for further information
Returns
-------
parameter: dict
"""
parameter['pitchTolUp'] = 0.75 if 'pitchTolUp' not in parameter else parameter['pitchTolUp']
parameter['pitchTolDown'] = 0.75 if 'pitchTolDown' not in parameter else parameter['pitchTolDown']
parameter['numHarmonics'] = 25 if 'numHarmonics' not in parameter else parameter['numHarmonics']
parameter['numTemplateFrames'] = 1 if 'numTemplateFrames' not in parameter else parameter['numTemplateFrames']
return parameter |
def mac_byte_mask(mask_bytes=0):
"""Return a MAC address mask with n bytes masked out."""
assert mask_bytes <= 6
return ':'.join(['ff'] * mask_bytes + (['00'] * (6 - mask_bytes))) |
def get_idx(array_like, idx):
"""
Given an array-like object (either list or series),
return the value at the requested index
"""
if hasattr(array_like, 'iloc'):
return array_like.iloc[idx]
else:
return array_like[idx] |
def palindrome(my_str):
"""
Returns True if an input string is a palindrome. Else returns False.
"""
stripped_str = "".join(l.lower() for l in my_str if l.isalpha())
return stripped_str == stripped_str[::-1] |
def to_snippet(text, length=40):
"""Shorten a string with ellipses as necessary to meet the target length"""
if len(text) <= length:
return text
return text[:length-3] + '...' |
def compare_unhashable_list(s, t):
"""
Compare list of unhashable objects (e.g. dictionaries). From SO by Steven Rumbalski.
"""
t = list(t) # make a mutable copy
try:
for elem in s:
t.remove(elem)
except ValueError:
return False
return not t |
def safe_repr(obj):
"""
Try to get ``__name__`` first, ``__class__.__name__`` second
and finally, if we can't get anything acceptable, fallback
to user a ``repr()`` call.
"""
name = getattr(obj, '__name__', getattr(obj.__class__, '__name__'))
if name == 'ndict':
name = 'dict'
return name or repr(obj) |
def vals_are_multiples(num, vals, digits=4):
"""decide whether every value in 'vals' is a multiple of 'num'
(vals can be a single float or a list of them)
Note, 'digits' can be used to specify the number of digits of accuracy
in the test to see if a ratio is integral. For example:
vals_are_multiples(1.1, 3.3001, 3) == 1
vals_are_multiples(1.1, 3.3001, 4) == 0
return 1 if true, 0 otherwise (including error)"""
if num == 0.0: return 0
try:
l = len(vals)
vlist = vals
except:
vlist = [vals]
for val in vlist:
rat = val/num
rem = rat - int(rat)
if round(rem,digits) != 0.0: return 0
return 1 |
def get_arb_formatted(input):
"""Arbitrary formatter takes a string and returns a string."""
return f'X{input}X' |
def build_constituents(sent_id: int, s: str) -> dict:
"""Generates a frame for a constituent tree JSON object."""
s = s.rstrip().lstrip()
open_bracket = s[0]
close_bracket = s[-1]
return {
'sentenceId': sent_id,
'labeledBracketing': f'{open_bracket}ROOT {s}{close_bracket}' if s[1:5] != 'ROOT' else s
} |
def get_next_xtalk(expressions, tx_prefix=""):
"""Get the list of all the Near End XTalk a list of excitation. Optionally prefix can
be used to retrieve driver names.
Example: excitation_names ["1", "2", "3"] output ["S(1,2)", "S(1,3)", "S(2,3)"]
Parameters
----------
expressions :
list of Drivers to include
tx_prefix :
prefix for TX (eg. "DIE") (Default value = "")
Returns
-------
type
list of string representing Near End XTalks
"""
next = []
if tx_prefix:
trlist = [i for i in expressions if tx_prefix in i]
else:
trlist = expressions
for i in trlist:
k = trlist.index(i)+1
while k < len(trlist):
next.append("S({},{})".format(i, trlist[k]))
k += 1
return next |
def get_file_type(path):
""" Sort volume files by type. """
if 'alto/' in path:
if path.endswith('.xml') or path.endswith('.xml.gz'):
return 'alto'
return None
if 'images/' in path:
if path.endswith('.jp2'):
return 'jp2'
if path.endswith('.jpg'):
return 'jp2'
if path.endswith('.tif'):
return 'tif'
if path.endswith('.pdf'):
return 'pdf'
return None
if 'casemets/' in path:
if path.endswith('.xml') or path.endswith('.xml.gz'):
return 'case'
return None
if path.endswith('METS.md5'):
return 'md5'
if path.endswith('METS.xml') or path.endswith('METS.xml.gz'):
return 'volume'
if path.endswith('BOXES.xml') or path.endswith('BOXES.xml.gz'):
return 'boxes'
return None |
def mapValues(function, dictionary):
""" Map `function` to the values of `dictionary`. """
return {key: function(value) for key, value in dictionary.items()} |
def strip_quotes(table_name):
"""
Strip quotes off of quoted table names to make them safe for use in index
names, sequence names, etc. For example '"USER"."TABLE"' (an Oracle naming
scheme) becomes 'USER"."TABLE'.
"""
has_quotes = table_name.startswith('"') and table_name.endswith('"')
return table_name[1:-1] if has_quotes else table_name |
def _crc32(data, crc, table):
"""Calculates the 32-bit CRC value for the provided input bytes.
This computes the CRC values using the provided reversed form CRC table.
"""
crc = ~crc & 0xFFFFFFFF
for byte in data:
index = (crc ^ byte) & 0xFF
crc = (crc >> 8) ^ table[index]
return ~crc & 0xFFFFFFFF |
def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c.
Note:
Copied without modification from Python 3.6.1 tokenize standard library module
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation; All Rights
Reserved"
See also py-cloud-compute-cannon/NOTICES.
"""
# Only care about the first 12 characters.
enc = orig_enc[:12].lower().replace("_", "-")
if enc == "utf-8" or enc.startswith("utf-8-"):
return "utf-8"
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
return "iso-8859-1"
return orig_enc |
def formatter(type):
"""Format floating point numbers in scientific notation
(integers use normal integer formatting)."""
if type == int:
return "%d"
elif type == float:
return "%.3e" |
def rgb_to_hex(red, green, blue):
"""Return color as #rrggbb for the given color values."""
return '#%02x%02x%02x' % (red, green, blue) |
def get_hosted_zone_id(session, hosted_zone):
"""Look up Hosted Zone ID by DNS Name
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
hosted_zone (string) : DNS Name of the Hosted Zone to lookup
Returns:
(string|None) : Hosted Zone ID or None if the Hosted Zone could not be located
"""
if session is None:
return None
client = session.client('route53')
response = client.list_hosted_zones_by_name(
DNSName=hosted_zone,
MaxItems='1'
)
if len(response['HostedZones']) >= 1:
full_id = response['HostedZones'][0]['Id']
id_parts = full_id.split('/')
return id_parts.pop()
else:
return None |
def booth(X, Y):
"""constraints=10, minimum f(1, 3)=0"""
return ((X) + (2.0 * Y) - 7.0) ** 2 + ((2.0 * X) + (Y) - 5.0) ** 2 |
def interval(mu,sigma):
""" methods of estimators """
a = mu - 4*sigma
b = mu + 4*sigma
return a, b |
def bytes_find_single(x: bytes, sub: int, start: int, end: int) -> int:
"""Where is the first location of a specified byte within a given slice of a bytes object?
Compiling bytes.find compiles this function, when sub is an integer 0 to 255.
This function is only intended to be executed in this compiled form.
Args:
x: The bytes object in which to search.
sub: The subsequence to look for, as a single byte specified as an integer 0 to 255.
start: Beginning of slice of x. Interpreted as slice notation.
end: End of slice of x. Interpreted as slice notation.
Returns:
Lowest index of match within slice of x, or -1 if not found.
Raises:
ValueError: The sub argument is out of valid range.
"""
if sub < 0 or sub > 255:
raise ValueError("byte must be in range(0, 256)")
if start < 0:
start += len(x)
if start < 0:
start = 0
if end < 0:
end += len(x)
if end < 0:
end = 0
if end > len(x):
end = len(x)
index = start
while index < end:
if x[index] == sub:
return index
index += 1
return -1 |
def getit(key, h):
"""Return h[key]. If key has '.' in it like static.max_fuel, return h[static][max_fuel]
getit('physics.tyre_wear', h') will get you h['physics']['tyre_wear'].
It's just syntactic sugar, but easier to read.
Exceptions are not catched
"""
if '.' in key:
keys = key.split('.')
return h.get(keys[0]).get(keys[1])
else:
return h.get(key) |
def apply_tariff(kwh, hour):
"""Calculates cost of electricity for given hour."""
if 0 <= hour < 7:
rate = 12
elif 7 <= hour < 17:
rate = 20
elif 17 <= hour < 24:
rate = 28
else:
raise ValueError(f'Invalid hour: {hour}')
return rate * kwh |
def real_units(bias, fb, mce_bias_r=467, dewar_bias_r=49, shunt_r=180E-6,
dewar_fb_r=5280, butterworth_constant=1218,
rel_fb_inductance=9, max_bias_voltage=5, max_fb_voltage=0.958,
bias_dac_bits=16, fb_dac_bits=14):
"""
Given an array of biases and corresponding array of feedbacks (all in DAC units)
calculate the actual current and voltage going through the TES.
Returns: (TES voltage array, TES current array) in Volts and Amps respectively.
The default values are taken from Carl's script
Modified from `zeustools/iv_tools
<https://github.com/NanoExplorer/zeustools/blob/master/zeustools/iv_tools.py>`_
:param bias: scalar or array, tes bias value(s) in adc unit
:rtype bias: int or float or numpy.ndarray
:param fb: scalar or array, sq1 feedback value(s) in adc unit, must have the
shape such that bias * fb yields valid result
:rtype fb: int or float or numpy.ndarray
:param int or float mce_bias_r: scalar, MCE bias resistance in ohm, default
467 ohm
:param int or float dewar_bias_r: scalar, dewar bias resistance in ohm,
default 49 ohm
:param int or float shunt_r: scalar, shunt resistance in ohm, default 180
uOhm
:param int or float dewar_fb_r: scalar, dewar feedback resistance in ohm,
default 5280 ohm
:param int or float butterworth_constant: scalar, when running in data mode 2
and the low pass filter is in the loop, all signals are multiplied by
this factor
:param int or float rel_fb_inductance: scalar, feedback inductance ratio,
default 9 which means for a change of 1 uA in the TES, the squid will
have to change 9 uA to keep up
:param int or float max_bias_voltage: scalar, maximum bias voltage in V,
default 5
:param int or float max_fb_voltage: scalar, maximum feedback voltage in V,
default 0.958
:param int bias_dac_bits: int, bias DAC bit number, default 16
:param int fb_dac_bits: int, feedback DAC bit number, default 14
"""
bias_raw_voltage = bias / 2 ** bias_dac_bits * max_bias_voltage * 2
# last factor of 2 is because voltage is bipolar
bias_current = bias_raw_voltage / (dewar_bias_r + mce_bias_r)
fb_real_dac = fb / butterworth_constant
fb_raw_voltage = fb_real_dac / 2 ** fb_dac_bits * max_fb_voltage * 2
# again, last factor of 2 is because voltage is bipolar
fb_current = fb_raw_voltage / dewar_fb_r
tes_current = fb_current / rel_fb_inductance
shunt_current = bias_current - tes_current
tes_voltage = shunt_current * shunt_r
return tes_voltage, tes_current |
def timeout_check(value):
"""
Checks timeout for validity.
Args:
value:
Returns:
Floating point number representing the time (in seconds) that should be
used for the timeout.
NOTE: Will raise an exception if the timeout in invalid.
"""
from argparse import ArgumentTypeError
try:
timeout = float(value)
except Exception as _e:
raise ArgumentTypeError(f"Timeout '{value}' must be a number. {_e}")
if timeout <= 0:
raise ArgumentTypeError(f"Timeout '{value}' must be greater than 0.0s.")
return timeout |
def update_orders(orders_dict, orders):
"""Updates current orders list and returns it"""
orders_dict['orders'] = orders
return orders_dict |
def underscore_to_camelcase(word):
"""Humanizes function names"""
return ' '.join(char.capitalize() for char in word.split('_')) |
def swap_chunk(chunk_orig):
"""Swap byte endianness of the given chunk.
Returns:
swapped chunk
"""
chunk = bytearray(chunk_orig)
# align to 4 bytes and pad with 0x0
chunk_len = len(chunk)
pad_len = chunk_len % 4
if pad_len > 0:
chunk += b'\x00' * (4 - pad_len)
chunk[0::4], chunk[1::4], chunk[2::4], chunk[3::4] =\
chunk[3::4], chunk[2::4], chunk[1::4], chunk[0::4]
return chunk |
def DerepCount(titleline):
"""
Takes a title from a uSearch dep'd fasta sequence, and returns the sequence count as an integer
"""
return int((titleline.split('size=')[1]).split(';')[0]) |
def _DistanceOfPointToRange( point, range ):
"""Calculate the distance from a point to a range.
Assumes point is covered by lines in the range.
Returns 0 if point is already inside range. """
start = range[ 'start' ]
end = range[ 'end' ]
# Single-line range.
if start[ 'line' ] == end[ 'line' ]:
# 0 if point is within range, otherwise distance from start/end.
return max( 0, point[ 'character' ] - end[ 'character' ],
start[ 'character' ] - point[ 'character' ] )
if start[ 'line' ] == point[ 'line' ]:
return max( 0, start[ 'character' ] - point[ 'character' ] )
if end[ 'line' ] == point[ 'line' ]:
return max( 0, point[ 'character' ] - end[ 'character' ] )
# If not on the first or last line, then point is within range for sure.
return 0 |
def iterable(x):
"""Tell whether an object is iterable or not."""
try:
iter(x)
except TypeError:
return False
else:
return True |
def prepareIDNName(name):
"""
Encode a unicode IDN Domain Name into its ACE equivalent.
This will encode the domain labels, separated by allowed dot code points,
to their ASCII Compatible Encoding (ACE) equivalent, using punycode. The
result is an ASCII byte string of the encoded labels, separated by the
standard full stop.
"""
return name.encode('idna') |
def gen_xacro_robot(macro):
"""
Generates (as a string) the complete urdf element sequence for a xacro
robot definition. This is essentially a string concatenation operation.
Note that the ``macro`` sequence should already be a string.
:param macro: The xacro macro to embed, ``str``
:returns: urdf element sequence for a xacro robot, ``str``
"""
return '<robot xmlns:xacro="http://ros.org/wiki/xacro">{}</robot>'.format(macro) |
def rec_ctp(grid, x, y, m, n):
"""
Recursive approach
"""
if x == 0 and y == n - 1:
return 1
if x < 0 or y > n-1:
return 0
if grid[x][y]:
return 0
return (rec_ctp(grid, x-1, y, m, n) + rec_ctp(grid, x, y+1, m, n))%1000003 |
def find_words(root):
""" print out all words in trie """
result = []
def find_words_path(node, path):
if node is None:
return
if node.is_end_word:
result.append(path + node.char)
if node.char is not None:
path += node.char
for child in node.children:
find_words_path(child, path)
if root is None:
return []
if root.is_end_word:
return [root.char]
find_words_path(root, "")
return result |
def reformat_variable(var, n_dim, dtype=None):
"""This function takes a variable (int, float, list, tuple) and reformat it into a list of desired length (n_dim)
and type (int, float, bool)."""
if isinstance(var, (int, float)):
var = [var] * n_dim
elif isinstance(var, (list, tuple)):
if len(var) == 1:
var = var * n_dim
elif len(var) != n_dim:
raise ValueError('if var is a list/tuple, it should be of length 1 or {0}, had {1}'.format(n_dim, var))
else:
raise TypeError('var should be an int, float, tuple, or list; had {}'.format(type(var)))
if dtype is not None:
if dtype == 'int':
var = [int(v) for v in var]
elif dtype == 'float':
var = [float(v) for v in var]
elif dtype == 'bool':
var = [bool(v) for v in var]
else:
raise ValueError('dtype should be "float", "int", or "bool"; had {}'.format(dtype))
return var |
def tensor2np(x):
"""Convert torch.Tensor to np.ndarray
Args:
x (torch.Tensor)
Returns:
np.ndarray
"""
if x is None:
return x
return x.cpu().detach().numpy() |
def _collected_label(collect, label):
"""Label of a collected column."""
if not collect.__name__.startswith('<'):
return label + ' ' + collect.__name__
else:
return label |
def replace(scope, strings, source, dest):
"""
Returns a copy of the given string (or list of strings) in which all
occurrences of the given source are replaced by the given dest.
:type strings: string
:param strings: A string, or a list of strings.
:type source: string
:param source: What to replace.
:type dest: string
:param dest: What to replace it with.
:rtype: string
:return: The resulting string, or list of strings.
"""
return [s.replace(source[0], dest[0]) for s in strings] |
def split_strings(strings, start, chr_lens):
"""split strings based on string lengths and given start"""
return [strings[i-start:j-start] for i, j in zip([start]+chr_lens[:-1], chr_lens)] |
def is_mixed_case(string: str) -> bool:
"""Check whether a string contains uppercase and lowercase characters."""
return not string.islower() and not string.isupper() |
def linear (x, parameters):
"""Sigmoid function
POI = a + (b * x )
Parameters
----------
x: float or array of floats
variable
parameters: dict
dictionary containing 'linear_a', and 'linear_b'
Returns
-------
float or array of floats:
function result
"""
a = parameters['linear_a']
b = parameters['linear_b']
return a + (b * x) |
def blank(l1):
"""
Display the length of the letters by " - " .
"""
bl = ""
for i in range(l1):
bl = bl + "-"
return bl |
def find_length(list_tensors):
"""find the length of list of tensors"""
length = [x.shape[0] for x in list_tensors]
return length |
def levenshtein(s: str, t: str, insert_cost: int = 1, delete_cost: int = 1, replace_cost: int = 1) -> int:
""" From Wikipedia article; Iterative with two matrix rows. """
# degenerate cases
if s == t:
return 0
len0 = len(s)
len1 = len(t)
if not len0:
return len1
if not len1:
return len0
# the array of distances
v0 = [0] * (len0 + 1)
v1 = [0] * (len0 + 1)
# initial cost of skipping prefix in s
for i in range(len(v0)):
v0[i] = i
# dynamically compute the array of distances
# transformation cost for each letter in t
for j in range(len1):
# initial cost of skipping prefix in t
v1[0] = j + 1
# transformation cost for each letter in s
for i in range(len0):
# matching current letters in both strings
match = 0 if s[i] == t[j] else 1
# computing cost for each transformation
cost_insert = v0[i + 1] + insert_cost
cost_delete = v1[i] + delete_cost
cost_replace = v0[i] + match * replace_cost
# keep minimum cost
v1[i + 1] = min(cost_insert, cost_delete, cost_replace)
# swap cost arrays
v0, v1 = v1, v0
# the distance is the cost for transforming all letters in both strings
return v0[len0] |
def kangaroo(x1: int, v1: int, x2: int, v2: int) -> str:
"""
>>> kangaroo(0, 2, 5, 3)
'NO'
>>> kangaroo(0, 3, 4, 2)
'YES'
>>> kangaroo(14, 4, 98, 2)
'YES'
>>> kangaroo(21, 6, 47, 3)
'NO'
"""
# if v1 > v2:
# i = 0
# while i <= x2:
# i += 1
# if (x1 + v1 * i) == (x2 + v2 * i):
# return 'YES'
# return 'NO'
ret = 'YES' if (v1 > v2) and (not (x2 - x1) % (v2 - v1)) else 'NO'
return ret |
def compute_counts(y_true, y_pred, label):
"""
:param y_true: List[str/int] : List of true labels (expected value) for each test
:param y_pred: List[str/int]: List of classifier predicted labels (observed_values) / test
:param label: label to use as reference for computing counts
:return: 5-tuple: Tuple(int, int, int, int, int, dict (contains same information as int but with headers)
"""
true_pos, false_neg, false_pos, true_neg = 0, 0, 0, 0
for y, y_ in zip(y_true, y_pred):
expected_matches_label = y == label
predicted_matches_expected = y == y_
true_pos += expected_matches_label and predicted_matches_expected
false_neg += expected_matches_label and not predicted_matches_expected
true_neg += not expected_matches_label and predicted_matches_expected
false_pos += not expected_matches_label and not predicted_matches_expected
return true_pos, false_neg, false_pos, true_neg |
def agenda_format_day(
number_of_days_before,
date_start,
cfg_today,
cfg_tomorrow,
cfg_in_days,
):
"""
Formats the string who indicates if the event is today, tomorrow, or else
in an arbitrary number of day.
Args:
number_of_days_before (int): The number of days before the event.
date_start (string): ISO 8601 formated date (& time).
cfg_today (string): The text to show if the event is today.
cfg_tomorrow (string): The text to if the event happens tomorrow.
cfg_in_days (string): The text to concatenate after the number of days before
the event, if it will happen in a number of days greater than tomorrow.
Returns :
The final formated string who indicates when will be the event.
"""
if number_of_days_before == 0: # if today
if "T" in date_start: # if there is time data
return date_start.split("T")[1][:5] # get the hour only
return cfg_today
if number_of_days_before == 1: # if tomorrow
return cfg_tomorrow
# else return the remaining number of days before the event
return f"{number_of_days_before}{cfg_in_days}" |
def relu(x):
"""
NumPy implementation of tf.nn.relu
:param x: Data to have ReLU activated
:type x: Union[ndarray, float]
:return: ReLU activated data
:rtype: Union[ndarray, float]
:History: 2018-Apr-11 - Written - Henry Leung (University of Toronto)
"""
return x * (x > 0) |
def obj_has_method(obj, method):
"""http://stackoverflow.com/questions/34439/finding-what-methods-an-object-has"""
return hasattr(obj, method) and callable(getattr(obj, method)) |
def mm2(mm):
"""Leave int values, give floats 2 decimals - for legible SVG"""
if type(mm) == int:
return str(mm)
if type(mm) == float:
return "{:.2f}".format(mm)
return "{:.2f}".format(mm) |
def get_board_as_string(game):
"""
Returns a string representation of the game board in the current state.
"""
board_str = """
{} | {} | {}
--------------
{} | {} | {}
--------------
{} | {} | {}
"""
return board_str.format(game["board"][0][0], game["board"][0][1],game["board"][0][2],game["board"][1][0],game["board"][1][1],game["board"][1][2],game["board"][2][0],game["board"][2][1],game["board"][2][2])
# "{name} is being {emotion}"".format(d) d = {'name': 'Yatri', 'emotion': 'funny'} |
def inside(r, q):
"""See if one rectangle inside another"""
rx, ry, rw, rh = r
qx, qy, qw, qh = q
return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh |
def generate_headers(token):
"""
:param token:
:return:
"""
authorization = 'Bearer ' + token
headers = {
'Authorization': authorization,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
return headers |
def surface_margin_dist (A_approx_dist, A_real_dist):
"""
Calculates the surface margin.
Parameters
----------
A_approximate_dist : float
The approximate heat ransfer area, [m**2]
A_real_dist : float
The real heat transfer area, [m**2]
Returns
-------
surface_margin : float
The surface margin, [%]
References
----------
???
"""
return (A_approx_dist - A_real_dist) * 100 / A_approx_dist |
def equal_without_whitespace(string1, string2):
"""Returns True if string1 and string2 have the same nonwhitespace tokens
in the same order."""
return string1.split() == string2.split() |
def EVLAAIPSName( project, session):
"""
Derive AIPS Name. AIPS file name will be project+session with project
truncated to fit in 12 characters.
* project = project name
* session = session code
"""
################################################################
Aname = Aname=(project.strip()+session)[0:12]
return Aname
# end EVLAAIPSName |
def hex_to_dec(x):
"""Convert hex to decimal.
:param x:
:return:
"""
return int(x, 16) |
def _get_suffix(pop_scenario, throughput_scenario, intervention_strategy):
"""
Get the filename suffix for each scenario and strategy variant.
"""
suffix = '{}_{}_{}'.format(
pop_scenario, throughput_scenario, intervention_strategy)
suffix = suffix.replace('baseline', 'base')
return suffix |
def median(y):
"""
Return the median (middle value) of numeric y.
When the number of y points is odd, return the middle y point.
When the number of y points is even, the median is interpolated by
taking the average of the two middle values:
>>> median([1, 3, 5])
3
>>> median([1, 3, 5, 7])
4.0
"""
y = sorted(y)
n = len(y)
if n%2 == 1:
return y[n//2]
else:
i = n//2
return (y[i - 1] + y[i])/2 |
def nested_dict_get_path(key, var):
"""Searches a nested dictionary for a key and returns
a list of strings designating the
complete path to that key.
Returns an empty list if key is not found.
Warning: if key is in multiple nest levels,
this will only return one of those values."""
path = []
if hasattr(var, 'iteritems'):
for k, v in var.items():
if k == key:
path.append(k)
break
if isinstance(v, dict):
local_path = [k]
maybe_path = nested_dict_get_path(key, v)
if maybe_path != []:
local_path.extend(maybe_path)
path.extend(local_path)
return path |
def _cdp_no_split_aligned_count(aligned_count_1, query_seq_fwd, query_seq_rvs, seq_dict_1):
"""
:param aligned_count_1:
:param query_seq_fwd:
:param query_seq_rvs:
:param seq_dict_1:
:return:
"""
if query_seq_fwd in seq_dict_1:
aligned_count_1 += seq_dict_1[query_seq_fwd]
if query_seq_rvs in seq_dict_1:
aligned_count_1 += seq_dict_1[query_seq_rvs]
return aligned_count_1 |
def transformInput(data):
""" separate input to seq_args and global_args
Args:
data: input data
Returns:
separated input data
"""
p3py_data = {}
p3py_data['seq_args'] = {}
p3py_data['global_args'] = {}
for key in data.keys():
if('SEQUENCE_' in key.upper()):
p3py_data['seq_args'][key.upper()] = data[key]
elif('PRIMER_' in key.upper()):
p3py_data['global_args'][key.upper()] = data[key]
return p3py_data |
def get_proxy_dict(ip, port, proxy_type='http' or 'socks5'):
"""get_proxy_dict return dict proxies as requests proxies
http://docs.python-requests.org/en/master/user/advanced/
:param ip: ip string
:param port: int port
:param proxy_type: 'http' or 'socks5'
"""
proxies = {
'http': '{proxy_type}://{ip}:{port}'.format(proxy_type=proxy_type, ip=ip, port=port),
'https': '{proxy_type}://{ip}:{port}'.format(proxy_type=proxy_type, ip=ip, port=port),
}
return proxies |
def parse_test_names(test_name_args):
"""Returns a dictionary mapping test case names to a list of test functions
:param test_name_args: The parsed value of the ``--test`` or ``--skip``
arguments
:return: None if ``test_name_args`` is None, otherwise return a dictionary
mapping test case names to a list of test functions to run. If list is
empty, no specific function was given for that class
"""
if test_name_args is None:
return None
class_map = {}
for test_name in test_name_args:
# Split <module>.[<function>]
test_name_parts = test_name.split('.')
class_map.setdefault(test_name_parts[0], [])
# If a function was specified, append it to the list of functions
if len(test_name_parts) > 1:
class_map[test_name_parts[0]].append(test_name_parts[1])
return class_map |
def WrapInTuple(response):
"""Wraps the response in a tuple to support legacy behavior.
Dictionaries and strings are placed in a tuple, while lists are unpacked into
the tuple. None will not be wrapped in a tuple at all.
Args:
response: mixed The response from the API to wrap in a tuple. Could be a
string, list, or dictionary depending on the operation.
Returns:
tuple: The given response wrapped in a tuple. Will be None if the input was
None.
"""
if response is None: return response
if not isinstance(response, (list, tuple)): response = [response]
return tuple(response) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.