content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_pairs(cluster):
"""Gets all contiguous pairs of homology groups in a cluster."""
pairs = []
for locus in cluster.loci:
total = len(locus.genes) - 1
pairs.extend(
(gene._group for gene in locus.genes[i:i+2])
for i in range(total)
)
return pairs | d1278f8ee2a7b18ec41098f8154882cefa54baef | 685,529 |
def non_negative_int(s: str) -> int:
"""
Return integer from `s`, if `s` represents non-negative integer,
otherwise raise ValueError.
"""
try:
n = int(s)
if n < 0:
raise ValueError
return n
except ValueError:
raise ValueError('Must be non-negative inte... | 5df9c1b340afc4251a288cded079ff4c15b05730 | 685,530 |
import torch
from typing import Sequence
def crop(data: torch.Tensor, corner: Sequence[int], size: Sequence[int], grid_crop: bool = False):
"""
Extract crop from last dimensions of data
Parameters
----------
data: torch.Tensor
input tensor [... , spatial dims] spatial dims can be arbitrar... | d917400cf078659c7ae0d83f9e5a6974f0d48fd0 | 685,531 |
import torch
def focal_prob(attn, batch_size, queryL, sourceL):
"""
consider the confidence g(x) for each fragment as the sqrt
of their similarity probability to the query fragment
sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj
attn: (batch, queryL, sourceL)
"""
# -> (batch, qu... | 7abc67493fdb2b47492efffb43ca14e3eb02a4e9 | 685,532 |
def get_page_by_uid(uid, pages):
"""
Get a page by its UID
Args:
uid (str): The page UID to search for
pages (list of dict): list of pages
Returns:
dict: The matching page if any
"""
page_info = [page for page in pages if page["uid"] == uid]
if page_info:
r... | d343ca403bd15972afaa634668165f1c1ed88b1f | 685,533 |
def get_vector16():
"""
Return the vector with ID 16.
"""
return [
0.5714286,
0.5000000,
0.4285714,
] | 0c5a20de9ee9de965be5e0a8cb4465d0b8cb2474 | 685,534 |
def union_contiguous_intervals(arr):
""" Union contiguous intervals.
arr = list of [(st,ed),...]
"""
arr = sorted(arr)
def _gen():
st0,ed0 = arr[0]
for st1,ed1 in arr[1:]:
if ed0 < st1: # ed1<st0 new interval
yield [st0,ed0]
st0,ed0 = st1,e... | 05371de6b55c80c51dbb2ba95c30a76b07a8d7ab | 685,535 |
def get_all_objects_filter_by_date(csl, user, start_date, end_date):
""" 获取用户在时间范围内 cls 的数据
args:
user: 访问用户 User
csl: 需要查找的表 例如,Tweet 或者 TweetMention
retrun:
用户在时间范围内 cls 的全部数据
"""
return csl.query.filter(
csl.user == user,
csl.created_at >= start_date,
... | 5d2fa56780f26593232ceeb368113f1da50a992d | 685,536 |
from typing import List
from typing import Tuple
def compare_triplets(a: List[int], b: List[int]) -> Tuple[int, ...]:
"""
>>> compare_triplets((5, 6, 7), (3, 6, 10))
(1, 1)
"""
zip_ab = tuple(zip(a, b))
# alice, bob = 0, 0
# for x, y in zip_ab:
# if x > y:
# alice += 1
... | 1ce3d19c0eace387ed96d2f282e7144b4e225510 | 685,537 |
def updates_to_the_transition_matrix(state1, state2):
"""
produces an update to the transition matrix due to transition from `state1` to `state2`
Returns list of tuples
"""
update = [[float(el1[0]), float(el2[0]), el1[1] * el2[1]]
for el1 in state1 for el2 in state2]
return upda... | ecbac20ef5565e253196ba72f4f93cdbeaa6f03d | 685,538 |
def valid_passphrase(passphrase: str) -> bool:
"""Find if there are no repeated words in this passphrase."""
all_words = passphrase.split()
return len(all_words) == len(set(all_words)) | ba7a2bbe6262c1bfc3ccee8547c1630860ba0816 | 685,540 |
def _mip__expt(self,tierMax=None,mips=None):
"""Return set of experiment item identifiers for experiments linked to this mip:
tierMax: maximum experiment tier: if set, only return experiments with tier <= tierMax;
mips: set of mip uid values: if set, return experiments for specified set."""
... | 1a013c40110c9c4e8167657a5eda4d118f953092 | 685,541 |
import os
def getAllFiles(rootDir):
"""Traverse a directory tree and find all the files.
Args:
rootDir: The directory to traverse
Returns:
A list of full filenames for the files
"""
fileList = []
for (dirPath, dirNames, fileNames) in os.walk(rootDir):
for filena... | cd68fb2f90b206c86ee18c55db87d2bbe565aa43 | 685,542 |
def immediate_reward(state_node):
"""
Estimate the reward with the immediate return of that state.
:param state_node:
:return:
"""
return state_node.state.reward(state_node.parent.parent.state,
state_node.parent.action) | d9b39ea76b3a7cf49166d201f9646fc8d4acc254 | 685,543 |
def update_waf_managed_rule_set(cmd, instance, rule_set_type, rule_set_version, rule_group_name=None, rules=None):
"""
Update(Override) existing rule set of a WAF policy managed rules.
"""
ManagedRuleSet, ManagedRuleGroupOverride, ManagedRuleOverride = \
cmd.get_models('ManagedRuleSet', 'Managed... | 750bb043313672339f17be0d10ebd871d6d32064 | 685,544 |
import time
def restart_on_failure(func):
""" Decorator to restart function if it failed or an exc raised"""
def wrapped(*args, **kwargs):
while True:
try:
func(*args, **kwargs)
except Exception as e:
print(e)
time.sleep(1)
retu... | 5995beb945a396ffb5262e331a36e4b2efdf00ce | 685,546 |
def is_client_error(code):
"""Return that the client seems to have erred."""
return 400 <= code <= 499 | 178d642f9c694fb5a488320626dddb32694ef45c | 685,547 |
def cmd_resolve_strings(lresolver, resolve_strings):
"""Handle resolve-string command."""
for string in resolve_strings:
print(lresolver.resolve_string(string))
return 0 | 6770bef9988334fedab1d5dcf5999372fdc44eb0 | 685,548 |
def get_dims(shape, max_channels=10):
"""Get the number of dimensions and channels from the shape of an array.
The number of dimensions is assumed to be the length of the shape, as long as the shape of the last dimension is
inferior or equal to max_channels (default 3).
:param shape: shape of an array. ... | bcffcc217226291963def5c8dba89ef4ebfa08fd | 685,549 |
def compare_broken_content(broken_content_prod, broken_content_dev):
"""Compare output between 2 content_validation runs"""
unique_ids_prod = set([i["unique_id"] for i in broken_content_prod])
unique_ids_dev = set([i["unique_id"] for i in broken_content_dev])
new_broken_content_ids = unique_ids_dev.diff... | 4f76c8b4feddba24cf62c567537a1b35250d535b | 685,550 |
from typing import List
def get_shrink_board(
board: List[List[str]],
is_flatten: bool
) -> List:
"""
Get only the building placeholder.
(Note: In other word, remove the row and column header.)
Parameters
----------
board: List[List[str]]
2D array conta... | 9428bca63e87d02f45e88f88bdb5b2baa9c34929 | 685,551 |
def scoring_from_max(ts):
"""
provide max of scoring from info
"""
return ts.groupby(level=["opp", "pos"]).max().unstack() | c09e5d81761da89bdbe37df8b12bb349d26e4030 | 685,552 |
def model_action(model, X_train, y_train, X_test,
sample_weight=None, action=None,):
"""choose fit,predict or predict_proba(only avaliable for classification)"""
if 'fit' == action:
if sample_weight is not None:
return model.fit(X_train, y_train, sample_weight=sample_weight)... | 4b8bea5aef70153ebd585efdd8c70d2ccf579553 | 685,555 |
def fixStringEnds(text):
"""
Shortening the note body for a one-line preview can chop two-byte unicode
characters in half. This method fixes that.
"""
# This method can chop off the last character of a short note, so add a dummy
text = text + '.'
# Source: https://stackoverflow.com/a/3048717... | f2076635966a956ee194967506d603f8836d041a | 685,556 |
def same_lists(first, second):
"""Do the 2 input lists contain equivalent objects?"""
nobjs = len(first)
if len(second) != nobjs:
return False
# This is a bit of a brute-force approach since I'm not sure whether
# ExposureGroups will get ordered consistently by a sort operation if
# the... | 1da33a0c5428406933a21faf0c3eb024b4785943 | 685,557 |
import argparse
def get_arg_parser():
"""
Parse command line options
"""
description = 'Read the frontend configuration, update the web staging area and generate intermediate configuration that can be consumed by the decision engine'
parser = argparse.ArgumentParser(
description=descript... | 86325860f092ca32f3bff62978781f6ae79ce50b | 685,558 |
import _ast
def simpleAssignToName(node):
"""If a simple assignment to a name, return name, otherwise None."""
if isinstance(node, _ast.Assign) and len(node.targets) == 1:
targetNode = node.targets[0]
if isinstance(targetNode, _ast.Name):
return targetNode.id
else:
... | 4edf036527e7dbb7bb325eaea17cbb675c5b5b62 | 685,560 |
import time
def update_state(last_state, initial_dist, current_dist, init_rate, acceleration, state):
"""
updates the leds
:param last_state: the last time the led state changed
:param initial_dist: the starting distance from the object
:param current_dist: the current distance from the object
... | 14289f4d64cbb00b5f82c04e737930c70d868dbc | 685,561 |
import os
def get_output_name(dataset_config, line):
""" Returns output name for specified config and line number
Args:
dataset_config (dict): configuration information about the dataset
line (int): line of the dataset for output
Returns:
filename (str): output filename
"""
re... | 400444393a991c4201023b83892b9000f6a5c299 | 685,562 |
def request(url_request):
"""
Generate the URI to send to the THETA S. The THETA IP address is
192.168.1.1
All calls start with /osc/
"""
url_base = "http://192.168.1.1/osc/"
url = url_base + url_request
return url | 983f8164c547cafe7d7dcc6f06cc5ff469a1d7af | 685,563 |
def parse_denormalized(line):
"""Parse one line of the original dataset into a (user, item, rating) triplet of strings."""
id_, rating = line.strip().split(',')
user, item = map(lambda x: x[1:], id_.split('_'))
return user, item, rating | e4534972527ae7ffc21d571191694f3accf099d2 | 685,565 |
def printpath(P, u, w):
"""
Given modified path cost matrix (see floydwarshall) return shortest path
from i to j.
"""
path = [u]
while P[u][w][1] != -1:
path.append(P[u][w][1])
u = P[u][w][1]
return path | 8d2d55023b8835f43a014dc79679b182e03da616 | 685,566 |
def response_format(data, status=200):
"""
:param data:
:param status:http status
:return:
"""
if not isinstance(data, dict):
return data, status
if "custom_status" not in data.keys():
return data, status
# custom_status 系统内部状态码
# 401是无权访问, 405表示该请求方式不存在
if data[... | db321ac7466941329d53e3b97f76c239bdced394 | 685,567 |
def tokenize_dataset_line_by_line(
dataset,
data_args,
training_args,
tokenizer,
text_column_name,
column_names,
max_seq_length,
return_special_tokens_mask,
):
"""Tokenize each nonempty line."""
def _tokenize(examples, data_args, tokenizer, text_column_name):
padding = "... | 1239667274361d07de12ab9f821ca14880991738 | 685,568 |
import re
def remove_tags(html, tags):
"""Returns the given HTML with given tags removed.
``remove_tags`` is different from ``django.utils.html.strip_tags`` which
removes each and every html tags found.
``tags`` is a space separated string of (case sensitive) tags to remove.
This is backported ... | 59e8e0cfdb34d24766b9be995ffc49532fdea56a | 685,569 |
def generate_colorbar_label(standard_name, units):
""" Generate and return a label for a colorbar. """
return standard_name.replace('_', ' ') + ' (' + units + ')' | a42c97ec673c882aabaeb54090e253a6bb46d645 | 685,570 |
import sys
def buildSymmetryMap(srcAxis, srcVertices):
"""
build a symmetry map for the source vertices
:param srcAxis: `string` axis to mirror from (+x, -x, +y, -y, +z, -z)
:param srcVertices: `list` source vertices MeshVertex list
:return: `dict` symmetry Map
"""
# filter source vertice... | ccea9b83c38301b79627ec43e1b7731b277507ae | 685,571 |
def safe_repr(x):
"""
A repr() that never fails, even if object has some bad implementation.
"""
try:
return repr(x)
except:
name = getattr(type(x), "__name__", "object")
return f"<{name} instance>" | a726e339973f089165a2d2032e87c2c82ad96f4c | 685,573 |
import sqlite3
def get_age_groups(tourn_id):
"""uses tournament id to select tournament age groups.
returns a list.
"""
db = sqlite3.connect('data/master')
cursor = db.cursor()
#get available age groups for tournament
groups = cursor.execute('''SELECT age FROM age WHERE tourn_id=?''',
... | 02018b902a117f5aa3283a6e123c16c6cd3e62c6 | 685,574 |
def ticker():
"""Plugin ticker decorator."""
def wrapper(func):
func._is_ticker = True
return func
return wrapper | 36547f0b9ed345cb1f388901bac10dbc572dc2dc | 685,575 |
import logging
import sys
def parse_args(argparser, argv):
"""Define available arguments and parse the command-line."""
args = argparser.parse_args(argv)
# We have to accept a list of option, to write an error message in case
# there are several -a or -pn, otherwise, they get overwritten quietly.
... | 35c49973988789d54aa2b4564dca07df0a62ff59 | 685,576 |
def read_tsp(path):
""" Read and parse TSP from given file path
Args:
path (string): location of *.tsp file
Returns:
data (dict): {city_index: {"x": xvalue, "y": yvalue}, ...}
"""
data = {}
with open(path, "r") as f:
# Specification block
for line in f:
... | 415c9f7c415f593a7823e0bab4863926aab15b49 | 685,577 |
def complete_graph(vertices_number: int) -> dict:
"""
Generate a complete graph with vertices_number vertices.
@input: vertices_number (number of vertices),
directed (False if the graph is undirected, True otherwise)
@example:
>>> print(complete_graph(3))
{0: [1, 2], 1: [0, 2], 2: [0... | 2ad1165635e962acc59b1fb21fa0dced732a6565 | 685,578 |
def is_hyponym(syn1, syn2):
""" Checks if syn1 is a child of syn2 """
while syn1 != syn2:
hypernyms = syn1.hypernyms()
if len(hypernyms) == 0:
return False
syn1 = hypernyms[0]
return True | 0102da3dadb5aa1ee9c3b0c0f4f14082c51d28ac | 685,579 |
def api_date(a_datetime, time=False):
"""Return datetime string in Google API friendly format."""
if time:
return ('{0:%Y-%m-%d %H:%M:%S}'.format(a_datetime))
else:
return ('{0:%Y-%m-%d}'.format(a_datetime)) | ddbebcfd6d6041f76ff5983f5257f71ba2963165 | 685,580 |
def realCounts(data):
"""Subtract the upper bins from the lower bins
"""
# Get number of columns, loop over, sum upper and subtract from lower.
columns = data.columns
for i in range(0, len(columns)):
sumup = data[columns[(i+1):]].sum(axis=1)
data[columns[i]] = data[columns[i]] - sumu... | 3d131eea7eb3b3287d99aac7889af56c449c88d8 | 685,581 |
def Choose(index, *args):
"""Choose from a list of options
If the index is out of range then we return None. The list is
indexed from 1.
"""
if index <= 0:
return None
try:
return args[index-1]
except IndexError:
return None | 62fd7dc5fb4128167e5ff59271356bef6b68a297 | 685,582 |
def ids_to_payload(ids: list[tuple[str, str]]) -> list[dict]:
"""
Convert a list of (type, id) tuples to a list of dicts that
can be used as payload for the kptncook api.
"""
payload = []
for id_type, id_value in ids:
if id_type == "oid":
payload.append({"identifier": id_valu... | b11db5581c6d1cba96be241f4e6cd0746b80bf98 | 685,583 |
import json
def read_json(pathname):
"""Read json from a file"""
with open(pathname) as data_file:
try:
json_data = json.load(data_file)
except:
print(f"Error reading file {pathname}")
return None
return json_data | e3e350e4da11f887f7861b39c0d9291316501636 | 685,584 |
def merge_dicts(d0, d1):
"""Create a new `dict` that is the union of `dict`s `d0` and `d1`."""
d = d0.copy()
d.update(d1)
return d | 55a72d1a10939d69528b2fadcdca0ab93d2bbc28 | 685,585 |
import os
def ls_files(path):
"""
List all files in path.
Args:
path (str): the path in which to search
Returns:
a set containing all files in path, None if path is non-existent
"""
for dirpath, dirnames, filenames in os.walk(path):
return set(filenames)
return No... | 115ac4f9280bc46bb3917f4036bfbcf7e18a2cd3 | 685,586 |
def find_keys_with_duplicate_values(ini_dict, value_to_key_function):
"""Finding duplicate values from dictionary using flip.
Parameters
----------
ini_dict: dict
A dict.
value_to_key_function : function
A function that transforms the value into a hashable type.
For example ... | 5ee901fe560ffa95c2d11ccce22b6f12b552a606 | 685,587 |
import struct
def len_pack(length):
"""int len to network big-endian"""
return struct.pack("!I", length) | 55ede6444e900a026d7e0913854b8af0582c7f95 | 685,588 |
def find_segtree_interval(interval_list, y_interval):
"""Find the starting and ending elementary y-interval for the given rectangle y-interval.
For instance, the sample data is divided into 5 elementary y-intervals: (1, 2, 2, 2, 1).
The rectangle coordinates in the sample data map to the elementary y-inter... | 9b917ea5fc40c9e68dec25216f96a3492f64391c | 685,589 |
def get_cfg(cfg_label, cfg_dict):
"""
Get requested configuration from given dictionary or raise an exception.
:param cfg_label:
Label of configuration to get
:param dict cfg_dict:
Dictionary with all configurations available
:raises: At
:return: Config from given structure
... | aa3ea21d5470a563b7e5e934135d3e29c2b5012c | 685,590 |
def refineAclForSet(acl):
"""
Sets the ACL composed from the UI on the WebDAV server. For that purpose the
ACL object gets refined first to form a well accepted ACL to be set by the
ACL WebDAV method.
@param acl: An ACL object to be refined.
@type acl: L{ACL} object
@return: A valid... | 5e60595bf7d4e42b2e0110ed43e81912bc6e4a02 | 685,591 |
def cyclic_shift(array, dist):
"""
:params array: list like iterable object
:params dist: int
Example::
>>> cyclic_shift([0, 1, 2], 1)
[2, 0, 1]
>>> cyclic_shift([0, 1, 2], -1)
[1, 2, 0]
**中文文档**
循环位移函数。
"""
dist = dist % len(array)
return array[... | 172d7e3d8728eaaec8db275fd2776cbba1516953 | 685,592 |
def _get_improper_type_key(improper, epsilon_conversion_factor):
"""Get the improper_type key for the harmonic improper
Parameters
----------
improper : parmed.topologyobjects.Dihedral
The improper information from the parmed.topologyobjects.Angle
epsilon_conversion_factor : float or int
... | c76479b9d48ead0aec9b034a26e0366a8731fd59 | 685,593 |
def bubble_sort(ar): # Bubbles sorts the array
"""This is `Open-Palm's` function that sorts an array
The input `ar` is a tuple of single argument. Therefore only the
first (0 th argument) is accessed.
The first argument of the tuple i.e `ar[0]`
is a list that contains testcases.
Here the fir... | e47da3ce73e92b52b002d4ac3d86b023b72efbcd | 685,594 |
import re
def escape_sms_commands(text):
"""
Twitter allow 'special commands' to be sent via a tweet:
https://support.twitter.com/articles/14020
Since any tweet starting with these commands will try to run the command
rather than actually updating our status, we need to turn off this behavior
... | 4b0fa542dc8d0fac51a92edad7ace46d0f39bb18 | 685,595 |
def get_revision(revision: str, current_revision: int) -> int:
"""
Gets the absolute revision to upgrade/downgrade to.
"""
# HEAD means the latest possible revision
if revision.lower() == "head":
# return some stupidly high value
# nobody will ever hit this
return 99999999999... | 6129da2734df44a1e4433f049c1829869852fb81 | 685,596 |
def _combine_counts(count1, count2):
""" Sum two counts, but check that if one is 'unknown',
both are 'unknown'. In those cases, return a single
value of 'unknown'. """
if count1 == 'unknown' or count2 == 'unknown':
assert(count1 == 'unknown' and count2 == 'unknown')
return 'unkn... | cfd896a291d12c489ae7b193992eea80f5a1f886 | 685,597 |
def formatDirPath(path):
"""Appends trailing separator to non-empty path if it is missing.
Args:
path: path string, which may be with or without a trailing separator,
or even empty or None
Returns:
path unchanged if path evaluates to False or already ends with a trailing
separator; otherwise,... | bc9b14c862fac02d3254ade1e1bbd710f6aa91ba | 685,598 |
def clean_thing_description(thing_description: dict) -> dict:
"""Change the property name "@type" to "thing_type" and "id" to "thing_id" in the thing_description
Args:
thing_description (dict): dict representing a thing description
Returns:
dict: the same dict with "@type" and "id" keys ar... | 6c4ba9cf74b17b920156f4cb745485ef68a87b74 | 685,599 |
def add_edges(graph, edges):
""" Adds edges to the graph. """
# pylint: disable=star-args
for e in edges:
if isinstance(e[0], tuple):
graph.edge(*e[0], **e[1])
else:
graph.edge(*e)
return graph | 859293f8e49989ac43b3fbefd337793ff8e90a4b | 685,600 |
def decode(value):
"""Decodes ``value`` from HS according to the protocol.
This is a reverse function of :func:`~.encode`.
:param string value: value to decode.
:rtype: string
"""
if value == '\0':
return None
decoded = ''
it = iter(value)
for char in it:
output = c... | 2740ae9dd8f818638e555facd29f296582734c9a | 685,601 |
def lettersearch(phrase:str, letters:str) -> set:
"""This module takes a phrase provided by the user and searches it for letters that the user provides"""
return set(letters).intersection(set(phrase)) | ce9004eff2b290bda8614b6f7ab01a2ac355711b | 685,602 |
import socket
import time
import os
def filename_from_host_and_date() -> str:
"""
Returns a string assembled from the host name and current date.
Returns
-------
out: str
A string combining host name and date.
"""
# the name of the machine running the program (supposedly, using the socket module gives ri... | 353b35cd07c3c225be7457a313e14907ddec5555 | 685,603 |
def make_docker_image_name(job_config, course, session, mode, prefix="MORF"):
"""
Create a uniqe name for the current job_config
:param job_config:
:return:
"""
name = "{}-{}-{}-{}-{}".format(prefix, job_config.morf_id, mode, course, session)
return name | 8d0aade888c2f792c85a47b9a97e1f6bacde9cfd | 685,604 |
def get_geo(twitter_msg):
"""
Generates GoogleMap link if msg has location data.
:param twitter_msg: Twitter Status Object
:return: string with gm link if possible or empty string otherwise
"""
try:
x, y = twitter_msg.place["bounding_box"]["coordinates"][0][0]
return "https://www... | 037262c8d8bfae2f280b66f1fa13467d4cda1e9d | 685,606 |
import math
def yield_strength(impactor_density_kgpm3):
"""
Yield strength equation for breakup altitude calculation. Only valid for density range 1000 to 8000.
:param impactor_density_kgpm3: Impactor density in kg/m^3
:returns: Yield Strength in Pascals.
:Reference: EarthImpactEffect.pdf, Equatio... | b09c8011acc396eb3e43fbefe956bf52074bb619 | 685,607 |
from pathlib import Path
def open_txt_doc(filename):
"""Opens texts in docs folder that go in front end of app"""
path = Path(__file__).parent / 'docs' / 'app' / filename
with open(path, 'r') as txtfile:
text = txtfile.read()
return text | 9eb396e76f1337adf010589e557fac310b6d49e7 | 685,608 |
def combine_split_result(s):
"""Combines the result of a re.split splitting
with the splitters retained. E.g. ['I', '/', 'am']
-> ['I', '/am'].
"""
if len(s) > 1:
ss = [s[0]]
for i in range(1, len(s)//2+1):
ii = i-1
ss.append(s[i] + s[i+1])
return ss
... | 5f054342484d598a6d85ec7a7c8751ba98c527f8 | 685,609 |
def clean_elements(orig_list):
"""Strip each element in list and return a new list.
[Params]
orig_list: Elements in original list is not clean, may have blanks or
newlines.
[Return]
clean_list: Elements in clean list is striped and clean.
[Example]
>>> clean_e... | c33403d28380246eed9a0f9a8eda2580d561e2ac | 685,610 |
from typing import List
def load_bookmarks(bookmark_path: str) -> List[int]:
"""
VSEdit bookmark loader.
load_bookmarks(os.path.basename(__file__)+".bookmarks")
will load the VSEdit bookmarks for the current Vapoursynth script.
:param bookmark_path: Path to bookmarks file
:return: ... | 668da5b806e596cf91aa941e70b00a3c219ab0cd | 685,611 |
def _overall_output(ts, format_str):
"""Returns a string giving the overall test status
Args:
ts: TestStatus object
format_str (string): string giving the format of the output; must
contain place-holders for status and test_name
"""
test_name = ts.get_name()
status = ts.get_overall_... | c16e4f7cc7d610a08c59af21abd5d295fad7ddbc | 685,612 |
def is_json(file_path):
"""
Checks if a certain file path is JSON.
:param file_path: The file path.
:return: True if it is JSON, False otherwise.
"""
return file_path.endswith('.json') | 59f15d76f618e3d2a16cf66d0f69a8a7f81290ab | 685,613 |
def mask_get(receptor_pdbqt):
"""Mask detector for cpptraj inputs.
This function returns a string indicating the residue numbers involved with the host protein.
Parameters
__________
receptor_pdbqt : string
The receptor file including path to be parsed.
Returns
_______
... | e2b073cb612465b7d86565021b157c7e7ed01cdf | 685,614 |
import os
import glob
def _find_all_or_none(globs_to_include, num_files, qt_library_info):
"""
globs_to_include is a list of file name globs
If the number of found files does not match num_files
then no files will be included.
"""
# This function is required because CI is failing to include li... | 8d90734825163680302cec6cc1e3a6dc6d30d497 | 685,615 |
import os
def get_config_data(config_file):
"""
This function takes in a config_file and loads the data
and returns the data
"""
# -----------
# get the config files without the path or the .py
# -----------
config_basename = os.path.basename(config_file)
if config_basename[-3... | 5cda0c2a89383d6201e610a0275cfa73396f9293 | 685,616 |
def create_tom(animal_clabject):
"""Create a 'clabject' representing the cartoon character Tom
Parameters
----------
animal_clabject : multilevel_py.core.MetaClabject
the Animal clabject, i.e. the top of the classification hierarchy defined above
Returns
-------
multilevel_py.core.... | 11ae3c62d5d3bdb6aeb0a779d7c8c096ee676af4 | 685,617 |
def genGeneral(general):
"""
Append values before the general to generate a json compliant footer definition
"""
return "".join(general) | f6d62d294a8276ea79dbf990e86b30b8c18ca300 | 685,618 |
def get_relation_id(relation):
"""Return id attribute of the object if it is relation, otherwise return given value."""
return relation.id if type(relation).__name__ == "Relation" else relation | d2aa5cb725e87ac20e75ca97d70e0032e0f31223 | 685,619 |
def _get_overlap(start1, end1, start2, end2):
"""Get overlap between the intervals [start1, end1] and [start2, end2].
Args:
start1 (float)
end1 (float)
start2 (float)
end2 (float)
"""
return max(0, min(end1, end2) - max(start1, start2)) | 2d1a60d8371ac2595ef83ba34611c729e5b49b4c | 685,620 |
def comp_div_per_year(div, vol_list, DRP_list):
"""
return total dividends for this stock, including stocks from DRP
"""
return sum(div * (i[0] + i[1]) for i in zip(vol_list, DRP_list)) | 89c6a578e2a0b07ea932069a8e9f24f24ac01886 | 685,621 |
import subprocess
def commit(cmd, failure_is_fatal=False):
"""Run the given command.
:param cmd: Command to run
:type cmd: str
:param failure_is_fatal: Whether to raise exception if command fails.
:type failure_is_fatal: bool
:raises: subprocess.CalledProcessError
"""
if failure_is_fa... | d49efa451bf7cf2b9d02483a668a3ce8eed15c9d | 685,622 |
def fast_overlap(s, t):
"""Return the overlap between sorted S and sorted T.
>>> fast_overlap([2, 3, 5, 6, 7], [1, 4, 5, 6, 7, 8])
3
"""
count, i, j = 0, 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
count, i, j = count + 1, i + 1, j + 1
elif s[i] < t[j]:
... | a33e91b9c84283414d0de0ab47e49c2614201083 | 685,623 |
def format_group(factors):
"""Formatted output: group factors and exponents."""
grouped = []
for factor in factors:
exponent = factors.count(factor)
grouped.extend([(factor, exponent)])
grouped = sorted(set(grouped))
return grouped | f982bf7f78c00765e7edeed37286ed1f93754586 | 685,624 |
def get_sample_region_coverage(sample_tabix_object, region_dict):
"""
get_sample_region_coverage
==========================
Get the coverage values for a specific sample at a specific region interval.
A list containing per base coverage values will be returned.
Parameters:
-----------
... | 3d94dd5559a089a0d8037a5d71734a6b24769154 | 685,625 |
def hasDuplicateValue(list):
"""
参数
list: 待检查重复的队列
返回值
True | False:有重复值就返回 True, 否则返回 False
效率: O(n^2)
"""
size = len(list)
for i in range(0, size - 1):
for j in range(i + 1, size):
if list[i] == list[j]:
return True
return False | 9917a98fbcb4372acf76baf066d13f92cb35f4e5 | 685,627 |
import string
def case_iteration(header, iteration):
"""
Modifies a string to determine the correct
case for each individual character in the string.
A character will be uppercase if the bit representing it in
the iteration value is set to 1.
For example, the string "hello" with an iteration... | e5b0cb2fcf9953eeb1da78b038846b5030493b02 | 685,628 |
import numpy
def expandJ(a):
"""
Expands an array by one row, averaging the data to the middle columns and
extrapolating for the first and last rows. Needed for shifting coordinates
from centers to corners.
"""
nj, ni = a.shape
b = numpy.zeros((nj+1, ni))
b[1:-1,:] = 0.5*( a[:-1,:] + a[1:,:] )
b[0,:... | b5e34c60b4fa77b6dfe5c996a0bd737ee611f34b | 685,629 |
def get_ca_atoms(chain):
"""
Returns the CA atoms of a chain, or all the atoms in case it doesn't have CA atoms.
Arguments:
- chain - Bio.PDB.Chain, the chain to get the atoms
"""
result = []
if chain.child_list[0].has_id("CA"):
for fixed_res in chain:
if fixed_res.ha... | 7ed4cade8bdf76f8ee4f2e11b3bb2f3c8c603ea4 | 685,630 |
def calculate_senate_bop(race, data):
"""
"total": The total number of seats held by this party.
Math: Seats held over (below) + seats won tonight
"needed_for_majority": The number of seats needed to have a majority.
Math: 51 (majority share) - total.
"total_pickups": The zero-indexed to... | a63cb4dae968bbec98a27e67c8a6338421f7b4a6 | 685,632 |
def find_best_thresh(preds, scores, na_probs, qid_to_has_ans, unanswerable_exists=False):
"""
Find the best threshold to determine a question is impossible to answer.
Args:
preds (dict): Dictionary with qa_id as keys and predicted answers as values.
scores (dict): Dictionary with qa_id as k... | 3cc63c79e5fba945c92411de929b566a990b8a4c | 685,633 |
def evaluate_prediction(y, y_hat):
"""
This is a function to calculate the different metrics based on the list of true label and predicted label
:param y: list of labels
:param y_hat: list of predictions
:return: (dict) ensemble of metrics
"""
true_positive = 0.0
true_negative = 0.0
... | daba4222eaa261521e9645b0de042189c621a90b | 685,634 |
def xi_func_theory(xi0, T, Tc, nu):
"""
Parameter
---------
xi0 : float
correlation length 0 (in m)
T : float
lattice constant of the cubic unit cell (in K)
Tc : float
critical temperature of the system (in K)
nu : float
critical exponent of the correlatio... | 03558350125322be0ff18753fb83c6a664bd0b51 | 685,635 |
def sigma_z(state, site):
"""
Returns `(sign, state)` where `sign` is 1 or -1 if the `site`th bit of the int `state`
is 0 or 1 respectively. Can also accept numpy arrays of ints and gives numpy arrays back
"""
return (-1.0) ** ((state >> site) & 1), state | d2c128d08fedf684683bca8cd4902ab8a785587f | 685,636 |
from datetime import datetime
def dateFormat(timestamp):
"""
Format timestamp (nb of sec, float) into a human-readable date string
"""
return datetime.fromtimestamp(
int(timestamp)).strftime('%a %b %d, %Y - %H:%M') | 090f0b8da439c15918f48aa37aa5effbcc3e101a | 685,637 |
def to_dict(key, resultset):
"""
Convert a resultset into a dictionary keyed off of one of its columns.
"""
return dict((row[key], row) for row in resultset) | aad419aeb1b7d81d14ab9ef2e70791d23b2a9082 | 685,638 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.