content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
def run(text, base_dir, debug_filename, symbols = set()):
"""Rudimentary resolver for the following preprocessor commands:
// #include <some-file>
(no check for cyclic includes!)
// #ifdef | #if <symbol>
// <contents>
// [ #elif
// <alt-contents> ]*
// [ #else
// <alt-contents> ]
// #endi... | de2e06f7cdf93e80eca05b6fef0dd0cab55175e3 | 3,645,702 |
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 |
import os
import ast
def read_config_key(fname='', existing_dict=None, delim=None):
"""
Read a configuration key.
"""
# Check file existence
if os.path.isfile(fname) is False:
logger.error("I tried to read key "+fname+" but it does not exist.")
return(existing_dict)
logger.i... | 87fa9ea607c34fd31b6a53224a8f8c2c5673e1f9 | 3,645,704 |
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 |
import os
def _log_from_checkpoint(args):
"""Infer logging directory from checkpoint file."""
int_dir, checkpoint_name = os.path.split(args.checkpoint)
logdir = os.path.dirname(int_dir)
checkpoint_num = int(checkpoint_name.split('_')[1])
_log_args(logdir, args, modified_iter=checkpoint_num)
re... | d5198c276dce969f9245db520f30ee2d8bd42363 | 3,645,708 |
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 os
import configparser
import ssl
import smtplib
def send_email(destination, code):
"""
Send the validation email.
"""
if 'CLOUD' not in os.environ:
# If the application is running locally, use config.ini anf if not, set environment variables
config = configparser.ConfigParser(... | e60c16137088b1ed1670628c59148c68d6cb49d5 | 3,645,711 |
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 os
def expand_home_folder(path):
"""Checks if path starts with ~ and expands it to the actual
home folder."""
if path.startswith("~"):
return os.environ.get('HOME') + path[1:]
return path | 3746859cc16b77dcfd02c675db81bfe4a195a85f | 3,645,722 |
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 |
import os
def get_file_xml(filename):
"""
:param filename: the filename, without the .xml suffix, in the tests/xml directory
:return: returns the specified file's xml
"""
file = os.path.join(XML_DIR, filename + '.xml')
with open(file, 'r') as f:
xml = f.read()
return xml | c08ef33bc12faa6b7194e1e7bac304e9f350bb09 | 3,645,727 |
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 |
import json
def submit(g_nocaptcha_response_value, secret_key, remoteip):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_response_field -- The value of recaptcha_response_field
from the form
secret_key -- your reCAPTCHA private key
rem... | 5dd56bd898862af8323a049e73e5cc3a9b983b26 | 3,645,735 |
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 os
def get_absolute_filepath(filepath: str) -> str:
"""Returns absolute filepath of the file/folder from the given `filepath` (along with the extension, if any)"""
absolute_filepath = os.path.realpath(path=filepath)
return absolute_filepath | be8ac0f55ed6fb039a746e0868bbd5ec2b8274ae | 3,645,760 |
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 |
import os
def schema_instance():
"""JSONSchema schema instance."""
schema_instance = JsonSchema(
schema=LOADED_SCHEMA_DATA,
filename="dns.yml",
root=os.path.join(FIXTURES_DIR, "schema", "schemas"),
)
return schema_instance | 7c9b2453e9db531d38fcfe5852a3df49d6839cfa | 3,645,764 |
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 os
import glob
import json
def load_measure_defs(measure_ids=None):
"""Load measure definitions from JSON files.
Since the lpzomnibus measure depends on other LP measures having already been
calculated, it is important that the measures are returned in alphabetical order.
(This is a bit of a h... | 4ff5eefceff2b5357c3b4c81f9de61148cff1745 | 3,645,768 |
import logging
import os
def setup_logger(name, warninglevel=logging.WARNING, logfilepath=path_to_log,
logformat='%(asctime)s %(levelname)s - %(name)-6s - %(message)s'):
"""Basic setup function to create a standard logging config. Default output
is to file in /tmp/dir."""
logfile=os.pat... | 87a00b5f0fd57e79e60cbf0847f86e35274aa9be | 3,645,769 |
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 |
def get_object(node):
""" Parse rebaron AtomTrailers node into Python object (taken from ongoing conversion object)
Works for object and local scope """
if len(node) > 1 and (node[0].value == 'self' or node[0].value == 'self_next'):
var_t = super_getattr(convert_obj, str(node))
else:
#... | 9b09dfaae08768e1544e676e93bcf5ce718c67d5 | 3,645,772 |
def read_label_from_txt(label_path):
"""Read label from txt file."""
text = np.fromfile(label_path)
bounding_box = []
with open(label_path, "r") as f:
labels = f.read().split("\n")
for label in labels:
if not label:
continue
label = label.split(" "... | dd6158af3531ec003b57c4fa47282957c3cb72ea | 3,645,773 |
from typing import Union
def _load_recipe(module, baked: bool = False) -> Union[BakedRecipe, Recipe]:
# load entry-point DAG
"""Load Queenbee plugin from Python package.
Usually you should not be using this function directly. Use ``load`` function
instead.
args:
module: Python module obj... | d0c400a234a777438418c4eb605723ea67509077 | 3,645,774 |
def compute_coeffs(shape, Aref, alfa):
"""Computes the lift and drag coefficients of the given shape at the given
angle of attack using the given reference area"""
alfa_vect = np.array([-np.sin(alfa),0,-np.cos(alfa)])
Fvect = np.array([0,0,0]) #Force coefficient vector
for panel in shape:
p... | 48cd922a460c56961cf2ebc2a3ecfc121622fe26 | 3,645,775 |
def draw_pitch(axis, rotate=False):
"""
Plots the lines of a soccer pitch using matplotlib.
Arguments
---------
axis : matplotlib.axes._subplots.AxesSubplot
- matplotlib axis object on which to plot shot freeze frame
rotate : bool
- if set to True, pitch is horizontal,
d... | 24a5b0de75ed70f6ce37afab8e04cf03afaa4651 | 3,645,776 |
import click
def file(filename, searchspec=None, searchtype=None, list_images=False,
sort_by=None, fields=None):
"""Examine images from a local file."""
if not list_images:
if searchtype is None or searchspec is None:
raise click.BadParameter(
'SEARCHTYPE and SEARC... | 6162ac7553f04225a6cad0fe262f2cc97dad39a2 | 3,645,777 |
def clip_to_norm(array, clip):
"""Clips the examples of a 2-dimensional array to a given maximum norm.
Parameters
----------
array : np.ndarray
Array to be clipped. After clipping, all examples have a 2-norm of at most `clip`.
clip : float
Norm at which to clip each example
R... | e7dca2cf9f129736ebc5f7909cb4fed41a4c7996 | 3,645,778 |
def getlineno(frame):
"""Get the line number from a frame object, allowing for optimization."""
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
return frame.f_lineno | b8c8d6fb3ebb8784d10250a42526b31e185e9b7a | 3,645,779 |
def _batch_sum(F, loss, batch_axis):
"""Return sum on the specified batch axis, not keeping the axis"""
if is_np_array():
axes = list(range(loss.ndim))
del axes[batch_axis]
return F.np.sum(loss, axis=axes)
else:
return F.sum(loss, axis=batch_axis, exclude=True) | 71bad3e21c1905e81b0e40b5be08ebc0426e1ca7 | 3,645,780 |
def tree_cons(a, tree: Pytree) -> Pytree:
"""
Prepend ``a`` in all tuples of the given tree.
"""
return jax.tree_map(
lambda x: _OpaqueSequence((a,) + tuple(x)),
tree,
is_leaf=lambda x: isinstance(x, tuple),
) | 1d82ca0a7b49d8e803fe8771f4f6b697826f5e27 | 3,645,781 |
from datetime import datetime
def add(moment: datetime) -> datetime:
"""Add one gigasecond to a given date and time."""
return moment + GIGASECOND | 87e009e408088d6c91ceb409408608947c0b9fd3 | 3,645,782 |
import os
def get_test_hooks(test_files, cfg, tracer=None):
"""Returns a list of test hooks from a given list of test modules."""
results = []
dirs = set(map(os.path.dirname, test_files))
for dir in list(dirs):
if os.path.basename(dir) == 'ftests':
dirs.add(os.path.join(os.path.dir... | eafe4a15a9410b600813588280ef48188b16738c | 3,645,783 |
def convert_to_short_log(log_level, message):
"""Convert a log message to its shorter format.
:param log_level: enum - 'LogLevel.<level>' e.g. 'LogLevel.Error'
:param message: str - log message
:return: enum - 'LogLevelInt.<value>` e.g. 'LogLevelInt.5'
"""
return f'{LogLevelInt[log_level.na... | 0d4c20ac4ec809dbb58494ef928586c95da88fbb | 3,645,784 |
import zipfile
import io
import pathlib
import warnings
def load_map(path, callback=None, meta_override=None):
"""Load a set of zipped csv AFM workshop data
If you are recording quantitative force-maps (i.e. multiple
curves on an x-y-grid) with AFM workshop setups, then you
might have realized that y... | bdf98f10a5decfc9a4dbd4b9cc90c75c7c95e76d | 3,645,785 |
def format_len(x):
"""
>>> format_len('abc')
3
>>> format_len(('(', ('(', 'def', ')'), 'yz', ')'))
11
"""
if not isinstance(x, (list, tuple)): return len(x)
if len(x) > 3: sep_len = 2 * (len(x) - 3)
else: sep_len = 0
return sum(map(format_len, x)) + sep_len | 723afb58bfed0cfb7fbd25a12b86b257bf8b40df | 3,645,786 |
import os
import platform
def build_user_agent():
"""Build the charmcraft's user agent."""
if any(key.startswith(prefix) for prefix in TESTING_ENV_PREFIXES for key in os.environ.keys()):
testing = " (testing) "
else:
testing = " "
os_platform = "{0.system}/{0.release} ({0.machine})".fo... | dcb036451388a900eb9f3d684167652247c720b4 | 3,645,787 |
def set_doi_ark(page_number, records_per_page, sort_on, doi_ark_value):
"""
Retrieve all metadata records for admin view. Retrieval is done
via POST because we must pass a session id so that the user is
authenticated.
Access control is done here. A user can modify only their own records
because... | 2b718232463a632dc07f73c1e6e5c3299ff57f18 | 3,645,788 |
from datetime import datetime
import argparse
def check_datetime(value):
"""
Check and convert "value" to a datetime object. Value can have multiple formats,
according to the argparse.ArgumentParser doc (defined in :func:`parse_cmd_args`)
Args:
value (str): The input value
Returns:
datetime.datetime: the i... | 7b85a85478f79f6e8ebb2a8663fd8d4860f16d18 | 3,645,789 |
def empiriline(x,p,L):
"""
Use the line L (which is an EmissionLine object) as a template.
The line is shifted, then interpolated, then rescaled, and allowed
to float.
"""
xnew = x - p[1]
yout = sp.zeros(len(xnew))
m = (xnew >= L.wv.min())*(xnew <= L.wv.max() )
ynew,znew = L.interp(x... | a0199a4623e834524711d0e78787d409da29d3ef | 3,645,790 |
def _get_z_slice_fn(z, data_dir):
"""Get array slice map to be applied to z dimension
Args:
z: String or 1-based index selector for z indexes constructed as any of the following:
- "best": Indicates that z slices should be inferred based on focal quality
- "all": Indicates that ... | 1982258bb98205fe4552de4db8b4e049e09af4bf | 3,645,791 |
def bar_data_wrapper(func):
"""Standardizes column names for any bar data"""
def wrapper(*args, **kwargs):
assert Ticker(args[0])
res: pd.DataFrame = func(*args, **kwargs)
return res.rename(columns=COL_NAMES).iterrows()
return wrapper | 4cfa9614ec430ba53ac3e86dc68c6a84ee3cfbee | 3,645,792 |
import torch
def rgb_to_grayscale(
image: Tensor, rgb_weights: list[float] = [0.299, 0.587, 0.114]
) -> Tensor:
"""Convert an RGB image to grayscale version of image. Image data is
assumed to be in the range of [0.0, 1.0].
Args:
image (Tensor[B, 3, H, W]):
RGB image to be converte... | d135a92e7189a745b2d9658b2b60a91c238fdbf8 | 3,645,793 |
from typing import Dict
from typing import Union
from datetime import datetime
import logging
def parse(msg: str) -> Dict[str, Union[str, int, float, bool, datetime]]:
"""Parse message from the feed output by dump1090 on port 30003
A dict is returned withAn SBS-1 message has the following attributes:
... | 9fd7d3b15eb08ebf11d77ac98a3ed215c9409cdd | 3,645,794 |
def _aware_to_agnostic(fr: NDFrame) -> NDFrame:
"""Recalculate values in tz-aware series or dataframe, to get a tz-agnostic one.
(i.e., A to B)."""
if not fr.index.tz:
raise ValueError("``fr`` must be tz-aware.")
idx_out = _idx_after_conversion(fr, None)
# Convert daily or longer.
if s... | c97b190828d5364033336b2dcc48d352aafe1132 | 3,645,795 |
import math
def cumulative_prob_to_value(prob, hp):
"""Convert a value from [0, 1] to a hyperparameter value."""
if isinstance(hp, Fixed):
return hp.value
elif isinstance(hp, Boolean):
return bool(prob >= 0.5)
elif isinstance(hp, Choice):
ele_prob = 1 / len(hp.values)
i... | d66e69f4cb580f8d3ce3004c082239717fd2854a | 3,645,796 |
import podpac
import podpac.datalib # May not be imported by default
import inspect
def get_ui_node_spec(module=None, category="default"):
"""
Returns a dictionary describing the specifications for each Node in a module.
Parameters
-----------
module: module
The Python module for which t... | 17978a9ebb50696990f601f449a0539bcf67c3dd | 3,645,797 |
def parse_branch_name(branch_name):
"""Split up a branch name of the form 'ocm-X.Y[-mce-M.N].
:param branch_name: A branch name. If of the form [remote/]ocm-X.Y[-mce-M.N] we will parse
it as noted below; otherwise the first return will be False.
:return parsed (bool): True if the branch_name was pa... | 2cb53aef0754c815dd61d4a1b640e12db64fbf83 | 3,645,798 |
import itertools
def symmetric_padding(
arr,
width):
"""
Pad an array using symmetric values.
This is equivalent to `np.pad(mode='symmetric')`, but should be faster.
Also, the `width` parameter is interpreted in a more general way.
Args:
arr (np.ndarray): The input array.... | dd91b4f3641332ecfffa734584fd87293c7169ee | 3,645,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.