content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def max_sum_naive(arr: list, length: int, index: int, prev_max: int) -> int:
"""
We can either take or leave the current number depending on previous max number
"""
if index >= length:
return 0
cur_max = 0
if arr[index] > prev_max:
cur_max = arr[index] + max_sum_naive(arr, lengt... | 644b5cb294e78a10add253cad96d3c3e2c3d67d7 | 3,636,500 |
import torch
def accuracy(X, X_ref):
""" Compute classification accuracy.
Parameters
----------
X : torch.Tensor
The classification score tensor of shape [..., num_classes]
X_ref : torch.Tensor
The target integer labels of shape [...]
Returns
-------
The average accua... | a62adda146de6573cdc190b636b0269852604608 | 3,636,501 |
import requests
def download_dataset(filepath=DATASET_PATH, url=DATASET_URL, **kwargs) -> pd.DataFrame:
"""
Download dataset
:param: file Output filename
"""
kwargs.setdefault("session", requests.Session())
r = kwargs['session'].get(url)
# Jos lataus epäonnistuu, epäonnistu nyt.
#... | 83cde597622e7708b90fc789c42925fcc0c8c00a | 3,636,502 |
from datetime import datetime
import uuid
def create_cert_builder(subject, issuer_name, public_key, days=365, is_ca=False):
"""
The method to create a builder for all types of certificates.
:param subject: The subject of the certificate.
:param issuer_name: The name of the issuer.
:param public_ke... | 04739a7b81c3e4b6d70bba96e646e64c2d5fdbb7 | 3,636,503 |
def _table_row(line):
"""
Return all elements of a data line.
Return all elements of a data line. Simply splits it.
Parameters
----------
line: string
A stats line.
Returns
-------
list of strings
A list of strings, containing the data on the line, split at white s... | dc5d76db80059b0da257b45f12513d75c2765d55 | 3,636,504 |
def ack_alert_alarm_definition(definition_id):
""" Acknowledge all alert(s) or an alarm(s) associated with the definition identified by definition_id.
"""
try:
# Get definition identified in request
definition = SystemEventDefinition.query.get(definition_id)
if definition is None:
... | 6b15f6019fad506937ed0bcc0c6eeb34ce21faf4 | 3,636,505 |
def range2d(range_x, range_y):
"""Creates a 2D range."""
range_x = list(range_x)
return [ (x, y) for y in range_y for x in range_x ] | ca33799a277f0f72e99836e81a7ffc98b191fc37 | 3,636,506 |
def kmeans_(X, sample_weights, n_clusters, init='kmeans++', max_iter=300):
"""
Weighted K-Means implementation (Lloyd's Algorithm).
:param X:
:param sample_weights:
:param n_clusters:
:param init: string in {'random', 'kmeans++'}, default 'kmeans++'
:param max_iter: maximum number of iterati... | 7c62df5c98312d1f2372939d28fecf632fd0c45b | 3,636,507 |
import os
def CPCT_LambdaPitch(refdir,main_fastfile,Lambda=None,Pitch=np.linspace(-10,40,5),WS=None,Omega=None, # operating conditions
TMax=20,bStiff=True,bNoGen=True,bSteadyAero=True, # simulation options
reRun=True,
fastExe=None,showOutputs=True,nCores=4): # execution options
""" ... | 8013e10fe68cc79f427afd5a203e55dabc29dcd9 | 3,636,508 |
import time
def segment(im, pad=0, caffemodel=None):
"""
Function which segments an input image. uses pyramidal method of scaling, performing
inference, upsampling results, and averaging results.
:param im: image to segment
:param pad: number of pixels of padding to add
:param caffemodel: path... | 0e6f0d8cfd363c7b59007105178eaea3f0238261 | 3,636,509 |
def check_consistency( # pylint: disable=too-many-arguments
num_users=None,
num_items=None,
users_hat=None,
items_hat=None,
users=None,
items=None,
user_item_scores=None,
default_num_users=None,
default_num_items=None,
default_num_attributes=None,
num_attributes=None,
at... | 4139a684751d25bef08d8f4806735be8769bb09e | 3,636,510 |
from datetime import datetime
def verify_forgot_password(request):
"""
Check the forgot-password verification and possibly let the user
change their password because of it.
"""
# get form data variables, and specifically check for presence of token
formdata = _process_for_token(request)
if... | 7ff10e96701c2733702a717fe9bd4fd7103189d1 | 3,636,511 |
import pywemo
import requests
def setup(hass, config):
"""Set up for WeMo devices."""
global SUBSCRIPTION_REGISTRY
SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
SUBSCRIPTION_REGISTRY.start()
def stop_wemo(event):
"""Shutdown Wemo subscriptions and subscription thread on exit."""
... | 1b77fb4ae2f2435cc7974c82b230f01420693bf2 | 3,636,512 |
def extend_node(node, out_size, axis=-1, value=0):
"""Extend size of `node` array
For now, this function works same with `extend_array` method,
this is just an alias function.
Args:
node (numpy.ndarray): the array whose `axis` to be extended.
first axis is considered as "batch" axi... | 08ef9f3f1cff5dce22ca8b4afacbc496e7d803ad | 3,636,513 |
def forward(X, weights, bias):
"""
Simulate the forward pass on one layer.
:param X: input matrix.
:param weights: weight matrix.
:param bias: bias vector.
:return:
"""
a = np.matmul(weights, np.transpose(X))
b = np.reshape(np.repeat(bias, np.shape(X)[0], axis=0), np.shape(a))
o... | fb330d01a42965c003367997381ca8929200d57e | 3,636,514 |
from typing import Any
def sanitize_for_params(x: Any) -> Any:
"""Sanitizes the input for a more flexible usage with AllenNLP's `.from_params()` machinery.
For now it is mainly used to transform numpy numbers to python types
Parameters
----------
x
The parameter passed on to `allennlp.co... | 538e2268f15960683bfe85e03b96076e7f2241db | 3,636,515 |
import os
def filename_fixture():
"""The name of the cities csv file for testing"""
return os.path.join('tests', 'fixtures', 'cities.csv') | d96b38d2ab616de9297526712521207c656593ea | 3,636,516 |
import os
def _get_color_context():
""" Run at beginning of color workflow functions (ex start() or resume()) to orient the function.
Assumes python current working directory = the relevant AN subdirectory with session.log in place.
Adapted from package mp_phot, workflow_session.py._get_session_co... | c9d2a62d490a4d5f54054777d60b35caf0ec3e81 | 3,636,517 |
import dns.resolver
def host_ip():
"""Test fixture to resolve and return host_ip as a string."""
query = dns.resolver.query("scanme.nmap.org")
assert len(query) > 0, "could not resolve target host name"
return query[0].address | ee801bc2be6311fb1fe0805f5d3efb0a4fe589be | 3,636,518 |
def with_behavior(strict=UNSET, extras=UNSET, hook=UNSET):
"""
Args:
strict (bool | Exception | callable): False: don't perform any schema validation
True: raise ValidationException when schema is not respected
E... | 1d80cf51d679e7cec9a5645253b64300fa9688a4 | 3,636,519 |
def get_subnet_from_list_by_id(subnet_id, subnets_list):
"""Get Neutron subnet by id from provided subnets list.
:param subnet_id: Neutron subnet ID
:param subnets_list: List of Neutron subnets, where target subnet should
be searched
"""
for subnet in subnets_list:
... | 93e294131a96de321d18ce5a0e5d3b6fb5913b72 | 3,636,520 |
def grafana_logo(dispatcher):
"""Construct an image_element containing the locally hosted Grafana logo."""
return dispatcher.image_element(dispatcher.static_url(GRAFANA_LOGO_PATH), alt_text=GRAFANA_LOGO_ALT) | 2311c77cf2b5054c3a103693a2d9b862a3e503af | 3,636,521 |
import json
def is_json(payload):
"""Check if a payload is valid JSON."""
try:
json.loads(payload)
except (TypeError, ValueError):
return False
else:
return True | a02499ffd0a890fa4697f1002c5deb0fc894cac0 | 3,636,522 |
def gram_schmidt(M):
"""
@param M:
A mxn matrix whose columns to be orthogonalized
@return ret
Matrix whose columns being orthogonalized
"""
columns = M.T
res = []
res.append(columns[0])
for x in range(1, columns.shape[0]):
tmp = np.array([0 for x in range(M.... | e64b2ea4e36c3a5f8394887ba666b4c392d0284c | 3,636,523 |
import networkx as nx
def contract_variation_linear(G, A=None, K=10, r=0.5, mode='neighborhood'):
"""
Sequential contraction with local variation and general families.
This is an implemmentation that improves running speed,
at the expense of being more greedy (and thus having slightly larger error).
... | 57368b7b55b061312346644970435a7ae679ea3b | 3,636,524 |
def horizon_main_nav(context):
""" Generates top-level dashboard navigation entries. """
if 'request' not in context:
return {}
current_dashboard = context['request'].horizon.get('dashboard', None)
dashboards = []
for dash in Horizon.get_dashboards():
if callable(dash.nav) and dash.n... | 40f2e5e5b8661d52d3688a04ac93b7c0d48b99f2 | 3,636,525 |
import warnings
def _filter_out_bad_segments(img1, seg1, img2, seg2):
"""
It's possible for shearing or scaling augmentation to sample
one segment completely out of the image- use this function
to filter out those cases
"""
minval = tf.reduce_min(tf.reduce_sum(seg1, [0,1])*tf.reduce_sum(seg2, ... | fa74ae956c063c15b7fd1e8c21fb6e0788fc19e6 | 3,636,526 |
def _seconds_to_hours(time):
"""Convert time: seconds to hours"""
return time / 3600.0 | d6abd9144882587833601e64d5c2226446f1bbdc | 3,636,527 |
import sys
def execute_command(api_instance, pod_info, exec_command):
"""
Execute a command inside a specified pod
exec_command = list of strings
"""
name = pod_info['name']
resp = None
try:
resp = api_instance.read_namespaced_pod(name=name,
... | 5b42bf12e96c6b516d2c3ee78750bd107b1dac75 | 3,636,528 |
async def process_cmd_entry_erase(guild_id: int, txt_channel: str, bosses: list,
channel = None):
"""Processes boss `entry` `erase` subcommand.
Args:
guild_id (int): the id of the Discord guild of the originating message
txt_channel (str): the id of the channel of the originating message,
... | e385768fc34ebb419f51124e0a0f5a4e1577ad00 | 3,636,529 |
import warnings
import scipy
def mle_iid_gamma(n):
"""Perform maximum likelihood estimates for parameters for i.i.d.
NBinom measurements, parametrized by alpha, b=1/beta"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res = scipy.optimize.minimize(
fun=lambd... | 089d181a85a72d42457c7ea1eae3aaabb3d6dd60 | 3,636,530 |
def build_tabnet_results(dataset, image_ids, rois, class_ids, scores, masks):
"""Arrange resutls to match COCO specs in http://cocodataset.org/#format
"""
# If no results, return an empty list
if rois is None:
return []
results = []
for image_id in image_ids:
# Loop through dete... | a564f28751436be9648b60a7badae651be3c4583 | 3,636,531 |
from typing import Callable
from typing import Dict
from typing import Any
def make_raw_serving_input_receiver_fn(
feature_spec: features_specs_type,
transform_input_tensor: Callable[[Dict[str, tf.Tensor]], None],
is_model_canned_estimator: bool = False,
batched_predictions: bool = True
) -> Callable[... | 2780f36ae373b1bd4623b6988ec7b4d130fb21ff | 3,636,532 |
from typing import List
import json
from typing import Set
def load_parentheses_dataset(path: str, depths: List[int]) -> torchtext.data.Dataset:
"""
Load equation verification data as a sequential torchtext Dataset, in infix
notation with parentheses.
The Dataset is additionally populated with `leaf_... | 048c5cc42660c21ab59d8dd2dc205aeeafb22bd3 | 3,636,533 |
from typing import List
def get_angle(v1: List[int], v2: List[int]):
"""
:param v1: 2D vector
:param v2: 2D vector
:return: the angle of v1 and v2 in degree
"""
dot = np.dot(v1, v2)
norm = np.linalg.norm(v1) * np.linalg.norm(v2)
return np.degrees(np.arccos(dot / norm)) | 669a4119c1b6da1bcf0fb84f3d2ce0056acd8170 | 3,636,534 |
import logging
def get_plasma_intersection(lon, lat, alt, plasma_alt=300., tx_lon=-75.552,
tx_lat=45.403, tx_alt=0.07):
"""
This function finds where a ray from a transmitter toward a satellite
intersects the peak plasma in the middle.
*** PARAMS ***
Satellite ephemeri... | 8234bf61ef2b0d501a723ef9553c6b63d3c51998 | 3,636,535 |
def plot_clusters(g, c):
"""
Draws a given graph g with vertex colours corresponding to clusters c and
displays the corresponding sizes of the clusters.
===========================================================================
Parameters
--------------------------------------------------------... | dbeec2b421a23c7b503dc71e29cd7caca3300dc5 | 3,636,536 |
def make_cat_advanced(simple=True, yolo=False):
"""fill the categories manually"""
cat_list = get_cat_list(simple)
if simple:
if yolo:
cat_mapping = {
"benign": 0,
"malign": 1,
}
else:
cat_mapping = [0, 1]
return ca... | 5b4f0bac9126ce3a84ec5ea8d27203f7dfe41e10 | 3,636,537 |
import operator
def process_fuel(context):
"""
Reformats Fuel consumed
"""
fuel = {
0: 'Petrol',
1: 'Desiel'
}
data = []
totals = []
for index, type in enumerate(context['Fuel']):
litresSold = operator.sub(type.closing_meter, type.opening_meter)
total = op... | fea31cb306417cf1dfcef8859ed2585c2903849b | 3,636,538 |
from bs4 import BeautifulSoup
import requests
def prepare_df_financials(
ticker: str, statement: str, quarter: bool = False
) -> pd.DataFrame:
"""Builds a DataFrame with financial statements for a given company
Parameters
----------
ticker : str
Company's stock ticker
statement : str
... | 1fdd3488c81bdf404764bba3b797f931ba77ad93 | 3,636,539 |
def build_si(cp, instruction):
"""
Build the integer representation of the source indices.
:param cp: CoreParameters instance for the target architecture
:param instruction: Instruction instance
:return: integer representation of si
"""
# Check sizing.
if len(instruction.source_indices... | 2d78d75486432c1e41847074ed819194b1f0e643 | 3,636,540 |
def getRegSampledPrfFitsByOffset(prfArray, colOffset, rowOffset):
"""
The 13x13 pixel PRFs on at each grid location are sampled at a 9x9 intra-pixel grid, to
describe how the PRF changes as the star moves by a fraction of a pixel in row or column.
To extract out a single PRF, you need to address the 117... | 551ec8624c9c41bca850cf5110d59f65179d6505 | 3,636,541 |
import click
def generate_list_display(object, attrs):
"""Generate a display string for an object based on some attributes.
Args:
object: An object which has specific attributes.
attrs: An interable of strings containing attributes to get from
the above object.
Returns:
... | 17c876261bede0c38d91b4bd3e7b0048616f8cbf | 3,636,542 |
import tempfile
def create_temporary_config_file():
""" Create a minimal config file with some default values
"""
toml_config = document()
toml_config.add("name", "Test Suite")
tmp_config_file = tempfile.NamedTemporaryFile(delete=False)
with tmp_config_file:
content = dumps(toml_conf... | ff7c226eb035aa6b5d8e79efa2acc8a92a925659 | 3,636,543 |
def shear(image, shear_factor, **kwargs):
"""
Shear image.
For details see:
http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.AffineTransform
>>> image = np.eye(3, dtype='uint8')
>>> rotated = rotate(image, 45)
:param numpy array image: Numpy array with range [... | 97f6cc57d1aa41569c84601470242350b2805ffc | 3,636,544 |
def segments():
"""Yields all segments in the unnannotated training Qatar-Living dataset."""
return (segment for document in documents() for segment in document.segments) | eea12bb25ca3c143c5b867987444e4d141982e94 | 3,636,545 |
from datetime import datetime
def get_options_between_dates(
start_date,
end_date):
"""get_options_between_dates
:param start_date: start date
:param end_date: end date
"""
valid_options = []
for rec in historical_options():
opt_date = datetime.datetime.strptime(
... | c2528e85f5e1fce9f537639d0ec88ca20477b93d | 3,636,546 |
def format_timestamp(timestamp_str, datetime_formatter):
"""Parse and stringify a timestamp to a specified format.
Args:
timestamp_str (str): A timestamp.
datetime_formatter (str): A format string.
Returns:
str: The formatted, stringified timestamp.
"""
try:
if '"' ... | 528f1a5f7fd2a45de9d4ee77a8eaf29e06dcb310 | 3,636,547 |
import math
def dyn_stdev(val, prev_stdev, prev_mean, n):
"""Dynamic stdev: computes the standard deviation based on a previous stdev plus a new value. Useful when stdev
is built incrementally, it saves the usage of huge arrays.
Keyword arguments:
val -- new val to add to the mean
prev_stdev -- ... | ccf58f769650b209128bc370fc67144f82e68850 | 3,636,548 |
import warnings
def get_detail_backtest_results(input_df,
features,
return_col_name='returns',
equity_identifier='Equity Parent',
date_col_name='date',
n_bins... | 702f80d378d12e3570af6bf69a786ec913eed4e9 | 3,636,549 |
def sid_invalid_retry(retry=1):
""" 鉴权失败,一般是因为在手机上登录,导致上次登录的 token 失效。
该函数用于返回一个函数修饰器,被修饰的 API 函数如果发生鉴权错误,
则重新登录后重新调用 API 函数,最高 retry 次
Args:
retry int 重新尝试的次数,默认只重试一次
Raises:
JoyrunSidInvalidError 超过重复校验次数后仍然鉴权失败
"""
def func_wrapper(func):
... | ceafd65bc67fe05e19287e2b690724d89123dfcf | 3,636,550 |
from typing import Counter
def check_train_balance(df,idx_train,keys):
"""
check the balance of the training set.
if only one of the classes has more 2 instances than the other
we will randomly take out those 'extra instances' from the major
class
"""
Counts = dict(Counter(df.iloc[idx_trai... | d99c9e1c4ae0d6124da576b91ce2b2786d53f07b | 3,636,551 |
def eye(w, n):
"""Create diagonal matrix with w on diagonal."""
return np.array([[w if i==j else 0.0*w for i in range(n)] for j in range(n)]) | e12ff719981ff7311c21339ad651d7bd38f204f6 | 3,636,552 |
def Messaging():
"""
Messaging
Creates JMS resources.
Only to use in a resource block.
"""
if state().block and state().block != 'resources':
raise SyntaxError('Messaging can only be used in a resources block')
return subscope('messaging') | 9017c8c0452cf75b05f422d6335b8ba5bcd7bc90 | 3,636,553 |
from datetime import datetime
def timestamp2WP(timestamp):
"""
Converts a Unix Epoch-based timestamp (seconds since Jan. 1st 1970 GMT)
timestamp to one acceptable by Wikipedia.
:Parameters:
timestamp : int
Unix timestamp to be converted
:Return:
string Wikipedia style timestamp
"""
return datet... | c4b9bef9e555c178991569472f3962c7a17d996c | 3,636,554 |
def get_available_node_types(nodenet_uid):
""" Return a dict of available built-in node types and native module types"""
return True, runtime.get_available_node_types(nodenet_uid) | 509730edf1c3ea7958a7356e3c784893c2b4c769 | 3,636,555 |
def dos_element_orbitals(
folder,
element_orbital_dict,
output='dos_element_orbitals.png',
fill=True,
alpha=0.3,
linewidth=1.5,
sigma=0.05,
energyaxis='x',
color_list=None,
legend=True,
total=True,
figsize=(4, 3),
erange=[-6, 6],
spin='up',
soc_axis=None,
... | 957e21298077ece088ef5f6c2c2c7ad5c3e599aa | 3,636,556 |
def get_ceph_nodes():
"""Query named relation 'ceph' to determine current nodes."""
hosts = []
for r_id in relation_ids('ceph'):
for unit in related_units(r_id):
hosts.append(relation_get('private-address', unit=unit, rid=r_id))
return hosts | 35ee1775c9e4d2636e8373cf0936e6e1a8cb0b76 | 3,636,557 |
def metadataAbstractElementIllegalChildElementTest1():
"""
No child elements, child elements not allowed.
>>> doctestMetadataAbstractElementFunction(
... testMetadataAbstractElementIllegalChildElements,
... metadataAbstractElementIllegalChildElementTest1())
[]
"""
metadata = """... | c8405bbe81db5d86941a68c62ba19a6576789e50 | 3,636,558 |
def discover_fields(layout):
"""Discover all fields defined in a layout object
This is used to avoid defining the field list in two places --
the layout object is instead inspected to determine the list
"""
fields = []
try:
comps = list(layout)
except TypeError:
return fiel... | 359a6ed1d23e1c56a699895e8c15a93bce353750 | 3,636,559 |
def replace(project_symbols):
"""
replace old source with non annotated signatures
:param project_symbols: symbols we will use to write out new source code
:return: bool
"""
for module_symbols in project_symbols:
if not write_new_source(module_symbols, access_attr... | b3a00199f336b6711fba2096bec9a0fc0c4976b8 | 3,636,560 |
def element_list_as_string(elements):
"""Flatten a list of elements into a space separated string."""
names = []
for element in elements:
if isinstance(element, AOVGroup):
names.append("@{}".format(element.name))
else:
names.append(element.variable)
return " ".... | baa0c1aaa6bd11932f388756c807c9240abb3958 | 3,636,561 |
from typing import Dict
import os
def load_sample_metadata(path: str, sample_id: str) -> Dict[str, str]:
"""
Read sample metadata from either an sqlite '.db' database or a tab-delimited file.
The tab-file has to have one sample per line and a header with a column
labelled 'Name' or 'S... | 7b4351be995018a0d9654e9cedc79574fb8acf06 | 3,636,562 |
def encode_corpus(storage: LetterStorage, corpus: tuple) -> tuple:
"""
Encodes sentences by replacing letters with their ids
:param storage: an instance of the LetterStorage class
:param corpus: a tuple of sentences
:return: a tuple of the encoded sentences
"""
if not isinstance(storage, Let... | 0fa6b4c6b5dd4a33c9e9aee8b1c81fdb119625a7 | 3,636,563 |
from typing import Type
def aggregated_column_unique(chart: Type[BaseChart], data):
"""
description:
main function to calculate histograms
input:
- chart
- data
output:
list_of_unique_values
"""
a_range = cuda.to_device(np.array([chart.min_value, chart.max_valu... | 79f2f896e5a8ad06dba5589896eadfe224e42246 | 3,636,564 |
from pathlib import Path
import os
from unittest.mock import call
def convert_image(qcow_image=None):
"""
:return:
"""
# A convert QCOW to VMDK
new_filename = Path(qcow_image).stem + ".vmdk"
path_to_vmdk = str(Path(qcow_image).parent.joinpath(new_filename))
if os.path.isfile(path_to_vmdk... | 4f882ffd06949b62339847ea80d1c1e40602e69f | 3,636,565 |
def collocations_table_exist(con):
"""Return True if the collocations table exist"""
query = con.query(
"select 1 from information_schema.tables "
"where table_name='collocations'")
return bool(list(query.dictresult())) | 9ffa05f698056d9fab6bb9651427b6bc64f414ea | 3,636,566 |
from bs4 import BeautifulSoup
import re
def ftp_profile(publish_settings):
"""Takes PublishSettings, extracts ftp user, password, and host"""
soup = BeautifulSoup(publish_settings, 'html.parser')
profiles = soup.find_all('publishprofile')
ftp_profile = [profile for profile in profiles if profile['publishmeth... | 003218e6d58d01afcbf062a14e68294d0033b8af | 3,636,567 |
from typing import List
def train(name,train_data:List[tuple],test_data=None)->tuple:
"""
Train Naive Bayes Classifier for Multinomial Models
:param list train_data: list train data of tuple (text,tag)
:param object get_features: function of features
:param list test_data: list test data of tuple... | 32fce3f0c69bdb85878549f95c159a1277104f97 | 3,636,568 |
def validate_article(article_json):
"""
Validate the content of a raw article
"""
if article_json is None:
return False
try:
# Filter title
if not vstrlen(article_json['title'], 16):
return False
# Filter contents
if not vstrlen(article_json['con... | 493a539ec933d43980a7724afadc6a478b4a1a6a | 3,636,569 |
def get_model_memory_usage(batch_size, model):
"""
Estimate how much memory the model will take, assuming all parameters is in float32
and float32 takes 4 bytes (32 bits) in memory.
:param batch_size:
:param model:
:return:
"""
# Calculate the total number of outputs from all layers
... | 0452e9943ff2a0c9dbcb8c870237344740502fe4 | 3,636,570 |
def calculate_deltaangle_distance(
org_ligs,
smiles_keys,
fg_factory,
file_prefix=None
):
"""
Calculate the change of bite angle of each ligand in the cage.
This function will not work for cages built from FGs other than
metals + AromaticCNC and metals + AromaticCNN.
Parameters
... | dfc367300b92561c8b167081121c90e5313187a1 | 3,636,571 |
import logging
import time
def wait_for_file_to_finish_writing(**args) -> tuple:
"""
This wait shouldn't be required but appears to be help with larger files.
"""
config = args.get('config')
logging.info("waiting {} seconds for file to finish writing and unlock".format(config.BULK_IMPORT_WAIT))
... | 915c5b159030c5860891e95f09ffc725f755c584 | 3,636,572 |
def get_max_id(connection, generic_sensor_type: str) -> int:
"""
Get the max id of a given generic sensor type.
:param generic_sensor_type: "asset", "market", or "weather_sensor"
"""
t_generic_sensor = sa.Table(
generic_sensor_type,
sa.MetaData(),
sa.Column("id", sa.Integer),... | 11a35d9e43e7c403271675fd7b6207d6e16e0c80 | 3,636,573 |
def _temp_dict_file_name():
"""Name of the expected python dictionary as a json file from run_external_python().
.. versionadded:: 9.1
"""
return '__shared_dictionary__' | 94f33562d775b041387b477d838a5efadfe38f00 | 3,636,574 |
from typing import Union
from typing import List
def pSpectrum(
data: Union[np.ndarray, List, None], samplefreq: float = 44100
) -> (np.ndarray, np.ndarray):
"""Power spectrum computation.
Compute the power spectrum of a data set using standard ffts, after padding
the data set to the next higher powe... | d8e5d279ef50df2e475d9e6fae4e041081f3e759 | 3,636,575 |
import sys
def get_environment(config, stage):
"""Find default environment name in stage."""
stage_data = get_stage_data(stage, config.get('stages', {}))
if not stage_data:
sys.exit(NO_STAGE_DATA.format(stage))
try:
return stage_data['environment']
except KeyError:
sys.exit... | f8fc4642110be2ceae9347739a5dd7514bed28c1 | 3,636,576 |
def anisotropic_Gaussian(ksize=25, theta=np.pi, l1=6, l2=6):
"""
https://github.com/cszn/KAIR/blob/master/utils/utils_sisr.py
Generate an anisotropic Gaussian kernel
Args:
ksize : e.g., 25, kernel size
theta : [0, pi], rotation angle range
l1 : [0.1,50], scaling of eigenvalue... | 259ae1590807e11d5805c1065fed82acf430b60b | 3,636,577 |
def get_mail(db, messages_obj, msg_id, user_id='me'):
"""Fetch a message from GMail by id and adds it to passed db.
Args:
db: Local db connection object.
messages_obj: Authenticated GMail user object.
msg_id: Id of Gmail message.
user_id: User's email address. The special value ... | b4622592137fbe988ca2c1c59ad518ad4fa606c6 | 3,636,578 |
import os
def get_history(ticker, start_date, end_date = None, granularity=granularity):
"""Fetch/load historical data from Coinbase API at specified granularity
params:
start_date: (str) (see pandas.to_datetime for acceptable formats)
end_date: (str)
granularity: (int) seconds (defau... | 1dd4a4342923a758c49b2d6605c636a4a31ed08e | 3,636,579 |
import sys
import time
import ast
import json
def run_command(net,cmd_list,cmd_str):
"""
This function returns the output of IOS command
Exit script if there is no any network device.
Parameters
----------
net (list): network device ip andid
cmd_list (list): available IOS commands in list... | ae25c0fb7ee8f0b5c9bad66228c536849b292384 | 3,636,580 |
import warnings
def fakemag_to_parallax(fakemag, mag, fakemag_err=None):
"""
To convert fakemag to parallax, Magic Number will be preserved
:param fakemag: astroNN fakemag
:type fakemag: Union[float, ndarray]
:param mag: apparent magnitude
:type mag: Union[float, ndarray]
:param fakemag_e... | 0086436f41707a74974d6358d101eacc3149777a | 3,636,581 |
def provenance_stamp(routine):
"""Return dictionary satisfying QCSchema,
https://github.com/MolSSI/QCSchema/blob/master/qcschema/dev/definitions.py#L23-L41
with QCElemental's credentials for creator and version. The
generating routine's name is passed in through `routine`.
"""
return {'creator'... | 34c1e11c69d0b0354e356bd0463a9f89cd438d51 | 3,636,582 |
def index_of(y):
"""
A helper function to get the index of an input to plot
against if x values are not explicitly given.
Tries to get `y.index` (works if this is a pd.Series), if that
fails, return np.arange(y.shape[0]).
This will be extended in the future to deal with more types of
label... | fae630e18bf20f1c9762e6c6f9d2d1b2f5cf93e2 | 3,636,583 |
def get_centered_box(center: np.ndarray, box_size: np.ndarray):
"""
Get box of size ``box_size``, centered in the ``center``.
If ``box_size`` is odd, ``center`` will be closer to the right.
"""
start = center - box_size // 2
stop = center + box_size // 2 + box_size % 2
return start, stop | 4d5ce84547281b27d8405894ce280139696329ba | 3,636,584 |
def _make_context(frames, cameras):
"""
Generate Context named tuple using camera, frame information
Args:
- cameras:
- frames:
Returns: A Context named tuple encapsulating given information
"""
return Context(cameras=cameras, frames=frames) | b338795bf367c7e12b769fa33049e3e52a0daf00 | 3,636,585 |
from sys import path
def isfile(hdfs_path, project=None):
"""
Return True if path refers to a file.
Args:
:hdfs_path: You can specify either a full hdfs pathname or a relative one (relative to your Project's path in HDFS).
:project: If this value is not specified, it will get the path to ... | 442279aca04271fdde353e3a662f453a35266f46 | 3,636,586 |
def get_list_from_file(filename):
"""
Returns a list of containers stored in a file (one on each line)
"""
with open(filename) as fh:
return [_ for _ in fh.read().splitlines() if _] | 8d9a271aa4adea81f62bf74bb1d3c308870f1baf | 3,636,587 |
def import_recipe():
"""Import recipe from base64 encoded text."""
form = Import()
errors = None
if form.validate_on_submit():
encoded = request.form["encoded"]
try:
decoded = loads(b64decode(encoded.encode("utf-8")).decode("utf-8"))
# recipe table
ti... | 7665af330f029c29e3cf5a2667204a3ba94409c2 | 3,636,588 |
def parse_xyz(filename, nbits):
"""Read xyz format point data and return header, points and points data."""
pointstrings = []
with open(filename) as points_file:
for line in points_file:
if not line.startswith('#'):
if not line.isspace():
line = line.r... | 51a9f7f34bbae5eeddd8b97139ed59ec53e43939 | 3,636,589 |
def compare_vecs(est, truth, zero_tol=0):
"""
Parameters
----------
est: array-like
The estimated vector.
truth: array-like
The true vector parameter.
zero_tol: float
Zero tolerance for declaring an element equal to zero.
Output
------
out: dict
Di... | ef977c31bbca818809f7d708d0ed6f754912239e | 3,636,590 |
def accumulator(init, update):
"""
Generic accumulator function.
.. code-block:: python
# Simplest Form
>>> a = 'this' + ' '
>>> b = 'that'
>>> c = functools.reduce(accumulator, a, b)
>>> c
'this that'
# The type of the initial value determines outp... | 6a4962932c8dba4d5c01aa8936787b1332a6323f | 3,636,591 |
def process_po_folder(domain, folder, extra=''):
""" Process each PO file in folder """
result = True
for fname in glob.glob(os.path.join(folder, '*.po')):
basename = os.path.split(fname)[1]
name = os.path.splitext(basename)[0]
mo_path = os.path.normpath('%s/%s%s' % (MO_DIR, name, MO... | c89a7952d9961ec096dac98f1d830a24b4d62ecd | 3,636,592 |
def create_service(
*,
db_session: Session = Depends(get_db),
service_in: ServiceCreate = Body(
...,
example={
"name": "myService",
"type": "pagerduty",
"is_active": True,
"external_id": "234234",
},
),
):
"""
Create a new s... | 890928f0a5b1a990ea27594886031bf6ede1a0db | 3,636,593 |
import os
def GetBuildRevisions(src_dir, webkit_dir=None, revision_dir=None):
"""Parses build revisions out of the provided directories.
Args:
src_dir: The source directory to be used to check the revision in.
webkit_dir: Optional WebKit directory, relative to src_dir.
revision_dir: If provided, this... | e1e8993921a95c54c47c9bb293e8ea516b47e3c2 | 3,636,594 |
from typing import Dict
import sysconfig
import os
def _get_scheme_dict(distribution_name: str) -> Dict[str, str]:
"""Calculate the scheme dictionary for the current Python environment."""
scheme_dict = sysconfig.get_paths()
installed_base = sysconfig.get_config_var("base")
assert installed_base
... | 4064bebdc0db24756a556908a6acec365d1cae12 | 3,636,595 |
import os
import easydev
def biokit_data(filename, where=None):
"""Simple utilities to retrieve data sets from biokit/data directory"""
biokit_path = easydev.get_package_location('biokit')
share = os.sep.join([biokit_path , "biokit", 'data'])
# in the code one may use / or \
if where:
fil... | f81680593b54a496de84a1683c9f83b3f77ed633 | 3,636,596 |
import json
def get_handler(event, context): # pylint: disable=unused-argument
"""REST API GET method to get data about a Minecraft game server."""
# gather the server data
name = event.get('pathParameters', {}).get('name')
server = gather(name)
# return the HTTP payload
return {
'st... | 61326050cbac4ad3a7a727ebef01bd7e496a254c | 3,636,597 |
def get_item(dataframe: DataFrame, col: str, new_col: str, index: any) -> DataFrame:
"""Return DF with a column that contains one item for an array
:param str col: name of the column
:param str new_col: type of the new column
:param any index: the index key
Examples:
```
SectionName:
... | e06090dad60f7522b1727d69926994bb94f669d6 | 3,636,598 |
import os
def appdatadirectory():
"""Attempt to retrieve the current user's app-data directory
This is the location where application-specific
files should be stored. On *nix systems, this will
be the ${HOME}/.config directory. On Win32 systems, it will be
the "Application Data" directory. Not... | a360204a7c7796c7130251070f468c1eba63d532 | 3,636,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.