content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
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 |
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 |
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 |
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 |
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 |
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 |
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 |
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 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 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 |
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 |
def plot_displacement(A, B, save=False, labels=None):
"""
A and B are both num_samples x num_dimensions
for now, num_dimensions must = 2
"""
assert A.shape == B.shape
assert A.shape[1] == 2
if not labels is None:
assert len(labels) == A.shape[0]
delta = B - A
delta_dir = delt... | 8cd05bbe56c590923e5d3a51d2b6eaf933b6a71b | 3,700 |
import math
def t_dp(tdb, rh):
""" Calculates the dew point temperature.
Parameters
----------
tdb: float
dry-bulb air temperature, [°C]
rh: float
relative humidity, [%]
Returns
-------
t_dp: float
dew point temperature, [°C]
"""
c = 257.14
b = 18... | d3cd7de10ef51f36bc5d5bd978d991d5bfe3ba4c | 3,701 |
def LinkConfig(reset=0, loopback=0, scrambling=1):
"""Link Configuration of TS1/TS2 Ordered Sets."""
value = ( reset << 0)
value |= ( loopback << 2)
value |= ((not scrambling) << 3)
return value | 901fe6df8bbe8dfa65cd516ac14692594608edfb | 3,703 |
def test_tedlium_release():
"""
Feature: TedliumDataset
Description: test release of tedlium
Expectation: release
set invalid data
get throw error
"""
def test_config(release):
try:
ds.TedliumDataset(DATA_DIR_TEDLIUM_RELEASE12, ... | a25f042745d1eea4dca62195e1259b7bcb8beb8d | 3,704 |
def get_data(n, input_dim, y_dim, attention_column=1):
"""
Data generation. x is purely random except that it's first value equals the target y.
In practice, the network should learn that the target = x[attention_column].
Therefore, most of its attention should be focused on the value addressed by atten... | 4c132abec92e8cd0ca6afd06e4032116d3631a50 | 3,705 |
def generate_tautomer_hydrogen_definitions(hydrogens, residue_name, isomer_index):
"""
Creates a hxml file that is used to add hydrogens for a specific tautomer to the heavy-atom skeleton
Parameters
----------
hydrogens: list of tuple
Tuple contains two atom names: (hydrogen-atom-name, he... | 69ec0c489d93edc7d8fe3ccde8df25c9c2fd01c9 | 3,706 |
def login(client=None, **defaults):
"""
@param host:
@param port:
@param identityName:
@param password:
@param serviceName:
@param perspectiveName:
@returntype: Deferred RemoteReference of Perspective
"""
d = defer.Deferred()
LoginDialog(client, d, defaults)
return d | a6c4593ef5b1fd29f46cba4a6484049bd093b6da | 3,707 |
import time
import json
import traceback
def insertInstrument():
""" Insert a new instrument or edit an existing instrument on a DAQBroker database. Guest users are not allowed to
create instruments. Created instruments are
.. :quickref: Create/Edit instrument; Creates or edits a DAQBroker instrument ins... | 537b89fa72b161c86c4b49a7a6813cf95df45f09 | 3,708 |
def find_distance_to_major_settlement(country, major_settlements, settlement):
"""
Finds the distance to the nearest major settlement.
"""
nearest = nearest_points(settlement['geometry'], major_settlements.unary_union)[1]
geom = LineString([
(
settlement['geomet... | 0bb33d3777ab0f60dfb05e69cb2f5ed711585b17 | 3,709 |
def x_for_half_max_y(xs, ys):
"""Return the x value for which the corresponding y value is half
of the maximum y value. If there is no exact corresponding x value,
one is calculated by linear interpolation from the two
surrounding values.
:param xs: x values
:param ys: y values corresponding to... | b18525664c98dc05d72a29f2904a13372f5696eb | 3,710 |
from typing import Union
from pathlib import Path
from typing import Dict
def get_dict_from_dotenv_file(filename: Union[Path, str]) -> Dict[str, str]:
"""
:param filename: .env file where values are extracted.
:return: a dict with keys and values extracted from the .env file.
"""
result_dict = {}
... | 97bce5a69e29f9606a58a54ed5cc4d05ab45fbca | 3,711 |
def calculate_note_numbers(note_list, key_override = None):
"""
Takes in a list of notes, and replaces the key signature (second
element of each note tuple) with the note's jianpu number.
Parameters
----------
note_list : list of tuples
List of notes to calculate jianpu numbers for.... | a32bbae7f64b381ad3384fdd8ae5c045c6887c87 | 3,712 |
import numpy as np
def _from_Gryzinski(DATA):
"""
This function computes the cross section and energy values from the files
that store information following the Gryzinski Model
"""
a_0 = DATA['a_0']['VALUES']
epsilon_i_H = DATA['epsilon_i_H']['VALUES']
epsilon_i = DATA['epsilon_... | 925fb1e76bf23915385cf56e3a663d111615700d | 3,713 |
from haversine import haversine
def stations_within_radius(stations, centre, r):
"""Returns an alphabetically-ordered list of the names of all the stations (in a list of stations objects) within a radius r (in km) of a central point
(which must be a Lat/Long coordinate)"""
# creates empty list
... | 36bf8312e4295638c1e297f4a31b535c9ee96eaf | 3,714 |
def ticket_message_url(request, structure_slug, ticket_id): # pragma: no cover
"""
Makes URL redirect to add ticket message by user role
:type structure_slug: String
:type ticket_id: String
:param structure_slug: structure slug
:param ticket_id: ticket code
:return: redirect
"""
s... | 29cec06302e943d74236ff82647cd28deb634107 | 3,716 |
from pathlib import Path
from datetime import datetime
from re import T
def load(
fin: Path,
azelfn: Path = None,
treq: list[datetime] = None,
wavelenreq: list[str] = None,
wavelength_altitude_km: dict[str, float] = None,
) -> dict[str, T.Any]:
"""
reads FITS images and spatial az/el calib... | bb656482c1db134c3045ac5a30b9cecb8d9f6716 | 3,717 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.