content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_predictions(theta):
"""Produce predictions for all molecules in the freesolv set"""
return np.array([predict_solvation_free_energy_jax(theta, distance_matrices[i], charges[i], type_slices[i]) for i in range(len(distance_matrices))]) | 6a19e6ab34e4d47d7285bf9f59779fe85ff5684b | 46,600 |
def train(corpus):
"""
Computes the chunk distribution by pos
The result is stored in a dictionary
:param corpus:
:return:
"""
pos_cnt = count_pos(corpus)
maxPos = {}
for pos in pos_cnt:
testChunkCnt = count_chunks(corpus, pos)
maxPos[pos] = maxDict(testChunkCnt)
... | 51cf7fc919cb3f04d3e0691716f3e2b0e3ec9f88 | 46,601 |
def get_suggestions():
"""
Get chatroom suggestions based on user-entered tag
:param tag: string, the tag a user would like to match to
:return: a JSON Response object, containing the matched results
as a list of dicts with keys room_id, name, members
"""
incoming = request.get_json()
... | d3b2a2c9abc80841a722d3e6ea0e0794215af007 | 46,602 |
def subset_by_value(samples, feature, value):
"""
Subset samples based on value
Parameters:
samples - Pandas DataFrame; last column is taken as the class labels
feature - Name of feature; should correspond to column in samples
value - Value to check for subset membership; can be literal value o... | 34f8f25ea312986599eb99a215db660fd5a2be83 | 46,603 |
def build_model(input_shape, conv_window_size, num_filters, reg, dropout, word2vec = True, max_token = None, sequence_len= 190):
"""
If random init
max_token is the vocabulary size
sequence_len is the number of words in the largenst sentence
"""
model = Sequential()
#model.add(E... | 6ace0c563555d33ade9468384193fe2546cafde7 | 46,604 |
import os
def csv_fetch_resource(series, **kwargs):
"""
Mock CSV resolver.
"""
path = os.path.join(FIXTURE_DIR, 'tiltmeter_selokopo.csv')
return pd.read_csv(path, **series.csv_params) | 2d761a53542a942107fc46ccdceb3d0bcbd80380 | 46,605 |
def validate(validation, dictionary):
"""
Validate that a dictionary passes a set of
key-based validators. If all of the keys
in the dictionary are within the parameters
specified by the validation mapping, then
the validation passes.
:param validation: a mapping of keys to validators
:... | 3c128992e9552ef973e5a94056891e50befa6043 | 46,606 |
def load_TD(file_path):
"""Returns the TD file given by file_path.
Can be either .val files generated by the windows GUI,
or .bin files generated by the linux C++ framework.
"""
if(file_path.endswith('.val')):
print 'Reading event file: ' + file_path
TD = eventvision.read_aer(fi... | 1fba382ee72eaf07b6541270d3f6da67e168db22 | 46,607 |
import socket
def test_get_ipv6_address(monkeypatch):
"""Test get own ipv6 address."""
class Socket(MockSocket):
def getsockname(self, *args, **kwargs):
return ("::1234",)
monkeypatch.setattr(socket, "socket", Socket)
assert get_internal_ipv6_address() == IPv6Address("::1234") | 4cf586745ff2412ed3b07f4ca75e4aa3c51c60e6 | 46,608 |
def hbb_to_kaa(hessian):
"""
Unit conversions on input Hessian matrix from (Hartrees/Bohr/Bohr)
(kcal/mol/Angstrom/Angstrom).
"""
hessian = (hessian * 627.509474) / (0.529177**2)
return hessian | e5daec25cba9104f8ecf1bcf30a0b4020969c704 | 46,609 |
def get_formatted_contents(
raw_contents,
use_color,
color_config,
squeeze,
subs
):
"""
Apply formatting to raw_contents and return the result. Formatting is
applied in the order: color, squeeze, subs.
"""
result = raw_contents
if use_color:
result = get_colorized_co... | 5f7594c859f6ffd3a31f608faf679e55b0a3fece | 46,610 |
import io
import os
def home_page(request):
"""View for the home route."""
with io.open(os.path.join(HERE, 'sample.html')) as the_file:
imported_text = the_file.read()
return Response(imported_text) | 954e6c27ad31dc0f14d36c311cb2533948ee8dbc | 46,611 |
from mpi4py import MPI
import inspect
import sys
def mpi_grad_fq(n_nodes, m_list, q, scatter_array, qbin):
"""
Breakup the grad F(Q) job across GPU enabled nodes
Parameters
----------
n_nodes: int
Number of allocated nodes, not including the head node
Returns
-------
list of f... | 893d07c912a57ef16f7274e27fe9e92802b7d448 | 46,612 |
import subprocess
import shlex
def run(cmd, input=None):
"""
Run *cmd*, optionally passing string *input* to it on stdin, and return
what the process writes to stdout
"""
try:
p = subprocess.Popen(shlex.split(cmd),
stdin=subprocess.PIPE,
... | 234ef2c678ea3a9e555444735cf68fec70bac601 | 46,613 |
import warnings
def compute_bin_assignment(position, x_edges, y_edges=None, include_edge=True):
"""Compute spatial bin assignment.
Parameters
----------
position : 1d or 2d array
Position information across a 1D or 2D space.
x_edges : 1d array
Edge definitions for the spatial binn... | 5b5d2b5a60ea925c75a883923c5df07321e8e0ff | 46,614 |
from typing import List
from typing import Union
import torch
from typing import Optional
from typing import Tuple
def padded_tensor(
items: List[Union[List[int], torch.LongTensor]],
pad_idx: int = 0,
left_padded: bool = False,
max_len: Optional[int] = None,
) -> Tuple[torch.LongTensor, List[int]]:
... | a43b09fd15d8d2e31db692a782d20ab2013a10e3 | 46,615 |
def coloring(color, text):
"""Print a text in a specified color"""
color_sequences = {
'default': '\033[0m',
'black': '\033[30m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'purple': '\033[35m',
'lightblue': '... | 3953d72329a01453f52fd099bb20624c7661aa87 | 46,616 |
def truediv(a, b):
"""Same as a / b."""
return a / b | 44b93737128efa6672eaaf33eff11ac9a0c56cac | 46,617 |
def calcDihedrals(prevCO, currN, currCA, currCO, nextN):
"""
Calculates phi and psi angles for an individual residue.
Requires coord tuple of each atom.
"""
prevCO = np.array(prevCO)
currN = np.array(currN)
currCA = np.array(currCA)
currCO = np.array(currCO)
nextN = np.array(nextN)
... | 034364f625229fba3e19d5cf345716e91a4c4c45 | 46,618 |
from typing import Any
def reset_password(
token: str = Body(...),
new_password: str = Body(...),
node: Node = Depends(deps.get_db),
) -> Any:
"""
Reset password
"""
db = node.db
email = verify_password_reset_token(token)
if not email:
raise HTTPException(status_code=400, d... | 362917982d493d1ea2f59291bcffbc18eeb121ed | 46,619 |
import importlib
def WorkerAgentGenerator(agent_class):
"""
Worker Agent generator, receives an Agent class and creates a Worker Agent class that inherits from that Agent.
"""
# Support special case where class is given as type-string (AgentsDictionary) or class-name-string.
if isinstance(agent_c... | dac55eda91ac6743ef530dd2ecd52a8331465e57 | 46,620 |
def series_mean_with_conf(xx):
"""
Compute series mean.
Also provide confidence of mean,
as estimated from its correlation-corrected variance.
"""
mu = mean(xx)
N = len(xx)
if np.allclose(xx,mu): return val_with_conf(mu, 0)
if (not np.isfinite(mu)) or N<=5: return val_with_conf(mu, n... | d007bd6f80fd494b65d47db5aafd056c0a2bf754 | 46,621 |
import token
import requests
def get_webhook():
"""
Getting installed webhooks
:return: installed webhooks
"""
header = {'Content-Type': 'application/json;charset=utf-8'}
request_address = 'https://api.ok.ru/graph/me/subscriptions?access_token={token}'.format(token=token)
response = reques... | 345a331514d276b336803d2fed182d7591eb8cc6 | 46,622 |
import math
def haversine(rad):
"""
Returns the haversine function of an angle in radians.
"""
return (1 - math.cos(rad)) / 2 | 294c901795aa499c42f3d67e6d6a3d5efecd46a8 | 46,623 |
def countingOp(i, m, Npair):
"""
Calculates the application of the counting operator to a basis state m. Returns 0 or 1, according to the occupation of the energy level.
"""
m1 = flipBit(m, Npair-i-1)
if m1 < m:
return 1
else:
return 0 | ee5e3fb1bcb1e5a3dfad25dffcaa3ee37671e9c5 | 46,624 |
def safestring_to_string(s):
"""Return the original string encoded by string_to_safestring"""
return _base64.b64decode(s.encode("utf-8")).decode("utf-8") | 4191bf8dedcdb56ffed09d329c572786f95dfe39 | 46,625 |
def apparent_spectrum_fit_function(wn, Z_ref, p, b, c, g):
"""
Function used to fit the apparent spectrum
:param wn: wavenumbers
:param Z_ref: reference spectrum
:param p: principal components of the extinction matrix
:param b: Reference's linear factor
:param c: Offset
:param g: Extinct... | 21de604e34a894f08b6fa7d39e67c052a58e534d | 46,626 |
def active_matrix_from_intrinsic_euler_xyz(e):
"""Compute active rotation matrix from intrinsic xyz Cardan angles.
Parameters
----------
e : array-like, shape (3,)
Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations)
Returns
-------
R : array-like, shape (3, 3)
... | 71bc22736c61449423a4c09fa0512987ef029068 | 46,627 |
def test_post_handlers():
# language=rst
"""
Post handlers
-------------
In the simplest cases, like in a create form, you only have one post handler.
You can do this yourself in the classic Django way:
"""
# @test
request = req('post', foo='foo', **{'-submit': True})
form = F... | 7cbc22b0edb3d7b0d1bcc3137f247d6522bd0a33 | 46,628 |
import attr
def parse(raw):
"""
Parses the given dict into a Entry object. This assumes the data is
formatted according to version 1.0 (or equivalent) of the RNAcentral JSON
schema.
"""
def key(raw):
return gene(raw) or ""
context = Context(
database=raw["metaData"]["data... | d0c44f515c9d00795b9ed6b72c155506c2802628 | 46,629 |
import inspect
def wrapper(f):
"""Internal wrapper, takes a function f, adds type checking and return handling.
"""
signature = inspect.signature(f)
@wraps(f)
def new_func(*args, **kwargs):
payload = request.json
new_args = []
new_kwargs = {}
try:
fo... | e1a787bb3742bc97f7dcc8613789db2c24b76274 | 46,630 |
import collections
def callbacks() -> dict:
"""
Return a dictionary of callbacks with asynchrony support.
:return: a collections.defaultdict that returns callbacks by name.
"""
return collections.defaultdict(MockCallable) | b3abf2ec0678e1c6633143224cfed07ccaed5524 | 46,631 |
import torch
def run_kmeans(x, args):
"""
Args:
x: data to be clustered
"""
results = {'im2cluster':[],'centroids':[],'density':[]}
for seed, num_cluster in enumerate(args.num_cluster):
print('performing kmeans clustering on ...',num_cluster)
# intialize fais... | 2fd3946a95a00fe640d1814dd50ff265b79ebe73 | 46,632 |
def gensym(name: str) -> str:
"""Generates a globally unique name, using the given one as a base"""
global GENSYM_COUNTER
uniq = f"{name}__{GENSYM_COUNTER}"
GENSYM_COUNTER += 1
return uniq | c886e0b7148c9a57c9aee5d670e325043652312d | 46,633 |
import os
import requests
def write_schedule(schedule):
"""Gets given schedule completed if not complete and calls SAVE_SCHEDULE API to write it.
1. Fill in given schedule to complete it - fill_incomplete_schedule(schedule)
2. Create target URL using environment variable SAVE_SCHEDULE_URL and... | f8b73659c5119115aba2b26f5b52be60236ac25f | 46,634 |
def bfs_algorithm():
"""
How to design a BFS algorithm.
"""
ans = """
How does the breadth-first search work?
It essentially is as follows:
1. Begin with a queue that has only one element in it: the starting node.
2. Add the neighbors of that node to the queue.
1. If destination node is present in ... | bf6268451d10baf91bf00ffbec109ae4cad1f657 | 46,635 |
from sys import stdin
def parse_args():
"""Set up and parse arguments"""
p = ArgumentParser()
p.add_argument('-t', '--train-file', default=stdin)
p.add_argument('-c', '--config', type=str,
help="Location of YAML config")
p.add_argument('-p', '--parameters', type=str,
... | 2488332dae1a3f51c09f5157bae8f96e8b57d99b | 46,636 |
def normal_empirical_cdf(
target_cdf: float = 0.5,
mean: float = 0.0,
sigma: float = 1.0,
samples: int = 1000000,
bins: int = 1000):
"""
computes the value x for target_cdf
"""
# --- argument checking
if target_cdf <= 0.0001 or target_cdf >= 0.9999:
ra... | 3356ddbd83f490b5fd4fdb4f26782d4719b567dc | 46,637 |
import requests
from datetime import datetime
def get_openweather_data():
"""Gathers weather data and returns the required list."""
response = requests.get(API_URL).json()
weather_data = response['list']
# Add date info
for entry in weather_data:
entry['date'] = datetime.fromtimestamp(ent... | 08f6c0644d06bbff1d74e990547683261a5acd03 | 46,638 |
def find_break_edges(ptree):
""" Find edges which to remove from the graph for the original tree behind this ptree.
==> edges between adjac
"""
ret = set()
if len(ptree.insert_descendants) > 0:
lca = ptree.insert_descendants[0]
for lca_child in lca:
ret.add((lca.nodei... | db9ff3ae36dba799d6f479f83e775b41d7bce3df | 46,639 |
def _getMASTidentifier(ID, lkwargs):
""" return KIC/TIC/EPIC for given ID.
If input ID is not a KIC/TIC/EPIC identifier then the target is looked up
on MAST and the identifier is retried. If a mission is not specified the
set of observations with the most quarters/sectors etc. will be used.
... | 130e29fce25b06eebc0c1c99200fdf778a3ba64f | 46,640 |
def generate_ui_list_data(item_type="parts", pack=None):
"""Generate a list of Blender UI friendly data of categories and parts.
When we retrieve presets we just want an item name.
For parts I am doing a trick where I am grouping sets of 3 parts in order
to make a grid in each UIList entry.
A... | 141502b94c51569437b1f771718ac299123e130a | 46,641 |
def pad_image(image):
"""
Parameters
----------
image : ndarray
DESCRIPTION.
Returns
-------
TYPE
padded image and its information
"""
padded_image = image
pad_x1, pad_x2, pad_y1, pad_y2, pad_z1, pad_z2 = 0, 0, 0, 0, 0, 0
# Padding on X axes
if image.sh... | c82c02473fdd1ce8363a4448004d509ed2a080e9 | 46,642 |
def parse_calibration(filename):
""" read calibration file with given filename
Returns
-------
dict
Calibration matrices as 4x4 numpy arrays.
"""
calib = {}
calib_file = open(filename)
for line in calib_file:
key, content = line.strip().split(":")
values = [float(v) for v... | 046cd945b0c2d78e0609a96379afb63e2910eceb | 46,643 |
def get_celsius(temperature_in_fahrenheit):
"""
Returns the temperature in Celsius of the given Fahrenheit temperature.
For example, this function returns XXX when given YYY.
Type hints:
:type temperature_in_fahrenheit: float
"""
return (temperature_in_fahrenheit - 32) * (5 / 9) | 501b5c3c6c7fe9792fd12cabbae71eddfbc34f58 | 46,644 |
def solve_f35d900a(x):
"""
Difficulty: High
The Problem: The input grid is a rectangular (list of lists) matrix with variable shape, with numbers ranging
from 0 to 9. (inclusive). Different colors of the color spectrum are represented by the integers.
The task is to identi... | da779b86563f684b6e8b00c7f229a0985e504e40 | 46,645 |
def config_fixture(hass):
"""Define a config entry data fixture."""
return {
CONF_USERNAME: "user@email.com",
CONF_PASSWORD: "password",
} | 7c14083c8254f367ec93e1b5e111f0502969b59a | 46,646 |
import scipy
def erfc(x):
"""
Complimentary error function, with handling of Quantity objects
Only Dimensionless quantities can be handled
erfc(x) = 1 - erf(x)
"""
if isinstance(x, Quantity):
return scipy.special.erfc(x.to("").magnitude)
else:
return scipy.special.erfc(x) | a5cb49b658252227b9b3fcd34ec8107bd399545d | 46,647 |
import requests
import sys
def call_responder(server, endpoint, payload=''):
"""
Call a responder
Keyword arguments:
server: server
endpoint: REST endpoint
psyload: POST payload
"""
url = CONFIG[server]['url'] + endpoint
try:
if payload:
headers = {"... | aad446b664131a2cbe28d5942fd8a38393bb9be5 | 46,648 |
import bz2
import json
import codecs
def json_exporter(data, filepath, compress=True):
"""Export a file to JSON. Compressed with ``bz2`` is ``compress``.
Returns the filepath of the JSON file. Returned filepath is not necessarily ``filepath``, if ``compress`` is ``True``."""
if compress:
filepath... | dcdb9026b302c3bec6b6a7215cee0498a8655a61 | 46,649 |
def is_linear(x, y):
"""
Returns True if molecule is linear
(largest eigenvalue almost equivalent to second largest)
"""
x = x - np.mean(x, axis=0)
y = y - np.mean(y, axis=0)
L, Q = sorted_eigh(build_F(x, y))
if L[0]/L[1] < 1.01 and L[0]/L[1] > 0.0:
return True
else:
... | e1316292474a23b9ee04bafac47c08ed47b02b43 | 46,650 |
import math
def _realroots_quadratic(a1, a0):
"""gives the real roots of x**2 + a1 * x + a0 = 0"""
D = a1*a1 - 4*a0
if D < 0:
return []
SD = math.sqrt(D)
return [0.5 * (-a1 + SD), 0.5 * (-a1 - SD)] | ad61307a09b9f5cbf444f0bd75448b39b09b2e96 | 46,651 |
def add_column(recarray, name, val, index=None):
#Stolen from Ska.Numpy
"""
Add a column ``name`` with value ``val`` to ``recarray`` and return a new
record array.
:param recarray: Input record array
:param name: Name of the new column
:param val: Value of the new column (np.array or list)
... | 92f05bfe58da4c1b37a9309d7aff624d422e2163 | 46,652 |
def gunning_fog_index(n_words, n_polysyllable_words, n_sents):
"""https://en.wikipedia.org/wiki/Gunning_fog_index"""
return 0.4 * ((n_words / n_sents) + 100 * (n_polysyllable_words / n_words)) | aeb295edfa563027952f6a934636487e04b2b266 | 46,653 |
import imageio
def makeGIF(FF_input, start_frame=0, end_frame =255, ff_dir = '.', deinterlace = True, print_name = True, optimize = True, Flat_frame = None, Flat_frame_scalar = None, dark_frame = None, gif_name_parse = None, repeat = True, fps = 25, minv = None, gamma = None, maxv = None, perfield = False, data_type=... | 077d238fac7fe9861eba05ff2128266a1ac4ad80 | 46,654 |
def russell_rao(
x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None
) -> float:
"""Russel-Rao similarity
Russell, P. F., & Rao, T. R. (1940).
On habitat and association of species of anopheline larvae in south-eastern Madras.
Journal of the Malaria Institute of India, ... | 6d5be97809f94bb217f60f5490c0accbb2dda76e | 46,655 |
def _generate_windows_body(hooks):
"""Generate Windows specific functions.
At the moment it implements load_impls_from_library, class destructor, and an utility function
to convert from utf8 to wide-strings so we can use the wide family of windows
functions that accept unicode.
"""
# generate d... | 27597f8556cdb4383179245a423a45a72324e2ae | 46,656 |
def get_binary(img_gray):
"""
Get binary threshold filter of image.
"""
thresh = cv2.threshold(img_gray, 128, 255, cv2.THRESH_BINARY)[1]
thresh = thresh[:, :, np.newaxis]
return thresh | 4353d807fc5d015a772ee138e358be3d24d1cba7 | 46,657 |
def bt_rr(weights, bounds):
"""
LP-based OBBT using ReLU relaxation. The procedure is named RR in the paper.
Assuming that NN model has K-1 hidden layers with ReLU activation and 1 linear output layer
Variables are named as x_i_j, where i is the layer number, and j is the unit number (of layer i)
... | 675abbd09569e70ee313ae430f0fe4e896c8537c | 46,658 |
def energy(sig: _Array) -> _Array:
"""Total energy of time domain signal.
Args:
sig: Time domain signal.
Returns:
Energy along fist axis.
"""
if not _np.isfinite(sig).all():
raise ValueError('Input ``sig`` contains NaNs or infinite values.')
return _np.sum(_np.square(_... | b102bf559e8c087f8fe2125c3e319dd1438b227f | 46,659 |
def _compute_expected_shocks(dense_key_to_choice_set_in_period, optim_paras):
"""Compute an array with the expected value of the shocks."""
n_wages = len(optim_paras["choices_w_wage"])
exp_shocks = np.zeros(len(optim_paras["choices"]))
var = np.diag(optim_paras["shocks_cholesky"].dot(optim_paras["shock... | b270b1507f930a4e91ac1dbc5fe61013f9f7ad53 | 46,660 |
import logging
def a_star(graph, start, goal):
""" this thing does not work :( """
# pdb.set_trace()
logger.setLevel(logging.INFO)
queue = [ [start] ]
step = 0
logging.info("START: %s" % start)
logging.info("GOAL: %s" % goal)
def a_star_sort(path1, path2):
l1 = path_length... | b0ffc567845c1c0ba15d6a7c1848af67de5e1230 | 46,661 |
def _preprocessor_public(X_raw):
"""Data preprocessing function.
This function prepares the features of the data for training,
evaluation, and prediction.
Parameters
----------
X_raw : ndarray
An array, this is the raw data as downloaded
Returns
... | 58ddca1808edffcd0020feb46735ff6302f56df7 | 46,662 |
def alreadyHasEntry(oldClassString, og):
""" Return true if there is already an owl:Class with the old id"""
namespace = oldClassString.split(':')[0]
if namespace == 'http':
target = rdflib.URIRef(oldClassString)
print('OLD CLASS ID IS A URL', oldClassString)
else:
try:
... | 482dbd7c62bff21dae9b9c563ca86fb9b5fab560 | 46,663 |
def loadTLE(tle_file, satlst=None):
""" load TLE from file """
with open(tle_file, 'r') as f:
satlist = []
for l1 in f:
l2 = f.readline()
l3 = f.readline()
norad_id = l2[2:8]
if satlst is not None:
if norad_id in satlst:
... | 1c33f3673a25fc5f052ebef1fbf193e8762ef509 | 46,664 |
from typing import Optional
from typing import Dict
from typing import Any
def bake(schema_name: str, config: Optional[Dict[str, Any]] = None) -> str:
"""
Links the directive to the appropriate schema and returns the SDL related
to the directive.
:param schema_name: schema name to link with
:param... | d2a58c0272ddeb6c39e7f1b78c56dd4c953ca9f0 | 46,665 |
def cents_to_ratio(c):
"""Cents to pitch ratio."""
return np.power(2, c/1200.0) | 018e7c962f77e3f25c1778fee2bdc5cb02adc27b | 46,666 |
def get_prev_frames(ind, path):
"""
for this index return the closest previous frame which is non none
:param ind: input index
:param path:
:return: frame and the count
"""
cur_ind = ind - 1
count = 1
while (path[cur_ind] is None and cur_ind >0):
count = count + 1
cur... | ddb48419e07a85c6c8d62eb4b034d6c5f2210a39 | 46,667 |
def test_metric_get(test_flask_client):
"""Tests the GET method"""
with mock.patch("bluebird.api.resources.metrics.utils", wraps=utils) as utils_patch:
sim_proxy_mock = mock.Mock()
utils_patch.sim_proxy.return_value = sim_proxy_mock
# Test no providers available
sim_proxy_moc... | 8d5a058b78ecb4d1e2703f16d99616fc87404bcb | 46,668 |
from typing import Dict
from typing import Any
async def create_remove_vote(res: Response, vote: VoteBaseModel) -> Dict[str, Any]:
"""create or remove a Vote from Vote table
Args:
vote (VoteBaseModel): vote to create or remove
Returns:
Dict[str, Any]: vote created
"""
response ... | 16c44d03a3ea9dc976091429b1d077cb043ef767 | 46,669 |
def delete_file(app_id, file_name, mode):
# type: (int, str, bool) -> bool
""" Call to delete_file.
:param app_id: Application identifier.
:param file_name: File name reference.
:param mode: Delete mode.
:return: The deletion result.
"""
return _COMPSs.delete_file(app_id, file_name, mod... | dac37c86de329ab39212589826c606dd0b6d210d | 46,670 |
def update_consumer_view(request):
"""
Updates a consuemr on ``POST`` request and returns the consumer update form for ``GET`` request.
.. http:get:: /consumer/update
Gets the consumer update form whose primary key matches the query parameter ``pk``.
**Example request**:... | d2a797fde068c7570611cac2d0943247b9c8726b | 46,671 |
def LastValueMinMaxQuantize(inputs,
min_var,
max_var,
bit_width,
is_training,
mode,
name_scope="LastValueMinMaxQuantize"):
"""Last value float scale q... | ae73bb701f3abfe6ef2a859880db60b5b39db63b | 46,672 |
import os
def write_out(df, meta, filename="tbl_{dims}--{name}", out_dir=None, filetype="csv"):
""" Write a dataframe to disk
"""
meta = meta.copy()
meta["dims"] = ".".join(df.index.names)
complete_file = filename.format(**meta)
if out_dir:
complete_file = os.path.join(out_dir, comple... | 5067667ad0460b52026d8159fb17a378662bd092 | 46,673 |
def wikitext103_local_cluster4k():
"""Routing attention on sequence length 4k."""
hparams = wikitext103_local4k()
hparams.local_num_heads = 8
hparams.sparsity_cluster_num_heads = 8
hparams.sparsity_cluster_attention_window = 512
hparams.sparsity_cluster_size = 8
hparams.share_qk = True
return hparams | 3a256772c521f8ba17d4dd795d9d204d1fb7de46 | 46,674 |
def log10(pred, depth):
""" Mean log10 Error (LOG10) """
return np.absolute(np.log10(pred) - np.log10(depth)).mean() | 9a228d8179e3aa4530b70dac202ba57fc7549f3a | 46,675 |
def test_plan_built_on_method(hook):
"""
Test @sy.meth2plan and plan send / get / send
"""
hook.local_worker.is_client_worker = False
x11 = th.tensor([-1, 2.0]).tag("input_data")
x21 = th.tensor([-1, 2.0]).tag("input_data")
device_1 = sy.VirtualWorker(hook, id="device_1", data=(x11,))
... | 12ecce26ee149a690abcc8a7e41651e5d8273092 | 46,676 |
def get_proto_deserializer(proto_class):
"""
Return a proto deserializer that takes in a proto type to deserialize
the serialized msg stored in the RedisState proto
"""
def _deserialize_proto(serialized_rule):
proto_wrapper = RedisState()
proto_wrapper.ParseFromString(serialized_rule... | 4c509dccea826169c396510ef7f80cbf5fcf9b18 | 46,677 |
import requests
import json
import logging
def last_failed(url, job_type):
"""Return last failed job for a specified job type."""
# query
query = {
"query": {
"bool": {
"must": [
{
"terms": {
"s... | 567e5ef7afaa460e7fb91e09fa74d2d011cb2cdb | 46,678 |
def p2pkh_address_to_pubkey_hash(address):
"""
Takes a P2PKH address (starting with a 1, m or n symbol) and extracts its
HASH160 hash (used as a public key hash).
:see: https://en.bitcoin.it/wiki/List_of_address_prefixes
:param address: P2PKH public address
:returns: HASH160 hash of the ... | 95b6237b1c4a2492ab7283f104f2e6590b05eedc | 46,679 |
from typing import Optional
def get_dashboard(dashboard_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDashboardResult:
"""
Resource schema for AWS::IoTSiteWise::Dashboard
:param str dashboard_id: The ID of the dashboard.
"""
__args__ = di... | bf5092d6c78edc6523c95ec1ffba79f86dec1924 | 46,680 |
def resize_intrinsics(intrinsics, target_size):
"""Transforms camera intrinsics when image is resized.
Args:
intrinsics: 1-d array containing w, h, fx, fy, x0, y0.
target_size: target size, a tuple of (height, width).
Returns:
A 1-d tensor containing the adjusted camera intrinsics.
"""
with tf.n... | 7216522da6a681d836171d16beb1507523bf4331 | 46,681 |
import json
import base64
def insert_artifact_v2(request_body: RequestBody, settings: config.APISettings = Depends(get_settings)):
"""Insert a JSON file of dbt artifacts v1.
NOTE:
The base configuration is implemented in `config.py`.
We can pass concrete values to it with an `.env.xxx` file.
... | 1b34697b3095ffb35240253d7c0273fcd1193d37 | 46,682 |
def fix_spaces_inside_quotes(text, quote='``'):
"""
>>> test = '''\
:meth:`update` accepte soit un autre objet dictionnaire ou un iterable de\
paires clé / valeur (comme tuples ou d'autres iterables de longueur deux).\
Si les arguments de mots clés sont spécifiés, le dictionnaire est alors mis\
... | cafb4dd7d15c4ab1a2cd252352d33b9aa20e4bca | 46,683 |
def toGoatLatin(S):
"""
:type S: str
:rtype: str
"""
count=1
sentences=S.split()
for i in range(len(sentences)):
if sentences[i][0].lower() in "aeiou":
sentences[i]+="ma"+count*"a"
else:
sentences[i]=sentences[i][1:]+sentences[i][0]+'ma'+count*"a"
count+=1
return " ".join(sentences) | ebc1e567dfa60436aea14412d7b347d8481f8b0a | 46,684 |
def __prepare_line(string, dir_source, replace_string):
"""
Prepare the line before it is being written into the content file
"""
if not replace_string == None:
string = string.replace(dir_source, replace_string)
return string | cbec6deab5c66960c5e8d57b52392e4ed3cf2b3d | 46,685 |
def create_adjacency_matrix(graph):
"""
Creating a sparse adjacency matrix.
:param graph: NetworkX object.
:return A: Adjacency matrix.
"""
index_1 = [edge[0] for edge in graph.edges()] + [edge[1] for edge in graph.edges()]
index_2 = [edge[1] for edge in graph.edges()] + [edge[0] for edge in... | 220a5465faa35c726008c7c4acf10c48bc44bb12 | 46,686 |
def count_trainable_parameters():
"""Counts the number of trainable parameters in the current default graph."""
tot_count = 0
for v in tf.trainable_variables():
v_count = 1
for d in v.get_shape():
v_count *= d.value
tot_count += v_count
return tot_count | 2e576db2be0815c770fdeea24bcf21d5d9353732 | 46,687 |
def create_diagram(start_from=None, kind="default", in_notebook=True):
"""Visually create a diagram.
Parameters
----------
start_from : list, optional
Starting coordinates (list of (x, y) tuples). By default uses a triangle.
kind : str
Can be one of "default", "x-marked".
in_not... | f99f4b7445c4d55f784892bc5294a29087be7b5c | 46,688 |
def extractsignalpdata(signalp_file_name,main_dic,translator_dic,n_termin_dict):
"""
This function reads an abridged signalp file, parses the signalp data and
adds the information in the (?) column to the main class.
"""
for line in open(signalp_file_name,'r'):
#Filter out title and s... | 2dc701d542c2a089fdf510de10885a89172fbd7b | 46,689 |
def mosaic_template(
endpoint: str, mapbox_access_token: str = "", mapbox_style="satellite"
) -> str:
"""Rio-viz viewer."""
return f"""<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Cogeo-Mosaic Viewer</title>
<meta name='viewport' content='initial-scale=1,maxi... | 9bb5e23caca6ce347ba56f3792ff8a130bbec423 | 46,690 |
def write_smiles(molecule, default_element='*', start=None):
"""
Creates a SMILES string describing `molecule` according to the OpenSMILES
standard.
Parameters
----------
molecule : nx.Graph
The molecule for which a SMILES string should be generated.
default_element : str
Th... | f1e13af728bdc8e1f13e6853d089ed3ce9b856e8 | 46,691 |
def find_closest_raster(return_period,aoi_col='AoI_RP{}y_unique',depth_col='RP{}_max_flood_depth'):
"""
Find the closest AoI and Flood raster column name for given return period
Arguments:
*return_period* (float): Return period of the flood for which to find the nearest inundation raster
*a... | 177041afc9a52d4942ab4095b7383cfc8e17652b | 46,692 |
def svn_diff_fns_invoke_datasource_get_next_token(*args):
"""svn_diff_fns_invoke_datasource_get_next_token(svn_diff_fns_t _obj, void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t"""
return _diff.svn_diff_fns_invoke_datasource_get_next_token(*args) | 9d9b0dd2ac2214c05cc7af5e1fca5f804b1feb5b | 46,693 |
def _is_bn_diff_doctypes(dyad):
"""Check if a dyad is between two different doctypes.
Args:
dyad (tuple): two-item tuple where each item is a dict which represents a document
Returns:
ind (bool): True if the dyad is between two different doctypes
"""
if dyad[0]["doctype"] != dyad[... | 2480cbca808164b2fec14fd13808cf5ebfb0dcc3 | 46,694 |
import operator
def selectcontains(table, field, value, complement=False):
"""Select rows where the given field contains the given value."""
return selectop(table, field, value, operator.contains,
complement=complement) | 29753f270791a3187bf0a2a87fc5ec6b379178ed | 46,695 |
def with_path_to(q, value, info, union=False, name='with_path_to'):
"""This will traverse any (any meaning any paths specified in the path
generation heuristic which prunes some redundant/wandering paths)
from the source entity to the given target type where it will
apply a given query.
This filter... | 68c9ceddf0a9b2bcc5d39262f5f7d94deb47e4db | 46,696 |
from typing import Dict
from typing import List
import urllib
from bs4 import BeautifulSoup
import logging
def get_links(entry: Dict, html_data: Text) -> List[urllib.parse.ParseResult]:
"""Extract any links from the html"""
links = []
soup = BeautifulSoup(html_data, "html.parser")
if soup:
li... | b3c1fc02c145387b3d4e639ff9fa0ff594953e55 | 46,697 |
def conjgrad (A, b, x = None, iterations = 10**6, epsilon = 10**(-10)):
"""
Méthode du gradient conjugué.
-----------------------------
Entrée:
A matrice symétrique définie positive.
b vecteur colonne.
(optional) x vecteur initial de la suite.
... | 62708a3d3dfd8afc20cf1b43fcff92614b0c3392 | 46,698 |
def get_and_check_counter(counter, cloudservice_name, management,
storageacct_name, warning, critical, verbosity):
"""retrieve performance counter and evaluate with respect to warning and
critical range and return appropriate error message
management - storagemanagement object
... | 396f9897c409f524ad8b143851aa49f4ad33871a | 46,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.