content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
from typing import Optional
def _get_build_to_download(build: str) -> Tuple[str, Optional[str]]:
"""Get the build version to download.
If the passed value is not an explict build number (eg. 15.0) then
the build for the current day of that major/minor will be downloaded.
:p... | 96215d80af60c25877da3eb7ff65147b2652a592 | 1,605 |
def label(type=None,
is_emphasis=True,
is_label_show=False,
label_pos=None,
label_text_color="#000",
label_text_size=12,
formatter=None,
**kwargs):
""" Text label of , to explain some data information about graphic item like value, name and so on... | 728997988797baef2ad080c8a317936e91f5c579 | 1,606 |
def MPC_ComputeCrc(card_type: TechnologyType, frame: bytes) -> bytes:
"""Computes frame CRC
Parameters
----------
card_type : TechnologyType
Technology type
frame : bytes
Input frame
Returns
-------
bytes
CRC bytes
"""
if not isinstance(card_type, Techno... | 3a545aea7adbae35d7fa3a8f4bd758a45dae78ae | 1,607 |
def max_contiguous(input, value, _builder=None):
"""
Let the compiler knows that the `value` first values in :code:`input` are contiguous.
"""
value = _constexpr_to_value(value)
return semantic.max_contiguous(input, value) | 6e90d76487677c270ecd73ece7ebbf39e4fdb9bf | 1,608 |
import torch
def kl_reverse(logu: torch.Tensor) -> torch.Tensor:
"""
Log-space Csiszar function for reverse KL-divergence D_f(p,q) = KL(q||p).
Also known as the exclusive KL-divergence and negative ELBO, minimizing
results in zero-forcing / mode-seeking behavior.
Args:
logu (torch.Tensor... | fcc9035de183cb6d5b51e169dd764ff92ab290aa | 1,609 |
import json
def json_configs(type, name):
"""
Base method that extracts the configuration info from the json file defined
in SETTINGS
Args:
type - the name of the type of configuration object to look in
name - the name of the object whose configs will be extracted
Returns... | 57507adc7a41666084df734972e067015d055cce | 1,613 |
def reload() -> bool:
"""Gracefully reloads uWSGI.
* http://uwsgi.readthedocs.io/en/latest/Management.html#reloading-the-server
"""
return False | f020356774d0a500b6755d53d548a804392c39d3 | 1,614 |
import re
def predict_imagen(titulo=None,
grados=None,
ano_lanzamiento=None,
paginas=None,
codbarras=None):
""" Predictor for Imagen from model/5a143f443980b50a74003699
Created using BigMLer
"""
tm_tokens = 'tokens_only... | ecee556bf9eb563cb40bf759bb6c4bfdf74922a0 | 1,615 |
def euler_to_axis_angle(roll: float, pitch: float, yaw: float) -> np.ndarray:
"""Converts Euler angle to Axis-angle format.
Args:
roll: rotation angle.
pitch: up/down angle.
yaw: left/right angle.
Returns:
Equivalent Axis-angle format.
"""
r = Rotation.from_euler('xyz', [roll, pitch, yaw])
... | 89fff617c2335c35110fa0cf2f7a2d1da194846c | 1,617 |
def add_scalebar(axis, matchx=True, matchy=True, hidex=True, hidey=True, unitsx=None, unitsy=None, scalex=1.0, scaley=1.0, xmax=None, ymax=None, space=None, **kwargs):
"""
Add scalebars to axes
Adds a set of scale bars to *ax*, matching the size to the ticks of the plot and optionally hiding the x and y ax... | 2d481f0313608a1a29d3c99fe4ac21faf1ab1d9d | 1,618 |
def create_medoids_summary(season, country, result, d, names):
"""
Create cluster based summary of medoids' description
Parameters:
season: str, season sued to cluster
country: str, used to cluster
result: cluster resutls joint to customer features
d: trajectory clustering re... | b86a266a7bf31ccd836b653d1e137f60d65c02ff | 1,620 |
from typing import Iterable
import time
def backtest(
strategy,
data, # Treated as csv path is str, and dataframe of pd.DataFrame
commission=COMMISSION_PER_TRANSACTION,
init_cash=INIT_CASH,
data_format="c",
plot=True,
verbose=True,
sort_by="rnorm",
**kwargs
):
"""
Backtest... | 4822d7f6ec2bdc260b084408b3668c0636c5f19c | 1,621 |
def mapflatdeep(iteratee, *seqs):
"""
Map an `iteratee` to each element of each iterable in `seqs` and recurisvely flatten the
results.
Examples:
>>> list(mapflatdeep(lambda n: [[n, n]], [1, 2]))
[1, 1, 2, 2]
Args:
iteratee (object): Iteratee applied per iteration.
... | df297c279f93edca4bff348189386241832c7e5b | 1,622 |
def eHealthClass_getSkinConductanceVoltage():
"""eHealthClass_getSkinConductanceVoltage() -> float"""
return _ehealth.eHealthClass_getSkinConductanceVoltage() | f97edfe96d443991a16cb94a405806815c29546a | 1,623 |
def construct_item(passage: str, labels):
"""
根据输入的passage和labels构建item,
我在巴拉巴拉...
['B-ASP', 'I-ASP', 'I-ASP', 'I-ASP', ..., 'I-OPI', 'I-OPI', 'O']
构造结果示例如下:
{
'passage': '使用一段时间才来评价,淡淡的香味,喜欢!',
'aspect': [['香味', 14, 16]],
'opinion': [['喜欢', 17, 19]]
}
:return:
... | b4a31b67df7c82b56e0eb388e964422f257a9293 | 1,624 |
def getStartingAddress(packet):
"""Get the address of a modbus request"""
return ((ord(packet[8]) << 8) + ord(packet[9])) | 83dc55585d67169b0716cc3e98008574c434213b | 1,625 |
from typing import Union
def rf_local_unequal(left_tile_col, rhs: Union[float, int, Column_type]) -> Column:
"""Cellwise inequality comparison between two tiles, or with a scalar value"""
if isinstance(rhs, (float, int)):
rhs = lit(rhs)
return _apply_column_function('rf_local_unequal', left_tile_c... | 3d2b95d35744f35c4f27802952366a5ffb1cf557 | 1,626 |
def get_normalized_star_spectrum(spectral_type, magnitude, filter_name):
"""
spec_data = get_normalized_star_spectrum(spectral_type, magnitude, filter_name)
Returns a structure containing the synthetic spectrum of the star having the spectral type and magnitude
in the specified input filter. Magnitude... | 001406dc4ffa1bc08960c27950333965ffa07836 | 1,627 |
def header(**kwargs):
"""
Create header node and return it.
Equivalent to :code:`return Element("header", attributes...)`.
"""
return Element("header", **kwargs) | e02784bbb8bf153fc7c815fb06a3e1246dbb1847 | 1,628 |
def bump_func(xs_arg, low, high, btype):
"""
Setup initial displacement distribution of a bump,
either sine or triangular.
"""
# check the case of a single float as input
if isinstance(xs_arg, (int, float)):
xs_in = np.array([float(xs_arg)])
scalar = True
else:
xs_in ... | 22991769be4f0c09992fcf3a069d05f98e6c0d55 | 1,629 |
def setup_session(username, password, check_url=None,
session=None, verify=True):
"""
A special call to get_cookies.setup_session that is tailored for
URS EARTHDATA at NASA credentials.
"""
if session is not None:
# URS connections cannot be kept alive at the moment.
... | e5d6eae8c79343249a7d22b1a8e90f94d4ee2420 | 1,630 |
import numbers
def is_number(item):
"""Check if the item is a number."""
return isinstance(item, numbers.Number) | 6c3fb6817a0eda2b27fcedd22763461dceef6bc1 | 1,631 |
def from_list(commands):
"""
Given a list of tuples of form (depth, text)
that represents a DFS traversal of a command tree,
returns a dictionary representing command tree.
"""
def subtrees(commands, level):
if not commands:
return
acc = []
parent, *commands... | 39dad022bf81712e074f6e8bb26813302da9ef9f | 1,632 |
def get_cassandra_config_options(config):
"""Parse Cassandra's Config class to get all possible config values.
Unfortunately, some are hidden from the default cassandra.yaml file, so this appears the only way to do this."""
return _get_config_options(config=config, config_class='org.apache.cassandra.config... | 2a52a50bed46105c7c1a1ea85e0c10a33ee02de1 | 1,633 |
def get_possible_zeros(coefficients: list) -> list:
"""Rational Zeros Theorem possible zeros of a polynomial function.
Args:
coefficients (list): The coefficients of a polynomial function,
in order of degree including all from a_n to a_0.
Returns:
list: A list containing all possib... | 751337e2a324ddba126ced8a896630eb816c63a6 | 1,634 |
import site
def view() -> pn.Column:
"""# Bootstrap Dashboard Page.
Creates a Bootstrap Dashboard Page with a Chart and a Table
- inspired by the [GetBoostrap Dashboard Template]
(https://getbootstrap.com/docs/4.4/examples/dashboard/)
- implemented using the `awesome_panel' Python package and in... | d3365ca9064a2354d5e848dd2c7666d90241c456 | 1,635 |
import doctest
def load_tests(loader, tests, ignore):
"""
Creates a ``DocTestSuite`` for each module named in ``DOCTEST_MODULES``
and adds it to the test run.
"""
for module in DOCTEST_MODULES:
tests.addTests(doctest.DocTestSuite(module))
return tests | 33befd96fc2401fe0ae4b03b4d8eb26098273150 | 1,636 |
def buildGeneMap(identifiers, separator="|"):
"""build map of predictions to genes.
Use an identifier syntax of species|transcript|gene. If none is
given, all transcripts are assumed to be from their own gene.
"""
map_id2gene, map_gene2ids = {}, {}
for id in identifiers:
f = id.spli... | e854639142bd600338563ffc1160b43359876cdd | 1,637 |
import warnings
import requests
import json
def get_kline(symbol, end_date, freq, start_date=None, count=None):
"""获取K线数据
:param symbol: str
聚宽标的代码
:param start_date: datetime
截止日期
:param end_date: datetime
截止日期
:param freq: str
K线级别,可选值 ['1min', '5min', '30min', ... | 5750784f2ef0a3080eac881faa1ee33d6b3b1a3d | 1,638 |
def magnitude(number: SnailNumber) -> int:
"""Calculates the magnitude of asnail number
Args:
number (SnailNumber): input number
Returns:
(int): mangitude
Examples:
>>> magnitude([[1, 1], [2, 2]])
35
>>> magnitude([[[[0,7],4],[[7,8],[6,0]]],[8,1]])
1384... | d89099f97e2c96e2e41c1e47a3b7ee74f5f0111c | 1,640 |
import tarfile
def _load_model_from_tarball(tarball_path, gpg_home_dir):
"""Load a model from a tarball
Args:
tarball_path: a path to a model gzipped tar file
gpg_home_dir: home directory for gpg to verify signed model (e.g. path/to/.gnupg)
Returns:
something of type Serializable... | cf6e9dedc0278847011ffaf0470813230d83e2dc | 1,641 |
def strip_begin_end_key(key) :
"""
Strips off newline chars, BEGIN PUBLIC KEY and END PUBLIC KEY.
"""
return key.replace("\n", "")\
.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "") | ef989872c5c1c136114310c142a0f989e2f888ca | 1,642 |
def add_expdvr(npoints: int, qmin: float, qmax: float) -> DVRSpecification:
"""Register a new exponential DVR
Args:
npoints (int): number of grid points
qmin (float): minimal x value
qmax (float): maximal x value
"""
return DVRSpecification("ExponentialDVR", npoints, qmin, qmax) | c0a6aa6f349433fc0c4266807343d73fad37a279 | 1,643 |
def sync_now(r, **attr):
"""
Manual synchronization of a repository
@param r: the S3Request
@param attr: controller options for the request
"""
T = current.T
auth = current.auth
response = current.response
rheader = attr.get("rheader", None)
if rheader:
rhe... | 85ac3be60da29982ac203dee2b408e18422f431a | 1,645 |
def checkdnsrr():
"""Check DNS records corresponding to a given
Internet host name or IP address"""
return NotImplementedError() | 7fda596230cc5f61e946e8a0949c67f365cf5563 | 1,646 |
from re import I
def get_horizontal_rainbow_00():
"""
Returns the main horizontal rainbow
Programs that use this function:
- Diagonal Ripple 1
- Diagonal Ripple 2
- Diagonal Ripple 3
- Diagonal Ripple 4
- Double Ripple 1
- Double Ripple 2
- Double R... | 86c1d632f3a9e7df94c710a323cd099bb5602e19 | 1,647 |
def xml_attr_or_element(xml_node, name):
""" Attempt to get the value of name from the xml_node. This could be an attribute or
a child element.
"""
attr_val = xml_node.get(name, None)
if attr_val is not None:
return attr_val.encode('utf-8').strip()
for child in xml_node.getchildren()... | 4ec061a9a865291d8d26d8de474141175d5aab28 | 1,648 |
import numpy
def kmeans_init_centroids(x_array, num_centroids_K):
"""
This function initializes K centroids that are to be used in K-means on the dataset x_array.
Parameters
----------
x_array : array_like
The dataset of size (m x n).
num_centroids_K : int
The number of clust... | 2e310dd3fe9eb6dd32999e32f583fc4a7fd0bbf0 | 1,649 |
def get_coinbase_candle_url(url, timestamp_from, pagination_id):
"""Get Coinbase candle URL."""
start = timestamp_from.replace(tzinfo=None).isoformat()
url += f"&start={start}"
if pagination_id:
url += f"&end={pagination_id}"
return url | a1bb4e975060ba5e3438b717d1c2281349cd51f1 | 1,650 |
def part2():
"""This view will be at the path ``/part2``"""
return "Part 2" | 92a8789b669a66989a74be2c2126e8958e4beece | 1,651 |
def create_strings_from_file(filename, count):
"""
Create all strings by reading lines in specified files
"""
strings = []
with open(filename, 'r') as f:
lines = [l.strip()[0:200] for l in f.readlines()]
if len(lines) == 0:
raise Exception("No lines could be read in... | 35eac3661e31f8e6e895c7575ad725a7ea27d846 | 1,652 |
def drive_around(a_th_gld=1.2):
"""
Function that implements the logic with which the robot will decide to navigate in 2D space, it is essentially based on the (frontal and lateral)
distance values of the golden tokens obtained by find_obstacles()
Args:
dist_left (float): distance of the closest golden token o... | c4ea2b855fdf40bc268232d11ff58f45362878b5 | 1,653 |
def a_request(session_request):
"""AnonymousUser request"""
session_request.user = AnonymousUser()
return session_request | ea651f420e62c455ee63ae1d158a07be719fa48c | 1,654 |
def subplot_index(nrow, ncol, k, kmin=1):
"""Return the i, j index for the k-th subplot."""
i = 1 + (k - kmin) // ncol
j = 1 + (k - kmin) % ncol
if i > nrow:
raise ValueError('k = %d exceeds number of rows' % k)
return i, j | 2d2b7ef9bf9bc82d06637157949ca9cb3cc01105 | 1,655 |
def _split_keys(keypath, separator):
"""
Splits keys using the given separator:
eg. 'item.subitem[1]' -> ['item', 'subitem[1]'].
"""
if separator:
return keypath.split(separator)
return [keypath] | 2f67a35a2e08efce863d5d9e64d8a28f8aa47765 | 1,657 |
def _get_referenced_type_equivalences(graphql_types, type_equivalence_hints):
"""Filter union types with no edges from the type equivalence hints dict."""
referenced_types = set()
for graphql_type in graphql_types.values():
if isinstance(graphql_type, (GraphQLObjectType, GraphQLInterfaceType)):
... | f92f4dba0d694e17ebecdb62922b121eeba23f87 | 1,659 |
import numpy
def E(poly, dist=None, **kws):
"""
Expected value operator.
1st order statistics of a probability distribution or polynomial on a given
probability space.
Args:
poly (Poly, Dist) : Input to take expected value on.
dist (Dist) : Defines the space the expected value is... | c3f051e522e0cecf0b951c194c43850b4016dd17 | 1,660 |
def spacify(string, spaces=2):
"""Add spaces to the beginning of each line in a multi-line string."""
return spaces * " " + (spaces * " ").join(string.splitlines(True)) | 7ab698d8b38a6d940ad0935b5a4ee8365e35f5da | 1,661 |
def simple_line_plot(x, y = None,
title = "",
xlabel = "",
ylabel = "",
context = 'notebook',
xlim = None,
ylim = None,
color = 'blue',
parse_axe... | 6839b12307c2ab8e2747f8d8fe8f913126253a28 | 1,662 |
def generate(parsed_data, template, opath, dme_vault, helper, **kwargs):
"""Generates collection and data-object metadata needed for DME upload.
For each collection (directory) and data-object (file), an output file is
generated in JSON format. 'opath' dictates where these files will be saved.
Returns a... | 885c25f4d7dcb933449bbf028f00a6cecae4233a | 1,663 |
from pysnmp.entity.rfc3413.oneliner import cmdgen
def _get_snmp(oid, hostname, community):
"""SNMP Wrapper function. Returns tuple of oid, value
Keyword Arguments:
oid --
community --
"""
cmd_gen = cmdgen.CommandGenerator()
error_indication, error_status, error_index, var_bind =... | 8911dbeece2bac9cc398fafc6a8fde8033752d00 | 1,664 |
from fontbakery.utils import get_glyph_name
def com_google_fonts_check_048(ttFont):
"""Font has **proper** whitespace glyph names?"""
def getGlyphEncodings(font, names):
result = set()
for subtable in font['cmap'].tables:
if subtable.isUnicode():
for codepoint, name in subtable.cmap.items()... | baa2c101859bc08060ff23d9bc12d2c3e573bc44 | 1,665 |
def find_nearest(array, value):
"""
Inputs:
array - array...
value - value to search for in array
Outputs:
array[idx] - nearest value in array
"""
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx] | f65156f8b084e8dff388fe51f56162be668a1bbc | 1,667 |
def vader_entity_sentiment(df,
textacy_col,
entity,
inplace=True,
vader_sent_types=['neg', 'neu', 'pos', 'compound'],
keep_stats=['count', 'mean', 'min', '25%', '50%', '7... | 6ef61a7f79c5ff148cf35309e3f828ffa17947f6 | 1,669 |
def post_list(request):
"""
Create a view that will return a list of
Posts that were published prior to 'now' and
render them to the 'blogposts.html' template
:param request:
:return:
"""
posts = Post.objects.filter(published_date__lte=timezone.now()
).or... | 043aff58ba50934d06b6a8221bcf270d1d0f98f5 | 1,670 |
def get_model():
"""
Returns a compiled convolutional neural network model. Assume that the
`input_shape` of the first layer is `(IMG_WIDTH, IMG_HEIGHT, 3)`.
The output layer should have `NUM_CATEGORIES` units, one for each category.
"""
# initialize a convolutional model
model = tf.keras.mo... | 735d6fc343a1e1eb1ab3cce51387284bfee113ba | 1,671 |
def get_app_icon_path():
"""Path to OpenPype icon."""
return resources.get_openpype_icon_filepath() | 20985ef5f0ada38ff466bb9160ea2264d53a83f4 | 1,672 |
def post_create_ipsec_endpoint_tunnel(
api_client,
endpoint_id,
remote_subnet=None,
local_subnet=None,
enabled=None,
ping_ipaddress=None,
ping_interface=None,
ping_interval=None,
description=None,
**kwargs
): # noqa: E501
"""post_create_ipsec_endpoint_tunnel # noqa: E501
... | c876113db138db252274d3f07ecec30ba4796701 | 1,673 |
from typing import List
from datetime import datetime
def cow_service(
wfo: List[str] = Query(
[], min_length=3, max_length=4, title="WFO Identifiers"
),
begints: datetime = Query(...),
endts: datetime = Query(...),
phenomena: List[str] = Query(None, max_length=2),
lsrtype: List[str] =... | 2e565deb0e2534c125fec70823c51ea6952ccbf4 | 1,674 |
def add_edges_reverse_indices(edge_indices, edge_values=None, remove_duplicates=True, sort_indices=True):
"""Add the edges for (i,j) as (j,i) with the same edge values. If they do already exist, no edge is added.
By default, all indices are sorted.
Args:
edge_indices (np.array): Index list of shape... | 0b35d67b6322371d7c7fac35d45b3c4a7da3bda1 | 1,675 |
from typing import Any
def isint(var:Any, raise_error:bool=False)-> bool:
"""Check if var is an integer
Args:
var (str): variable to check
raise_error (bool, optional): TypeError raised if set to `True`. Defaults to `False`.
Raises:
TypeError: raised if var is not an integer
... | c4698e4cead5fdd7c73b3efebd3c475c3cbdeca3 | 1,676 |
def convert_interpolate2d(g, op, x):
"""Operator converter for interpolate 2D(dims == 4)."""
def get_interpolate_mode(op):
"""conver 'interp_method' attr of paddle to tvm"""
interp_method = op.attr("interp_method")
align_corners = op.attr("align_corners")
align_mode = op.attr("... | 9c089baf0a5d8d8ff78d3cadff1e17d8a19b7b0d | 1,677 |
import math
def calc_dif_mod_cn (x, y):
""" Check if the difference between the modulus of consecutive numbers is a prime number """
modx = math.sqrt(x.real ** 2 + x.imag ** 2) # modulus of the first complex number
mody = math.sqrt(y.real ** 2 + y.imag ** 2) # modulus of the second complex number
d... | 88e353e4a948c3b6adc65b91265a5f6d2e68a1c1 | 1,679 |
import re
def mitochondrialGTF(concatenated_gff, output_directory):
"""Convert GFF file with information for mitochondrial genes to GTF and return the path to GTF file.
Keyword arguments:
concatenated_gff -- path to concatenated GFF file
output_directory -- path to directory where GTF file should be placed
Imp... | 24c0987d5c2208b1a96020b8eea19791c86b3f5e | 1,680 |
def get_none_zero_region(im, margin):
"""
get the bounding box of the non-zero region of an ND volume
"""
input_shape = im.shape
if(type(margin) is int ):
margin = [margin]*len(input_shape)
assert(len(input_shape) == len(margin))
indxes = np.nonzero(im)
idx_min = []
idx_max =... | 6ca56b94becd254b0ecbaf85e25475bb574586a9 | 1,681 |
import json
from datetime import datetime
def create_short_link(request):
"""Given an URL, return a shortened link.
Args:
url: URL to be shortened.
Returns:
short_link: Shortened result of URL.
expires_at: Timestamp before which the link is valid.
"""
payload = json.loads(requ... | 4d870b21484ced46e5fd538545cb5cca6c1b3b8a | 1,682 |
import gzip
def get_mapped_tracks_file(mode='r', **kwargs):
""" Returns a file descriptor-like object to the file containing the
raw track.
(A mapped track is a collection of tuples). Each tuple is:
- linking pairs
- paths
- linking pairs
- points
Arguments:
mode: r/w mode
driver_id: s... | 281ba7bd0f05b61fb13041c2193caed1de1f918f | 1,683 |
def ne_2beta(r, ne0, rc_outer, beta_outer, f_inner, rc_inner, beta_inner):
"""
Electron number density [cm^-3] in the double-beta profile of the hydrostratic equilibrium model.
r : distance from the center of the cluster [kpc]
ne0 : central electron number density [cm^-3]
rc_outer : core radius fro... | cac79f2f9a76cb94c2ad08c344844ddec6ff3a45 | 1,684 |
def sell():
"""Sell shares of stock"""
"""Sell shares of stock"""
if request.method == "POST":
symbol = request.form.get("symbol")
amount = request.form.get("shares")
try:
amount = int(amount)
except:
return apology("enter a proper value")
prin... | ae385e94eb6765eca7b9b4b74ef3320c2a265e62 | 1,685 |
from typing import Any
def assemble_block(n_rows: Int, n_cols: Int, pdf: pd.DataFrame, cov_matrix: NDArray[(Any, Any),
Float],
row_mask: NDArray[Any]) -> NDArray[Float]:
"""
Creates a dense n_rows by n_cols ... | 25f8c3923050c64cb4c7a7b9842007a9e8d7723b | 1,686 |
def calc_xixj_from_braggphi(
det_cent=None,
det_nout=None, det_ei=None, det_ej=None,
det_outline=None,
summit=None, nout=None, e1=None, e2=None,
bragg=None, phi=None,
option=None, strict=None,
):
""" Several options for shapes
de_cent, det_nout, det_ei and det_ej are always of shape (3,... | f11829d0d3dfe6b523a8336c8b7dbf5cfaa9f36e | 1,687 |
def _check_index_good(X):
"""Check the index of X and return boolean."""
# check the first index elements for "__total"
tot_chk = np.any(X.index.get_level_values(level=0).isin(["__total"]))
return tot_chk | 8e39b7d18af2c247c427a4e9658fc1e18ff1dd89 | 1,688 |
import torch
def endpoint_error(estimate, ground_truth):
"""Computes the average end-point error of the optical flow estimates."""
error = torch.norm(
estimate - ground_truth[:, :2, :, :], 2, 1, keepdim=False)
if ground_truth.size(1) == 3:
mask = (ground_truth[:, 2, :, :] > 0).float()
... | f40de83768ad6760620120c59eb377d1e12ff8b1 | 1,690 |
import functools
def output(log_message=None, success_message=None,
fail_message=None):
"""This is a decorator to trap the typical exceptions that occur
when applying and removing modules. It returns the proper output
corresponding to the error messages automatically. If the function
return... | 18d39d94c930a0ec99e0fb122f20e3a18d62328d | 1,691 |
def custom_mape(approxes, targets):
"""Competition metric is a slight variant on MAPE."""
nominator = np.abs(np.subtract(approxes, targets))
denominator = np.maximum(np.abs(targets), 290000)
return np.mean(nominator / denominator) | 7c8b8eab352f516c63202ef0b26253265acc68a4 | 1,692 |
def frohner_cor_3rd_order(sig1,sig2,sig3,n1,n2,n3):
"""
Takes cross-sections [barns] and atom densities [atoms/barn] for
three thicknesses of the same sample, and returns extrapolated
cross section according to Frohner.
Parameters
----------
sig1 : array_like
Cross section of the ... | d6f0b39368c19aeda899265eb187190bb4beb944 | 1,694 |
def nodeInTree(root, k):
"""
Checks if the node exists in the tree or not
"""
if root == None:
return False
if root.data == k or nodeInTree(root.left, k) or nodeInTree(root.right, k):
return True
return False | 14db01c8d2370bfaa01220d3608798165ea1a096 | 1,695 |
def split_and_filter(intermediate_str, splitter):
"""
Split string with given splitter - practically either one of "," or "/'".
Then filter ones that includes "https" in the split pickles
:param intermediate_str : string that in the middle of parsing
:param splitter
:return: chunk of string(s) a... | a4b800df1aca89ca1e8eedfc65a5016a995acd48 | 1,697 |
def organism_code(genus, species):
"""Return code from genus and species."""
return (
f"{genus[:GENUS_CODE_LEN].lower()}{species[:SPECIES_CODE_LEN].lower()}"
) | 6b52342ccf8388a2b8a98cc3d640dc3ea5b97e66 | 1,698 |
def _daily_prevalence(data):
"""
Returns a series where each value is a true fraction of currently infected population.
Args:
(dict): tracker data loaded from pkl file.
Returns:
(np.array): 1D array where each value is the above described fraction
"""
n_infected_per_day = data[... | 2a5b83c09d9f06a8021c27dec45be9a872f3a9bb | 1,700 |
from operator import or_
def users_view(page):
"""
The user view page
Returns:
a rendered user view template
"""
user_search = request.args.get("search")
user_role = request.args.get("user_role")
users_query = model.User.query
if user_search:
term = "%" + user_search... | 9646b76721ec26f9177bff99cca02d0c4b5a7954 | 1,701 |
def serial_christie_power_state(connection):
"""Ask a Christie projector for its power state and parse the response"""
connection.reset_input_buffer()
response = serial_send_command(connection, "(PWR?)", char_to_read=21)
result = None
if len(response) > 0:
if "PWR!001" in response:
... | 4ce78b773ecf2f4ed9a515e4653512a461a82f24 | 1,702 |
def cuda_tanh(a):
""" Hyperbolic tangent of GPUArray elements.
Parameters:
a (gpu): GPUArray with elements to be operated on.
Returns:
gpu: tanh(GPUArray)
Examples:
>>> a = cuda_tanh(cuda_give([0, pi / 4]))
array([ 0., 0.6557942])
>>> type(a)
<class 'p... | 6d7608c943ded7eeeb37194a4d938aa4e47c16ef | 1,703 |
def normalize_multi_header(df):
"""将有MultiIndex的column字符串做标准化处理,去掉两边空格等"""
df_copy = df.copy()
df_copy_columns = [ tuple(y.strip().lower() for y in x) for x in df_copy.columns ]
df_copy.columns = pd.core.index.MultiIndex.from_tuples(df_copy_columns)
return df_copy | acd75a73919f1fd9b8f8c57e2f70cbb607634c82 | 1,704 |
def scapy_packet_Packet_hasflag(self, field_name, value):
"""Is the specified flag value set in the named field"""
field, val = self.getfield_and_val(field_name)
if isinstance(field, EnumField):
if val not in field.i2s:
return False
return field.i2s[val] == value
else:
return (1 << field.names.index([value... | 77b4a1d772e61c7bfaaf7e9d9d3debe95f799f62 | 1,705 |
def grid_points_2d(length, width, div, width_div=None):
"""Returns a regularly spaced grid of points occupying a rectangular
region of length x width partitioned into div intervals. If different
spacing is desired in width, then width_div can be specified, otherwise
it will default to div. If div < 2 i... | d041f563bb8d3cd84e1829f49e6786b0331e1ef0 | 1,706 |
import itertools
def analytic_gradient(circuit, parameter=None):
"""Return the analytic gradient of the input circuit."""
if parameter is not None:
if parameter not in circuit.parameters:
raise ValueError('Parameter not in this circuit.')
if len(circuit._parameter_table[parameter... | 126357a3aa25a1a38e5226657f92e626cb8b2339 | 1,707 |
def _get_shipping_voucher_discount_for_cart(voucher, cart):
"""Calculate discount value for a voucher of shipping type."""
if not cart.is_shipping_required():
msg = pgettext(
'Voucher not applicable',
'Your order does not require shipping.')
raise NotApplicable(msg)
s... | cba3299f02d3cc2169e9ad8367b8c5e67a08a459 | 1,708 |
def ottawa(location, **kwargs):
"""Ottawa Provider
:param location: Your search location you want geocoded.
"""
return get(location, provider='ottawa', **kwargs) | b1e32842ce887b72f317c5b88cbcb390524b59af | 1,709 |
import copy
import random
def entries():
""" Basic data for a test case """
return copy.deepcopy(
{"arb_key": "text", "randn": random.randint(0, 10),
"nested": {"ntop": 0, "nmid": {"list": ["a", "b"]},
"lowest": {"x": {"a": -1, "b": 1}}},
"collection": {1, 2, 3}}) | 5d6cde325b69e43598f9d0158ae5989a4d70b54c | 1,710 |
def count_ref_alleles(variant, *traits):
"""Count reference allels for a variant
Parameters
----------
variant : a Variant as from funcgenom
the variant for which alleles should be counted
*traits : str
the traits for which alleles should be counted
Returns
-------... | 10ea3468f5de8f2b77bb97b27b888af808c541b7 | 1,711 |
def preprocess_image(image, image_sz=48):
"""
Preprocess an image. Most of this is stuff that needs to be done for the Keras CNN model to work,
as recommended by: https://chsasank.github.io/keras-tutorial.html
"""
# we need to convert to saturation, and value (HSV) coordinates
hsv_image = color... | ade5d63ad8e2a25622795d15c90c1e062a76006d | 1,712 |
def pspace_independent(a, b):
"""
Tests for independence between a and b by checking if their PSpaces have
overlapping symbols. This is a sufficient but not necessary condition for
independence and is intended to be used internally.
Notes
=====
pspace_independent(a, b) implies independent(... | 5c6a253e266af1673c6e05c4b7f81b04a1201803 | 1,713 |
def img_aspect_ratio(width, height):
"""
Returns an image's aspect ratio.
If the image has a common aspect ratio, returns the aspect ratio in the format x:y,
otherwise, just returns width/height.
"""
ratio = round(width/height, 2)
for ar, val in COMMON_ASPECT_RATIOS.items():
if ratio... | 82104f3d4105fd4c22bc4cfed51e4c8261d32079 | 1,714 |
def _get_active_sculpting_mesh_for_deformer(deformer):
"""
If sculpting is enabled on the deformer, return the output mesh. Otherwise,
return None.
"""
# If sculpting is enabled, .tweak[0] will be connected to the .tweakLocation of
# a mesh.
connections = cmds.listConnections('%s.tweak[0]' ... | a0864999d6aec487a23bac4dfb602f01b0b45d8f | 1,715 |
def get_client_versions():
"""Gets the client versions (or client equivalent for server).
Returns:
A list of client versions (or client equivalent for server).
E.g. '10' for Windows 10 and Windows Server 2016.
"""
version_nubmer = get_os_version_number()
if version_nubmer in _WIN32_CLIENT_NAMES:
... | 0954754b608b745d2dbc9f6c83bd85bc0c2549e2 | 1,716 |
from CA import caget
from CA import caput
def PV_property(name,default_value=nan):
"""EPICS Channel Access Process Variable as class property"""
def prefix(self):
prefix = ""
if hasattr(self,"prefix"): prefix = self.prefix
if hasattr(self,"__prefix__"): prefix = self.__prefix__
... | 745fe42d760f42dbc4e729d45256dd291be7e5b3 | 1,717 |
import random
def random_in_range(a: int, b: int) -> int:
""" Return a random number r with a <= r <= b. """
return random.randint(a, b) | 611c2754ace92eac4951f42e1e31af2f441ed0c2 | 1,720 |
import sqlite3
from datetime import datetime
def count_items():
"""
:returns: a dictionary with counts in fields 'total', 'done'.
"""
con = sqlite3.connect(PROGRESS_DB_FILE_NAME)
cur = con.cursor()
# do not count root
cur.execute("SELECT COUNT(*) FROM item WHERE pk<>0")
total = cur.fet... | 904c72b74603fd9a9c2a1c249641ba61a7b85b04 | 1,721 |
def app() -> None:
"""This app renders the Data Analyzer page"""
# TEXT:
st.write(
"""
# Data Analysis Dashboard
Please provide an asset name to display historical data.
"""
)
# INPUTs:
st.sidebar.title("Parameters")
col1, col2, c... | 6890ed875368eec3271f8ee0625d4182aaeb769d | 1,722 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.