content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def multiply_str(char, times):
"""
Return multiplied character in string
"""
return char * times | cc69f0e16cba1b8c256301567905e861c05291ea | 3,645,500 |
def calories_per_item(hundr, weight, number_cookies, output_type):
"""
>>> calories_per_item(430, 0.3, 20, 0)
'One item has 64.5 kcal.'
>>> calories_per_item(430, 0.3, 20, 1)
'One item has 64.5 Calories.'
>>> calories_per_item(1, 1000, 10, 1)
'One item has 1000.0 Calories.'
>>> calories_... | 9ca16eee8aa8a81424aeaa30f696fb5bec5e3956 | 3,645,501 |
def bitcoind_call(*args):
"""
Run `bitcoind`, return OS return code
"""
_, retcode, _ = run_subprocess("/usr/local/bin/bitcoind", *args)
return retcode | efa585a741da1ba3bf94650de1d7296228c15e7e | 3,645,502 |
def getItemProduct(db, itemID):
"""
Get an item's linked product id
:param db: database pointer
:param itemID: int
:return: int
"""
# Get the one we want
item = db.session.query(Item).filter(Item.id == itemID).first()
# if the query didn't return anything, raise noresult exception
... | fbbd2b2108bba78af1abc4714653065e12906ee3 | 3,645,503 |
from typing import Optional
def find_board(board_id: BoardID) -> Optional[Board]:
"""Return the board with that id, or `None` if not found."""
board = db.session.get(DbBoard, board_id)
if board is None:
return None
return _db_entity_to_board(board) | 16f687304d1008b3704d641a7e9e5e624475e045 | 3,645,504 |
from typing import Any
def test_isin_pattern_0():
"""
Test IsIn pattern which expresses the IsIn/OneOf semantics.
"""
inputs = Tensor(np.ones([42]), mindspore.float16)
softmax_model = nn.Softmax()
@register_pass(run_only_once=True)
def softmax_relu_pass():
x = Any()
softma... | 78e169fcab894c3cf7956884bd3553983fda5bae | 3,645,505 |
from datetime import datetime
def ENsimtime():
"""retrieves the current simulation time t as datetime.timedelta instance"""
return datetime.timedelta(seconds= _current_simulation_time.value ) | 4dd971b3af9d0a2544e809ea7726521d9ce8e5b1 | 3,645,506 |
def solar_true_longitude(solar_geometric_mean_longitude, solar_equation_of_center):
"""Returns the Solar True Longitude with Solar Geometric Mean Longitude,
solar_geometric_mean_longitude, and Solar Equation of Center,
solar_equation_of_center."""
solar_true_longitude = solar_geometric_mean_longitude +... | a335bb82002846eb2bc2106675c13e9f3ee28900 | 3,645,507 |
import base64
def image_to_fingerprint(image, size=FINGERPRINT_SIZE):
"""Create b64encoded image signature for image hash comparisons"""
data = image.copy().convert('L').resize((size, size)).getdata()
return base64.b64encode(bytes(data)).decode() | 83ff567bce0530b69a9b43c40ea405af825831ff | 3,645,508 |
from datetime import datetime
import pandas
def get_indices(
time: str | datetime | date, smoothdays: int = None, forcedownload: bool = False
) -> pandas.DataFrame:
"""
alternative going back to 1931:
ftp://ftp.ngdc.noaa.gov/STP/GEOMAGNETIC_DATA/INDICES/KP_AP/
20 year Forecast data from:
http... | e8880caac96e9b3333c2f1f557b5918ee40cdbbe | 3,645,509 |
import argparse
def get_args():
"""Get CLI arguments and options
:return: AccuRev branch, git repository location, append option boolean
"""
parser = argparse.ArgumentParser(description='Migrate AccuRev branch history to git')
parser.add_argument('accurevBranch', help='The AccuRev branch which wi... | cb90769315ddce080c3eb9e234f8f7a569a546e2 | 3,645,510 |
import json
def check(device, value):
"""Test for valid setpoint without actually moving."""
value = json.loads(value)
return zmq_single_request("check_value", {"device": device, "value": value}) | f08e80348f97531ed51207aff685a470ca62bc41 | 3,645,511 |
import sys
def prove(formula, verbose):
"""
:param formula: String representation of a modal formula.
The syntax for such a formula is per the grammar as stipulated in the README.
Example input: "(a|b) & (~c => d)"
:return string showing the outcome of the proof, that is valid or not valid.
"... | 280570027016d5d285caae6610b0be8d39e6252c | 3,645,512 |
def get_projectID(base_url, start, teamID, userID):
"""
Get all the project from jama
Args:
base_url (string): jama instance base url
start (int): start at a specific location
teamID (string): user team ID, for OAuth
userID (string): user ID, for OAuth
Returns:
(... | 92deaf007530b67be6459c7fd0a0e196dbe18216 | 3,645,513 |
def to_world(points_3d, key2d, root_pos):
""" Trasform coordenates from camera to world coordenates """
_, _, rcams = data_handler.get_data_params()
n_cams = 4
n_joints_h36m = 32
# Add global position back
points_3d = points_3d + np.tile(root_pos, [1, n_joints_h36m])
# Load the appropriat... | 9b56b946569dac35231282009389a777e908d09f | 3,645,514 |
def orbital_energies_from_filename(filepath):
"""Returns the orbital energies from the given filename through
functional composition
:param filepath: path to the file
"""
return orbital_energies(spe_list(
lines=list(content_lines(filepath, CMNT_STR)))) | 669bfbe18bb8686e2f9fdc89dcdb3a36aeec6940 | 3,645,515 |
def _dict_merge(a, b):
""" `_dict_merge` deep merges b into a and returns the new dict.
"""
if not isinstance(b, dict):
return b
result = deepcopy(a)
for k, v in b.items():
if k in result and isinstance(result[k], dict):
result[k] = _dict_merge(result[k], v)
else:... | 278bfa6f8895fda0ae86b0ff2014602a7e9225df | 3,645,516 |
import stat
import functools
import operator
def flags(flags: int, modstring: str) -> int:
""" Modifies the stat flags according to *modstring*, mirroring the syntax for POSIX `chmod`. """
mapping = {
'r': (stat.S_IRUSR, stat.S_IRGRP, stat.S_IROTH),
'w': (stat.S_IWUSR, stat.S_IWGRP, stat.S_IWOTH),
'x... | 9acfeb4d9b90a12d2308c0ec992cfbb47f11000c | 3,645,517 |
def _can_contain(ob1, ob2, other_objects, all_obj_locations, end_frame,
min_dist):
""" Return true if ob1 can contain ob2. """
assert len(other_objects) == len(all_obj_locations)
# Only cones do the contains, and can contain spl or smaller sphere/cones,
# cylinders/cubes are too large
... | 391119dae5e86efe0c99bae7c603a1f785c69c04 | 3,645,518 |
def twolmodel(attr, pulse='on'):
"""
This is the 2-layer ocean model
requires a forcing in W/m2
pulse = on - radiative pulse W/m2
pulse = off - time varyin radaitive forcing W/m2/yr
pulse = time - use output from simple carbon model
"""
#### Parameters ####
yeartosec = 30.25*24*60*6... | 4f6649a8df1febe54a6c04fdee938591a0c997b2 | 3,645,519 |
def maximumToys(prices, k):
"""Problem solution."""
prices.sort()
c = 0
for toy in prices:
if toy > k:
return c
else:
k -= toy
c += 1
return c | 0ce709ff7b106b5379217cb6b7f1f481d27c94e7 | 3,645,520 |
import os
import pprint
import errno
def batch_process(process, **kwargs):
"""Runs a process on a set of files and batches them into subdirectories.
Arguments:
process ((IN, OUT, Verbosity) -> str): The function to execute on each
file.
Keyword Arguments:
file (Optional[str])... | 24ba57f463f48f2d2ada56d4c6fff848a1c45f10 | 3,645,521 |
def get_X_HBR_d_t_i(X_star_HBR_d_t):
"""(47)
Args:
X_star_HBR_d_t: 日付dの時刻tにおける負荷バランス時の居室の絶対湿度(kg/kg(DA))
Returns:
日付dの時刻tにおける暖冷房区画iの実際の居室の絶対湿度(kg/kg(DA))
"""
X_star_HBR_d_t_i = np.tile(X_star_HBR_d_t, (5, 1))
return X_star_HBR_d_t_i | 125d70ff96ce1a035df98d6995aa55ea3728ffa9 | 3,645,522 |
from typing import Optional
from typing import Dict
from typing import Callable
from typing import Any
def add_route(url: str,
response: Optional[str] = None,
method: str = 'GET',
response_type: str = 'JSON',
status_code: int = 200,
headers: Option... | f103b6d6faffff4a816fdf7c3c0124ea41622fe1 | 3,645,523 |
def findUsername(data):
"""Find a username in a Element
Args:
data (xml.etree.ElementTree.Element): XML from PMS as a Element
Returns:
username or None
"""
elem = data.find('User')
if elem is not None:
return elem.attrib.get('title')
return None | f7b6bb816b9eeeca7e865582935a157cdf276928 | 3,645,524 |
import argparse
from typing import Union
def preprocess_config_factory(args: argparse.Namespace, ref_paths: dict,
dataset_type: str) -> Union[BratsConfig, CamCanConfig, IBSRConfig, CANDIConfig, IXIConfig]:
"""Factory method to create a pre-processing config based on the parsed comman... | fdd96ac09bc6b86801ea39956a7d456a380ed546 | 3,645,525 |
def GET(request):
"""Get this Prefab."""
request.check_required_parameters(path={'prefabId': 'string'})
prefab = Prefab.from_id(request.params_path['prefabId'])
prefab.check_exists()
prefab.check_user_access(request.google_id)
return Response(200, 'Successfully retrieved prefab', prefab.obj) | 07a7078cb73893309372c0a8d48857eefc77a41e | 3,645,526 |
def fix_empty_strings(tweet_dic):
"""空文字列を None に置換する"""
def fix_media_info(media_dic):
for k in ['title', 'description']:
if media_dic.get('additional_media_info', {}).get(k) == '':
media_dic['additional_media_info'][k] = None
return media_dic
for m in tweet_dic... | 436daaeb9b96b60867d27812ed7388892ab79b1a | 3,645,527 |
import json
def group_joinrequest(request, group_id):
"""
Handle post request to join a group.
"""
if not request.is_ajax() or request.method != 'POST':
raise Http404
result = {}
content_type = 'application/json; charset=utf-8'
group_id = int(group_id)
group = get_group(group... | befa5d7e64f1fde3be4c4e589e7c6ed3fdec8b7e | 3,645,528 |
import math
def fibonacci(**kwargs):
"""Fibonacci Sequence as a numpy array"""
n = int(math.fabs(kwargs.pop('n', 2)))
zero = kwargs.pop('zero', False)
weighted = kwargs.pop('weighted', False)
if zero:
a, b = 0, 1
else:
n -= 1
a, b = 1, 1
result = np.array([a])
... | 055d157120866c9bfe74374d62cffcc8f599d4bb | 3,645,529 |
def read_data():
"""Reads in the data from (currently) only the development file
and returns this as a list. Pops the last element, because it is empty."""
with open('../PMB/parsing/layer_data/4.0.0/en/gold/dev.conll') as file:
data = file.read()
data = data.split('\n\n')
data.pop(-... | da75e237bbc7b2168cd5af76eefaf389b29d4b30 | 3,645,530 |
def argrelextrema(data, comparator, axis=0, order=1, mode='clip'):
"""
Calculate the relative extrema of `data`.
Parameters
----------
data : ndarray
Array in which to find the relative extrema.
comparator : callable
Function to use to compare two data points.
Should tak... | 66d565fad5672615f1340979a3c59e5abbbab3f5 | 3,645,531 |
import math
def dijkstra(G, s):
"""
find all shortest paths from s to each other vertex in graph G
"""
n = len(G)
visited = [False]*n
weights = [math.inf]*n
path = [None]*n
queue = []
weights[s] = 0
hq.heappush(queue, (0, s))
while len(queue) > 0:
g, u = hq.heap... | 85069b177ac646f449ce8e3ccf6d9c5b9de7b2e3 | 3,645,532 |
def prepare_create_user_db():
"""Clear a user from the database to be created."""
username = TEST_USERS[0][0]
connection = connect_db()
connection.cursor().execute('DELETE FROM Users WHERE username=%s',
(username,))
connection.commit()
close_db(connection)
ret... | beb1fd7a7f6c571f9d5e57a79d3b15c62a215789 | 3,645,533 |
def _getlocal(ui, rpath):
"""Return (path, local ui object) for the given target path.
Takes paths in [cwd]/.hg/hgrc into account."
"""
try:
wd = os.getcwd()
except OSError, e:
raise util.Abort(_("error getting current working directory: %s") %
e.strerror)
... | 4dc90dc62084e13c22b1a602fa20c552557e258c | 3,645,534 |
import hashlib
def get_size_and_sha256(infile):
"""
Returns the size and SHA256 checksum (as hex) of the given file.
"""
h = hashlib.sha256()
size = 0
while True:
chunk = infile.read(8192)
if not chunk:
break
h.update(chunk)
size += len(chunk)
... | 32c37ca6762f9c62d806e22c991b60f9d60947f4 | 3,645,535 |
def cmServiceAbort():
"""CM SERVICE ABORT Section 9.2.7"""
a = TpPd(pd=0x5)
b = MessageType(mesType=0x23) # 00100011
packet = a / b
return packet | 1ae9744fd21760775a45066ffeb11d7dea12c127 | 3,645,536 |
def get_distribution(distribution_id):
"""
Lists inforamtion about specific distribution by id.
:param distribution_id: Id of CDN distribution
"""
cloudfront = CloudFront()
return cloudfront.get_distribution(distribution_id=distribution_id) | 082c572341435423cb42ec895369af7822caee80 | 3,645,537 |
import sqlite3
def get_information_per_topic(db_path: str, topic: str, field: str):
""" Query all alert data monitoring rows for a given topic
Parameters
----------
db_path: str
Path to the monitoring database. The database will be created if
it does not exist yet.
topic: str
... | 97e95942506d15f1604d026c2a9954408ea01c29 | 3,645,538 |
from sys import prefix
def gripper_client(finger_positions):
"""Send a gripper goal to the action server."""
action_address = '/' + prefix + 'driver/fingers_action/finger_positions'
client = actionlib.SimpleActionClient(action_address,
kinova_msgs.msg.SetFingersPo... | eb22363d63b84bcd14e8cf17317d2c1780db7167 | 3,645,539 |
import re
from datetime import datetime
import numpy
def validate_column(column_name,value,lookup_values):
"""Validates columns found in Seq&Treat tuberculosis AST donation spreadsheets.
This function understands either the format of a passed column or uses values
derived from lookup Pandas dataframes to... | a84df7f80e9e146f742f4d25050bfd4591a0c5cf | 3,645,540 |
def get_html_from_url(url, timeout=None):
"""Get HTML document from URL
Parameters
url (str) : URL to look for
timeout (float) : Inactivity timeout in seconds
Return
The HTML document as a string
"""
resp = reqget(url, timeout=timeout)
return resp.text | f909db702c812be029f00dd73bfaef8ac48966ba | 3,645,541 |
def clean(column, output_column=None, file_path=None, df=None, symbols='!@#$%^&*()+={}[]:;’\”/<>',
replace_by_space=True, keep_original=False):
"""
cleans the cell values in a column, creating a new column with the clean values.
Args:
column: the column to be cleaned.
output_colum... | 575d30a704c9ad37c027251ef609ef9c70445139 | 3,645,542 |
def len_lt(name, value):
"""
Only succeed if the length of the given register location is less than
the given value.
USAGE:
.. code-block:: yaml
foo:
check.len_lt:
- value: 42
run_remote_ex:
local.cmd:
- tgt: '*'
- func: tes... | fde2db2e73d7ac711677b33518b6d5342b5dcbdb | 3,645,543 |
from typing import Iterable
def _ll_to_xy(latitude, longitude, wrfin=None, timeidx=0,
stagger=None, method="cat", squeeze=True, cache=None,
_key=None, as_int=True, **projparams):
"""Return the x,y coordinates for a specified latitude and longitude.
The *latitude* and *longitude* a... | 9d96d0d6e520731f16079c69389eff0c47c70dce | 3,645,544 |
def onedsinusoid(x,H,A,omega,phi):
"""
Returns a 1-dimensional sinusoid of form
H+A*np.sin(omega*x+phi)
"""
phi = np.pi/180 * phi
return H+A*np.sin(omega*x+phi) | 9917b462a6cd39c84a354d031ad8c6a09afcdec0 | 3,645,545 |
def _make_wrapper_func(func_name):
"""
make_eus_instance()から呼ばれるEus_pkgクラスコンストラクタにて、eusの関数名のエントリからラッパー関数を作成する際の補助関数。
引数部の構築は_translate_args()を用いて行う。
Args:
func_name (str): もとのEuslispでの関数名でpkg::を含む。なお、関数は内部シンボルと仮定している。(exportされてたら外部シンボルアクセス:(1個)を使わなければならない)。
Returns:
wrapper (functio... | 34bf7d930129432be50a7ddada6641bf6d8eea0e | 3,645,546 |
def number_in_english(number):
"""Returns the given number in words
>>> number_in_english(0)
'zero'
>>> number_in_english(5)
'five'
>>> number_in_english(11)
'eleven'
>>> number_in_english(745)
'seven hundred and fourty five'
>>> number_in_english(1380)
'one thousand three hu... | b3d580ed843d5d4bf3c62662c831391536e7479e | 3,645,547 |
def create_app(environment):
"""Factory Method that creates an instance of the app with the given config.
Args:
environment (str): Specify the configuration to initilize app with.
Returns:
app (Flask): it returns an instance of Flask.
"""
app = Flask(__name__)
app.config.from_obj... | 5cd5867a80ec696ee2a5647448c8e8b60fe2e023 | 3,645,548 |
def heating_design_temp(tmy_id):
"""Returns the heating design temperature (deg F) for the TMY3 site
identified by 'tmy_id'.
"""
return df_tmy_meta.loc[tmy_id].heating_design_temp | 204e219840ed5d2e04e9bb53706883d0fc1c6cfa | 3,645,549 |
def tonal_int(x):
"""
>>> tonal_int((4,7))
7
>>> tonal_int((4,7,2))
31
>>> tonal_int((6,11,-1))
-1
>>> tonal_int((0,-1,-1))
-13
>>> tonal_int((6,0,0))
12
>>> tonal_int((0,11,0))
-1
>>> tonal_int((0,11))
-1
>>> tonal_int((2, 0))
0
"""
i... | c7fb8dfd7ac5c82a81241efb807a7e45b877eee4 | 3,645,550 |
import re
import warnings
def read_vcf(vcf_file, gene_filter=None, experimentalDesig=None):
"""
Reads an vcf v4.0 or 4.1 file and generates :class:`~epytope.Core.Variant.Variant` objects containing
all annotated :class:`~epytope.Core.Transcript.Transcript` ids an outputs a list :class:`~epytope.Core.Varia... | d277369ff340ddb7adefdb70009b69a3d1f5c533 | 3,645,551 |
def sqrtmod(a, p):
"""
Returns a square root of a modulo p.
Input:
a -- an integer that is a perfect
square modulo p (this is checked)
p -- a prime
Output:
int -- a square root of a, as an integer
between 0 and p-1.
Examples:
>>> sqrtmod(4, 5)... | 638481b8d42b9047df1dbd3a8f964762baab783e | 3,645,552 |
def DrtVariableExpression(variable):
"""
This is a factory method that instantiates and returns a subtype of
``DrtAbstractVariableExpression`` appropriate for the given variable.
"""
if is_indvar(variable.name):
return DrtIndividualVariableExpression(variable)
elif is_funcvar(variable.na... | a37b6e3f295e603d4ee78007dc4d4a22d22d1c3f | 3,645,553 |
def process_cv_results(cv_results):
"""
This function reformats the .cv_results_ attribute of a fitted randomized
search (or grid search) into a dataframe with only the columns we care
about.
Args
--------------
cv_results : the .cv_results_ attribute of a fitted randomized search
(or g... | a47b9cbc3fcb00f782eb46269f55259995d4b73c | 3,645,554 |
def cbow(currentWord, C, contextWords, tokens, inputVectors, outputVectors,
dataset, word2vecCostAndGradient = softmaxCostAndGradient):
""" CBOW model in word2vec """
# Implement the continuous bag-of-words model in this function.
# Input/Output specifications: same as the skip-gram model
# We will... | 5766b3c2facba8272431796b46da8abbd7264292 | 3,645,555 |
import yaml
def generate_dlf_yaml(in_yaml):
"""
Generate DLF-compatible YAML configuration file using
"templates/dlf_out.yaml" as template.
:param in_yaml: dict representation of a YAML document defining
placeholder values in "templates/dlf_out.yaml"
:type in_yaml: dict
:raises Placeholde... | c3bdf86731eb26904cae95b65c5b6181cc130ae8 | 3,645,556 |
def dice_coefficient(x, target):
"""
Dice Loss: 1 - 2 * (intersection(A, B) / (A^2 + B^2))
:param x:
:param target:
:return:
"""
eps = 1e-5
n_inst = x.size(0)
x = x.reshape(n_inst, -1)
target = target.reshape(n_inst, -1)
intersection = (x * target).sum(dim=1)
union = (x *... | c73cd86ed11bf89d94fb84db16186d6ace39d814 | 3,645,557 |
def batch_intersection_union(output, target, nclass):
"""mIoU"""
# inputs are numpy array, output 4D, target 3D
predict = np.argmax(output, axis=1) + 1 # [N,H,W]
target = target.astype(float) + 1 # [N,H,W]
predict = predict.astype(float) * np.array(target > 0).astype(float)
intersection = pre... | a62596ee500ec7525ceefeb6e6de0fd6673c522d | 3,645,558 |
import torch
def convert(trainset,testset,seed=1,batch_size=128, num_workers=2,pin_memory=True):
"""
Converts DataSet Object to DataLoader
"""
SEED = 1
cuda = torch.cuda.is_available()
torch.manual_seed(SEED)
if cuda:
torch.cuda.manual_seed(SEED)
dataloader_args = dict(shuffle=True, batch_size=128, num_w... | c380caa064b07ffc108ae33acc98361910b8f28f | 3,645,559 |
def build_gradcam(img_path, heatmap, color_map, original_image_colormap, alpha=0.5):
"""
Builds the gradcam.
Args:
img_path (_type_): Image path.
heatmap (_type_): Heatmap.
color_map (_type_): Color map.
original_image_colormap (_type_): Original image colormap.
alpha (float... | c71c24cc3fccc962b1083c1491e8da0fae9464ed | 3,645,560 |
def sample_joint_comorbidities(age, country):
"""
Default country is China.
For other countries pass value for country from {us, Republic of Korea, japan, Spain, italy, uk, France}
"""
return sample_joint(age, p_comorbidity(country, 'diabetes'), p_comorbidity(country, 'hypertension')) | 8190e73ccd637b78270a974773259c9bb4367fd5 | 3,645,561 |
def generate_tsdf_3d_ewa_image(depth_image, camera,
camera_extrinsic_matrix=np.eye(4, dtype=np.float32),
field_shape=np.array([128, 128, 128]), default_value=1,
voxel_size=0.004,
array_offset=np.a... | a7665434e58e3485af6a2f4124d9707b2a67f4b9 | 3,645,562 |
import pydoc
def locate(name):
"""
Locate the object for the given name
"""
obj = pydoc.locate(name)
if not obj:
obj = globals().get(name, None)
return obj | 24f31b241ffcbd2e983889f209bff9a1ff8b1fc3 | 3,645,563 |
from stentseg.utils import PointSet
from stentseg.utils.centerline import points_from_mesh
def get_mesh_deforms(mesh, deforms, origin, **kwargs):
"""
input : mesh object
deforms forward for mesh?!
origin (from volume)
output: PointSet of mesh vertices (duplicates removed) and list ... | 710530c68d46e03d14eabc83db1fa448e76ebc2e | 3,645,564 |
import argparse
def parse_args():
"""parse args for binlog2sql"""
parser = argparse.ArgumentParser(description='Parse MySQL binlog to SQL you want', add_help=False)
connect_setting = parser.add_argument_group('connect setting')
connect_setting.add_argument('-h', '--host', dest='host', type=str,
... | e6ef917b97ea15097b30684a1069ea1c74b16064 | 3,645,565 |
def lnLikelihoodDouble(parameters, values, errors, weights=None):
"""
Calculates the total log-likelihood of an ensemble of values, with
uncertainties, for a double Gaussian distribution (two means and
two dispersions).
INPUTS
parameters : model parameters (see below)
value... | a387d0f8c52b380c57c4cd86ba06111c187db7b8 | 3,645,566 |
import urllib
def moleculeEntry(request, adjlist):
"""
Returns an html page which includes the image of the molecule
and its corresponding adjacency list/SMILES/InChI, as well
as molecular weight info and a button to retrieve thermo data.
Basically works as an equivalent of the molecule search fu... | 6a53812894b7150fc76444238597e8038f8ffa0c | 3,645,567 |
def has_user_id(id: int):
"""Checks if the Command Author's ID is the same as the ID passed into the function"""
def predicate(ctx) -> bool:
if ctx.author.id == id:
return True
raise MissingID(id, "Author")
return commands.check(predicate) | e83fff93f6ef3ebc06ebadc3470b1e74a18b3a39 | 3,645,568 |
def _polar_gbps(out, in_args, params, per_iter=False):
""" `speed_function` for `benchmark` estimating the effective bandwidth
of a polar decomposition in GB/s. The number of elements is estimated as
2 * the size of the input.
For a matrix multiplication of dimensions `m, n, k` that
took `dt` seconds, we defi... | a0428dfc9df6c4dd7f9d25712c3894d71bcd1700 | 3,645,569 |
def is_FreeMonoid(x):
"""
Return True if `x` is a free monoid.
EXAMPLES::
sage: from sage.monoids.free_monoid import is_FreeMonoid
sage: is_FreeMonoid(5)
False
sage: is_FreeMonoid(FreeMonoid(7,'a'))
True
sage: is_FreeMonoid(FreeAbelianMonoid(7,'a'))
... | d4fae223bcdec1f365406b9fb3c546f56db38565 | 3,645,570 |
import requests
def get_quote_data(ticker):
"""Inputs: @ticker
Returns a dictionary containing over 70 elements corresponding to the
input ticker, including company name, book value, moving average data,
pre-market / post-market price (when applicable), and more."""
site = "https://query1.finance.... | a23d7e091547ceca3c66f0ae90e84ea9f89d4e1c | 3,645,571 |
from typing import Dict
import click
def _import_stack_component(
component_type: StackComponentType, component_config: Dict[str, str]
) -> str:
"""import a single stack component with given type/config"""
component_type = StackComponentType(component_type)
component_name = component_config.pop("name"... | ec03abab6b005f5047dd7963ab93b83f4f891140 | 3,645,572 |
def unpack_range(a_range):
"""Extract chromosome, start, end from a string or tuple.
Examples::
"chr1" -> ("chr1", None, None)
"chr1:100-123" -> ("chr1", 99, 123)
("chr1", 100, 123) -> ("chr1", 100, 123)
"""
if not a_range:
return Region(None, None, None)
if isinsta... | f44b6069eb5e0fc8c85f01d5cbe708667a09a005 | 3,645,573 |
import torch
def _old_extract_roles(x, roles):
"""
x is [N, B, R, *shape]
roles is [N, B]
"""
N, B, R, *shape = x.shape
assert roles.shape == (N, B)
parts = []
for n in range(N):
parts.append(x[n:n+1, range(B), roles[n]])
return torch.cat(parts, dim=0) | 07a7be138558baa28ab1a10e2be2c7f17501ae96 | 3,645,574 |
import os
def read_cam_intr(file_path):
"""Reading camera intrinsic.
Args:
file_path (str): File path.
Return:
k (numpy.array): Camera intrinsic matrix, dim = (3, 3).
"""
assert os.path.exists(file_path), '{}: file not found'.format(file_path)
f = open(file_path, 'r')
k_str = f.readlines(... | 431569a6e1c061214546f89962a2c5ed8c90213d | 3,645,575 |
def setup(i):
"""
See "install" API with skip_process=yes
"""
i['skip_process']='yes'
return install(i) | d4478adc27e444ac43dc9b4c8cd999157555c831 | 3,645,576 |
import requests
def post_merge_request(profile, payload):
"""Do a POST request to Github's API to merge.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``t... | 26131ac3dc078a9e33b7b2b785a71c51ec1d9072 | 3,645,577 |
def is_valid_table_name(cur, table_name):
"""
Checks whether a name is for a table in the database.
Note: Copied from utils.database for use in testing, to avoid
a circular dependency between tests and implementation.
Args:
cur: sqlite3 database cursor object
table_name (str): name t... | f1efc66220baa215a73f374da19842ab38c619be | 3,645,578 |
def create_mssql_pyodbc(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pyodbc.
"""
return create_engine(
_create_mssql_pyodbc(username, password, host, port, database),
**kwargs
) | dac74a0c32f1c693eb059d6a61f84d2288651969 | 3,645,579 |
def _wait_for_multiple(driver,
locator_type,
locator,
timeout,
wait_for_n,
visible=False):
"""Waits until `wait_for_n` matching elements to be present (or visible).
Returns located elements when fo... | d96c10d95877d699f8b284ea41e8b8ef5aebbf3c | 3,645,580 |
def relu(x):
"""
x -- Output of the linear layer, of any shape
Returns:
Vec -- Post-activation parameter, of the same shape as Z
cash -- for computing the backward pass efficiently
"""
Vec = np.maximum(0, x)
assert(Vec.shape == x.shape)
cash = x
return Vec, cash | 1d94d3008aca7ab613dfa92504061264111f1c28 | 3,645,581 |
def _declare_swiftdoc(
*,
actions,
arch,
label_name,
output_discriminator,
swiftdoc):
"""Declares the swiftdoc for this Swift framework.
Args:
actions: The actions provider from `ctx.actions`.
arch: The cpu architecture that the generated swiftdoc... | 589828527b8fe775aafca8fb1bee677d716a88c6 | 3,645,582 |
def threshold_image(gray_image, name_bw, threshold):
"""
This computes the binary image of the input image using a threshold
:param gray_image: input image
:param threshold: input threshold
:param name_bw: name of the binary image
:return: BW image
"""
# perform Gaussian blurring to re... | 98c14281a322b110594e12a4e2b10016a8d6533f | 3,645,583 |
def kalman_update(
states,
upper_chols,
loadings,
control_params,
meas_sd,
measurements,
controls,
log_mixture_weights,
debug,
):
"""Perform a Kalman update with likelihood evaluation.
Args:
states (jax.numpy.array): Array of shape (n_obs, n_mixtures, n_states) with
... | d44eb03c9b99e288abf0103abfdbf83eec7f9df2 | 3,645,584 |
import re
def sub_repeatedly(pattern, repl, term):
"""apply sub() repeatedly until no change"""
while True:
new_term = re.sub(pattern, repl, term)
if new_term == term:
return term
term = new_term | e57c648fb057f81e35e0fc2d2dc57edd0b400baf | 3,645,585 |
from typing import Tuple
def _dtw(distance_matrix: np.ndarray, gully: float = 1., additive_penalty: float = 0.,
multiplicative_penalty: float = 1.) -> Tuple[np.ndarray, np.ndarray, float]:
"""
Compute the dynamic time warping distance between two sequences given a distance matrix.
DTW score of lo... | 388b070d4bd2bbca42371b85d27f0807f86ae09b | 3,645,586 |
async def _ensure_meadowgrid_security_groups() -> str:
"""
Creates the meadowgrid coordinator security group and meadowgrid agent security
group if they doesn't exist. The coordinator security group allows meadowgrid agents
and the current ip to access the coordinator, as well as allowing the current ip... | b0fc2c0e1fb767c5cfbb365d0c58cf39d327caf3 | 3,645,587 |
def _create_pairs_numba(
to_match, indexer, first_stage_cum_probs, group_codes_per_individual, seed
):
"""
Args:
to_match (np.ndarry): 2d boolean array with one row per individual
and one column sub-contact model.
indexer (numba.List): Numba list that maps id of county to a numpy... | 5c7bed67a644104dc7b22b79d3858fc5e27cf14d | 3,645,588 |
def test_set_attr():
"""
Tests that generate_schema returns a schema that has the ability to
set instance variables based on keys of different format in the
dictionary provided in schema.load(d)
"""
class TestObject(object):
def __init__(self):
super().__init__()
... | 7b12cef9864f6e9d8e6a9d18cb486bbce8812c5e | 3,645,589 |
def filter_known_bad(orbit_points):
"""
Filter some commands that are known to be incorrect.
"""
ops = orbit_points
bad = np.zeros(len(orbit_points), dtype=bool)
bad |= (ops['name'] == 'OORMPEN') & (ops['date'] == '2002:253:10:08:52.239')
bad |= (ops['name'] == 'OORMPEN') & (ops['date'] == '... | c8f64b541be5d2f7fce3554dc83c7f36ee8bc0a4 | 3,645,590 |
def create_lexicon(word_tags):
"""
Create a lexicon in the right format for nltk.CFG.fromString() from
a list with tuples with words and their tag.
"""
# dictionary to filter the double tags
word_dict = {}
for word, tag in word_tags:
if tag not in word_dict:
word_dict[ta... | 3a91671d559f5924ec9326520db6e11a1672fee4 | 3,645,591 |
import glob
import os
import re
import requests
from datetime import datetime
import shutil
def process_datasets_metadata(input_file=None, dryrun=True, staging=True, sample=0, report=False, memory='4g', rmlstreamer_run=False):
"""Read a RDF metadata file with infos about datasets, check if the dataset exist in th... | 16d54395cf7a37bcc98a56696bd6b942979f0140 | 3,645,592 |
def display_time(seconds, granularity=2):
"""Display time as a nicely formatted string"""
result = []
if seconds == 0:
return "0 second"
for name, count in intervals:
value = seconds // count
if value:
seconds -= value * count
if value == 1:
... | d8fe16585a66d085a08941b7b038d448fee23570 | 3,645,593 |
def reciprocal(x):
"""
Returns the reciprocal of x.
Args:
x (TensorOp): A tensor.
Returns:
TensorOp: The reciprocal of x.
"""
return ReciprocalOp(x) | 3678efa2d69948e85ccaae43f34492783a77cef9 | 3,645,594 |
from typing import Callable
from typing import Iterable
def get_protocol(remote_debugging_url: str, request_json: Callable[[str], Iterable]):
""" The current devtools protocol, as JSON """
return request_json(f"{remote_debugging_url}/json/protocol") | eaca70f6115a9091f2e35452cae4eb6b22cfdb18 | 3,645,595 |
def csv_saver_parser():
"""
Csv saver parser. Returns tuple with args as dictionary
and sufix that needs to be removed.
:return: tuple
"""
csv_saver_parser = ArgumentParser(description='Parser for saving data into CSV files.')
csv_saver_parser.add_argument('--F-csvsave',
... | d98fd53217eafa24826df56e114720a7881f17bb | 3,645,596 |
def get_var(expr: Expression) -> Var:
"""
Warning: this in only true for expressions captured by a match statement.
Don't call it from anywhere else
"""
assert isinstance(expr, NameExpr)
node = expr.node
assert isinstance(node, Var)
return node | f8bec4c919858f6aaa5126fc4e55f825f2ca677c | 3,645,597 |
def sight(unit_type: int):
"""Return the sight range of a unit, given its unit type ID
:param unit_type: the unit type ID, according to :mod:`pysc2.lib.stats`
:type unit_type: int
:return: the unit's sight range
:rtype: float
"""
return __data['Sight'][unit_type] | 84c3b8fdbfaaede81e7abc10cc190830df9e2c86 | 3,645,598 |
def decode_jwt(encoded_jwt):
"""
解码jwt
"""
global key
# 注意当载荷里面申明了 aud 受众的时候,解码时需要说明
decoded_jwt = jwt.decode(encoded_jwt, key, audience='dev', algorithms=["HS256"])
return decoded_jwt | 467bfcce7c5264813ab57f420da277b7674976db | 3,645,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.