content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def timed_zip_map_agent(func, in_streams, out_stream,
call_streams=None, name=None):
"""
Parameters
----------
in_streams: list of Stream
The list of input streams of the agent.
Each input stream is timed, i.e. the elements
are pairs (timestam... | 0c23ff84ed72ee25b04bf118d57203c7831702e8 | 3,600 |
def get_repository_ids_requiring_prior_install( trans, tsr_ids, repository_dependencies ):
"""
Inspect the received repository_dependencies and determine if the encoded id of each required repository is in the received tsr_ids. If so,
then determine whether that required repository should be installed prio... | 035e7f358b8af7d4915b255b988f1fabc56605c1 | 3,601 |
from typing import Iterable
from typing import Tuple
from typing import List
def get_words_and_spaces(
words: Iterable[str], text: str
) -> Tuple[List[str], List[bool]]:
"""Given a list of words and a text, reconstruct the original tokens and
return a list of words and spaces that can be used to create a ... | 205c48435018a99433fce298a6035de902774810 | 3,602 |
from typing import List
import ast
def parse_names(source: str) -> List['Name']:
"""Parse names from source."""
tree = ast.parse(source)
visitor = ImportTrackerVisitor()
visitor.visit(tree)
return sum([split_access(a) for a in visitor.accessed], []) | 42f622052bc8acd5cdec187cd16695cec3b86154 | 3,603 |
def get_supported_language_variant(lang_code, strict=False):
"""
Returns the language-code that's listed in supported languages, possibly
selecting a more generic variant. Raises LookupError if nothing found.
If `strict` is False (the default), the function will look for an alternative
country-spec... | 6e99dc7d280ea28c3240f76a70b57234b9da98d3 | 3,604 |
def mean_square_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
"""
Calculate MSE loss
Parameters
----------
y_true: ndarray of shape (n_samples, )
True response values
y_pred: ndarray of shape (n_samples, )
Predicted response values
Returns
-------
MSE of g... | a9dbbd2264cba04618531024ce7eaae0e7c76b8d | 3,605 |
import sys
import os
import pickle
def gmail_auth(logfile, mode):
"""Handles Gmail authorization via Gmail API."""
creds = None
# the file .token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time
pickle... | 223ea8c1b9e80505f8b0aa58a9fdebb8b411d262 | 3,606 |
def graduation_threshold(session):
"""get graduation threshold
url : "/user/graduation-threshold"
Args:
session ([requests.session]): must be login webap!
Returns:
[requests.models.Response]: requests response
other error will return False
"""
# post it, it will re... | 18a1e3f1389995ee1c41fe49d16f047a3e4d8bf8 | 3,607 |
def q_conjugate(q):
"""
quarternion conjugate
"""
w, x, y, z = q
return (w, -x, -y, -z) | bb7e28d0318702d7d67616ba2f7dc0e922e27c72 | 3,608 |
def row_r(row, boxsize):
"""Cell labels in 'row' of Sudoku puzzle of dimension 'boxsize'."""
nr = n_rows(boxsize)
return range(nr * (row - 1) + 1, nr * row + 1) | b69e3995475b9ab62d9684c79d0d2473273487c7 | 3,609 |
from typing import Sequence
def get_set_from_word(permutation: Sequence[int], digit: Digit) -> set[int]:
"""
Returns a digit set from a given digit word,
based on the current permutation.
i.e. if:
permutation = [6, 5, 4, 3, 2, 1, 0]
digit = 'abcd'
then output = {6, 5, 4, 3}
"""
r... | 06058d96e94398f4a26613aefc8b5eeb92dec3e5 | 3,610 |
def get_avg_sentiment(sentiment):
"""
Compiles and returnes the average sentiment
of all titles and bodies of our query
"""
average = {}
for coin in sentiment:
# sum up all compound readings from each title & body associated with the
# coin we detected in keywords
averag... | 6a79c3d4f28e18a33290ea86a912389a5b48b0f3 | 3,611 |
def is_valid(url):
"""
Checks whether `url` is a valid URL.
"""
parsed = urlparse(url)
return bool(parsed.netloc) and bool(parsed.scheme) | 80e981d4556b0de79a68994666ac56d8dbe9bdd5 | 3,612 |
def data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_total_size_put(uuid, tapi_common_capacity_value=None): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_total_size_put
creates or updates tapi.common.CapacityValue # noqa: E501
:... | b03bf60af4b98099a7b07278e72c72cf8b247823 | 3,613 |
def statistics_power_law_alpha(A_in):
"""
Compute the power law coefficient of the degree distribution of the input graph
Parameters
----------
A_in: sparse matrix or np.array
The input adjacency matrix.
Returns
-------
Power law coefficient
"""
degrees = A_in.sum(ax... | 72f1ead0fa1e42752154ef1567ea8c10d407019d | 3,614 |
import os
def does_file_exist(path):
""" Checks if the given file is in the local filesystem.
Args:
path: A str, the path to the file.
Returns:
True on success, False otherwise.
"""
return os.path.isfile(path) | 38768ca739cf8a6f482bfb5d35cef397c70227c1 | 3,615 |
def common_gnuplot_settings():
""" common gnuplot settings. """
g_plot = Gnuplot.Gnuplot(persist=1)
# The following line is for rigor only. It seems to be assumed for .csv files
g_plot('set datafile separator \",\"')
g_plot('set ytics nomirror')
g_plot('set xtics nomirror')
g_plot('set xtics ... | 0a8149c2fce1d7738b4c85bfb2eb82d32fa3c540 | 3,616 |
def video_feed_cam1():
"""Video streaming route. Put this in the src attribute of an img tag."""
cam = Camera(0)
return Response(gen(cam), mimetype='multipart/x-mixed-replace; boundary=frame') | ca11f40bb603dc45d2709b46719fc11bde526c55 | 3,617 |
def listDatasets(objects = dir()):
"""
Utility function to identify currently loaded datasets.
Function should be called with default parameters,
ie as 'listDatasets()'
"""
datasetlist = []
for item in objects:
try:
if eval(item + '.' + 'has_key("DATA")') == True:
... | 061d7c9287c6166b3e7d55449be49db30400ce56 | 3,618 |
def _(node: FromReference, ctx: AnnotateContext) -> BoxType:
"""Check that the parent node had {node.name} as a valid reference. Raises
an error if not, else copy over the set of references.
"""
t = box_type(node.over)
ft = t.row.fields.get(node.name, None)
if not isinstance(ft, RowType):
... | f53c4f47d2027ae0a7fe59fb52f3fa48f463dda3 | 3,619 |
from typing import Mapping
from typing import Dict
def invert(d: Mapping):
"""
invert a mapper's key and value
:param d:
:return:
"""
r: Dict = {}
for k, v in d.items():
r[v] = of(r[v], k) if v in r else k
return r | 65a49d107b4277a97035becb7d8be3cc1098544f | 3,620 |
def data_dir() -> str:
"""The directory where result data is written to"""
return '/tmp/bingads/' | 7ace22372ad0043eb6492e028687e31e78d8a85f | 3,621 |
def intensity_weighted_dispersion(data, x0=0.0, dx=1.0, rms=None,
threshold=None, mask_path=None, axis=0):
"""
Returns the intensity weighted velocity dispersion (second moment).
"""
# Calculate the intensity weighted velocity first.
m1 = intensity_weighted_velocit... | dd3539ac2f48a1e9a6ceacc8262dc3a8e3646205 | 3,622 |
import requests
def vrtnws_api_request(service, path, params=None):
"""Sends a request to the VRTNWS API endpoint"""
url = BASE_URL_VRTNWS_API.format(service, path)
try:
res = requests.get(url, params)
try:
return res.json()
except ValueError:
return None
... | 9dad4e372348ff699762a5eaa42c9c1e7700e18e | 3,623 |
from typing import Type
def test_coreapi_schema(sdk_client_fs: ADCMClient, tested_class: Type[BaseAPIObject]):
"""Test coreapi schema"""
def _get_params(link):
result = {}
for field in link.fields:
result[field.name] = True
return result
schema_obj = sdk_client_fs._ap... | 8c205a2055ede6941b549112ef0893c37367ad71 | 3,624 |
def augment_tensor(matrix, ndim=None):
"""
Increase the dimensionality of a tensor,
splicing it into an identity matrix of a higher
dimension. Useful for generalizing
transformation matrices.
"""
s = matrix.shape
if ndim is None:
ndim = s[0]+1
arr = N.identity(ndim)
arr[:... | 89d6ea36d016f8648cdc62852e55351a965eae02 | 3,625 |
def ping_redis() -> bool:
"""Call ping on Redis."""
try:
return REDIS.ping()
except (redis.exceptions.ConnectionError, redis.exceptions.ResponseError):
LOGGER.warning('Redis Ping unsuccessful')
return False | 0584109627470629141fccadc87075bfbb82e753 | 3,626 |
def calculate_pool_reward(height: uint32) -> uint64:
"""
Returns the pool reward at a certain block height. The pool earns 7/8 of the reward in each block. If the farmer
is solo farming, they act as the pool, and therefore earn the entire block reward.
These halving events will not be hit at the exact t... | 9493c9b422eb58d429b586d3ea19da4e537a0d71 | 3,627 |
import sys
def get_argument(index, default=''):
"""
取得 shell 參數, 或使用預設值
"""
if len(sys.argv) <= index:
return default
return sys.argv[index] | c2c8d78b608745428a1d6b4d97b5081e1f0961e7 | 3,628 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
username = request.form.get("username").strip()
password = request.form.get("password")
# Ensure username was subm... | dcb37d57fc30d399c397c472d619b157575556ec | 3,629 |
def get_string_property(device_t, property):
""" Search the given device for the specified string property
@param device_t Device to search
@param property String to search for.
@return Python string containing the value, or None if not found.
"""
key = cf.CFStringCreateWithCString(
kCF... | fb08c31cd0bdbc3198b23a1c7d37d15d932a158f | 3,630 |
from typing import Callable
from typing import Any
def gamma_from_delta(
fn: Callable[..., Tensor], *, create_graph: bool = False, **params: Any
) -> Tensor:
"""Computes and returns gamma of a derivative from the formula of delta.
Note:
The keyword argument ``**params`` should contain at least on... | 508cb5df3cb19c5406ad190dbb0562140eab097a | 3,631 |
import re
def clean_filename(string: str) -> str:
"""
清理文件名中的非法字符,防止保存到文件系统时出错
:param string:
:return:
"""
string = string.replace(':', '_').replace('/', '_').replace('\x00', '_')
string = re.sub('[\n\\\*><?\"|\t]', '', string)
return string.strip() | 805023382e30c0d0113715cdf6c7bcbc8b383066 | 3,632 |
def homework(request, id_class):
"""
View for listing the specified class' assignments
"""
cl = Classes.objects.get(pk=id_class)
assm = Assignments.objects.all().filter(a_class=cl)
return render_to_response("assignments.html", {"assignments": assm, "class": cl}, context_instance=RequestContext(r... | be828d4519b73cdbd6f8f34b0aa10eda1299c0f0 | 3,633 |
import os
import importlib
def build_model(master_config):
"""
Imports the proper model class and builds model
"""
available_models = os.listdir("lib/classes/model_classes")
available_models = [i.replace(".py", "") for i in available_models]
model_type = master_config.Core_Config.Model_Config.... | 3089df4094e211a0e5a7fe521bc08b2ca5ff23b0 | 3,634 |
def get_digits_from_right_to_left(number):
"""Return digits of an integer excluding the sign."""
number = abs(number)
if number < 10:
return (number, )
lst = list()
while number:
number, digit = divmod(number, 10)
lst.insert(0, digit)
return tuple(lst) | 6b5626ad42313534d207c75d2713d0c9dc97507c | 3,635 |
def make_diamond(block):
"""
Return a block after rotating counterclockwise 45° to form a diamond
"""
result = []
upper = upper_triangle(block)
upper = [i.rjust(size-1) for i in upper]
upper_form = []
upper_length = len(upper)
for i in range(upper_length):
upper_form.append... | e8e2afbdd34465a03e9db53169bf5c6bec1a375a | 3,636 |
def do_sitelist(parser, token):
"""
Allows a template-level call a list of all the active sites.
"""
return SitelistNode() | 208288989469a57e141f64be37d595fe8a1f84d6 | 3,637 |
def events_from_file(filepath):
"""Returns all events in a single event file.
Args:
filepath: Path to the event file.
Returns:
A list of all tf.Event protos in the event file.
"""
records = list(tf_record.tf_record_iterator(filepath))
result = []
for r in records:
event = event_pb2.Event()
... | 6408fe02facd709a0d449cb87a2d963a0d92a007 | 3,638 |
def build_null_stop_time_series(feed, date_label='20010101', freq='5Min',
*, split_directions=False):
"""
Return a stop time series with the same index and hierarchical columns
as output by :func:`compute_stop_time_series_base`,
but fill it full of null values.
"""
start = date_label
end =... | da638448f7f5b88d6e23e487f2ecdbc0e72a6607 | 3,639 |
import signal
def yulewalk(order, F, M):
"""Recursive filter design using a least-squares method.
[B,A] = YULEWALK(N,F,M) finds the N-th order recursive filter
coefficients B and A such that the filter:
B(z) b(1) + b(2)z^-1 + .... + b(n)z^-(n-1)
---- = -------------------------------------
... | d3e0f709d303c7432854d4975c858b5968245084 | 3,640 |
async def get_user_from_event(event):
""" Get the user from argument or replied message. """
if event.reply_to_msg_id:
previous_message = await event.get_reply_message()
user_obj = await tbot.get_entity(previous_message.sender_id)
else:
user = event.pattern_match.group(1)
if... | 600fc6d1e73f4637f51479d2e2ebabaa93723b34 | 3,641 |
import json
def parse_contest_list(json_file):
"""Parse a list of Contests from a JSON file.
Note:
Template for Contest format in JSON in contest_template.json
"""
with open(json_file, 'r') as json_data:
data = json.load(json_data)
contests = []
for contest in data:
... | 637da8b03fe975aa2183d78eaa3704d57d66680d | 3,642 |
def get_image_blob(roidb, mode):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
if mode == 'train' or mode == 'val':
with open(roidb['image'], 'rb') as f:
data = f.read()
data = np.frombuffer(data, dtype='uint8')
img = cv2.imdecode(d... | 35fdea333b8245294c16907e8c26c16164fb4906 | 3,643 |
def rx_weight_fn(edge):
"""A function for returning the weight from the common vertex."""
return float(edge["weight"]) | 4c405ffeae306a3920a6e624c748fb00cc1ee8ac | 3,644 |
def image_inputs(images_and_videos, data_dir, text_tmp_images):
"""Generates a list of input arguments for ffmpeg with the given images."""
include_cmd = []
# adds images as video starting on overlay time and finishing on overlay end
img_formats = ['gif', 'jpg', 'jpeg', 'png']
for ovl in images_and_videos:
... | b210687d00edc802cbf362e4394b61e0c0989095 | 3,645 |
def generate_graph(data_sets: pd.DataFrame, data_source: str, data_state: str, toggle_new_case: bool, year: int) -> tuple[px.line, px.bar]:
"""Takes in the inputs and returns a graph object. The inputs are the source, data, location and year.
The graph is a prediction of the sentiment from the comments as a fun... | 437e34419e187ba7ae86bd50c57844a5e55a4bf7 | 3,646 |
def f_not_null(seq):
"""过滤非空值"""
seq = filter(lambda x: x not in (None, '', {}, [], ()), seq)
return seq | a88eab0a03ef5c1db3ceb4445bb0d84a54157875 | 3,647 |
def flickr(name, args, options, content, lineno,
contentOffset, blockText, state, stateMachine):
""" Restructured text extension for inserting flickr embedded slideshows """
if len(content) == 0:
return
string_vars = {
'flickid': content[0],
'width': 400,
'height'... | 9b41c558dd5f5ef7be1aff1e9567f1c5d5b26f31 | 3,648 |
def serialize(key):
"""
Return serialized version of key name
"""
s = current_app.config['SERIALIZER']
return s.dumps(key) | dba2202e00960420252c00120333b142d3a8f216 | 3,649 |
def calc_disordered_regions(limits, seq):
"""
Returns the sequence of disordered regions given a string of
starts and ends of the regions and the sequence.
Example
-------
limits = 1_5;8_10
seq = AHSEDQNAAANTH...
This will return `AHSED_AAA`
"""
seq = seq.replace(' ', '... | 2c9a487a776a742470deb98e6f471b04b23a0ff7 | 3,650 |
import random
def person_attribute_string_factory(sqla):
"""Create a fake person attribute that is enumerated."""
create_multiple_attributes(sqla, 5, 1)
people = sqla.query(Person).all()
if not people:
create_multiple_people(sqla, random.randint(3, 6))
people = sqla.query(Person).all()... | b2c3f632c0671b41044e143c5aab32abf928a362 | 3,651 |
def forward_pass(log_a, log_b, logprob_s0):
"""Computing the forward pass of Baum-Welch Algorithm.
By employing log-exp-sum trick, values are computed in log space, including
the output. Notation is adopted from https://arxiv.org/abs/1910.09588.
`log_a` is the likelihood of discrete states, `log p(s[t] | s[t-1... | e3c6cc193ea01bd308c821de31c43ab42c9fea69 | 3,652 |
def TonnetzToString(Tonnetz):
"""TonnetzToString: List -> String."""
TonnetzString = getKeyByValue(dictOfTonnetze, Tonnetz)
return TonnetzString | db878b4e0b857d08171653d53802fb41e6ca46a4 | 3,653 |
def get_mc_calibration_coeffs(tel_id):
"""
Get the calibration coefficients from the MC data file to the
data. This is ahack (until we have a real data structure for the
calibrated data), it should move into `ctapipe.io.hessio_event_source`.
returns
-------
(peds,gains) : arrays of the ped... | 0bd202f608ff062426d8cdce32677c2c2f2583de | 3,654 |
from math import exp, pi, sqrt
def bryc(K):
"""
基于2002年Bryc提出的一致逼近函数近似累积正态分布函数
绝对误差小于1.9e-5
:param X: 负无穷到正无穷取值
:return: 累积正态分布积分值的近似
"""
X = abs(K)
cnd = 1.-(X*X + 5.575192*X + 12.77436324) * exp(-X*X/2.)/(sqrt(2.*pi)*pow(X, 3) + 14.38718147*pow(X, 2) + 31.53531977*X + 2*12.77436324)
... | e2feb6fa7f806294cef60bb5afdc4e70c95447f8 | 3,655 |
def grid_square_neighbors_1d_from(shape_slim):
"""
From a (y,x) grid of coordinates, determine the 8 neighors of every coordinate on the grid which has 8
neighboring (y,x) coordinates.
Neighbor indexes use the 1D index of the pixel on the masked grid counting from the top-left right and down.
For ... | 72c0009915b397005c9b9afb52dfb2fa20c1c99c | 3,656 |
def get_total_entries(df, pdbid, cdr):
"""
Get the total number of entries of the particular CDR and PDBID in the database
:param df: dataframe.DataFrame
:rtype: int
"""
return len(get_all_entries(df, pdbid, cdr)) | fec351a6d23fd73e082d3b5c066fa9d367629dea | 3,657 |
def _gf2mulxinvmod(a,m):
"""
Computes ``a * x^(-1) mod m``.
*NOTE*: Does *not* check whether `a` is smaller in degree than `m`.
Parameters
----------
a, m : integer
Polynomial coefficient bit vectors.
Polynomial `a` should be smaller degree than `m`.
Returns
-------
... | e60e99cd7ebfd3df795cdad5d712f1278b7b9a0f | 3,658 |
def find_cuda_family_config(repository_ctx, script_path, cuda_libraries):
"""Returns CUDA config dictionary from running find_cuda_config.py"""
python_bin = repository_ctx.which("python3")
exec_result = execute(repository_ctx, [python_bin, script_path] + cuda_libraries)
if exec_result.return_code:
... | e71c14528946c8815bef2355cbcc797bbc03bb39 | 3,659 |
def _prediction_feature_weights(booster, dmatrix, n_targets,
feature_names, xgb_feature_names):
""" For each target, return score and numpy array with feature weights
on this prediction, following an idea from
http://blog.datadive.net/interpreting-random-forests/
"""
... | 54814b1d0d2ce0ca66e7bdd5c5933477c5c8c169 | 3,660 |
from typing import Sequence
from typing import Collection
from typing import List
def group_by_repo(repository_full_name_column_name: str,
repos: Sequence[Collection[str]],
df: pd.DataFrame,
) -> List[np.ndarray]:
"""Group items by the value of their "reposito... | 8e10e32d1a1bb8b31e25000dc63be0b3cd1645d0 | 3,661 |
def _row_or_col_is_header(s_count, v_count):
"""
Utility function for subdivide
Heuristic for whether a row/col is a header or not.
"""
if s_count == 1 and v_count == 1:
return False
else:
return (s_count + 1) / (v_count + s_count + 1) >= 2. / 3. | 525b235fe7027524658f75426b6dbc9c8e334232 | 3,662 |
def values_hash(array, step=0):
"""
Return consistent hash of array values
:param array array: (n,) array with or without structure
:param uint64 step: optional step number to modify hash values
:returns: (n,) uint64 array
"""
cls, cast_dtype, view_dtype = _get_optimal_cast(array)
array ... | 7d2fedf0ca244797dd33e4f344dc81726b26efb6 | 3,663 |
import urllib
async def get_molecule_image(optimization_id: str):
"""Render the molecule associated with a particular bespoke optimization to an
SVG file."""
task = _get_task(optimization_id=optimization_id)
svg_content = smiles_to_image(urllib.parse.unquote(task.input_schema.smiles))
svg_respon... | 6e3b178f18cef7d8a7ed4c75b75dfb0acd346fbe | 3,664 |
import torch
def total_variation_divergence(logits, targets, reduction='mean'):
"""
Loss.
:param logits: predicted logits
:type logits: torch.autograd.Variable
:param targets: target distributions
:type targets: torch.autograd.Variable
:param reduction: reduction type
:type reduction:... | 75f848e71e6fc78c60341e3fb46a2ff7d4531cbc | 3,665 |
def initialize_parameters(n_in, n_out, ini_type='plain'):
"""
Helper function to initialize some form of random weights and Zero biases
Args:
n_in: size of input layer
n_out: size of output/number of neurons
ini_type: set initialization type for weights
Returns:
params: ... | 1350d086c12dc40792a2f84a3a5edf5e683f9e95 | 3,666 |
def logcdf(samples, data, prior_bounds, weights=None, direction=DEFAULT_CUMULATIVE_INTEGRAL_DIRECTION, num_proc=DEFAULT_NUM_PROC):
"""estimates the log(cdf) at all points in samples based on data and integration in "direction".
Does this directly by estimating the CDF from the weighted samples WITHOUT building ... | 5b57b964a57cae59425e73b089a3d1d6f7fbf95d | 3,667 |
import requests
import json
def post_gist(description, files):
"""Post a gist of the analysis"""
username, password = get_auth()
sess = requests.Session()
sess.auth = (username, password)
params = {
'description': description,
'files': files,
'public': False,
}
he... | a348203a08455099f6eefb660a234796d22380ae | 3,668 |
def compute_exposure_params(reference, tone_mapper="aces", t_max=0.85, t_min=0.85):
"""
Computes start and stop exposure for HDR-FLIP based on given tone mapper and reference image.
Refer to the Visualizing Errors in Rendered High Dynamic Range Images
paper for details about the formulas
:param reference: float t... | 330265585be9a27f38f20cef55d6a2c588819d35 | 3,669 |
import os
def gen_filenames(only_new=False):
"""Returns a list of filenames referenced in sys.modules and translation
files.
"""
global _cached_modules, _cached_filenames
module_values = set(module_white_list())
if _cached_modules == module_values:
# No changes in module list, short-ci... | 7f526930729d830cd10f4b100f2dbea76025b926 | 3,670 |
from typing import Literal
from typing import Any
def scores_generic_graph(
num_vertices: int,
edges: NpArrayEdges,
weights: NpArrayEdgesFloat,
cond: Literal["or", "both", "out", "in"] = "or",
is_directed: bool = False,
) -> NpArrayEdgesFloat:
"""
Args:
num_vertices: int
... | 6f3b4b969663ff48be7b0a4cf3571800dd0d15e8 | 3,671 |
def handle_storage_class(vol):
"""
vol: dict (send from the frontend)
If the fronend sent the special values `{none}` or `{empty}` then the
backend will need to set the corresponding storage_class value that the
python client expects.
"""
if "class" not in vol:
return None
if vo... | a2747b717c6b83bb1128f1d5e9d7696dd8deda19 | 3,672 |
def spherical_to_cartesian(radius, theta, phi):
""" Convert from spherical coordinates to cartesian.
Parameters
-------
radius: float
radial coordinate
theta: float
axial coordinate
phi: float
azimuthal coordinate
Returns
-------
list: cartesian vector
"... | bc76aa608171243f3afc1fbdbaca90931b1e3d17 | 3,673 |
import torch
def compute_mrcnn_bbox_loss(mrcnn_target_deltas, mrcnn_pred_deltas, target_class_ids):
"""
:param mrcnn_target_deltas: (n_sampled_rois, (dy, dx, (dz), log(dh), log(dw), (log(dh)))
:param mrcnn_pred_deltas: (n_sampled_rois, n_classes, (dy, dx, (dz), log(dh), log(dw), (log(dh)))
:param targ... | b6f62a3255f21ce26cd69b6e53a778dfc23a7b86 | 3,674 |
import torch
def _sharpness(prediction):
"""TODO: Implement for discrete inputs as entropy."""
_, chol_std = prediction
scale = torch.diagonal(chol_std, dim1=-1, dim2=-2)
return scale.square().mean() | a914c43011d98a183c83fbb6024da7fbb1f87887 | 3,675 |
def dummy_sgs(dummies, sym, n):
"""
Return the strong generators for dummy indices
Parameters
==========
dummies : list of dummy indices
`dummies[2k], dummies[2k+1]` are paired indices
sym : symmetry under interchange of contracted dummies::
* None no symmetry
* 0 ... | 774203b62a0335f9bea176a1228673b2466324e3 | 3,676 |
import time
def mc_tracing(func):
"""
This decorator is used below and logs certain statistics about the formula evaluation.
It measures execution time, and how many nodes are found that statisfy each subformula.
"""
@wraps(func)
def wrapper(*args):
formula = args[1]
start = ti... | c3a318de80a7d0c29e2a5b2dd0f4873d3242f1d9 | 3,677 |
def get_uniform_comparator(comparator):
""" convert comparator alias to uniform name
"""
if comparator in ["eq", "equals", "==", "is"]:
return "equals"
elif comparator in ["lt", "less_than"]:
return "less_than"
elif comparator in ["le", "less_than_or_equals"]:
return "less_th... | 20c24ba35dea92d916d9dd1006d110db277e0816 | 3,678 |
def inorder_traversal(root):
"""Function to traverse a binary tree inorder
Args:
root (Node): The root of a binary tree
Returns:
(list): List containing all the values of the tree from an inorder search
"""
res = []
if root:
res = inorder_traversal(root.left)
re... | f6d5141cbe9f39da609bd515133b367975e56688 | 3,679 |
def get_extractor_metadata(clowder_md, extractor_name, extractor_version=None):
"""Crawl Clowder metadata object for particular extractor metadata and return if found.
If extractor_version specified, returned metadata must match."""
for sub_metadata in clowder_md:
if 'agent' in sub_metadata:
... | 15a5e41003211dbd2e52a467ccd221102ebc28c1 | 3,680 |
def intensity_scale(X_f, X_o, name, thrs, scales=None, wavelet="Haar"):
"""
Compute an intensity-scale verification score.
Parameters
----------
X_f: array_like
Array of shape (m, n) containing the forecast field.
X_o: array_like
Array of shape (m, n) containing the verification... | 1f38d30378a9ec2dff7babd4edb52fceb8e23dab | 3,681 |
def make_count(bits, default_count=50):
"""
Return items count from URL bits if last bit is positive integer.
>>> make_count(['Emacs'])
50
>>> make_count(['20'])
20
>>> make_count(['бред', '15'])
15
"""
count = default_count
if len(bits) > 0:
last_bit = bits[len(... | 8e7dc356ba7c0787b4b44ee8bba17568e27d1619 | 3,682 |
def synthesize_ntf_minmax(order=32, osr=32, H_inf=1.5, f0=0, zf=False,
**options):
"""
Alias of :func:`ntf_fir_minmax`
.. deprecated:: 0.11.0
Function is now available from the :mod:`NTFdesign` module with
name :func:`ntf_fir_minmax`
"""
warn("Function supers... | 6c6752584a4f9760218456b640187e442f2442aa | 3,683 |
def r2f(value):
"""
converts temperature in R(degrees Rankine) to F(degrees Fahrenheit)
:param value: temperature in R(degrees Rankine)
:return: temperature in F(degrees Fahrenheit)
"""
return const.convert_temperature(value, 'R', 'F') | 31e08dd0f3194912e5e306a5a2a5a4c9a98ef723 | 3,684 |
import os
def get_currently_playing_track():
"""Returns currently playing track as a file
No request params.
"""
try:
pt, _, _ = Track.get_currently_playing()
path = pt.track.path
return send_file( os.path.join( '..', path ) )
except DoesNotExist:
return error_resp... | ae1ec9123f70e1650813bae1397fbf2500287356 | 3,685 |
def get_statistics_percentiles(d_min, stats):
"""
For a given set of statistics, determine their percentile ranking compared
to other crystal structures at similar resolution.
"""
if (d_min is None):
return dict([ (s, None) for s in stats.keys() ])
try :
db = load_db()
except Exception as e :
... | 1c38bec6ee0c3f3acbaaf0064fdbbfa6d166150e | 3,686 |
import re
def normalize_number(value: str, number_format: str) -> str:
"""
Transform a string that essentially represents a number to the corresponding number with the given number format.
Return a string that includes the transformed number. If the given number format does not match any supported one, r... | c22bff28fc6ef6f424d0e9b8b0358b327cd153c5 | 3,687 |
import os
import subprocess
def get_returning_users(returning_count):
"""
Returns a list of returning users
:return:
"""
# Read the exclusion file
if os.path.exists(stats_dir + 'exclusion.lst'):
exclusion_file = open(stats_dir + 'exclusion.lst', 'r')
exclusion_list = exclusion_... | 021edab459a033a726f2c0af9872c3e3dfea0a72 | 3,688 |
def benchmark(Algorithm_, Network_, test):
"""
Benchmarks the Algorithm on a given class of Networks. Samples variable network size, and plots results.
@param Algorithm_: a subclass of Synchronous_Algorithm, the algorithm to test.
@param Network_: a subclass of Network, the network on which to benchmar... | ee8d0d2bd9c9bc11eb8db07c09bfd6dc22e61ace | 3,689 |
def scale(obj, scale_ratio):
"""
:param obj: trimesh or file path
:param scale_ratio: float, scale all axis equally
:return:
author: weiwei
date: 20201116
"""
if isinstance(obj, trm.Trimesh):
tmpmesh = obj.copy()
tmpmesh.apply_scale(scale_ratio)
return tmpmesh
... | bdc84d04e9fd7d9009a60e2c47e59322526e3248 | 3,690 |
import collections
def _case_verify_and_canonicalize_args(pred_fn_pairs, exclusive, name,
allow_python_preds):
"""Verifies input arguments for the case function.
Args:
pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor, and a
callable which returns a ... | 6a6b16561600ce24ef69964ff33a309d664bb53f | 3,691 |
def get_policy(policy_name: str) -> Policy:
"""Returns a mixed precision policy parsed from a string."""
# Loose grammar supporting:
# - "c=f16" (params full, compute+output in f16),
# - "p=f16,c=f16" (params, compute and output in f16).
# - "p=f16,c=bf16" (params in f16, compute in bf16, output... | 2aac684706f001b537bdb103abfc63ffc79eb4c5 | 3,692 |
def reset():
"""Reset password page. User launch this page via the link in
the find password email."""
if g.user:
return redirect('/')
token = request.values.get('token')
if not token:
flash(_('Token is missing.'), 'error')
return redirect('/')
user = verify_auth_token(to... | fd6e2c356bb664b87d1d2ad9dcd2305a05d541ec | 3,693 |
from pathlib import Path
def usort_file(path: Path, dry_run: bool = False, diff: bool = False) -> Result:
"""
Sorts one file, optionally writing the result back.
Returns: a Result object.
Note: Not intended to be run concurrently, as the timings are stored in a
global.
"""
result = Resul... | b8455cc81f25890ecb88e809aab7d016ee1604d2 | 3,694 |
from datetime import datetime
import dateutil
def datetimeobj_a__d_b_Y_H_M_S_z(value):
"""Convert timestamp string to a datetime object.
Timestamps strings like 'Tue, 18 Jun 2013 22:00:00 +1000' are able to be
converted by this function.
Args:
value: A timestamp string in the format '%a, %d ... | 2d3761d842a6f21ea646f6ac539d7ca4d78e20e9 | 3,695 |
def fn_sigmoid_proxy_func(threshold, preds, labels, temperature=1.):
"""Approximation of False rejection rate using Sigmoid."""
return tf.reduce_sum(
tf.multiply(tf.sigmoid(-1. * temperature * (preds - threshold)), labels)) | 84a248f4883ab383e2afc6556a335f33d114a9ae | 3,696 |
from typing import Optional
from typing import Sequence
def get_images(filters: Optional[Sequence[pulumi.InputType['GetImagesFilterArgs']]] = None,
sorts: Optional[Sequence[pulumi.InputType['GetImagesSortArgs']]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetImagesR... | 0e56efb6f7735f3b15f2241e7bfa43e28863f866 | 3,697 |
def polevl(x, coef):
"""Taken from http://numba.pydata.org/numba-doc/0.12.2/examples.html"""
N = len(coef)
ans = coef[0]
i = 1
while i < N:
ans = ans * x + coef[i]
i += 1
return ans | 2c7c0f5b329ab5ea28d123112ec065dd0c292c12 | 3,698 |
import os
def is_regular_file(path):
"""Check whether 'path' is a regular file, especially not a symlink."""
return os.path.isfile(path) and not os.path.islink(path) | 28ad19350d1a11b62e858aa8408cb29dc4d4c126 | 3,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.