content
stringlengths 39
14.9k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def _extractRGBFromHex(hexCode):
"""
Extract RGB information from an hexadecimal color code
Parameters:
hexCode (string): an hexadecimal color code
Returns:
A tuple containing Red, Green and Blue information
"""
hexCode = hexCode.lstrip('#') # Remove the '#' from the string
# Convert each byte into decimal, store it in a tuple and return
return tuple(int(hexCode[i:i+2], 16) for i in (0, 2, 4)) | e1d67b4f2004e5e2d4a646a3cc5dc49a1e8cd890 | 705,723 |
def get_user_partition_groups(course_key, user_partitions, user, partition_dict_key='name'):
"""
Collect group ID for each partition in this course for this user.
Arguments:
course_key (CourseKey)
user_partitions (list[UserPartition])
user (User)
partition_dict_key - i.e. 'id', 'name' depending on which partition attribute you want as a key.
Returns:
dict[partition_dict_key: Group]: Mapping from user partitions to the group to
which the user belongs in each partition. If the user isn't
in a group for a particular partition, then that partition's
ID will not be in the dict.
"""
partition_groups = {}
for partition in user_partitions:
group = partition.scheme.get_group_for_user(
course_key,
user,
partition,
)
if group is not None:
partition_groups[getattr(partition, partition_dict_key)] = group
return partition_groups | 3bb2f76f4a48ce0af745637810903b8086b2fc02 | 705,725 |
import collections
def factory_dict(value_factory, *args, **kwargs):
"""A dict whose values are computed by `value_factory` when a `__getitem__` key is missing.
Note that values retrieved by any other method will not be lazily computed; eg: via `get`.
:param value_factory:
:type value_factory: A function from dict key to value.
:param *args: Any positional args to pass through to `dict`.
:param **kwrags: Any kwargs to pass through to `dict`.
:rtype: dict
"""
class FactoryDict(collections.defaultdict):
@staticmethod
def __never_called():
raise AssertionError('The default factory should never be called since we override '
'__missing__.')
def __init__(self):
super().__init__(self.__never_called, *args, **kwargs)
def __missing__(self, key):
value = value_factory(key)
self[key] = value
return value
return FactoryDict() | f7d4898e62377958cf9d9c353ed12c8d381f042f | 705,727 |
def build_or_passthrough(model, obj, signal):
"""Builds the obj on signal, or returns the signal if obj is None."""
return signal if obj is None else model.build(obj, signal) | bee9c8557a89a458cf281b42f968fe588801ed46 | 705,728 |
import requests
import json
def warc_url(url):
"""
Search the WARC archived version of the URL
:returns: The WARC URL if found, else None
"""
query = "http://archive.org/wayback/available?url={}".format(url)
response = requests.get(query)
if not response:
raise RuntimeError()
data = json.loads(response.text)
snapshots = data["archived_snapshots"]
if not snapshots:
return None
return snapshots["closest"]["url"] | afc24876f72915ba07233d5fde667dd0ba964f5a | 705,729 |
def set_attrib(node, key, default):
"""
Parse XML key for a given node
If key does not exist, use default value
"""
return node.attrib[key] if key in node.attrib else default | 0e21b6b0e5a64e90ee856d4b413084a8c395b070 | 705,732 |
def is_order_exist(context, symbol, side) -> bool:
"""判断同方向订单是否已经存在
:param context:
:param symbol: 交易标的
:param side: 交易方向
:return: bool
"""
uo = context.unfinished_orders
if not uo:
return False
else:
for o in uo:
if o.symbol == symbol and o.side == side:
context.logger.info("同类型订单已存在:{} - {}".format(symbol, side))
return True
return False | 42363c8b3261e500a682b65608c27537b93bcfb1 | 705,733 |
import math
def gvisc(P, T, Z, grav):
"""Function to Calculate Gas Viscosity in cp"""
#P pressure, psia
#T temperature, °R
#Z gas compressibility factor
#grav gas specific gravity
M = 28.964 * grav
x = 3.448 + 986.4 / T + 0.01009 * M
Y = 2.447 - 0.2224 * x
rho = (1.4926 / 1000) * P * M / Z / T
K = (9.379 + 0.01607 * M) * T ** 1.5 / (209.2 + 19.26 * M + T)
return K * math.exp(x * rho ** Y) / 10000 | 5ff1ad63ef581cea0147348104416913c7b77e37 | 705,738 |
def is_base(base_pattern, str):
"""
base_pattern is a compiled python3 regex.
str is a string object.
return True if the string match the base_pattern or False if it is not.
"""
return base_pattern.match(str, 0, len(str)) | d0b0e3291fdbfad49698deffb9f57aefcabdce92 | 705,741 |
def predicate(line):
"""
Remove lines starting with ` # `
"""
if "#" in line:
return False
return True | ff7d67c1fd7273b149c5a2148963bf898d6a3591 | 705,752 |
def sort_list_by_list(L1,L2):
"""Sort a list by another list"""
return [x for (y,x) in sorted(zip(L2,L1), key=lambda pair: pair[0])] | 04b7c02121620be6d9344af6f56f1b8bfe75e9f3 | 705,755 |
def unpack_singleton(x):
"""Gets the first element if the iterable has only one value.
Otherwise return the iterable.
# Argument:
x: A list or tuple.
# Returns:
The same iterable or the first element.
"""
if len(x) == 1:
return x[0]
return x | cf551f242c8ea585c1f91eadbd19b8e5f73f0096 | 705,756 |
from typing import List
from typing import Dict
def make_car_dict(key: str, data: List[str]) -> Dict:
"""Organize car data for 106 A/B of the debtor
:param key: The section id
:param data: Content extract from car data section
:return: Organized data for automobile of debtor
"""
return {
"key": key,
"make": data[0],
"model": data[1],
"year": data[2],
"mileage": data[3],
"other_information": data[5],
"property_value": data[6],
"your_property_value": data[7],
} | 671cb2f82f15d14345e34e9823ea390d72cf040a | 705,757 |
import struct
def get_array_of_float(num, data):
"""Read array of floats
Parameters
----------
num : int
Number of values to be read (length of array)
data : str
4C binary data file
Returns
-------
str
Truncated 4C binary data file
list
List of floats
"""
length = 4
results = struct.unpack('f' * num, data[:num * length])
pos = num * length
new_data = data[pos:]
return new_data, list(results) | 92a0a4cc653046826b14c2cd376a42045c4fa641 | 705,762 |
def cver(verstr):
"""Converts a version string into a number"""
if verstr.startswith("b"):
return float(verstr[1:])-100000
return float(verstr) | 1ad119049b9149efe7df74f5ac269d3dfafad4e2 | 705,765 |
def _replace_oov(original_vocab, line):
"""Replace out-of-vocab words with "UNK".
This maintains compatibility with published results.
Args:
original_vocab: a set of strings (The standard vocabulary for the dataset)
line: a unicode string - a space-delimited sequence of words.
Returns:
a unicode string - a space-delimited sequence of words.
"""
return u" ".join(
[word if word in original_vocab else u"UNK" for word in line.split()]) | 2e2cb1464484806b79263a14fd32ed4d40d0c9ba | 705,768 |
def geq_indicate(var, indicator, var_max, thr):
"""Generates constraints that make indicator 1 iff var >= thr, else 0.
Parameters
----------
var : str
Variable on which thresholding is performed.
indicator : str
Identifier of the indicator variable.
var_max : int
An upper bound on var.
the : int
Comparison threshold.
Returns
-------
List[str]
A list holding the two constraints.
"""
lb = "- %s + %d %s <= 0" % (var, thr, indicator)
ub = "- %s + %d %s >= -%d" % (var, var_max - thr + 1, indicator, thr - 1)
return [lb, ub] | 319f18f5343b806b7108dd9c02ca5d647e132dab | 705,773 |
import torch
def compute_accuracy(logits, targets):
"""Compute the accuracy"""
with torch.no_grad():
_, predictions = torch.max(logits, dim=1)
accuracy = torch.mean(predictions.eq(targets).float())
return accuracy.item() | af15e4d077209ff6e790d6fdaa7642bb65ff8dbf | 705,779 |
def gm_put(state, b1, b2):
"""
If goal is ('pos',b1,b2) and we're holding b1,
Generate either a putdown or a stack subtask for b1.
b2 is b1's destination: either the table or another block.
"""
if b2 != 'hand' and state.pos[b1] == 'hand':
if b2 == 'table':
return [('a_putdown', b1)]
elif state.clear[b2]:
return [('a_stack', b1, b2)] | c9076ac552529c60b5460740c74b1602c42414f2 | 705,780 |
def get_child(parent, child_index):
"""
Get the child at the given index, or return None if it doesn't exist.
"""
if child_index < 0 or child_index >= len(parent.childNodes):
return None
return parent.childNodes[child_index] | 37f7752a4a77f3d750413e54659f907b5531848c | 705,782 |
def get_renaming(mappers, year):
"""Get original to final column namings."""
renamers = {}
for code, attr in mappers.items():
renamers[code] = attr['df_name']
return renamers | 33197b5c748b3ecc43783d5f1f3a3b5a071d3a4e | 705,784 |
async def clap(text, args):
""" Puts clap emojis between words. """
if args != []:
clap_str = args[0]
else:
clap_str = "👏"
words = text.split(" ")
clappy_text = f" {clap_str} ".join(words)
return clappy_text | 09865461e658213a2f048b89757b75b2a37c0602 | 705,785 |
def remove_extra_two_spaces(text: str) -> str:
"""Replaces two consecutive spaces with one wherever they occur in a text"""
return text.replace(" ", " ") | d8b9600d3b442216b1fbe85918f313fec8a5c9cb | 705,786 |
def load_utt_list(utt_list):
"""Load a list of utterances.
Args:
utt_list (str): path to a file containing a list of utterances
Returns:
List[str]: list of utterances
"""
with open(utt_list) as f:
utt_ids = f.readlines()
utt_ids = map(lambda utt_id: utt_id.strip(), utt_ids)
utt_ids = filter(lambda utt_id: len(utt_id) > 0, utt_ids)
return list(utt_ids) | 6a77e876b0cc959ac4151b328b718ae45522448b | 705,787 |
def compute_flow_for_supervised_loss(
feature_model,
flow_model,
batch,
training
):
"""Compute flow for an image batch.
Args:
feature_model: A model to compute features for flow.
flow_model: A model to compute flow.
batch: A tf.tensor of shape [b, seq, h, w, c] holding a batch of triplets.
training: bool that tells the model to use training or inference code.
Returns:
A tuple consisting of the images, the extracted features, the estimated
flows, and the upsampled refined flows.
"""
feature_dict = feature_model(batch[:, 0],
batch[:, 1],
training=training)
return flow_model(feature_dict, training=training) | a74f392c1d4e234fdb66d18e63d7c733ec6669a7 | 705,788 |
import itertools
def labels_to_intervals(labels_list):
"""
labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs
Args:
labels_list: list of labels of each frame
e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}]
Returns:
tags - set of time intervals where a tag occurs:
{ (label, start, end) }, a video from time 0 (inclusive) to time T (exclusive)
e.g. {('cat', 3, 9), ('dog', 5, 8), ('people', 0, 6)}
e.g. {('cat', 0, 1), ('cat', 2, 4), ('cat', 6, 8), ('dog', 0, 3),
('dog', 6, 8), ('people', 0, 2), ('people', 4, 6)}
"""
labels_dict = dict()
for frame, labels in enumerate(labels_list):
for label in labels:
if label in labels_dict:
labels_dict[label].add(frame)
else:
labels_dict[label] = {frame}
output = set()
for key, value in labels_dict.items():
frame_list = sorted(value)
for interval in [(t[0][1], t[-1][1]) for t in
(tuple(g[1]) for g in itertools.groupby(enumerate(frame_list), lambda x: x[0]-x[1]))]:
output.add((key, interval[0], interval[1]+1))
return output | 65b63ea3e6f097e9605e1c1ddb8dd434d7db9370 | 705,791 |
def get_wolfram_query_url(query):
"""Get Wolfram query URL."""
base_url = 'www.wolframalpha.com'
if not query:
return 'http://{0}'.format(base_url)
return 'http://{0}/input/?i={1}'.format(base_url, query) | 0122515f1a666cb897b53ae6bd975f65da072438 | 705,792 |
def compute_diff(old, new):
"""
Compute a diff that, when applied to object `old`, will give object
`new`. Do not modify `old` or `new`.
"""
if not isinstance(old, dict) or not isinstance(new, dict):
return new
diff = {}
for key, val in new.items():
if key not in old:
diff[key] = val
elif old[key] != val:
diff[key] = compute_diff(old[key], val)
for key in old:
if key not in new:
diff[key] = "$delete"
return diff | f6e7674faa2a60be17994fbd110f8e1d67eb9886 | 705,798 |
def default_rollout_step(policy, obs, step_num):
"""
The default rollout step function is the policy's compute_action function.
A rollout step function allows a developer to specify the behavior
that will occur at every step of the rollout--given a policy
and the last observation from the env--to decide
what action to take next. This usually involves the rollout's
policy and may perform learning. It also, may involve using, updating,
or saving learning related state including hyper-parameters
such as epsilon in epsilon greedy.
You can provide your own function with the same signature as this default
if you want to have a more complex behavior at each step of the rollout.
"""
return policy.compute_action(obs) | a6e9dff784e46b9a59ae34334a027b427e8d230a | 705,801 |
import glob
def find_file(filename):
"""
This helper function checks whether the file exists or not
"""
file_list = list(glob.glob("*.txt"))
if filename in file_list:
return True
else:
return False | 42895e66e258ba960c890f871be8c261aec02852 | 705,802 |
def true_fov(M, fov_e=50):
"""Calulates the True Field of View (FOV) of the telescope & eyepiece pair
Args:
fov_e (float): FOV of eyepiece; default 50 deg
M (float): Magnification of Telescope
Returns:
float: True Field of View (deg)
"""
return fov_e/M | 7735135d326f3000ac60274972263a8a71648033 | 705,808 |
def air_density(temp, patm, pw = 0):
"""
Calculates the density of dry air by means of the universal gas law as a
function of air temperature and atmospheric pressure.
m / V = [Pw / (Rv * T)] + [Pd / (Rd * T)]
where:
Pd: Patm - Pw
Rw: specific gas constant for water vapour [Rw = 461.495 MJ/kg/K]
Rv: specific gas constant for dry air [Rv = 287.058 MJ/kg/K]
T: air temperature [K]
m/V: density of air [kg/m³]
Parameters
----------
temp : float
Air temperature [K].
patm : float
Atmospheric pressure [Pa].
pw : float
Vapour pressure [Pa]. Default to 0 Pa (dry air).
Returns
-------
float
Air density [kg/m³].
"""
rd, rw = 287.058, 461.495 # specific gas constant for dry air and water vapour [J / (kg K)]
pd = patm - pw
return (pd / (rd * temp)) + (pw / (rw * temp)) | 1af7afbf562fec105566a2c934f83c73f0be1173 | 705,812 |
def getblock(lst, limit):
"""Return first limit entries from list lst and remove them from the list"""
r = lst[-limit:]
del lst[-limit:]
return r | 8d230dec59fe00375d92b6c6a8b51f3e6e2d9126 | 705,815 |
import functools
import warnings
def ignore_python_warnings(function):
"""
Decorator for ignoring *Python* warnings.
Parameters
----------
function : object
Function to decorate.
Returns
-------
object
Examples
--------
>>> @ignore_python_warnings
... def f():
... warnings.warn('This is an ignored warning!')
>>> f()
"""
@functools.wraps(function)
def wrapped(*args, **kwargs):
"""
Wrapped function.
"""
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return function(*args, **kwargs)
return wrapped | 438e54fe927f787783175faacf4eb9608fd27cf0 | 705,816 |
def get_requirements(extra=None):
"""
Load the requirements for the given extra from the appropriate
requirements-extra.txt, or the main requirements.txt if no extra is
specified.
"""
filename = f"requirements-{extra}.txt" if extra else "requirements.txt"
with open(filename) as fp:
# Parse out as one per line
return [l.strip() for l in fp.readlines() if l.strip()] | 7ce9e348357925b7ff165ebd8f13300d849ea0ee | 705,817 |
def _format_mojang_uuid(uuid):
"""
Formats a non-hyphenated UUID into a whitelist-compatible UUID
:param str uuid: uuid to format
:return str: formatted uuid
Example:
>>> _format_mojang_uuid('1449a8a244d940ebacf551b88ae95dee')
'1449a8a2-44d9-40eb-acf5-51b88ae95dee'
Must have 32 characters:
>>> _format_mojang_uuid('1')
Traceback (most recent call last):
...
ValueError: Expected UUID to have 32 characters
"""
if len(uuid) != 32:
raise ValueError('Expected UUID to have 32 characters')
return uuid[:8] + '-' + uuid[8:12] + '-' + uuid[12:16] + '-' + uuid[16:20] + '-' + uuid[20:] | 517071b28f1e747091e2a539cd5d0b8765bebeba | 705,818 |
def get_word(path):
""" extract word name from json path """
return path.split('.')[0] | e749bcdaaf65de0299d35cdf2a2264568ad5051b | 705,821 |
import json
def readJsonFile(filePath):
"""read data from json file
Args:
filePath (str): location of the json file
Returns:
variable: data read form the json file
"""
result = None
with open(filePath, 'r') as myfile:
result = json.load(myfile)
return result | cf15e358c52edcfb00d0ca5257cf2b5456c6e951 | 705,825 |
def get_namespace_leaf(namespace):
"""
From a provided namespace, return it's leaf.
>>> get_namespace_leaf('foo.bar')
'bar'
>>> get_namespace_leaf('foo')
'foo'
:param namespace:
:return:
"""
return namespace.rsplit(".", 1)[-1] | 0cb21247f9d1ce5fa4dd8d313142c4b09a92fd7a | 705,826 |
def sort(list_):
"""
This function is a selection sort algorithm. It will put a list in numerical order.
:param list_: a list
:return: a list ordered by numerial order.
"""
for minimum in range(0, len(list_)):
for c in range(minimum + 1, len(list_)):
if list_[c] < list_[minimum]:
temporary = list_[minimum]
list_[minimum] = list_[c]
list_[c] = temporary
return list_ | 99007e4b72a616ae73a20358afc94c76e0011d3e | 705,827 |
def __charge_to_sdf(charge):
"""Translate RDkit charge to the SDF language.
Args:
charge (int): Numerical atom charge.
Returns:
str: Str representation of a charge in the sdf language
"""
if charge == -3:
return "7"
elif charge == -2:
return "6"
elif charge == -1:
return "5"
elif charge == 0:
return "0"
elif charge == 1:
return "+1"
elif charge == 2:
return "+2"
elif charge == 3:
return "+4"
else:
return "0" | 1bfda86ee023e8c11991eaae2969b87a349b7f7e | 705,833 |
def get_volumetric_scene(self, data_key="total", isolvl=0.5, step_size=3, **kwargs):
"""Get the Scene object which contains a structure and a isosurface components
Args:
data_key (str, optional): Use the volumetric data from self.data[data_key]. Defaults to 'total'.
isolvl (float, optional): The cuoff for the isosurface to using the same units as VESTA so e/bhor
and kept grid size independent
step_size (int, optional): step_size parameter for marching_cubes_lewiner. Defaults to 3.
**kwargs: kwargs for the Structure.get_scene function
Returns:
[type]: [description]
"""
struct_scene = self.structure.get_scene(**kwargs)
iso_scene = self.get_isosurface_scene(
data_key=data_key,
isolvl=isolvl,
step_size=step_size,
origin=struct_scene.origin,
)
struct_scene.contents.append(iso_scene)
return struct_scene | 836fb5f3158ed5fe55a2975ce05eb21636584a95 | 705,838 |
def reduce_aet_if_dry(aet, wat_lev, fc):
""" Reduce actual evapotranspiration if the soil is dry. If the water level
in a cell is less than 0.7*fc, the rate of evapo-transpiration is
reduced by a factor. This factor is 1 when wat_lev = 0.7*fc and
decreases linearly to reach 0 when wat_lev = 0 i.e. where
wat_lev < 0.7*fc, apply a correction factor of
wat_lev/(0.7*fc) to the aet grid.
Args:
aet: "Raw" actual evapotranspiration grid.
wat_lev: Water level grid
fc: Soil field capacity grid.
Returns:
Array (modified AET grid with AET reduced where necessary).
"""
# Get a boolean array showing which cells need correcting
bool_array = wat_lev < (0.7*fc)
# Calculate a correction factor for all cells, but subtract 1 from answer
cor_facts_minus1 = (wat_lev / (0.7*fc)) - 1
# Multiplying bool_array by cor_facts_minus1 gives a grid with values of
# (cor_fact - 1) for cells which need correcting and zero otherwise. Add 1
# to this to get a grid of cor_facts and ones
cor_facts = (bool_array * cor_facts_minus1) + 1
return aet*cor_facts | 170462a23c3903a390b89963aa6ce21839e5d44b | 705,839 |
def get_python3_status(classifiers):
"""
Search through list of classifiers for a Python 3 classifier.
"""
status = False
for classifier in classifiers:
if classifier.find('Programming Language :: Python :: 3') == 0:
status = True
return status | b4bf347dc0bbf3e9a198baa8237f7820cbb86e0b | 705,845 |
def ratings_std(df):
"""calculate standard deviation of ratings from the given dataframe
parameters
----------
df (pandas dataframe): a dataframe cotanis all ratings
Returns
-------
standard deviation(float): standard deviation of ratings, keep 4 decimal
"""
std_value = df['ratings'].std()
std_value = round(std_value,4)
return std_value | b1bf00d25c0cee91632eef8248d5e53236dd4526 | 705,847 |
import hashlib
def _hash(file_name, hash_function=hashlib.sha256):
"""compute hash of file `file_name`"""
with open(file_name, 'rb') as file_:
return hash_function(file_.read()).hexdigest() | 463d692116fbb85db9f1a537cbcaa5d2d019ba05 | 705,848 |
def _get_perf_hint(hint, index: int, _default=None):
"""
Extracts a "performance hint" value -- specified as either a scalar or 2-tuple -- for
either the left or right Dataset in a merge.
Parameters
----------
hint : scalar or 2-tuple of scalars, optional
index : int
Indicates whether the hint value is being extracted for the left or right Dataset.
0 = left, 1 = right.
_default : optional
Optional default value, returned if `hint` is None.
Returns
-------
Any
The extracted performance hint value.
"""
if hint is None:
return _default
elif isinstance(hint, tuple):
return hint[index]
else:
return hint | d67a70d526934dedaa9f571970e27695404350f2 | 705,849 |
def sentences_from_doc(ttree_doc, language, selector):
"""Given a Treex document, return a list of sentences in the given language and selector."""
return [bundle.get_zone(language, selector).sentence for bundle in ttree_doc.bundles] | d9c09249171d5d778981fb98a8a7f53765518479 | 705,855 |
def file_to_list(filename):
"""
Read in a one-column txt file to a list
:param filename:
:return: A list where each line is an element
"""
with open(filename, 'r') as fin:
alist = [line.strip() for line in fin]
return alist | 33bee263b98c4ff85d10191fa2f5a0f095c6ae4b | 705,857 |
def gen_model_forms(form, model):
"""Creates a dict of forms. model_forms[0] is a blank form used for adding
new model objects. model_forms[m.pk] is an editing form pre-populated
the fields of m"""
model_forms = {0: form()}
for m in model.objects.all():
model_forms[m.pk] = form(instance=m)
return model_forms | 28bf3f007a7f8f971c18980c84a7841fd116898f | 705,858 |
def cleanFAAText(origText):
"""Take FAA text message and trim whitespace from end.
FAA text messages have all sorts of trailing whitespace
issues. We split the message into lines and remove all
right trailing whitespace. We then recombine them into
a uniform version with no trailing whitespace.
The final line will not have a newline character at the
end.
Args:
origText (str): Message text as it comes from the FAA.
Returns:
str: Cleaned up text as described above.
"""
lines = origText.split('\n')
numLines = len(lines)
# Remove empty line at end if present
if lines[-1] == '':
numLines -= 1
for i in range(0, numLines):
lines[i] = lines[i].rstrip()
newText = '\n'.join(lines).rstrip()
return newText | ea9882e24c60acaa35cae97f8e95acb48f5fd2a6 | 705,861 |
def _read_hyperparameters(idx, hist):
"""Read hyperparameters as a dictionary from the specified history dataset."""
return hist.iloc[idx, 2:].to_dict() | b2a036a739ec3e45c61289655714d9b59b2f5490 | 705,863 |
def disassemble_pretty(self, addr=None, insns=1,
arch=None, mode=None):
"""
Wrapper around disassemble to return disassembled instructions as string.
"""
ret = ""
disas = self.disassemble(addr, insns, arch, mode)
for i in disas:
ret += "0x%x:\t%s\t%s\n" % (i.address, i.mnemonic, i.op_str)
return ret | 39bddf246b880decbc84015ef20c5664f88d917e | 705,870 |
def IOU(a_wh, b_wh):
"""
Intersection over Union
Args:
a_wh: (width, height) of box A
b_wh: (width, height) of box B
Returns float.
"""
aw, ah = a_wh
bw, bh = b_wh
I = min(aw, bw) * min(ah, bh)
area_a = aw * ah
area_b = bw * bh
U = area_a + area_b - I
return I / U | 92580147eac219d77e6c8a38875c5ee809783790 | 705,872 |
import re
def check_pre_release(tag_name):
"""
Check the given tag to determine if it is a release tag, that is, whether it
is of the form rX.Y.Z. Tags that do not match (e.g., because they are
suffixed with someting like -beta# or -rc#) are considered pre-release tags.
Note that this assumes that the tag name has been validated to ensure that
it starts with something like rX.Y.Z and nothing else.
"""
release_re = re.compile('^r[0-9]+\\.[0-9]+\\.[0-9]+')
return False if release_re.match(tag_name) else True | 8e24a0a61bfa6fe84e936f004b4228467d724616 | 705,875 |
def _get_target_connection_details(target_connection_string):
"""
Returns a tuple with the raw connection details for the target machine extracted from the connection string provided
in the application arguments. It is a specialized parser of that string.
:param target_connection_string: the connection string provided in the arguments for the application.
:return: A tuple in the form of (user, password, host, port) if a password is present in the connection string or
(user, host, port) if a password is not present
"""
password = None
connection_string_format_error = 'Invalid connection string provided. Expected: user[/password]@host[:port]'
if '@' not in target_connection_string:
raise TypeError(connection_string_format_error)
connection_string_parts = target_connection_string.split('@')
if len(connection_string_parts) != 2:
raise TypeError(connection_string_parts)
authentication_part = connection_string_parts[0]
target_part = connection_string_parts[1]
if '/' in authentication_part:
auth_parts = authentication_part.split('/')
if len(auth_parts) != 2:
raise TypeError(connection_string_format_error)
user, password = auth_parts
else:
user = authentication_part
if ':' in target_part:
conn_parts = target_part.split(':')
if len(conn_parts) != 2:
raise TypeError(connection_string_format_error)
host, port = conn_parts
try:
port = int(port)
except ValueError:
raise TypeError(connection_string_format_error)
else:
host = target_part
port = 22
if not len(user) or not len(host):
raise TypeError(connection_string_format_error)
if password:
return user, password, host, int(port)
else:
return user, host, int(port) | 5e6ee870c0e196f54950f26ee6e551476688dce9 | 705,876 |
import codecs
def read(filepath):
"""Read file content from provided filepath."""
with codecs.open(filepath, encoding='utf-8') as f:
return f.read() | bff53fbb9b1ebe85c6a1fa690d28d6b6bec71f84 | 705,878 |
import inspect
def is_bound_builtin_method(meth):
"""Helper returning True if meth is a bound built-in method"""
return (inspect.isbuiltin(meth)
and getattr(meth, '__self__', None) is not None
and getattr(meth.__self__, '__class__', None)) | a7a45f0f519119d795e91723657a1333eb6714e4 | 705,879 |
def vocabulary_size(tokens):
"""Returns the vocabulary size count defined as the number of alphabetic
characters as defined by the Python str.isalpha method. This is a
case-sensitive count. `tokens` is a list of token strings."""
vocab_list = set(token for token in tokens if token.isalpha())
return len(vocab_list) | 5e26e1be98a3e82737277458758f0fd65a64fe8f | 705,882 |
def get_transit_boundary_indices(time, transit_size):
""" Determines transit boundaries from sorted time of transit cut out
:param time (1D np.array) sorted times of transit cut out
:param transit_size (float) size of the transit crop window in days
:returns tuple:
[0] list of transit start indices (int)
[1] list of sequence lengths (int) of each transit
"""
sequence_lengths = []
transit_start_indices = [0]
for i, t in enumerate(time):
if t - time[transit_start_indices[-1]] > transit_size:
sequence_lengths.append(i - transit_start_indices[-1])
transit_start_indices.append(i)
# last length is from last transit start til the end of the array
sequence_lengths.append(len(time) - transit_start_indices[-1])
return transit_start_indices, sequence_lengths | cd3775d72690eb4539e0434b0ac7f715d14374a6 | 705,883 |
def _computePolyVal(poly, value):
"""
Evaluates a polynomial at a specific value.
:param poly: a list of polynomial coefficients, (first item = highest degree to last item = constant term).
:param value: number used to evaluate poly
:return: a number, the evaluation of poly with value
"""
#return numpy.polyval(poly, value)
acc = 0
for c in poly:
acc = acc * value + c
return acc | 0377ba0757439409824b89b207485a99f804cb41 | 705,885 |
def odd_desc(count):
"""
Replace ___ with a single call to range to return a list of descending odd numbers ending with 1
For e.g if count = 2, return a list of 2 odds [3,1]. See the test below if it is not clear
"""
return list(reversed(range(1,count*2,2))) | 2f90095c5b25f8ac33f3bb86d3f46e67932bc78a | 705,886 |
def outside_range(number, min_range, max_range):
"""
Returns True if `number` is between `min_range` and `max_range` exclusive.
"""
return number < min_range or number > max_range | dc3889fbabb74db38b8558537413ebc5bc613d05 | 705,887 |
from typing import Any
def device_traits() -> dict[str, Any]:
"""Fixture that sets default traits used for devices."""
return {"sdm.devices.traits.Info": {"customName": "My Sensor"}} | 1ccaeac4a716706915654d24270c24dac0210977 | 705,889 |
def get_parser_args(args=None):
"""
Transform args (``None``, ``str``, ``list``, ``dict``) to parser-compatible (list of strings) args.
Parameters
----------
args : string, list, dict, default=None
Arguments. If dict, '--' are added in front and there should not be positional arguments.
Returns
-------
args : None, list of strings.
Parser arguments.
Notes
-----
All non-strings are converted to strings with :func:`str`.
"""
if isinstance(args,str):
return args.split()
if isinstance(args,list):
return list(map(str,args))
if isinstance(args,dict):
toret = []
for key in args:
toret += ['--%s' % key]
if isinstance(args[key],list):
toret += [str(arg) for arg in args[key]]
else:
val = str(args[key])
if val: toret += [val]
return toret
return args | 41b607a6ebf12526efcd38469192b398419327bf | 705,894 |
def set_name_line(hole_lines, name):
"""Define the label of each line of the hole
Parameters
----------
hole_lines: list
a list of line object of the slot
name: str
the name to give to the line
Returns
-------
hole_lines: list
List of line object with label
"""
for ii in range(len(hole_lines)):
hole_lines[ii].label = name + "_" + str(ii)
return hole_lines | a57667f269dac62d39fa127b2a4bcd438a8a989b | 705,895 |
def is_reserved(word):
"""
Determines if word is reserved
:param word: String representing the variable
:return: True if word is reserved and False otherwise
"""
lorw = ['define','define-struct']
return word in lorw | 0b0e3706bcafe36fc52e6384617223078a141fb2 | 705,901 |
import csv
def read_csv_from_file(file):
"""
Reads the CSV data from the open file handle and returns a list of dicts.
Assumes the CSV data includes a header row and uses that header row as
fieldnames in the dict. The following fields are required and are
case-sensitive:
- ``artist``
- ``song``
- ``submitter``
- ``seed``
Other fields are ultimately preserved untouched in the output CSV.
If the CSV doesn't have a header row, uses the following hardcoded list:
- ``order``
- ``seed``
- ``submitter``
- ``year``
- ``song``
- ``artist``
- ``link``
If a tab character is present in the first row, assumes the data is
tab-delimited, otherwise assumes comma-delimited.
:returns: All parsed data from the already-opened CSV file given, as a list
of dicts as generated by `csv.DictReader`
"""
data = list(file)
delimiter = "\t" if "\t" in data[0] else ","
# Look for a header row
reader = csv.reader([data[0]], delimiter=delimiter)
row = next(reader)
for col in row:
try:
int(col)
# Found an integer, no headers present
headers = ["order", "seed", "submitter", "year", "song", "artist", "link"]
break
except ValueError:
pass
else:
# Unable to find an integer here, must be a header row
# Pop the header row off the data list and create a new reader just to
# parse that row
data.pop(0)
headers = row
return list(csv.DictReader(data, fieldnames=headers, delimiter=delimiter)) | 89cfce0be6270076230051a6e852d1add3f4dcaf | 705,904 |
import hashlib
import six
def make_hashkey(seed):
"""
Generate a string key by hashing
"""
h = hashlib.md5()
h.update(six.b(str(seed)))
return h.hexdigest() | 38d088005cb93fc0865933bbb706be171e72503a | 705,905 |
def fix(x):
"""
Replaces spaces with tabs, removes spurious newlines, and lstrip()s each
line. Makes it really easy to create BED files on the fly for testing and
checking.
"""
s = ""
for i in x.splitlines():
i = i.lstrip()
if i.endswith('\t'):
add_tab = '\t'
else:
add_tab = ''
if len(i) == 0:
continue
i = i.split()
i = '\t'.join(i) + add_tab + '\n'
s += i
return s | ecd3a4d7f470feae1b697025c8fbf264d5c6b149 | 705,906 |
def get_ngram_universe(sequence, n):
"""
Computes the universe of possible ngrams given a sequence. Where n is equal to the length of the sequence, the resulting number represents the sequence universe.
Example
--------
>>> sequence = [2,1,1,4,2,2,3,4,2,1,1]
>>> ps.get_ngram_universe(sequence, 3)
64
"""
# if recurrance is possible, the universe is given by k^t (SSA pg 68)
k = len(set(sequence))
if k > 10 and n > 10:
return 'really big'
return k**n | 3dbfe1822fdefb3e683b3f2b36926b4bb066468f | 705,907 |
def cartToRadiusSq(cartX, cartY):
"""Convert Cartesian coordinates into their corresponding radius squared."""
return cartX**2 + cartY**2 | 3fb79d2c056f06c2fbf3efc14e08a36421782dbd | 705,909 |
def unique_entity_id(entity):
"""
:param entity: django model
:return: unique token combining the model type and id for use in HTML
"""
return "%s-%s" % (type(entity).__name__, entity.id) | c58daf9a115c9840707ff5e807efadad36a86ce8 | 705,910 |
def variable_to_json(var):
"""Converts a Variable object to dict/json struct"""
o = {}
o['x'] = var.x
o['y'] = var.y
o['name'] = var.name
return o | 86497a7915e4825e6e2cbcfb110c9bc4c229efed | 705,913 |
def getOrElseUpdate(dictionary, key, opr):
"""If given key is already in the dictionary, returns associated value.
Otherwise compute the value with opr, update the dictionary and return it.
None dictionary are ignored.
>>> d = dict()
>>> getOrElseUpdate(d, 1, lambda _: _ + 1)
2
>>> print(d)
{1: 2}
@type dictionary: dictionary of A => B
@param dictionary: the dictionary
@type key: A
@param key: the key
@type opr: function of A => B
@param opr: the function to compute new value from keys
@rtype: B
@return: the value associated with the key
"""
if dictionary is None:
return opr(key)
else:
if key not in dictionary:
dictionary[key] = opr(key)
return dictionary[key] | 95454d7ca34d6ae243fda4e70338cf3d7584b827 | 705,915 |
def filt_all(list_, func):
"""Like filter but reverse arguments and returns list"""
return [i for i in list_ if func(i)] | 72010b483cab3ae95d49b55ca6a70b0838b0a34d | 705,920 |
def _rav_setval_ ( self , value ) :
"""Assign the valeu for the variable
>>> var = ...
>>> var.value = 10
"""
value = float ( value )
self.setVal ( value )
return self.getVal() | 80ad7ddec68d5c97f72ed63dd6ba4a1101de99cb | 705,921 |
def bb_to_plt_plot(x, y, w, h):
""" Converts a bounding box to parameters
for a plt.plot([..], [..])
for actual plotting with pyplot
"""
X = [x, x, x+w, x+w, x]
Y = [y, y+h, y+h, y, y]
return X, Y | 10ea3d381969b7d30defdfdbbac0a8d58d06d4d4 | 705,924 |
from typing import Counter
def count_items(column_list:list):
"""
Contar os tipos (valores) e a quantidade de items de uma lista informada
args:
column_list (list): Lista de dados de diferentes tipos de valores
return: Retorna dois valores, uma lista de tipos (list) e o total de itens de cada tipo (list)
"""
counter = Counter(column_list)
item_types = list(counter.keys())
count_items = list(counter.values())
return item_types, count_items | 06cf25aed4d0de17fa8fb11303c9284355669cf5 | 705,925 |
def to_graph(grid):
"""
Build adjacency list representation of graph
Land cells in grid are connected if they are vertically or horizontally adjacent
"""
adj_list = {}
n_rows = len(grid)
n_cols = len(grid[0])
land_val = "1"
for i in range(n_rows):
for j in range(n_cols):
if grid[i][j] == land_val:
adj_list[(i,j)] = []
if i > 0 and grid[i-1][j] == land_val:
adj_list[(i,j)].append((i-1,j))
if i < n_rows-1 and grid[i+1][j] == land_val:
adj_list[(i,j)].append((i+1,j))
if j > 0 and grid[i][j-1] == land_val:
adj_list[(i,j)].append((i,j-1))
if j < n_cols-1 and grid[i][j+1] == land_val:
adj_list[(i,j)].append((i,j+1))
return adj_list | ebdd0406b123a636a9d380391ef4c13220e2dabd | 705,926 |
import re
def _remove_comments_inline(text):
"""Removes the comments from the string 'text'."""
if 'auto-ignore' in text:
return text
if text.lstrip(' ').lstrip('\t').startswith('%'):
return ''
match = re.search(r'(?<!\\)%', text)
if match:
return text[:match.end()] + '\n'
else:
return text | 463e29e1237a88e91c13a58ffea1b2ccdafd4a1d | 705,929 |
import fcntl
def has_flock(fd):
"""
Checks if fd has flock over it
True if it is, False otherwise
:param fd:
:return:
:rtype: bool
"""
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return True
else:
return False | 9ae997d06a12d73a659958bc2f0467ebdf0142b7 | 705,937 |
import json
def assertDict(s):
""" Assert that the input is a dictionary. """
if isinstance(s,str):
try:
s = json.loads(s)
except:
raise AssertionError('String "{}" cannot be json-decoded.'.format(s))
if not isinstance(s,dict): raise AssertionError('Variable "{}" is not a dictionary.'.format(s))
return s | 302defb4e1eecc9a6171cda0401947e3251be585 | 705,942 |
import ast
from typing import Tuple
from typing import List
from typing import Any
def get_function_args(node: ast.FunctionDef) -> Tuple[List[Any], List[Any]]:
"""
This functon will process function definition and will extract all
arguments used by a given function and return all optional and non-optional
args used by the function.
Args:
node: Function node containing function that needs to be analyzed
Returns:
(non_optional_args, optional_args): named function args
"""
assert (
type(node) == ast.FunctionDef
), "Incorrect node type. Expected ast.FunctionDef, got {}".format(type(node))
total_args = len(node.args.args)
default_args = len(node.args.defaults)
optional_args = []
non_optional_args = []
# Handle positional args
for i in range(total_args):
if i + default_args < total_args:
non_optional_args.append(node.args.args[i].arg)
else:
optional_args.append(node.args.args[i].arg)
# Handle named args
for arg in node.args.kwonlyargs:
optional_args.append(arg.arg)
return non_optional_args, optional_args | a4fe9dccedd5684050a7d5e7949e384dd4021035 | 705,943 |
def index_containing_substring(list_str, substring):
"""For a given list of strings finds the index of the element that contains the
substring.
Parameters
----------
list_str: list of strings
substring: substring
Returns
-------
index: containing the substring or -1
"""
for i, s in enumerate(list_str):
if substring in s:
return i
return -1 | 2816899bc56f6b2c305192b23685d3e803b420df | 705,945 |
def calculate_n_inputs(inputs, config_dict):
"""
Calculate the number of inputs for a particular model.
"""
input_size = 0
for input_name in inputs:
if input_name == 'action':
input_size += config_dict['prior_args']['n_variables']
elif input_name == 'state':
input_size += config_dict['misc_args']['state_size']
elif input_name == 'reward':
input_size += 1
elif input_name in ['params', 'grads']:
if config_dict['approx_post_args']['constant_scale']:
input_size += config_dict['prior_args']['n_variables']
else:
input_size += 2 * config_dict['prior_args']['n_variables']
return input_size | 78d750ff4744d872d696dcb454933c868b0ba41e | 705,950 |
def all_not_none(*args):
"""Shorthand function for ``all(x is not None for x in args)``. Returns
True if all `*args` are not None, otherwise False."""
return all(x is not None for x in args) | 2d063f39e253a78b28be6857df08d8f386d8eb4a | 705,954 |
import logging
import requests
def scrape_page(url):
"""
scrape page by url and return its html
:param url: page url
:return: html of page
"""
logging.info('scraping %s...', url)
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
logging.error('get invalid status code %s while scraping %s', response.status_code, url)
except requests.RequestException:
logging.error('error occurred while scraping %s', url, exc_info=True) | a09eb79ce6abe25e4eb740dcfeb7a4debfca0b88 | 705,959 |
def get_all_applications(user, timeslot):
"""
Get a users applications for this timeslot
:param user: user to get applications for
:param timeslot: timeslot to get the applications.
:return:
"""
return user.applications.filter(Proposal__TimeSlot=timeslot) | 40aec747174fa4a3ce81fe2a3a5eee599c81643a | 705,961 |
import importlib
def get_dataset(cfg, designation):
"""
Return a Dataset for the given designation ('train', 'valid', 'test').
"""
dataset = importlib.import_module('.' + cfg['dataset'], __package__)
return dataset.create(cfg, designation) | 3f872d6407110cf735968ad6d4939b40fec9167d | 705,962 |
def RestrictDictValues( aDict, restrictSet ):
"""Return a dict which has the mappings from the original dict only for values in the given set"""
return dict( item for item in aDict.items() if item[1] in restrictSet ) | 4333c40a38ad3bce326f94c27b4ffd7dc24ae19c | 705,963 |
def abs_length_diff(trg, pred):
"""Computes absolute length difference
between a target sequence and a predicted sequence
Args:
- trg (str): reference
- pred (str): generated output
Returns:
- absolute length difference (int)
"""
trg_length = len(trg.split(' '))
pred_length = len(pred.split(' '))
return abs(trg_length - pred_length) | b5baf53609b65aa1ef3b1f142e965fa0606b3136 | 705,966 |
import re
def parse_msig_storage(storage: str):
"""Parse the storage of a multisig contract to get its counter (as a
number), threshold (as a number), and the keys of the signers (as
Micheline sequence in a string)."""
# put everything on a single line
storage = ' '.join(storage.split('\n'))
storage_regexp = r'Pair\s+?([0-9]+)\s+?([0-9]+)\s+?(.*)\s*'
match = re.search(storage_regexp, storage)
assert match is not None
return {
'counter': int(match[1]),
'threshold': int(match[2]),
'keys': match[3],
} | 6e04091721177cdd3d40b86717eb86ebbb92a8ff | 705,967 |
from functools import reduce
from operator import add
def assemble_docstring(parsed, sig=None):
"""
Assemble a docstring from an OrderedDict as returned by
:meth:`nd.utils.parse_docstring()`
Parameters
----------
parsed : OrderedDict
A parsed docstring as obtained by ``nd.utils.parse_docstring()``.
sig : function signature, optional
If provided, the parameters in the docstring will be ordered according
to the parameter order in the function signature.
Returns
-------
str
The assembled docstring.
"""
parsed = parsed.copy()
indent = parsed.pop('indent')
pad = ' '*indent
# Sort 'Parameters' section according to signature
if sig is not None and 'Parameters' in parsed:
order = tuple(sig.parameters.keys())
def sort_index(p):
key = p[0].split(':')[0].strip(' *')
if key == '':
return 9999
return order.index(key)
parsed['Parameters'] = sorted(parsed['Parameters'], key=sort_index)
d = []
for k, v in parsed.items():
if isinstance(v[0], list):
flat_v = reduce(add, v)
else:
flat_v = v
if k is not None:
d.extend(['', pad + k, pad + '-'*len(k)])
d.extend([(pad + l).rstrip() for l in flat_v])
return '\n'.join(d) | 90553c468a2b113d3f26720128e384b0444d5c93 | 705,968 |
import torch
def log_cumsum(probs, dim=1, eps=1e-8):
"""Calculate log of inclusive cumsum."""
return torch.log(torch.cumsum(probs, dim=dim) + eps) | 7f1ab77fd9909037c7b89600c531173dab80c11e | 705,970 |
def race_from_string(str):
"""Convert race to one of ['white', 'black', None]."""
race_dict = {
"White/Caucasian": 'white',
"Black/African American": 'black',
"Unknown": None,
"": None
}
return race_dict.get(str, 'other') | 1d38469537c3f5f6a4a42712f5ec1dbd26a471bd | 705,971 |
from typing import List
def normalize(value: str) -> str:
"""Normalize a string by removing '-' and capitalizing the following character"""
char_list: List[str] = list(value)
length: int = len(char_list)
for i in range(1, length):
if char_list[i - 1] in ['-']:
char_list[i] = char_list[i].upper()
return ''.join(char_list).replace('-', '') | 52c1c8b5e950347cf63ed15d1efde47046b07873 | 705,973 |
def binary_str(num):
""" Return a binary string representation from the posive interger 'num'
:type num: int
:return:
Examples:
>>> binary_str(2)
'10'
>>> binary_str(5)
'101'
"""
# Store mod 2 operations results as '0' and '1'
bnum = ''
while num > 0:
bnum = str(num & 0x1) + bnum
num = num >> 1
return bnum | dde400323fccb9370c67197f555d9c41c40084a6 | 705,979 |
def compute_phot_error(flux_variance, bg_phot, bg_method, ap_area, epadu=1.0):
"""Computes the flux errors using the DAOPHOT style computation
Parameters
----------
flux_variance : array
flux values
bg_phot : array
background brightness values.
bg_method : string
background method
ap_area : array
the area of the aperture in square pixels
epadu : float
(optional) Gain in electrons per adu (only use if image units aren't e-). Default value is 1.0
Returns
-------
flux_error : array
an array of flux errors
"""
bg_variance_terms = (ap_area * bg_phot['aperture_std'] ** 2.) * (1. + ap_area/bg_phot['aperture_area'])
variance = flux_variance / epadu + bg_variance_terms
flux_error = variance ** .5
return flux_error | 4470277ebc41cce0e2c8c41c2f03e3466473d749 | 705,980 |
def weighted_sequence_identity(a, b, weights, gaps='y'):
"""Compute the sequence identity between two sequences, different positions differently
The definition of sequence_identity is ambyguous as it depends on how gaps are treated,
here defined by the *gaps* argument. For details and examples, see
`this page <https://pyaln.readthedocs.io/en/latest/tutorial.html#sequence-identity>`_
Parameters
----------
a : str
first sequence, with gaps encoded as "-"
b : str
second sequence, with gaps encoded as "-"
weights : list of float
list of weights. Any iterable with the same length as the two input sequences
(including gaps) is accepted. The final score is divided by their sum
(except for positions not considered, as defined by the gaps argument).
gaps : str
defines how to take into account gaps when comparing sequences pairwise. Possible values:
- 'y' : gaps are considered and considered mismatches. Positions that are gaps in both sequences are ignored.
- 'n' : gaps are not considered. Positions that are gaps in either sequences compared are ignored.
- 't' : terminal gaps are trimmed. Terminal gap positions in either sequences are ignored, others are considered as in 'y'.
- 'a' : gaps are considered as any other character; even gap-to-gap matches are scored as identities.
Returns
-------
float
sequence identity between the two sequences
Examples
--------
>>> weighted_sequence_identity('ATGCA',
... 'ATGCC', weights=[1, 1, 1, 1, 6])
0.4
>>> weighted_sequence_identity('ATGCA',
... 'ATGCC', weights=[1, 1, 1, 1, 1])
0.8
Note
----
To compute sequence identity efficiently among many sequences, use :func:`~pyaln.Alignment.score_similarity` instead.
See also
--------
pyaln.Alignment.score_similarity, weighted_sequence_identity
"""
if len(a)!=len(b):
raise IndexError('sequence_identity ERROR sequences do not have the same length')
if len(weights)!=len(a):
raise IndexError('sequence_identity ERROR weights must be the same length as sequences')
if gaps=='y':
pos_to_remove=[i for i in range(len(a)) if a[i]=='-' and b[i]=='-' ]
elif gaps=='n':
pos_to_remove=[i for i in range(len(a)) if a[i]=='-' or b[i]=='-' ]
elif gaps=='t':
pos_to_remove=[i for i in range(len(a)) if a[i]=='-' and b[i]=='-' ]
for s in [a,b]:
for i,c in enumerate(s):
if c=='-':
pos_to_remove.append(i)
else:
break
for i, c in reversed(list(enumerate(s))):
if c=='-':
pos_to_remove.append(i)
else:
break
elif gaps=='a':
total_weight= sum( weights )
count_identical=sum([int(ca == b[i])*weights[i] for i,ca in enumerate(a)])
return count_identical/total_weight if total_weight else 0.0
else:
raise Exception('sequence_identity ERROR gaps argument must be one of {a, y, n, t}')
exclude_pos=set(pos_to_remove)
actual_weights=[w for i,w in enumerate(weights) if not i in exclude_pos]
total_weight= sum( actual_weights )
count_identical=sum([int(ca == b[i] and ca!='-' )*weights[i] for i,ca in enumerate(a) if not i in exclude_pos])
return count_identical/( total_weight ) if total_weight else 0.0 | 8face090454e984d0d4b9ea5fe78b6600a6e6b03 | 705,983 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.