content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def add_metadata(amr_df, metadata_df):
"""
Adds the extra information in the metadata tsv into the amr df
"""
merged_df = amr_df.merge(metadata_df, on=['genome_id','genome_name','taxon_id'], how='left')
return merged_df | 92c4431eaff937d9a6b49ae5806fe97838f56bf6 | 33,723 |
from typing import Optional
def _parse_str(arg: 'Optional[str]') -> str:
"""Parse argument as :obj:`str`.
Args:
arg: Original request argument.
Returns:
Parsed query argument.
"""
if arg is None:
return ''
return arg | 1886e0399cb7a6d9de4656ab4b39e0eb16d3c395 | 33,725 |
import torch
def to_onehot(c):
""" Creates a onehot torch tensor """
onehot = torch.zeros((1, 1000))
onehot[:, c] = 1.0
return onehot | c89356180d41243158dcee838eab7181f00f870a | 33,726 |
import bs4
def is_declaration(obj): # pragma: no cover
"""Is declaration."""
return isinstance(obj, bs4.Declaration) | 431f704a141c34f57c72218256f4d50fe2e8a99d | 33,727 |
import math
def normal_cdf(x, mu=0.0, sigma=1.0):
""" 평균이 mu이고, 표준편차가 sigma인
정규 분포의 누적 분포 함수(cumulative distribution function).
math.erf() 함수(error function)를 이용해서 구현"""
return (1 + math.erf((x - mu) / (math.sqrt(2) * sigma))) / 2 | 5287d3740d6232e034609e0e0fce8a4b87e8ae45 | 33,728 |
import typing
def _read_exact(stream: typing.BinaryIO, byte_count: int) -> bytes:
"""Read ``byte_count`` bytes from ``stream`` and raise an exception if too few bytes are read
(i. e. if EOF was hit prematurely).
"""
data = stream.read(byte_count)
if len(data) != byte_count:
raise ValueError(f"Attempted to re... | 701180cb98985eca620c7e4d200050d92cc889ea | 33,730 |
def compute_min_distance_mendelian_ci(proband_CI, parent_CIs):
"""Commute the smallest distance between the given proband confidence interval, and the confidence intervals of
parental genotypes.
Args:
proband_CI (Interval): ExpansionHunter genotype confidence interval.
parent_CIs (list of I... | 9b8f71c612972410054b18b05c5e86bda3c96321 | 33,731 |
import json
def filter_items(df):
"""
Filter items of interest from the stays.csv files
:param events_df:
:param itemIDs:
:return:
"""
with open('simplimicapp/items.JSON') as infobj:
items_dict = json.load(infobj)
all_relevant = [_ for d in items_dict.values() for v in d.value... | cfd8df9f6f69a486cf9183f3d98b81270b4a3ab2 | 33,732 |
def is_valid_status_code(status_code):
"""
Returns whether the input is a valid status code. A status code is valid if it's an integer value and in the
range [100, 599] :param status_code: :return:
"""
return type(status_code) == int and 100 <= status_code < 600 | 903878d7fabd6e3abd25d83bb0bbd37e0c8d3ce5 | 33,733 |
import os
import json
def load_settings(session_path):
"""
Load PyBpod Settings files (.json).
[description]
:param session_path: Absolute path of session folder
:type session_path: str
:return: Settings dictionary
:rtype: dict
"""
path = os.path.join(session_path, "raw_behavior_... | 7663d6c18526e830b55c4e50544c118cfadf8ebb | 33,734 |
import subprocess
import time
def subprocess_execute(command, time_out=60):
"""executing the command with a watchdog"""
# launching the command
c = subprocess.Popen(command)
# now waiting for the command to complete
t = 0
while t < time_out and c.poll() is None:
time.sleep(1) # (com... | 9f8755498942e2376cd3097ed03677d8cc9d0484 | 33,735 |
def get_change_segment_details(change_segment):
"""
Function returns details for single change segment as a dictionary.
"""
change_segment_dict = {}
change_segment_dict['change_time'] = change_segment\
.find_element_by_xpath(".//strong[@class='qa-segment-change-time']").text
return c... | 15a9408e3f7d817deacac9d71e48f4a653b667b6 | 33,736 |
from typing import Tuple
def coordinates_to_chunk(x: int, y: int, chunk_size: int) -> Tuple[int, int]:
"""
Convert x, y coordinates to chunk coordinates
"""
normal_x = x // chunk_size
normal_y = y // chunk_size
middle_x = normal_x*chunk_size+(chunk_size//2)
middle_y = normal_y*chunk_size+(... | 40ab03f2a6391f2d11e72cc80d510a3f82af536e | 33,737 |
def prepare_plot_data(n_labels, legends, markers):
"""
:param int n_labels: Number of labels
:param list_or_None legends: List of legends
If None, it will be transformed to list of None
:param list_or_None markers: List of markers
If None, it will be transformed to list of 'circle'
... | 84ce953fd03e9dd548f3e2e7a3e5fcce43b4364a | 33,738 |
def premium(q,par):
""" Returns the (minimum) premium that an insurance company would take
Args:
q (float): coverage
par (namespace): parameter values
Returns:
(float): premium
"""
return par.p*q | 2166bc6e16577a26d3adc17afe5929bf8fca073b | 33,739 |
def _thermocycle_error_text():
"""
Returns formatted error text for thermocycle value errors
"""
return """Thermocycle input types must take a list of dictionaries in the form of:
[{"cycles": integer,
"steps": [{
"duration": duration,
"temperature": temperature
"read": boolean (... | cee2fb445da91e50f32fe6799dfd328e8c3d5edc | 33,741 |
def parse_cookie(string):
"""
parse_cookie(string) -> dict
Parse the given Cookie: header value and return a mapping from cookie
names to values.
"""
ret = {}
for el in string.split(';'):
n, _, v = el.partition('=')
ret[n.strip()] = v.strip()
return ret | 5da1fbfa7ee9cde5dfb742355cf96c2931633d80 | 33,744 |
def comm_self_to_comm_world(s, w):
"""
Convert a function defined on a mesh with a MPI_COMM_SELF to
a function defined on the same geometry, but with MPI_COMM_WORLD.
The mesh and function spaces mush be identical except for the
MPI communicator.
- s is the MPI_COMM_SELF function
- w is the ... | 0c29f4b1273f3f4ca4d40dacbe615c0fdad061ec | 33,745 |
import os
def list_files_in_subdir(filepath: str) -> list:
"""
Get a list of all the filepath of files in directory and subdirectory.
"""
res = []
for path, _, files in os.walk(filepath):
for name in files:
res.append(os.path.join(path, name))
return res | c3a56bb5bf77860b400ea706879db261ad8bc237 | 33,746 |
def strip_comments(line):
"""strip comments ('! blubb', '# blabb') off a line"""
line = line.replace('#', '!')
return line.split('!')[0] | 9bdc62c5d843da540244ba40c8d2107f751ede98 | 33,747 |
import numpy
def linbleeched_F0(data):
"""
Calculate a linear fit (:math:`y(t)=m t+y_0)` for each pixel, which is assumed to correct for bleeching effects.
:param data: he video data of shape (M,N,T).
:return: tuple (m,y0) with two images each with shape (M,N).
"""
# generate c coordinates
... | 278772624246186d0495e3b61ca2635533e3aa3e | 33,748 |
def fetch_vendor_id(vendor_name, conn):
"""
Retrieve our vendor id from our PostgreSQL DB, table data_vendor.
args:
vendor_name: name of our vendor, type string.
conn: a Postgres DB connection object
return:
vendor id as integer
"""
cur = conn.cursor()
cur.execute("SE... | 504cb7e71791ef7385edf5e143ffa0f4c3d09313 | 33,750 |
def enter(e):
"""Allows user to specify if they want pdfcp() to automatically append a
carriage return to the end of copied pdf text in addition to removing
line breaks while pdfcp() is running.
Parameters
----------
e : str ("y" or "")
Carriage return append u... | d4aa4fbd55b483ac7e7cfa6384a01ebc253f44af | 33,751 |
import random
import math
def ferma(number: int, k: int = 100) -> bool:
"""Тест простоты Ферма
Wiki:
https://en.wikipedia.org/wiki/Fermat_primality_test
:param number: проверяемое число
:type number: int
:param k: количество тестов
:type k: int, default 100
:return: True если чис... | a36d193ab34db4c75b1738ce63998452b7517693 | 33,752 |
def read_file_first_line(filename):
""" Read first line of given filename """
result = None
with open(filename, 'r') as f:
result = f.readline()
result = result.rstrip("\n")
f.close()
return result | 4cc6502ab76e2bdbf2ccdb2367e69bf02bccf572 | 33,753 |
import torch
def reparameterize(mu, logvar):
"""
Reparameterize for the backpropagation of z instead of q.
This makes it so that we can backpropagate through the sampling of z from
our encoder when feeding the sampled variable to the decoder.
(See "The reparameterization trick" section of https:/... | 339204d7471f319eef4179ca5f89fff79f68f70f | 33,754 |
def number_of_bases_above_threshold(high_quality_base_count, base_count_cutoff=2, base_fraction_cutoff=None):
"""
Finds if a site has at least two bases of high quality, enough that it can be considered
fairly safe to say that base is actually there.
:param high_quality_base_count: Dictionary of count ... | c703020b0a3b0b1b3c39f38f4a4bae1be9946269 | 33,756 |
def placeholder(x):
"""
Placeholder description.
:param int x: integer number taken as input
:return int or float: returns x
"""
return x | 5ec8cff976e9b9e94e83d7a6ab8c825e4f2f0982 | 33,758 |
def get_last_valid_idx(output_k, forecast_cycle, ar_iterations):
"""Provide the last available index for training, once accounted for all forecasted timesteps."""
future_idxs = output_k[output_k >= 0]
if future_idxs.size == 0: # empty
future_idxs = 0
else:
future_idxs = abs(max(futur... | 7f67ecee0c22402973ba9b03ad23cce424bf2ad9 | 33,760 |
from typing import Any
def key(request: Any) -> Any:
"""A key to test indexing into DictConfig."""
return request.param | d61ba3341f34ff36bbc0b4d95ba1978dbd8d1125 | 33,764 |
import torch
def batchify(data):
"""返回带有负采样的跳元模型的小批量样本."""
max_len = max(len(c) + len(n) for _, c, n in data)
centers, contexts_negatives, masks, labels = [], [], [], []
for center, context, negative in data:
cur_len = len(context) + len(negative)
centers += [center]
contexts_n... | 731c85bef3639e565621a1f7f05dd3df40beceff | 33,767 |
def get_reference(node, identifiers):
"""Recurses through yaml node to find the target key."""
if len(identifiers) == 1:
return {identifiers[0]: node[identifiers[0]]}
if not identifiers[0]: # skip over any empties
return get_reference(node, identifiers[1:])
return get_reference(node[id... | 5297e7cd7d97b7c7e494a814de8077c3a37f9b90 | 33,769 |
import sys
def find_first_app_frame_and_name(ignores=None):
"""
Remove ignorable calls and return the relevant app frame. Borrowed from
structlog, but fixes an issue when the stack includes an 'exec' statement
or similar (f.f_globals doesn't have a '__name__' key in that case).
Parameters
---... | 953148f64336a37ffdf40b175fefefc472db7f66 | 33,770 |
def orange_settings(c):
"""Return a dictionary of settings for the leo.core.leoAst.Orange class."""
allow_joined_strings = c.config.getBool(
'beautify-allow-joined-strings', default=False)
n_max_join = c.config.getInt('beautify-max-join-line-length')
max_join_line_length = 88 if n_max_join is No... | ffefc29515a79ebe50be53194bb59f49c2d8e1e2 | 33,771 |
import tarfile
def get_file_from_tar(tar_path, file_name):
"""
Using a partial or full file name, get the full path of the file within the tar.
@param tar_path: path to a tar file
@param file_name: full file name or end of the filename to find
@return the path for the file
"""
with tarfile... | 3f9e093a653aa7f6e9fc4f68138250b8038fbaa2 | 33,774 |
import pytz
def _dates_to_naive_utc(date_objects):
"""Converts dates to UTC time zone and strips time zone info.
Date objects can be time zone aware. If the input date objects are time
zone aware, they are converted to UTC time and then the time zone info is
removed from the resulting object.
If... | 0ba479f94f07bba8ea7d54fb7100e6f0732803b8 | 33,775 |
def scale_factor(redshift):
"""
Calculates the scale factor, a, at a given redshift.
a = (1 + z)**-1
Parameters
----------
redshift: array-like
The redshift values.
Returns
-------
a: array-like
The scale factor at the given redshift.
Examples
--------
... | d682cb510f2c7fe53d96b76e88cd5f2bfc964cb5 | 33,777 |
def _get_annotations(generator, sample_array):
"""
Get the ground truth annotations from the generator.
The result is a list of lists such that the size is:
all_annotations[num_images][num_classes] = annotations[num_class_annotations, 5]
Args:
generator: The generator used to retrieve gr... | 08f8f1c263ce01b29fce88d0b416304dc3b1b5fc | 33,778 |
import re
def asset_name_from_label(label):
"""Builds a filename from the asset label string.
Args:
- label (str): User-friendly label
Returns:
- the asset file name
"""
assetDir = re.sub(r'[^\w]', '', re.sub(' ', '_', label)) + '.rma'
return assetDir | 880e10c3f9b717f7551b910770820b502d6cd7af | 33,779 |
def _time_string(time_value):
"""hrs:mins:secs"""
minutes, seconds = divmod(time_value, 60)
hours, minutes = divmod(minutes, 60)
return '%d:%02d:%02d' % (hours, minutes, seconds) | d690dcd48aba7712b9a4a1772bb7c37e4d7b7cbd | 33,780 |
import pathlib
def path_to_uri(path):
"""
Convert OS specific path to file:// URI.
Accepts either unicode strings or bytestrings. The encoding of any
bytestring will be maintained so that :func:`uri_to_path` can return the
same bytestring.
Returns a file:// URI as an unicode string.
"""
... | 4d05bbb7bb07f9bb9f6d86ab4980368f89c0db60 | 33,781 |
def extend_train_set(sentences1, sentences2, is_similar, test_sentences1, test_sentences2, test_labels):
"""
Increase the size of the training set by adding the first half of the testing
set to the training set
Args:
sentences1 (list): first list of training sentences
sentences2 (list... | cd98ee71f95dc88f2487daaaffaeba3a8066825e | 33,782 |
def abs2(x):
"""Square modulus of x. Fastest way possible for a numpy array."""
return x.real**2 + x.imag**2 | 5b733ed33cda6f2a5aebf938a8291631fc65af08 | 33,783 |
def mock_get_benchmark_config(benchmark):
"""Mocked version of common.benchmark_config.get_config."""
if benchmark == 'benchmark1':
return {
'unsupported_fuzzers': ['fuzzer2'],
}
if benchmark == 'benchmark2':
return {
'unsupported_fuzzers': ['fuzzer2', 'fuzzer... | 2496495fae2293e6ea4b5411f3f44cba1a8dee5d | 33,784 |
def es_subcadena(adn1, adn2):
"""
(str, str) -> boolean
funcion que nos permite definir la subcadena de una secuencia dada
>>> es_subcadena('atcgta', 'gta')
True
>>> es_subcadena('atcg', 'tta')
False
:param adn1: str con la cadena 1
:param adn2: str con la cadena 2
:return: s... | 91e981b41194fdd3a11d6d59a91f4c88d7ffa118 | 33,785 |
def extractRadiantSampleParameters(sample_list):
""" Given a list of samples, extract the parameters into a list. """
jd_list = [s.jd for s in sample_list]
la_sun_list = [s.la_sun for s in sample_list]
rag_list = [s.ra_g for s in sample_list]
decg_list = [s.dec_g for s in sample_list]
vg_list =... | 5f39f27dde793609a3754aa7ee0a8f7c12e12d7e | 33,786 |
def get_batch_len(batch):
"""Return the number of data items in a batch."""
if isinstance(batch, (tuple,list)): # non-vectorized modalities
return len(batch[0])
return len(batch) | 9794e5c050edf951dcc96166364e429a3d61df27 | 33,787 |
from typing import Tuple
def tuple_to_string(tup: Tuple) -> str:
"""Standardized assembly of tuple strings for DTS files
:param tup: typing.Tuple
:return: str
"""
string = ' '.join(tup)
return string | d1abafff084bfd05a4fbfc5116f8004c390a97da | 33,788 |
def extract_pillar_shape(grid):
"""Returns string indicating whether whether pillars are curved, straight, or vertical as stored in xml.
returns:
string: either 'curved', 'straight' or 'vertical'
note:
resqml datasets often have 'curved', even when the pillars are actually 'vertical' or 'str... | 12c754543b89cde31f9c3ef0ebc04d4322ce71f0 | 33,789 |
def generate_shape(shape_id):
"""
Utility function called by generate_target
"""
shape = None
if shape_id == 1:
shape = [[0, 0], [0, 1], [1, 0], [1, 1]]
elif shape_id == 2:
shape = [[0, 0], [1, 0], [2, 0], [3, 0]]
elif shape_id == 3:
shape = [[0, 0], [0, 1], [0, 2], [... | d07cda9f4eafea0a5f0db416340a81fd9776cdd6 | 33,791 |
def parse_archive_csv(path):
"""
Parses archives names file. Returns list of filename lists: [[archive1, archive2, archive3], ...]
:param path:
:return:
"""
with open(path) as f:
lines = f.readlines()
_archives = []
for line in lines:
_archives.append([x for x in line.sp... | ecac6efe412b9f38d0335c2bbe82dc77e6d19547 | 33,794 |
import os
def get_pg_url() -> str:
""" create postgresql connection string """
return (
f"postgres+psycopg2://{os.getenv('POSTGRESQL_USER')}"
f":{os.getenv('POSTGRESQL_PASSWORD')}@{os.getenv('POSTGRES_SERVICE_HOST', 'postgres')}"
f":{os.getenv('POSTGRESQL_PORT', '5432')}/{os.getenv('PO... | 066c4de4308aa50664c47a1f22aa8ce15598b5c1 | 33,795 |
def ccw_to_cw(ccw_points):
"""
Converts counter clockwise points to clockwise points
"""
cw_points = ccw_points.copy()
cw_points[:, 4:7] = ccw_points[:, 13:16]
cw_points[:, 7:10] = ccw_points[:, 10:13]
cw_points[:, 10:13] = ccw_points[:, 7:10]
cw_points[:, 13:16] = ccw_points[:, 4:7]
... | a5486b4063cad75257bfeff88f94984a08787deb | 33,796 |
import argparse
def parse_arguments():
"""
Parse input arguments for train script
i.e.: python train.py --arch=vgg16 --learning_rate=0.01 --hidden_units="4096, 2048"
:return: Parsed arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("data_dir", type=str, help="Path of flo... | e6e4280034a3c07bef761a3b58cfc9ba99cc8f8c | 33,797 |
import os
def get_package_name() -> str:
"""Get the name of the package."""
cwd = os.getcwd()
return cwd.split(os.path.sep)[-1] | b5e24edec2202a7c370b4cd7b8cd4f5a5184c429 | 33,798 |
def _get_tcp_slave_address(config):
"""
Get the TCP slave address to be used for the tests.
"""
return config.getoption("--tcp-address") | adec5d4a52f36737766fbc3e7d9b35a8bc5f6eb8 | 33,800 |
def mean_group_min_count(df, group_col, mean_col, min_count=10):
"""Calculate mean of column col in df, grouped by group_col, but normalising the
sum by either the actual number of rows in the group or min_count, whichever is
larger
"""
counts = df.groupby(group_col)[mean_col].count()
counts[co... | ced80f28c0231c84f394b5cd398af94012413a5a | 33,801 |
def parse_filter_parameters (parameters, parse):
"""
Parse command parameters to get information filtering flags for the command.
:param parameters: The list of parameters provided to the command.
:param parse: The list of filtering parameter names to parse.
:return A list with the values ... | 479ce6b11be9137523c842e64629159b3424b090 | 33,802 |
def subsample_fourier(x, k):
"""Subsampling in the Fourier domain.
Subsampling in the temporal domain amounts to periodization in the Fourier
domain, so the input is periodized according to the subsampling factor.
Parameters
----------
x : numpy array
Input numpy array with at least 3 ... | eba3a9d4a0fea71c0d42c3b7da7b762e56766974 | 33,803 |
def Column_hasCode(cont_Code_center):
"""
:param cont_Code_center: The sequence of Code objects contained in this Column
:type cont_Code_center: Array
"""
return len(cont_Code_center) > 0 | d54c3fe293d032106b5588dc09a4f7609cea754d | 33,805 |
def _get_bone_matrix(bone):
"""bone should be a Bone
B_b
"""
if bone.parent:
b_mat = bone.matrix_local.inverted() * bone.parent.matrix_local
else:
b_mat = bone.matrix_local.inverted()
return b_mat | ee4ed9fc131172bb100eea2558f3573796031b0e | 33,806 |
def parse_multiple(s, f, values=None):
"""Parse one or more comma-separated elements, each of which is parsed
using function f."""
if values is None: values = []
values.append(f(s))
if s.pos < len(s) and s.cur == ',':
s.pos += 1
return parse_multiple(s, f, values)
else:
... | 3ee6dbf85769541bdadcdf4f2de910f54d8dbef5 | 33,808 |
from numpy.distutils.misc_util import Configuration
def configuration(parent_package='', top_path=None):
"""Configure the package."""
config = Configuration('camcan', parent_package, top_path)
config.add_subpackage('datasets')
config.add_subpackage('datasets/tests')
config.add_subpackage('datase... | 04c0c97688e335eba96b1c16e0f86738fb6c41e7 | 33,810 |
import os
import fnmatch
def glob_r(directory, pattern):
"""Recursively scan a directory looking for files matching the given pattern.
The pattern matches the full path relative to the given directory. Matches are
checked using the fnmatch module.
Args:
directory: The directory to start searching in.
... | 5222d84ba77fcf46f732fbb63909586929f26aad | 33,812 |
import torch
def evaluateMasks(predSegmentations, gtSegmentations, device, pred_non_plane_idx, gt_non_plane_idx=20, printInfo=False):
"""
:param predSegmentations:
:param gtSegmentations:
:param device:
:param pred_non_plane_idx:
:param gt_non_plane_idx:
:param printInfo:
:return:
... | 701102fe285134a7cff3767e6a1744de0529e63a | 33,813 |
from typing import List
def _get_columns(words: List, headers: List[str]) -> List:
"""Finds columns based on headers.
Finds column members by finding all words in `words` that are below `head`
and have (roughly) the same x0 value as `header[i]` for all headers in
`headers`. Pads lists with "{"text": ... | e791ca35c3c8aa191a1842edbb6126f88f4f4a4c | 33,814 |
from datetime import datetime
def epochs_to_timestamp(epochs: int, date_format: str = "%B %d, %Y %H:%M:%S %p") -> str:
"""
Converts epochs time representation to a new string date format.
Args:
epochs (int): time in epochs (seconds)
date_format (str): the desired format that the timestamp... | 1535be9f82292a9387abf1123e934af02f743c92 | 33,816 |
from typing import Dict
from typing import Any
def dict2argstr(d: Dict[str, Any]) -> str:
"""Convert a dict to a text of kwd=arg pairs"""
return ",".join("{!s}={!r}".format(key, val) for (key, val) in d.items()) | 88955a2effb166e11f6fec87bb959f536f97d197 | 33,818 |
def load_chromosomes(fpath):
"""
:param fpath:
:return:
"""
chroms = dict()
with open(fpath, 'r') as infile:
for line in infile:
if not line.strip():
continue
cols = line.strip().split()
chroms[cols[0]] = int(cols[1])
return chroms | 3aaf3e6c85fb9ca64094b3ae06652b380371231f | 33,819 |
import six
def safebinary(obj):
"""
Make sure obj is binary type
"""
if isinstance(obj, six.binary_type):
return obj
try:
return six.binary_type(obj)
except UnicodeEncodeError:
return obj.encode('utf-8') | 6859c802456bccf54db095ccf254d2607e63ef8f | 33,820 |
def _node_types_match(node, node_template):
"""
Verifies whether input and output types of two nodes match. The first has fixed arities of
the input type whereas the second is a template with variable arities.
:param node: Node with fixed input types arities.
:param node_template: A node template w... | 46cb2c6c23aa6965536988c5918f4efa87dc9065 | 33,822 |
import re
def mapping_account(account_map, keyword):
"""Finding which key of account_map contains the keyword, return the corresponding value.
Args:
account_map: A dict of account keywords string (each keyword separated by "|") to account name.
keyword: A keyword string.
Return:
An acco... | 7fa67f75c1b621ca00d87359072c7516b3f097b7 | 33,823 |
def mesh(osi, tag, args):
"""
Create a mesh object. See below for available mesh types... toctree:::maxdepth:
2linemeshtrimeshquadmeshtetmeshpartmeshbgmesh
Parameters
----------
osi: o3seespy.OpenSeesInstance
tag: None
args: None
"""
_parameters = [tag,... | d5e6f4c29381e6ec1eb7307f853eaea740f133f2 | 33,825 |
import re
def expand_contractions(tweet):
"""
Expands language contractions found in the English vocabulary
in the tweet.
INPUT:
tweet: original tweet as a string
OUTPUT:
tweet with its contractions expanded
"""
tweet = re.sub("can't", 'cannot', tweet, flags=re.I)
#twee... | 5ba8fd9b59488935e3a4f49372b6c5d1959537d8 | 33,826 |
import math
import torch
def rand_angles():
"""
random rotation angles
"""
alpha, gamma = 2 * math.pi * torch.rand(2)
beta = torch.rand(()).mul(2).sub(1).acos()
return alpha, beta, gamma | ff1b930989dfc78d4dfec00d569c7c410a3ddcc0 | 33,827 |
def is_correct(dictionary, word):
""" (Open File for reading, str) -> bool
Return True iff word is a correctly-spelled word in dictionary.
Note: due to a PCRS-specific constraint, the example calls below use Open with a capital 'O'.
The actual function has a lowercase 'o'.
>>> dict1 = Open... | 3fc9d0d112ce5ec4f736fa38318f0b14dcd215d5 | 33,828 |
def _closest_ref_length(references, trans_length):
"""Find the reference that has the closest length to the translation.
Parameters
----------
references: list(list(str))
A list of references.
trans_length: int
Length of the translation.
Returns
-------
closest_ref_len:... | aaa5b2f021fc1996d30258af8dbe2ada69bc85aa | 33,829 |
def check_for_comment_block(line, file_type):
"""
:param line:
:param file_type:
:return:
"""
line = line.strip()
if file_type == "py":
return line.startswith('"""') and ('"""' not in line and len(line) > 3)
if file_type in ["java", "js", "jsx", "c", "cpp", "cxx", "h"]:
... | d1ef849cdacb8eef441fb0c6c69f26d28e5cca2a | 33,830 |
def cli_parse(parser):
"""Add method specific options to CLI parser.
Parameters
----------
parser : argparse object
Returns
----------
Updated argparse object
"""
parser.add_argument('--max-order', type=int, required=False, default=2,
choices=[1, 2],
... | c267bb818c8fa317162304c5aa37d02bad63daee | 33,832 |
import socket
def get_ip_addresses(ip_address_or_hostname):
"""
Provide an ip or hostname and return all valid ip4 or ipv6 addresses.
:return: ip addresses
"""
addresses = []
for res in socket.getaddrinfo(ip_address_or_hostname, 0):
addresses.append(res[4][0])
return list(set(addr... | b64cef29932d3166c63faceb196b70a5436806f6 | 33,833 |
from datetime import datetime
def print_stamp():
"""
Pre: User needs nothing to pass in.
Post: Returns a string catalogging the date and time in the format of [month day year, 24hour:minute:seconds]
"""
day = datetime.today()
string = day.strftime("[%b %m, %y, %H:%M:%S]")
return string + "... | d2fc9a83100fa7d39f98e036a594d8dcc0be6f81 | 33,834 |
import pathlib
import json
def save(data: dict, path: pathlib.Path) -> bool:
"""Save a provided dictionary to file in json.
Parameters
----------
data : dict
The dictionary to be saved to file.
path : pathlib.Path
The path to the file to be saved. This path should included the... | e272abbc4e0f4a1193d2bb4ed7b11ed452519daa | 33,835 |
def filter_none(data):
"""Helper function which drop dict items with a None value."""
assert isinstance(data, dict), "Dict only"
out = {key: value for key, value in data.items() if value is not None}
return out | 25c09c878e1e5c25b93d4947937d38f4bf2b965a | 33,836 |
import tqdm
import torch
def mixture_proposal_elbo_samples(num_samples, hier_elbo, checkpoints):
"""Use a mixture of q(nu) distributions as proposals, at many temperatures.
q(nu) = \sum_k \pi_k q_k(nu).
To sample, draw k ~ Categorical(1/K), then draw nu ~ q_k(nu).
"""
raise ValueError('Incorrect: does ... | 5f412720b64b25c245eaed6b6d0d4e18e2238b69 | 33,837 |
def pfunc_doctor_banding(args):
"""Intermediate function, because we can't pass a member function to the
concurrent.futures system (it seems), and can only pass a single parameter,
so we pass the object and the function argument to this (as a single
list)."""
rota = args[0]
doc = args[1]
ret... | f2f33b020852819ab9e827e45600db1533e67216 | 33,838 |
import argparse
def get_parser() -> argparse.ArgumentParser:
"""Returns CLI arguments parser"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"ticket_name", type=str, help="Jira Ticket Number (e.g., BASE-12345)"
)
... | 61266fc5841d0ad09ae03f45686b90bde729925c | 33,840 |
import numpy
def CalculateDelay(start, stop, step, points):
"""Quantizes the time coordinates for the delay.
Quantizes points by rounding the timestamps downwards to the nearest
point in the time sequence start, start+step, start+2*step... Takes
the average of the delays of points rounded to the same. Retu... | d8d5e81a0f46aa2d3ec37777f1a746365666fe3d | 33,841 |
def readData(infile):
"""read data from infile."""
dd = {}
for line in infile:
if line[0] == "#":
continue
d = line[:-1].split("\t")
contig, start, end, score = d[0], int(d[3]), int(d[4]), float(d[5])
# if contig != "I": continue
if contig not in dd:
... | 3ccdfed40b610f452ae1d0e9b4f670e1a71b8b72 | 33,842 |
def _parse_positions(S, M):
"""
returns the index in S of the marker M
"""
all_locations = set()
for index in range(0, len(S)):
if S[index] is M:
all_locations.add(index)
return all_locations | 127c92b73298eb050ba7ff3b101714321b085d80 | 33,844 |
def clean_bulk_add(contents):
"""
A helper function for adding many articles at a time (by uploading a
JSON file of article information). Clean the data, ensure that only
complete entries are included, and add all of the entries to our database.
"""
clean_articles = []
for article in conten... | cca48e35099fa061d6a9198e90aeaab18fdfb704 | 33,845 |
from pathlib import Path
def get_pocket_name(s):
""" For xuefeng generated data files """
s = Path(s).stem
s = str(s)
idx = s.find("_round1_dock_ena+db_fingerprints")
s = s[:idx]
return s | 47d6fe6d07afb18068e74b65f27ec767d3c866ed | 33,846 |
import random
def retrieve(team, year):
"""
Part of the Retriever interface
returns random popularity for the last 10 years for 30 teams.
"""
return random.randint(100,200) | 3b80777c2a4077074b1745e4e8456fafc8db9fa8 | 33,847 |
def _get_synid_dd(syn, cohort, synid_table_prissmm):
"""Get Synapse ID of the most current PRISSMM non-PHI data dictionary for the BPC cohort."""
query = f"SELECT id FROM {synid_table_prissmm} WHERE cohort = '{cohort}' ORDER BY name DESC LIMIT 1"
query_results = syn.tableQuery(query)
synid_folder_pris... | cdd59827e9f8a955d3be4ba9b511b0d37fb145e1 | 33,849 |
from operator import add
def _solve_method_2(N, queries):
"""
This section right here uses some Pythonic optimizations, but they still
don't cut on speed. This at least is much faster I think, assuming each of
these operations is atomic.
"""
arr = [0] * N
largest = -1
for query in qu... | 6daaf01512c18cf17bafe42a9da9de1425ba9b17 | 33,850 |
def max_integer(my_list=[]):
"""
finds the largest integer of a list
"""
if len(my_list) == 0:
return (None)
my_list.sort()
return (my_list[-1]) | d6aa168b1d5207d04761542285bb388c1d235c2b | 33,851 |
def unwrap_twist(twist):
"""
Unwraps geometry_msgs/Twist into two tuples of linear and angular velocities
"""
l_x = twist.linear.x
l_y = twist.linear.y
l_z = twist.linear.z
a_x = twist.angular.x
a_y = twist.angular.y
a_z = twist.angular.z
return (l_x, l_y, l_z), (a_x, a_y, a_z) | 66c4eceeea7791790252ea01c7e8aabe28ea9be0 | 33,852 |
import math
def refract(uv, n, etai_over_etat):
"""
refraction
"""
cos_theta = min(uv.negative().dot(n), 1.0)
r_out_perp = (uv + n.multiply(cos_theta)).multiply(etai_over_etat)
r_out_parallel = n.multiply(-math.sqrt(abs(1.0 - r_out_perp.length_square())))
return r_out_parallel + r_out_per... | 6af8bb5c57518acc432ba040bf1091567664856b | 33,855 |
def _get_axis_pivots_SW(robot_geometry, units='cm'):
"""
Converts robot geometry into -x, -y, -z coordinates of axis pivots
Converts from robot frame to maya frame and converts from mm to cm
Maya Robot
x ----- y
y ----- z
z ----- x
:return axis_pivots: x-y-z loaction of each axi... | 1aece2e330600f81bb2f8c5b8f001c6cd0c8f86e | 33,856 |
def connection_groups(**kwargs):
"""
Called to return the list of groups to automatically add/remove
this connection to/from.
"""
return ["dashboard"] | 32b766fcc7807f6ed68e5d21ed0c8af4552f879d | 33,857 |
def is_x_a_square(x: int) -> bool:
"""Is x a square number?"""
if x == 0:
return False
left = 1
right = x
while left <= right:
mid = left + (right - left) // 2
if mid ** 2 == x:
return True
elif mid ** 2 < x:
left = mid + 1
else:
... | d6587a6e52c5c189e42da06976fb8f2027c9de82 | 33,858 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.