content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def input_fn(is_training, data_dir, batch_size, num_epochs=1):
"""Input_fn using the tf.data input pipeline for CIFAR-10 dataset.
Args:
is_training: A boolean denoting whether the input is for training.
data_dir: The directory containing the input data.
batch_size: The number of samples per batch.
... | 94875b205df2d67993dd658f33fbf3be917cf701 | 3,645,657 |
def num_list(to_parse):
"""
Creates list from its string representation
Arguments:
to_parse {string} -- String representation of list, can include 'None' or internal lists, represented by separation with '#'
Returns:
list[int] -- List represented in to_parse
"""
if len(... | b444554e37434b5ae42ebc913bcc0f9b99c65ce9 | 3,645,659 |
def total_scatter_matrix(data):
"""
Total sum of square (TSS) : sum of squared distances of points around the baycentre
References : Clustering Indices, Bernard Desgraupes (April 2013)
"""
X = np.array(data.T.copy(), dtype=np.float64)
for feature_i in range(data.shape[1]):
X[feature_i] ... | 829bfdbf838d087517465e7173e480796e52cf8e | 3,645,661 |
def save_camera_zip(camera_id, year, month, file_path=None):
"""
Download a camera ZIP archive.
:param camera_id: int, camera ID
:param year: int, year
:param month: int, month
:param file_path: str, optional, path to save file
:return: bool, status of download
"""
# Setup file name... | 41e4ef0f5f412850266de2d136da719adae08e04 | 3,645,662 |
def read_user(str):
""" str -> dict """
pieces = str.split()
return {
'first': pieces[0],
'last': pieces[1],
'username': pieces[5],
'custID': pieces[3],
'password': pieces[7],
'rank': 0,
'total': 0
} | fcb24a2b791f0df8f40ea4080cdabe83d51fe068 | 3,645,663 |
import calendar
def lweekdate(weekday, year, month, nextDay=0):
"""
Usage
lastDate = lweekdate(weekday, year, month, nextDay)
Notes
Date of last occurrence of weekday in month
returns the serial date number for the last occurrence of Weekday in the given
year and month and in a week that also contains ... | 60367db7223f104260e2b7d757b367d6388d222b | 3,645,664 |
def multi_polygon_gdf(basic_polygon):
"""
A GeoDataFrame containing the basic polygon geometry.
Returns
-------
GeoDataFrame containing the basic_polygon polygon.
"""
poly_a = Polygon([(3, 5), (2, 3.25), (5.25, 6), (2.25, 2), (2, 2)])
gdf = gpd.GeoDataFrame(
[1, 2],
geome... | 9acfa76ca3a51603d96e1388dc7c7a1178ec3fa1 | 3,645,665 |
import traceback
def get_or_create_pull(github_repo, title, body, head, base, *, none_if_no_commit=False):
"""Try to create the PR. If the PR exists, try to find it instead. Raises otherwise.
You should always use the complete head syntax "org:branch", since the syntax is required
in case of listing.
... | 3968fc99c006c45e20eabce1329d95247ad855c8 | 3,645,666 |
import json
from typing import OrderedDict
def get_board_properties(board, board_path):
"""parses the board file returns the properties of the board specified"""
with open(helper.linux_path(board_path)) as f:
board_data = json.load(f, object_pairs_hook=OrderedDict)
return board_data[board] | e5fa5542c540c643ecf8b57314e227d14e193a56 | 3,645,667 |
def get_repository_username(repo_url):
"""
Returns the repository username
:return: (str) Repository owner username
"""
repo_path = _get_repo_path(repo_url)
return repo_path[0] | 008e67435c11e4fbb12ca19149e795dd50c12526 | 3,645,670 |
from IPython.config import Application
import logging
def get_logger():
"""Grab the global logger instance.
If a global IPython Application is instantiated, grab its logger.
Otherwise, grab the root logger.
"""
global _logger
if _logger is None:
if Application.initialized():
... | 717487ac1c94c09ab7831e405255283aea4570a5 | 3,645,671 |
def process_y(y_train: pd.Series, max_mult=20, large_sampsize=50000):
"""
Drop missing values, downsample the negative class
if sample size is large and there is significant class imbalance
"""
# Remove missing labels
ytr = y_train.dropna()
# The code below assumes the negative class is ove... | 2f36ba3bce93d47f944784f83fd731b9aa315acc | 3,645,672 |
def _distance(y1, y2):
"""1D distance calculator"""
inner = (y2 - y1) ** 2
d = np.sqrt(inner)
return d | 696c5ccbe720301d22d9b142e9a5d5f3c507b738 | 3,645,673 |
def create_container(context, values):
"""Create a new container.
:param context: The security context
:param values: A dict containing several items used to identify
and track the container, and several dicts which are
passed
into the Drivers when m... | b9047467a0a96c1b08bc92b4e74399e0a413ba45 | 3,645,674 |
from google.protobuf.json_format import MessageToDict
from typing import Callable
from typing import Dict
def build_model_from_pb(name: str, pb_model: Callable):
"""
Build model from protobuf message.
:param name: Name of the model.
:param pb_model: protobuf message.
:return: Model.
"""
... | a1de965b13b6cbbe33a08a52561f699042dd93f8 | 3,645,675 |
def create_proof_of_time_pietrzak(discriminant, x, iterations, int_size_bits):
"""
Returns a serialized proof blob.
"""
delta = 8
powers_to_calculate = proof_pietrzak.cache_indeces_for_count(iterations)
powers = iterate_squarings(x, powers_to_calculate)
y = powers[iterations]
proof = pr... | d31ac6eadcc3ce155d682e2cef4b392561a1412b | 3,645,676 |
def resample_dataset ( fname, x_factor, y_factor, method="mean", \
data_min=-1000, data_max=10000 ):
"""This function resamples a GDAL dataset (single band) by a factor of
(``x_factor``, ``y_factor``) in x and y. By default, the only method used
is to calculate the mean. The ``data_min`` and ``d... | f32465711d7dae3a8e7350676cb0e90f084bf5c5 | 3,645,677 |
def int2bytes(number, fill_size=None, chunk_size=None, overflow=False):
"""
Convert an unsigned integer to bytes (base-256 representation)::
Does not preserve leading zeros if you don't specify a chunk size or
fill size.
.. NOTE:
You must not specify both fill_size and chunk_size. Only one... | 091764ffeb9a15036b484380750f04496db36da1 | 3,645,678 |
def compFirstFivePowOf2(iset={0, 1, 2, 3, 4}):
"""
task 0.5.6
a comprehension over the given set whose value is the set consisting
of the first five powers of two, starting with 2**0
"""
return {2**x for x in iset} | a7b04ab6b127ef5ee7fdd3598b1569e171fd009e | 3,645,679 |
import types
import pandas
def sdc_pandas_dataframe_getitem(self, idx):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.DataFrame.getitem
Get data from a DataFrame by indexer.
Limitations
-----------
Supported ``key`` c... | 90b335db7327da883561665909a2b335437efc83 | 3,645,680 |
def display_finds_meta(r):
"""A list of urls in r is displayed as HTML"""
rows = ["<tr><td><img src='{row}'</td><td><a href = {meta} target='_'>{meta}</a></td></tr>".format(row=row, meta=row) for row in r]
return HTML("""<html><head></head>
<body>
<table>
{rows}
</table>
</body>
... | bd769bc4b0b6d4d55ec721e02c623f30d5eb5e1f | 3,645,681 |
def __pairwise__(iterable):
""" Converts a list of elements in a list of pairs like:
list -> (list[0], list[1]), (list[2], list[3]), (list[4], list[5]), ...
:param iterable: Input list.
:return: List of pairs of the given list elements.
"""
a = iter(iterable)
return zip(a, a) | 59eae23e0e6f9ccba528f9632caf77fe28698c5b | 3,645,682 |
def _generateTriangleSequence():
"""
Generates list of elements following sequence of triangle numbers.
Returns:
sequenceElements - List of elements following the sequence.
"""
sequenceElements = []
totalCharactersInNewSequence = 0
total = 1
currentAddend = 2
while totalCharac... | 453b5e672a4817281f5e4ba51ca3ea426fcdb3d2 | 3,645,683 |
import math
def normalize_neurons_range(neurons, standard_diagonal_line: int or float):
"""
:param neurons: should be refined.
:param standard_diagonal_line: pre-defined standard length of diagonal line of xoy plate
:return: neurons, width_scale, [width_span, height_span, z_span]
width_s... | 1709b68054aa10ccd9d065b04d809e2df4d3a8e2 | 3,645,684 |
def distort_image(image):
"""Perform random distortions to the given 4D image and return result"""
# Switch to 3D as that's what these operations require
slices = tf.unpack(image)
output = []
# Perform pixel-wise distortions
for image in slices:
image = tf.image.random_flip_left_right... | 70db49a2a3dfe31c0b511824342a95ad5da30430 | 3,645,685 |
from io import StringIO
def tablebyname(filehandle, header):
"""fast extraction of the table using the header to identify the table
This function reads only one table from the HTML file. This is in contrast to `results.readhtml.titletable` that will read all the tables into memory and allows you to interacti... | ba1c228843f631b0441fc69c66b0d9ae7acbf813 | 3,645,686 |
def BuildDataset():
"""Create the dataset"""
# Get the dataset keeping the first two features
iris = load_iris()
x = iris["data"][:,:2]
y = iris["target"]
# Standardize and keep only classes 0 and 1
x = (x - x.mean(axis=0)) / x.std(axis=0)
i0 = np.where(y == 0)[0]
i1 = np.where(y... | f6b3cc216262899880f048dd6d4823596d111c1a | 3,645,687 |
def read_tile(file, config):
"""Read a codex-specific 5D image tile"""
# When saving tiles in ImageJ compatible format, any unit length
# dimensions are lost so when reading them back out, it is simplest
# to conform to 5D convention by reshaping if necessary
slices = [None if dim == 1 else slice(No... | 3e0e61d8fa5ac497377c02c90a03bcbd176752ab | 3,645,688 |
def rmsd(V, W):
""" Calculate Root-mean-square deviation from two sets of vectors V and W. """
D = len(V[0])
N = len(V)
rmsd = 0.0
for v, w in zip(V, W):
rmsd += sum([(v[i] - w[i]) ** 2.0 for i in range(D)])
return np.sqrt(rmsd / N) | dc537f1cc742f7c4c5231af4c45d470e582be623 | 3,645,689 |
from re import L
def partition(f, xs):
"""
partition :: (a -> Bool) -> [a] -> ([a], [a])
The partition function takes a predicate a list and returns the pair of
lists of elements which do and do not satisfy the predicate.
"""
yes, no = [], []
for item in xs:
if f(item):
... | 7fde3557fa9d1e3bdf232885dda360a6695dabc0 | 3,645,690 |
from math import exp, pi, sin
def bvp2_check():
"""
Using scikits.bvp_solver to solve the bvp
y'' + y' + sin y = 0, y(0) = y(2*pi) = 0
y0 = y, y1 = y'
y0' = y1, y1' = y'' = -sin(y0) - y1
"""
lbc, rbc = .1, .1
def function1(x , y):
return np.array([y[1] , -sin(y[0]) -y[1] ])
def boundary_conditions(... | 6fe48b76945d3c322c21938049ab74099d022c7d | 3,645,691 |
import zarr
def get_zarr_store(file_path):
"""Get the storage type
"""
ZARR_STORE_MAP = {"lmdb": zarr.LMDBStore,
"zip": zarr.ZipStore,
"dbm": zarr.DBMStore,
"default": zarr.DirectoryStore}
suffix, subsuffix = get_subsuffix(file_path)
... | ecc17168d56bd9cc725a2db51914cddd098aa1af | 3,645,692 |
def convert_string(inpt):
"""Return string value from input lit_input
>>> convert_string(1)
'1'
"""
if PY2:
return str(inpt).decode()
else:
return str(inpt) | a88ee436726a6587e673fb71673c771851b83cea | 3,645,693 |
def get_ipc_kernel(imdark, tint, boxsize=5, nchans=4, bg_remove=True,
hotcut=[5000,50000], calc_ppc=False,
same_scan_direction=False, reverse_scan_direction=False):
""" Derive IPC/PPC Convolution Kernels
Find the IPC and PPC kernels used to convolve detector pixel data... | 4646ccc138d7f625941e9bc43382e1c5ef57e5c5 | 3,645,694 |
from datetime import datetime
def get_description():
""" Return a dict describing how to call this plotter """
desc = dict()
desc['data'] = True
desc['cache'] = 86400
desc['description'] = """This plot presents the trailing X number of days
temperature or precipitation departure from long term... | 04d19dde79c25bfc3cc606cd1a2b09ecd8a6408b | 3,645,695 |
def SpringH(z,m,k):
""" with shapes (bs,2nd)"""
D = z.shape[-1] # of ODE dims, 2*num_particles*space_dim
q = z[:,:D//2].reshape(*m.shape,-1)
p = z[:,D//2:].reshape(*m.shape,-1)
return EuclideanK(p,m) + SpringV(q,k) | 0895d44933a0390a65da42d596fcf1e822f0f93c | 3,645,696 |
def write_sushi_input_files(lhafile):
""" Add SusHi-related blocks to LHA file """
outfiles = {}
for higgsname, higgstype in {'H': 12, 'A': 21}.iteritems():
lha = LHA(lhafile)
sushi = Block('SUSHI', comment='SusHi specific')
sushi.add(Entry([1, 2], commen... | f2f88c79d19de05109748c5c839550bfab905581 | 3,645,697 |
import functools
def pytest_collection(session): # pylint: disable=unused-argument
"""Monkey patch lru_cache, before any module imports occur."""
# Gotta hold on to this before we patch it away
old_lru_cache = functools.lru_cache
@wraps(functools.lru_cache)
def lru_cache_wrapper(*args, **kwargs... | 56f218c06c1d8cc64d884e94f503ae51be135c7f | 3,645,698 |
def __graph_laplacian(mtx):
""" Compute the Laplacian of the matrix.
.. math::
"""
L = np.diag(np.sum(mtx, 0)) - mtx
return L | 54f7fd0a359863bcf31ca9800c30e9eadf32ba8f | 3,645,699 |
def moon_illumination(phase: float) -> float:
"""Calculate the percentage of the moon that is illuminated.
Currently this value increases approximately linearly in time from new moon
to full, and then linearly back down until the next new moon.
Args:
phase: float
The phase angle of... | c40a3a6cb4de6da1fd64a188c99892afe3d385d7 | 3,645,700 |
def convex_hull_mask_iou(points_uv, im_shape, gt_hull_mask):
"""Computes masks by calculating a convex hull from points. Creates two masks (if possible),
one for the estimated foreground pixels and one for the estimated background pixels.
Args:
points_uv: (2, N) Points in u, v coordinates
i... | 09cb5cf8f7721a7430ab3825e0e6ddbbb0966be6 | 3,645,701 |
from typing import Callable
from typing import Awaitable
import inspect
def load_callback(module: ModuleType, event: Event) -> Callable[..., Awaitable[None]]:
"""
Load the callback function from the handler module
"""
callback = getattr(module, "handler")
if not inspect.iscoroutinefunction(callbac... | e961adaae0c7f4ad5abe228ef677b3b61288d531 | 3,645,703 |
def molmer_sorensen(theta, N=None, targets=[0, 1]):
"""
Quantum object of a Mølmer–Sørensen gate.
Parameters
----------
theta: float
The duration of the interaction pulse.
N: int
Number of qubits in the system.
target: int
The indices of the target qubits.
Retur... | 8b5e7bc221c4f785bd8747a5b04d4a9299ebeefc | 3,645,705 |
import math
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int): average green value across all images
... | 9ad0a30090e735daac4c7d470ea40e7d4dc0010f | 3,645,706 |
def structure_pmu(array: np.ndarray) -> np.ndarray:
"""Helper function to convert 4 column array into structured array
representing 4-momenta of particles.
Parameters
----------
array : numpy ndarray of floats, with shape (num particles, 4)
The 4-momenta of the particles, arranged in co... | 519173b131d4120f940022b567faef018be2f2ed | 3,645,707 |
def url_query_parameter(url, parameter, default=None, keep_blank_values=0):
"""Return the value of a url parameter, given the url and parameter name
General case:
>>> import w3lib.url
>>> w3lib.url.url_query_parameter("product.html?id=200&foo=bar", "id")
'200'
>>>
Return a default value i... | d2ed39b6d6054baa9f8be90dfe1e1c8a06e47746 | 3,645,709 |
def read_ground_stations_extended(filename_ground_stations_extended):
"""
Reads ground stations from the input file.
:param filename_ground_stations_extended: Filename of ground stations basic (typically /path/to/ground_stations.txt)
:return: List of ground stations
"""
ground_stations_extende... | 2492dc8d5c55f124696aafbec11d74e609c3f397 | 3,645,710 |
import uuid
def shortPrescID():
"""Create R2 (short format) Prescription ID
Build the prescription ID and add the required checkdigit.
Checkdigit is selected from the PRESCRIPTION_CHECKDIGIT_VALUES constant
"""
_PRESC_CHECKDIGIT_VALUES = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+'
hexString = str(... | db491d3fe299adfbcd6f202eb46bc4669f829613 | 3,645,712 |
def rmse(predictions, verbose=True):
"""Compute RMSE (Root Mean Squared Error).
.. math::
\\text{RMSE} = \\sqrt{\\frac{1}{|\\hat{R}|} \\sum_{\\hat{r}_{ui} \in
\\hat{R}}(r_{ui} - \\hat{r}_{ui})^2}.
Args:
predictions (:obj:`list` of :obj:`Prediction\
<surprise.prediction_... | 2898f98fba50d71ef20e66b9654e1d539531f17b | 3,645,713 |
import ast
def get_module_docstring(path):
"""get a .py file docstring, without actually executing the file"""
with open(path) as f:
return ast.get_docstring(ast.parse(f.read())) | e253372bfb6f65907a5461332d14c414c2370c66 | 3,645,714 |
def get_authenticate_kwargs(oauth_credentials=None, http_=None):
"""Returns a dictionary with keyword arguments for use with discovery
Prioritizes oauth_credentials or a http client provided by the user
If none provided, falls back to default credentials provided by google's command line
utilities. If ... | da3cef34a51fe1bc74cb8ce221e9610160f0f176 | 3,645,715 |
from re import T
def get_transforms(size=128, mobilenet=False):
"""
Gets all the torchvision transforms we will be applying to the dataset.
"""
# These are the transformations that we will do to our dataset
# For X transforms, let's do some of the usual suspects and convert to tensor.
# Don't ... | ddacbf265ba12ac259ec35ef57798688a3e36f02 | 3,645,716 |
def transform(f, a, b, c, d):
"""
Transform a given function linearly.
If f(t) is the original function, and a, b, c, and d are the parameters in
order, then the return value is the function
F(t) = af(cx + d) + b
"""
return lambda x: a * f(c * x + d) + b | a47b3f4f3dc1e3ed5ddb6155bcd67b8297c298ed | 3,645,717 |
def delete_rules(request):
"""
Deletes the rules with the given primary key.
"""
if request.method == 'POST':
rules_id = strip_tags(request.POST['post_id'])
post = HouseRules.objects.get(pk=rules_id)
post.filepath.delete() # Delete actual file
post.delete()
return re... | e6be9d39dfe07d17fdb18634b422262917fbe6eb | 3,645,718 |
def display_word(word, secret_word, word_to_guess):
"""Function to edit the word to display and the word to guess (word to display
is the test word with its colored letter and the word to guess is the word
with spaces in it, for each missing letter).
Args:
word (str): the input word
secr... | e55ef943d5e3d837ca1698ba1e2e65d9062b16f0 | 3,645,719 |
def get_config_cache(course_pk: 'int') -> dict:
"""Cacheからコンフィグを取得する.存在しない場合,新たにキャッシュを生成して格納後,コンフィグを返す."""
cache_key = f"course-config-{course_pk}"
cached_config = cache.get(cache_key, None)
if cached_config is None:
config = Config.objects.filter(course_id=course_pk).first()
cached_conf... | a155ce5354d8ec00eab0da42c919ac15eac43bb4 | 3,645,720 |
import logging
def log_command(func):
"""
Logging decorator for logging bot commands and info
"""
def log_command(*args, **kwargs):
slack, command, event = args
user = slack.user_info(event["user"])
log_line = 'USER: %s | CHANNEL ID: %s | COMMAND: %s | TEXT: %s'
command... | 8ab4f36ff6c01a3799061f532d0c25ec04d725e8 | 3,645,721 |
import copy
def calc_stats(scores_summ, curr_lines, curr_idx, CI=0.95, ext_test=None,
stats="mean", shuffle=False):
"""
calc_stats(scores_summ, curr_lines, curr_idx)
Calculates statistics on scores from runs with specific analysis criteria
and records them in the summary scores datafr... | ddaa5b5a2c70c25488f572ad894f7aa0bedc7189 | 3,645,723 |
def report_date_time() -> str:
"""Return the report date requested as query parameter."""
report_date_string = dict(bottle.request.query).get("report_date")
return str(report_date_string).replace("Z", "+00:00") if report_date_string else iso_timestamp() | 391db86e523c55f88c40c1bc8b9fb1ed6f3d97ff | 3,645,724 |
def assign_colour_label_data(catl):
"""
Assign colour label to data
Parameters
----------
catl: pandas Dataframe
Data catalog
Returns
---------
catl: pandas Dataframe
Data catalog with colour label assigned as new column
"""
logmstar_arr = catl.logmstar.values... | 4f56cc4d4ac1ae722deffb92d63d5867a885fb0e | 3,645,725 |
def get_policy(arn):
"""Get info about a policy."""
client = get_client("iam")
response = client.get_policy(PolicyArn=arn)
return response | c56d79bfd8cf744bbe010ad0d5dfbaeaa3d59e76 | 3,645,726 |
def _write_roadways(roadway_feature_class, condition):
"""Writes roadway feature class to STAMINA syntax
Arguments:
roads_feature_class {String} -- Path to feature class
condition {String} -- Existing, NoBuild, or Build. Determines fields to use from geospatial template
Returns:
... | 0c82db17f3632a2c7023a6437a3f7e8221e667ba | 3,645,728 |
from .tf import TF_BACKEND
from .torch import TORCH_BACKEND
from .jax import JAX_BACKEND
from .math.backend import BACKENDS
def detect_backends() -> tuple:
"""
Registers all available backends and returns them.
This includes only backends for which the minimal requirements are fulfilled.
Returns:
... | 4d7fb7c80e8a931a614549539b9e157223602d31 | 3,645,729 |
import random
def mix_audio(word_path=None,
bg_path=None,
word_vol=1.0,
bg_vol=1.0,
sample_time=1.0,
sample_rate=16000):
"""
Read in a wav file and background noise file. Resample and adjust volume as
necessary.
"""
... | fba93e1f0d13bab4b9a30fe2d849fa3b1cf99927 | 3,645,730 |
def analytical_pulse_width(ekev):
"""
Estimate analytical_pulse_width (FWHM) from radiation energy (assumes symmetrical beam)
:param ekev: radiation energy [keV]
:return sig: Radiation pulse width (FWHM) [m]
"""
sig = np.log((7.4e03/ekev))*6
return sig/1e6 | c56f861d1a83147ff425de7760416e870e1a69d4 | 3,645,731 |
def progress_timeout(progress_bar):
"""
Update the progress of the timer on a timeout tick.
Parameters
----------
progress_bar : ProgressBar
The UI progress bar object
Returns
-------
bool
True if continuing timer, False if done.
"""
global time_remaining, time... | 1b7e4976a5d96b2ede671c413ff0a7702603c6d8 | 3,645,732 |
def socket_file(module_name):
"""
Get the absolute path to the socket file for the named module.
"""
module_name = realname(module_name)
return join(sockets_directory(), module_name + '.sock') | df92c1a23374296d96c6419f32cdffd55b6564cf | 3,645,733 |
def postBuild(id: str):
"""Register a new build.
Args:
id: Identifier of Repository for which build is to be registered.
Returns:
build_id: Identifier of Build created.
"""
return register_builds(
id, request.headers["X-Project-Access-Token"], request.json
) | 13b8aed703e9e5cf2191baaf98583374021fb494 | 3,645,734 |
def boundary(shape, n_size, n):
""" Shape boundaries & their neighborhoods
@param shape 2D_bool_numpy_array: True if pixel in shape
@return {index: neighborhood}
index: 2D_int_tuple = index of neighborhood center in shape
neighborhood: 2D_bool_numpy_array of size n_size
Boundaries are s... | 619050d3dfff50ccea204538a4cabcd7ef2190ab | 3,645,736 |
def centered_mols(self, labels, return_trans=False):
"""
Return the molecules translated at the origin with a corresponding cell
Parameters
----------
labels : int or list of ints
The labels of the atoms to select
print_centro : bool
Print the translation vector which was detect... | 858fd2b43f0ac9eaca3db94108f9bec0dbf305c7 | 3,645,737 |
import torch
def binary_accuracy(output: torch.Tensor, target: torch.Tensor) -> float:
"""Computes the accuracy for binary classification"""
with torch.no_grad():
batch_size = target.size(0)
pred = (output >= 0.5).float().t().view(-1)
correct = pred.eq(target.view(-1)).float().sum()
... | 306d7d0e85a617b8b4508f2dfbbbac1f5fb67bc5 | 3,645,738 |
def prepare_config(config):
"""
Prepares a dictionary to be stored as a json.
Converts all numpy arrays to regular arrays
Args:
config: The config with numpy arrays
Returns:
The numpy free config
"""
c = {}
for key, value in config.items():
if isinstance(value, n... | 4ad31fc20fab7e3f7a7de9f50b0431d8000df029 | 3,645,739 |
import json
def load_config(path='config.json'):
"""
Loads configruation from config.json file.
Returns station mac address, interval, and units for data request
"""
# Open config JSON
with open(path) as f:
# Load JSON file to dictionary
config = json.load(f)
... | 5522f023ed3293149613dcc2dc007e34d50f3fa8 | 3,645,740 |
import torch
def log_px_z(pred_logits, outcome):
"""
Returns Bernoulli log probability.
:param pred_logits: logits for outcome 1
:param outcome: datapoint
:return: log Bernoulli probability of outcome given logits in pred_logits
"""
pred = pred_logits.view(pred_logits.size(0), -1)
y ... | 6369d893cc9bfe5c3f642f819511798d01ae3ae9 | 3,645,741 |
def _sort_rows(matrix, num_rows):
"""Sort matrix rows by the last column.
Args:
matrix: a matrix of values (row,col).
num_rows: (int) number of sorted rows to return from the matrix.
Returns:
Tensor (num_rows, col) of the sorted matrix top K rows.
"""
tmatrix = tf.transpose(a=matrix, perm=... | e9e8fcb6275915e8a42798411c0712eb34bbbfe4 | 3,645,742 |
import functools
def partial_at(func, indices, *args):
"""Partial function application for arguments at given indices."""
@functools.wraps(func)
def wrapper(*fargs, **fkwargs):
nargs = len(args) + len(fargs)
iargs = iter(args)
ifargs = iter(fargs)
posargs = (next((ifargs,... | 1b45e0bd8baea869d80c6b5963c6063f6b8fbdd4 | 3,645,743 |
import importlib
def try_load_module(module_name):
"""
Import a module by name, print the version info and file name.
Return None on failure.
"""
try:
mod = importlib.import_module(module_name)
print green("%s %s:" % (module_name, mod.__version__)), mod.__file__
return mod
... | 527c2fb3dbbb3ef8ee5800f492a727a2d565892d | 3,645,744 |
def project_image(request, uid):
"""
GET request : return project image
PUT request : change project image
"""
project = Project.objects.filter(uid=uid).first()
imgpath = project.image.path if project.image else get_thumbnail()
if request.method == "PUT":
file_object = request.data.... | f05db1026f41ab15eece1068fe182e0673e798e3 | 3,645,745 |
from typing import Optional
def validate(prefix: str, identifier: str) -> Optional[bool]:
"""Validate the identifier against the prefix's pattern, if it exists.
:param prefix: The prefix in the CURIE
:param identifier: The identifier in the CURIE
:return: Whether this identifier passes validation, af... | bbdc0eef34a03670963354d0cdf6e414eaa2aa8d | 3,645,746 |
import torch
def laplacian_positional_encoding(g, pos_enc_dim):
"""
Graph positional encoding v/ Laplacian eigenvectors
"""
# Laplacian
A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float)
N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float)
L = ... | 69b09e69f37fc870fa36510ef05172f35bfc0093 | 3,645,747 |
async def replace_chain():
""" replaces the current chain with the most recent and longest chain """
blockchain.replace_chain()
blockchain.is_chain_valid(chain=blockchain.chain)
return{'message': 'chain has been updated and is valid',
'longest chain': blockchain.chain} | 3ef0797ca582dbd2cb7ab47b09c847a4380215d5 | 3,645,748 |
import copy
def ucb(bufferx,
objective_weights,
regression_models,
param_space,
scalarization_method,
objective_limits,
iteration_number,
model_type,
classification_model=None,
number_of_cpus=0):
"""
Multi-objective ucb acquisition functi... | 4ec8615d979fb9c3ee7539cd5e161ee920bc1c3a | 3,645,749 |
def np_array_to_binary_vector(np_arr):
""" Converts a NumPy array to the RDKit ExplicitBitVector type. """
binary_vector = DataStructs.ExplicitBitVect(len(np_arr))
binary_vector.SetBitsFromList(np.where(np_arr)[0].tolist())
return binary_vector | c1865c47cd1abb71fbb3d3ce1b9a9cc75e87f70a | 3,645,750 |
def augment_features(data, feature_augmentation):
"""
Augment features for a given data matrix.
:param data: Data matrix.
:param feature_augmentation: Function applied to augment the features.
:return: Augmented data matrix.
"""
if data is not None and feature_augmentation is not None:
... | 687a7ff2a4b61131f5d95e1f7d6eb77d75bd6f06 | 3,645,751 |
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None):
""" Helper function for _get_data that handles empty lists. """
fields = get_field_list(fields, schema)
return {'cols': _get_cols(fields, schema), 'rows': []}, 0 | bd1c219ed2ef738cf403b984cccc4aa4cd96aa2f | 3,645,752 |
def copy_keys_except(dic, *keys):
"""Return a copy of the dict without the specified items.
"""
ret = dic.copy()
for key in keys:
try:
del ret[key]
except KeyError:
pass
return ret | b1e57db9dbacbc2a7c502c36082f40598a0f4b90 | 3,645,753 |
import random
import math
def get_params(img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (PIL Image): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio crop... | 80838328fc9383731e1a853c8dc572228d1a4567 | 3,645,754 |
from typing import Any
async def start_time() -> Any:
"""
Returns the contest start time.
"""
return schemas.Timestamp(timestamp=settings.EVENT_START_TIME) | 5613f6d8928c1d1ca49677e829617769a3e6f8c3 | 3,645,755 |
def reshape(v, shape):
"""Implement `reshape`."""
return np.reshape(v, shape) | 249e17a4b503b3434c5ec0d3e14bef1208321e92 | 3,645,756 |
def generate_html_from_module(module):
"""
Extracts a module documentations from a module object into a HTML string
uses a pre-written builtins list in order to exclude built in functions
:param module: Module object type to extract documentation from
:return: String representation of an HTML file
... | 3e59931f3716dd3c50dfdda3ba17807b62f04c14 | 3,645,757 |
def _phi(r, order):
"""Coordinate-wise nonlinearity used to define the order of the
interpolation.
See https://en.wikipedia.org/wiki/Polyharmonic_spline for the definition.
Args:
r: input op
order: interpolation order
Returns:
phi_k evaluated coordinate-wise on r, for k = r
... | b2270f17260e90b995c60b4bc0fb65f49be9c514 | 3,645,758 |
def updated_topology_description(topology_description, server_description):
"""Return an updated copy of a TopologyDescription.
:Parameters:
- `topology_description`: the current TopologyDescription
- `server_description`: a new ServerDescription that resulted from
a hello call
Called ... | 3fe6f527c8fdb177f608d5130c0ce239aef84c20 | 3,645,759 |
import numpy
def target_mask(image, path, num_grid_corners):
"""
Arguments:
image: grayscale image of shape (N, M)
path: pathlib.Path object for the image
Returns: Boolean mask of shape (N, M), which is True for pixels that
we think are on the calibration target.
"""
ret, ... | 369a37b1cc5a49761413bac0a9b48a275bb76e59 | 3,645,761 |
from pathlib import Path
def read_data(spec: dict) -> (dict, DataFrame):
"""Creates Pandas DataFrame by reading file at path.
Appropriate read_* pandas method will be called based
on the extension of the input file specified."""
path = spec['input']['file']
ext = Path(path).suffix
kwarg... | 22e18a0702261c23e322fe03687864d694ecba98 | 3,645,762 |
import textwrap
def bunk_choose(bot, update, user_data):
"""Removes keyboardMarkup sent in previous handler.
Stores the response (for Lectures/Practicals message sent in previous handler) in a ``user_data``
dictionary with the key `"stype"`.
``user_data`` is a user relative dictionary which holds dat... | 11d1249ec1953cc38be80470a21ba95b694c1ed5 | 3,645,763 |
def module_of(obj):
"""Return the Module given object is contained within.
"""
if isinstance(obj, Module):
return obj
elif isinstance(obj, (Function, Class)):
return obj.module
elif isinstance(obj, Method):
return module_of(obj.klass)
elif isinstance(obj, TestCase):
... | 02c69c72d46e8448f7cdf41e18582508b431e4e7 | 3,645,765 |
def day(date, atmos=atmos):
"""
Returns a dataframe of daily aggregated data
Parameters
-------
date: str
Format yyyy/mm/dd
"""
path = f"{get_day_folder_path(date)}{date.replace('/','')}_daily_agg.csv.gz"
return load_agg(path, atmos) | 84f56d078b0aec9605a261ed26656d4771e0eb11 | 3,645,766 |
async def find_deck_position(hcapi: OT3API, mount: OT3Mount) -> float:
"""
Find the true position of the deck in this mount's frame of reference.
The deck nominal position in deck coordinates is 0 (that's part of the
definition of deck coordinates) but if we have not yet calibrated a
particular too... | f75c3d066c367853036adc1de138755a2a1ee29b | 3,645,767 |
import random
def create_symbol_id(path_to_db: str) -> str:
"""
When creating a new symbol, need to ensure
that ID is not already used in the Physics Derivation Graph
Args:
path_to_db: filename of the SQL database containing
a JSON entry that returns a nested dictionary
... | 1394f7f348abd43ee1cbb4fed8119fda39341028 | 3,645,770 |
import re
def get_file_name(content_disposition: str, ) -> str:
"""Content-Disposition has the filename between the `"`. get it.
Args:
content_disposition: the content disposition from download header
Returns:
the file name
"""
if match := re.search(r'"(.*?)"', content_dispositio... | f81c8ee80d341bf62b970565c062db348324905f | 3,645,771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.