content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_object(node):
""" Parse rebaron AtomTrailers node into Python object (taken from ongoing conversion object)
Works for object and local scope """
if len(node) > 1 and (node[0].value == 'self' or node[0].value == 'self_next'):
var_t = super_getattr(convert_obj, str(node))
else:
#... | 9b09dfaae08768e1544e676e93bcf5ce718c67d5 | 3,645,772 |
def read_label_from_txt(label_path):
"""Read label from txt file."""
text = np.fromfile(label_path)
bounding_box = []
with open(label_path, "r") as f:
labels = f.read().split("\n")
for label in labels:
if not label:
continue
label = label.split(" "... | dd6158af3531ec003b57c4fa47282957c3cb72ea | 3,645,773 |
from typing import Union
def _load_recipe(module, baked: bool = False) -> Union[BakedRecipe, Recipe]:
# load entry-point DAG
"""Load Queenbee plugin from Python package.
Usually you should not be using this function directly. Use ``load`` function
instead.
args:
module: Python module obj... | d0c400a234a777438418c4eb605723ea67509077 | 3,645,774 |
def compute_coeffs(shape, Aref, alfa):
"""Computes the lift and drag coefficients of the given shape at the given
angle of attack using the given reference area"""
alfa_vect = np.array([-np.sin(alfa),0,-np.cos(alfa)])
Fvect = np.array([0,0,0]) #Force coefficient vector
for panel in shape:
p... | 48cd922a460c56961cf2ebc2a3ecfc121622fe26 | 3,645,775 |
def draw_pitch(axis, rotate=False):
"""
Plots the lines of a soccer pitch using matplotlib.
Arguments
---------
axis : matplotlib.axes._subplots.AxesSubplot
- matplotlib axis object on which to plot shot freeze frame
rotate : bool
- if set to True, pitch is horizontal,
d... | 24a5b0de75ed70f6ce37afab8e04cf03afaa4651 | 3,645,776 |
import click
def file(filename, searchspec=None, searchtype=None, list_images=False,
sort_by=None, fields=None):
"""Examine images from a local file."""
if not list_images:
if searchtype is None or searchspec is None:
raise click.BadParameter(
'SEARCHTYPE and SEARC... | 6162ac7553f04225a6cad0fe262f2cc97dad39a2 | 3,645,777 |
def clip_to_norm(array, clip):
"""Clips the examples of a 2-dimensional array to a given maximum norm.
Parameters
----------
array : np.ndarray
Array to be clipped. After clipping, all examples have a 2-norm of at most `clip`.
clip : float
Norm at which to clip each example
R... | e7dca2cf9f129736ebc5f7909cb4fed41a4c7996 | 3,645,778 |
def getlineno(frame):
"""Get the line number from a frame object, allowing for optimization."""
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
return frame.f_lineno | b8c8d6fb3ebb8784d10250a42526b31e185e9b7a | 3,645,779 |
def _batch_sum(F, loss, batch_axis):
"""Return sum on the specified batch axis, not keeping the axis"""
if is_np_array():
axes = list(range(loss.ndim))
del axes[batch_axis]
return F.np.sum(loss, axis=axes)
else:
return F.sum(loss, axis=batch_axis, exclude=True) | 71bad3e21c1905e81b0e40b5be08ebc0426e1ca7 | 3,645,780 |
def tree_cons(a, tree: Pytree) -> Pytree:
"""
Prepend ``a`` in all tuples of the given tree.
"""
return jax.tree_map(
lambda x: _OpaqueSequence((a,) + tuple(x)),
tree,
is_leaf=lambda x: isinstance(x, tuple),
) | 1d82ca0a7b49d8e803fe8771f4f6b697826f5e27 | 3,645,781 |
from datetime import datetime
def add(moment: datetime) -> datetime:
"""Add one gigasecond to a given date and time."""
return moment + GIGASECOND | 87e009e408088d6c91ceb409408608947c0b9fd3 | 3,645,782 |
def convert_to_short_log(log_level, message):
"""Convert a log message to its shorter format.
:param log_level: enum - 'LogLevel.<level>' e.g. 'LogLevel.Error'
:param message: str - log message
:return: enum - 'LogLevelInt.<value>` e.g. 'LogLevelInt.5'
"""
return f'{LogLevelInt[log_level.na... | 0d4c20ac4ec809dbb58494ef928586c95da88fbb | 3,645,784 |
import zipfile
import io
import pathlib
import warnings
def load_map(path, callback=None, meta_override=None):
"""Load a set of zipped csv AFM workshop data
If you are recording quantitative force-maps (i.e. multiple
curves on an x-y-grid) with AFM workshop setups, then you
might have realized that y... | bdf98f10a5decfc9a4dbd4b9cc90c75c7c95e76d | 3,645,785 |
def format_len(x):
"""
>>> format_len('abc')
3
>>> format_len(('(', ('(', 'def', ')'), 'yz', ')'))
11
"""
if not isinstance(x, (list, tuple)): return len(x)
if len(x) > 3: sep_len = 2 * (len(x) - 3)
else: sep_len = 0
return sum(map(format_len, x)) + sep_len | 723afb58bfed0cfb7fbd25a12b86b257bf8b40df | 3,645,786 |
def set_doi_ark(page_number, records_per_page, sort_on, doi_ark_value):
"""
Retrieve all metadata records for admin view. Retrieval is done
via POST because we must pass a session id so that the user is
authenticated.
Access control is done here. A user can modify only their own records
because... | 2b718232463a632dc07f73c1e6e5c3299ff57f18 | 3,645,788 |
def empiriline(x,p,L):
"""
Use the line L (which is an EmissionLine object) as a template.
The line is shifted, then interpolated, then rescaled, and allowed
to float.
"""
xnew = x - p[1]
yout = sp.zeros(len(xnew))
m = (xnew >= L.wv.min())*(xnew <= L.wv.max() )
ynew,znew = L.interp(x... | a0199a4623e834524711d0e78787d409da29d3ef | 3,645,790 |
def _get_z_slice_fn(z, data_dir):
"""Get array slice map to be applied to z dimension
Args:
z: String or 1-based index selector for z indexes constructed as any of the following:
- "best": Indicates that z slices should be inferred based on focal quality
- "all": Indicates that ... | 1982258bb98205fe4552de4db8b4e049e09af4bf | 3,645,791 |
def bar_data_wrapper(func):
"""Standardizes column names for any bar data"""
def wrapper(*args, **kwargs):
assert Ticker(args[0])
res: pd.DataFrame = func(*args, **kwargs)
return res.rename(columns=COL_NAMES).iterrows()
return wrapper | 4cfa9614ec430ba53ac3e86dc68c6a84ee3cfbee | 3,645,792 |
import torch
def rgb_to_grayscale(
image: Tensor, rgb_weights: list[float] = [0.299, 0.587, 0.114]
) -> Tensor:
"""Convert an RGB image to grayscale version of image. Image data is
assumed to be in the range of [0.0, 1.0].
Args:
image (Tensor[B, 3, H, W]):
RGB image to be converte... | d135a92e7189a745b2d9658b2b60a91c238fdbf8 | 3,645,793 |
def _aware_to_agnostic(fr: NDFrame) -> NDFrame:
"""Recalculate values in tz-aware series or dataframe, to get a tz-agnostic one.
(i.e., A to B)."""
if not fr.index.tz:
raise ValueError("``fr`` must be tz-aware.")
idx_out = _idx_after_conversion(fr, None)
# Convert daily or longer.
if s... | c97b190828d5364033336b2dcc48d352aafe1132 | 3,645,795 |
import math
def cumulative_prob_to_value(prob, hp):
"""Convert a value from [0, 1] to a hyperparameter value."""
if isinstance(hp, Fixed):
return hp.value
elif isinstance(hp, Boolean):
return bool(prob >= 0.5)
elif isinstance(hp, Choice):
ele_prob = 1 / len(hp.values)
i... | d66e69f4cb580f8d3ce3004c082239717fd2854a | 3,645,796 |
import podpac
import podpac.datalib # May not be imported by default
import inspect
def get_ui_node_spec(module=None, category="default"):
"""
Returns a dictionary describing the specifications for each Node in a module.
Parameters
-----------
module: module
The Python module for which t... | 17978a9ebb50696990f601f449a0539bcf67c3dd | 3,645,797 |
def parse_branch_name(branch_name):
"""Split up a branch name of the form 'ocm-X.Y[-mce-M.N].
:param branch_name: A branch name. If of the form [remote/]ocm-X.Y[-mce-M.N] we will parse
it as noted below; otherwise the first return will be False.
:return parsed (bool): True if the branch_name was pa... | 2cb53aef0754c815dd61d4a1b640e12db64fbf83 | 3,645,798 |
import itertools
def symmetric_padding(
arr,
width):
"""
Pad an array using symmetric values.
This is equivalent to `np.pad(mode='symmetric')`, but should be faster.
Also, the `width` parameter is interpreted in a more general way.
Args:
arr (np.ndarray): The input array.... | dd91b4f3641332ecfffa734584fd87293c7169ee | 3,645,799 |
def _uid_or_str(node_or_entity):
""" Helper function to support the transition from `Entitie`s to `Node`s.
"""
return (
node_or_entity.uid
if hasattr(node_or_entity, "uid")
else str(node_or_entity)
) | 82f5747e8c73e1c167d351e1926239f17ea37b98 | 3,645,800 |
def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8):
"""
estimate power for a given allele frequency, effect size beta and sample size N
Assumption:
z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis
the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )... | 1806718cd0af5deb38a25a90864bb14f40e2c57a | 3,645,801 |
def get_rotation_matrix(angle: float, direction: np.ndarray, point: np.ndarray = None) -> np.ndarray:
"""Compute rotation matrix relative to point and direction
Args:
angle (float): angle of rotation in radian
direction (np.ndarray): axis of rotation
point (np.ndarray, optional): center... | fd7c8d22368b51310a85453f6a9732f56a443803 | 3,645,802 |
def answer(panel_array):
""" Returns the maximum product of positive and (odd) negative numbers."""
print("panel_array=", panel_array)
# Edge case I: no panels :]
if (len(panel_array) == 0):
return str(0)
# Get zero panels.
zero_panels = list(filter(lambda x: x == 0 , panel_arra... | 7169fba8dcf6c0932722dcbc606d6d60fdaf3ed1 | 3,645,805 |
def load_fromh5(filepath, dir_structure, slice_num, strt_frm=0):
"""
load_fromh5 will extract the sinogram from the h5 file
Output: the sinogram
filepath: where the file is located in the system
dir_structure: the h5 file directory structure
slice_num: the slice where the singoram will be ext... | 90aa278a7429cc832071a374df9de2d8dd2abb88 | 3,645,806 |
def lqr_6_2(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns an LQR environment with 6 bodies of which first 2 are actuated."""
return _make_lqr(
n_bodies=6,
n_actuators=2,
control_cost_coef=_CONTROL_COST_COEF,
time_limit=time_limit,
rando... | b27a4fd55d67cfcbb9a651b7915fd2e3b4460af9 | 3,645,807 |
def machine_stop(request, tenant, machine):
"""
Stop (power off) the specified machine.
"""
with request.auth.scoped_session(tenant) as session:
serializer = serializers.MachineSerializer(
session.stop_machine(machine),
context = { "request": request, "tenant": tenant }
... | b91a375c1aa8b62a6ed665d0045ff4b9eeae6a18 | 3,645,808 |
from typing import Tuple
from typing import Dict
from typing import Any
def _get_input_value(arg: Tuple[str, GraphQLArgument]) -> Dict[str, Any]:
"""Compute data for the InputValue fragment of the introspection query for a particular arg."""
return {
"name": __InputValue.fields["name"].resolve(arg, No... | 7e82936b07b01531b0716c6904709c37e807d868 | 3,645,810 |
def wrapper(X_mixture,X_component):
""" Takes in 2 arrays containing the mixture and component data as
numpy arrays, and prints the estimate of kappastars using the two gradient
thresholds as detailed in the paper as KM1 and KM2"""
N=X_mixture.shape[0] ... | f5e093590897c363bbab2360a14d7c3a82fd6bcd | 3,645,811 |
import torch
def iou(
outputs: torch.Tensor,
targets: torch.Tensor,
eps: float = 1e-7,
threshold: float = 0.5,
activation: str = "sigmoid"
):
"""
Args:
outputs (torch.Tensor): A list of predicted elements
targets (torch.Tensor): A list of elements that are to be predicted
... | 4c43832560126c19b8b9ebc01daf3920603b5f17 | 3,645,812 |
def readCoords(f):
"""Read XYZ file and return as MRChem JSON friendly string."""
with open(f) as file:
return '\n'.join([line.strip() for line in file.readlines()[2:]]) | 0cf1a9d07b4b3fe1836ce5c8a308ff67b5fe4c70 | 3,645,813 |
def api_update_note(note_id: int):
"""Update a note"""
db = get_db()
title = request.form["title"] if "title" in request.form.keys() else None
content = request.form["content"] if "content" in request.form.keys() else None
note = db.update_note(note_id, title, content)
return jsonify(note.__dict... | d6668b89854e4aa6c248041a97a55c95cd568e9e | 3,645,815 |
def padding_oracle(decrypt, cipher, *, bs, unknown=b"\x00", iv=None):
"""Padding Oracle Attack
Given a ciphersystem such that:
- The padding follows the format of PKCS7
- The mode of the block cipher is CBC
- We can check if the padding of a given cipher is correct
- We can try to decrypt ciphe... | 077eeed2f8f0f2e91aa482c93f36825bdbcef17a | 3,645,816 |
def pixels():
"""
Raspberry Pi pixels
"""
return render_template("pixels.html") | d3af0be80b09096e05a29ef3e9209cef2dba8431 | 3,645,817 |
async def get_song_info(id: str):
"""
获取歌曲详情
"""
params = {'ids': id}
return get_json(base_url + '/song/detail', params=params) | 2185c62db03bba3019d9d010fc5603c432a0048f | 3,645,818 |
def _find_odf_idx(map, position):
"""Find odf_idx in the map from the position (col or row).
"""
odf_idx = bisect_left(map, position)
if odf_idx < len(map):
return odf_idx
return None | 642398d72abe89aa63b7537372499655af5a5ded | 3,645,819 |
def get_or_create(session, model, **kwargs):
"""
Creates and returns an instance of the model with given kwargs,
if it does not yet exist. Otherwise, get instance and return.
Parameters:
session: Current database session
model: The Class of the database model
**kw... | 4d3e4f0da5ca61789171db5d8d16a5fa06e975cc | 3,645,820 |
def pack_asn1(tag_class, constructed, tag_number, b_data):
"""Pack the value into an ASN.1 data structure.
The structure for an ASN.1 element is
| Identifier Octet(s) | Length Octet(s) | Data Octet(s) |
"""
b_asn1_data = bytearray()
if tag_class < 0 or tag_class > 3:
raise ValueError(... | 14aad1709b5efa46edc5d7ac8659fe1de0615a57 | 3,645,821 |
from typing import Dict
def choose(text: str, prompt: str, options: Dict[str, str], suggestion: str, none_allowed: bool):
"""
Helper function to ask user to select from a list of options (with optional description).
Suggestion can be given. 'None' can be allowed as a valid input value.
"""
p = Col... | 0b43452f00378ddc1345b85ca72b37ff1edfae05 | 3,645,822 |
def util_color(
graph: list[list[int]], max_color: int, colored_vertices: list[int], index: int
) -> bool:
"""
alur :
1. Periksa apakah pewarnaan selesai
1.1 Jika pengembalian lengkap True
(artinya kita berhasil mewarnai grafik)
Langkah Rekursif:
2. Iterasi atas setiap warna:
... | 081bf9e8b1e0dcc847fdd0bc78167819506e3f1c | 3,645,824 |
def reverse_complement(sequence):
""" Return reverse complement of a sequence. """
complement_bases = {
'g':'c', 'c':'g', 'a':'t', 't':'a', 'n':'n',
'G':'C', 'C':'G', 'A':'T', 'T':'A', 'N':'N', "-":"-",
"R":"Y", "Y":"R", "S":"W", "W":"S", "K":"M", "M":"K",
"B":"V", "V":"B", "D": ... | d28e520a9159cb4812079b4a7a5f2f6eb5723403 | 3,645,825 |
def get_variable_ddi(
name, shape, value, init, initializer=None, dtype=tf.float32,
regularizer=None, trainable=True):
"""Wrapper for data-dependent initialization."""
kwargs = {"trainable": trainable}
if initializer:
kwargs["initializer"] = initializer
if regularizer:
kwargs["regularizer"] = re... | b941f110ee8efbdfb9e4d2a6b5ba0a5b3e5881ed | 3,645,826 |
def conv3x3(in_planes, out_planes, Conv=nn.Conv2d, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return Conv(in_planes, out_planes, kernel_size=3, stride=stride,
padding=dilation, groups=groups, bias=False, dilation=dilation) | 7741248a5af70e33abe803469c8a20eb2f4bcdb1 | 3,645,828 |
async def async_setup(hass, config):
"""Set up the AirVisual component."""
hass.data[DOMAIN] = {}
hass.data[DOMAIN][DATA_CLIENT] = {}
hass.data[DOMAIN][DATA_LISTENER] = {}
if DOMAIN not in config:
return True
conf = config[DOMAIN]
hass.async_create_task(
hass.config_entrie... | e44beaaf7657848fa377700021671d6c27317696 | 3,645,829 |
def hasConnection(document):
"""
Check whether document has a child of :class:`Sea.adapter.connection.Connection`.
:param document: a :class:`FreeCAD.Document` instance
"""
return _hasObject(document, 'Connection') | d0999c488ea1af1d0117eb53a6e67d5ce876a142 | 3,645,830 |
from typing import List
def trsfrm_aggregeate_mulindex(df:pd.DataFrame,
grouped_cols:List[str],
agg_col:str,
operation:str,
k:int=5):
"""transform aggregate statistics for multiindex
... | f84ac88bb3f3474fe5611486031e746e4dc9954d | 3,645,831 |
from typing import Optional
def get_hub_virtual_network_connection(connection_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
virtual_hub_name: Optional[str] = None,
opts: Option... | 3275fdf70d088df2f00bfe9e0148026caca16fcc | 3,645,832 |
def newcombe_binomial_ratio_err(k1,n1, k2,n2, z=1.0):
""" Newcombe-Brice-Bonnett ratio confidence interval of two binomial proportions.
"""
RR = (k1/n1) / (k2/n2) # mean
logRR = np.log(RR)
seLogRR = np.sqrt(1/k1 + 1/k2 - 1/n1 - 1/n2)
ash = 2 * np.arcsinh(z/2 * seLogRR)
lower ... | 8ea31bcbbc1d6393e2d60d9ef6a1052b3b5347c5 | 3,645,833 |
from typing import Any
from typing import Optional
import json
def parse_metrics(rpcs: Any, detokenizer: Optional[detokenize.Detokenizer],
timeout_s: Optional[float]):
"""Detokenizes metric names and retrieves their values."""
# Creates a defaultdict that can infinitely have other defaultdic... | d169e9e247d8b969f6adf5161f0f7399a7b69da6 | 3,645,834 |
def cigarlist_to_cigarstring(cigar_list):
"""
Convert a list of tuples into a cigar string.
Example::
[ (0, 10), (1, 1), (0, 75), (2, 2), (0, 20) ]
=> 10M 1I 75M 2D 20M
=> 10M1I75M2D20M
:param cigar_list: a list of tuples (code, l... | 4d3a039f60f8976893e5ad3775f61fbfa2656acc | 3,645,835 |
def add(x, y):
"""Add two numbers"""
return x+y | 7f18ee62d6cd75e44a9401d000d9bcada63f2c24 | 3,645,836 |
def clean_acl(name, value):
"""
Returns a cleaned ACL header value, validating that it meets the formatting
requirements for standard Swift ACL strings.
The ACL format is::
[item[,item...]]
Each item can be a group name to give access to or a referrer designation
to grant or deny base... | 1cceb2af22d2f5bbf223a0eb381b4c6643d76f0e | 3,645,839 |
def test(X, Y, perms=10000, method="pearson", tail="two-tail", ignore_nans=False):
"""
Takes two distance matrices (either redundant matrices or condensed vectors)
and performs a Mantel test. The Mantel test is a significance test of the
correlation between two distance matrices.
Parameters
---... | 7f0d7447ed475292f221e1dc6e4944f5cb2e8bd4 | 3,645,840 |
def get_format_datestr(date_str, to_format='%Y-%m-%d'):
"""
Args:
date_str (str): ''
to_format (str): '%Y-%m-%d'
Returns:
date string (str)
"""
date_obj = parser.parse(date_str).date()
return date_obj.strftime(to_format) | bf443aad3ca38eb35b647d26b38b1404cf82f387 | 3,645,841 |
def lor(*goalconsts):
""" Logical or for goal constructors
>>> from logpy.arith import lor, eq, gt
>>> gte = lor(eq, gt) # greater than or equal to is `eq or gt`
"""
def goal(*args):
return lany(*[gc(*args) for gc in goalconsts])
return goal | 9726cc24f6d79214e652d42ff1b872f60b5a4594 | 3,645,842 |
import logging
from operator import gt
def score(input,
index,
output=None,
scoring="+U,+u,-s,-t,+1,-i,-a",
filter=None, # "1,2,25"
quality=None,
compress=False,
threads=1,
raw=False,
remove_existing=False):
"""Score the in... | c4b0fee2df964e65ee0aec12c84b0b1d7985a254 | 3,645,845 |
def keyword_search(queryset: QuerySet, keywords: str) -> QuerySet:
"""
Performs a keyword search over a QuerySet
Uses PostgreSQL's full text search features
Args:
queryset (QuerySet): A QuerySet to be searched
keywords (str): A string of keywords to search the QuerySet
Returns:
... | 1fb38af2c3aa3bdf092196e8e12539e0a2cf9e58 | 3,645,846 |
def classification_loss(hidden, labels, n_class, initializer, name, reuse=None,
return_logits=False):
"""
Different classification tasks should use different scope names to ensure
different dense layers (parameters) are used to produce the logits.
An exception will be in tr... | c89fd14fae7099b43f639bf0825600e26b60e417 | 3,645,847 |
def do_pdfimages(pdf_file, state, page_number=None, use_tmp_identifier=True):
"""Convert a PDF file to images in the TIFF format.
:param pdf_file: The input file.
:type pdf_file: jfscripts._utils.FilePath
:param state: The state object.
:type state: jfscripts.pdf_compress.State
:param int page_... | e5a48cdf2c93b037c4f983a56467e839920fa06c | 3,645,848 |
def connect(transport=None, host='localhost', username='admin',
password='', port=None, key_file=None, cert_file=None,
ca_file=None, timeout=60, return_node=False, **kwargs):
""" Creates a connection using the supplied settings
This function will create a connection to an Arista EOS nod... | 09407d39e624f9a863a7633627d042b17b7a6158 | 3,645,850 |
def cov_hc2(results):
"""
See statsmodels.RegressionResults
"""
# probably could be optimized
h = np.diag(np.dot(results.model.exog,
np.dot(results.normalized_cov_params,
results.model.exog.T)))
het_scale = results.resid**2/(1-h)
cov_hc2_ ... | 328eeb88e37a2d78a6c0f0f9b3b81459230d87d5 | 3,645,851 |
def add_people():
"""
Show add form
"""
if request.method == 'POST':
#save data to database
db_conn = get_connection()
cur = db_conn.cursor()
print ('>'*10, request.form)
firstname = request.form['first-name']
lastname = request.form['last-name']
address = request.form['address']
country = request.... | db2fcd7a2d9ed0073741d02a0bcafef37f714299 | 3,645,852 |
import inspect
def api_to_schema(api: "lightbus.Api") -> dict:
"""Produce a lightbus schema for the given API"""
schema = {"rpcs": {}, "events": {}}
if isinstance(api, type):
raise InvalidApiForSchemaCreation(
"An attempt was made to derive an API schema from a type/class, rather than... | d07f6c6915967a1e61bc8f9bd1b72adb24207684 | 3,645,853 |
def sum2(u : SignalUserTemplate, initial_state=0):
"""Accumulative sum
Parameters
----------
u : SignalUserTemplate
the input signal
initial_state : float, SignalUserTemplate
the initial state
Returns
-------
SignalUserTemplate
the output signal of the filter
... | 3649942de13f698a92703747d8ea73be7ece4ddb | 3,645,854 |
def approve_report(id):
"""
Function to approve a report
"""
# Approve the vulnerability_document record
resource = s3db.resource("vulnerability_document", id=id, unapproved=True)
resource.approve()
# Read the record details
vdoc_table = db.vulnerability_document
record = db(vdo... | ce1bdb00a5fb6958c51422543e62f289de5e96cb | 3,645,855 |
def sparse_column_multiply(E, a):
"""
Multiply each columns of the sparse matrix E by a scalar a
Parameters
----------
E: `np.array` or `sp.spmatrix`
a: `np.array`
A scalar vector.
Returns
-------
Rescaled sparse matrix
"""
ncol = E.shape[1]
if ncol != a.shape[... | a215440e630aeb79758e8b0d324ae52ea87eba52 | 3,645,856 |
def soup_extract_enzymelinks(tabletag):
"""Extract all URLs for enzyme families from first table."""
return {link.string: link['href']
for link in tabletag.find_all("a", href=True)} | 7baabd98042ab59feb5d8527c18fe9fa4b6a50af | 3,645,857 |
def loops_NumbaJit_parallelFast(csm, r0, rm, kj):
""" This method implements the prange over the Gridpoints, which is a direct
implementation of the currently used c++ methods created with scipy.wave.
Very strange: Just like with Cython, this implementation (prange over Gridpoints)
produces wrong r... | 82201310483b72c525d1488b5229e628d44a65ca | 3,645,859 |
import numpy
import scipy
def sobel_vertical_gradient(image: numpy.ndarray) -> numpy.ndarray:
"""
Computes the Sobel gradient in the vertical direction.
Args:
image: A two dimensional array, representing the image from which the vertical gradient will be calculated.
Returns:
A two di... | f8f9bf6fadbae962206255ab3de57edbab9d935e | 3,645,860 |
def custom_field_sum(issues, custom_field):
"""Sums custom field values together.
Args:
issues: List The issue list from the JQL query
custom_field: String The custom field to sum.
Returns:
Integer of the sum of all the found values of the custom_field.
"""
... | 32c1cce310c06f81036ee79d70a8d4bbe28c8417 | 3,645,861 |
def routingAreaUpdateReject():
"""ROUTING AREA UPDATE REJECT Section 9.4.17"""
a = TpPd(pd=0x3)
b = MessageType(mesType=0xb) # 00001011
c = GmmCause()
d = ForceToStandbyAndSpareHalfOctets()
packet = a / b / c / d
return packet | b9bb0e498a768eb6b7875018c78ca23e54353620 | 3,645,862 |
def doRipsFiltration(X, maxHomDim, thresh = -1, coeff = 2, getCocycles = False):
"""
Run ripser assuming Euclidean distance of a point cloud X
:param X: An N x d dimensional point cloud
:param maxHomDim: The dimension up to which to compute persistent homology
:param thresh: Threshold up to which to... | a0e4cabb613ac77659fda2d31867a7e9df32f288 | 3,645,863 |
def build_target_areas(entry):
"""Cleanup the raw target areas description string"""
target_areas = []
areas = str(entry['cap:areaDesc']).split(';')
for area in areas:
target_areas.append(area.strip())
return target_areas | 48e76a5c1ed42aed696d441c71799b47f9193b29 | 3,645,864 |
def convert_to_celcius(scale, temp):
"""Convert the specified temperature to Celcius scale.
:param int scale: The scale to convert to Celcius.
:param float temp: The temperature value to convert.
:returns: The temperature in degrees Celcius.
:rtype: float
"""
if scale == temp_scale.FARENHEI... | a7c2f0f7405eea96c1ebb4a7e103cf28a95b6f5a | 3,645,865 |
def config_file_settings(request):
"""
Update file metadata settings
"""
if request.user.username != 'admin':
return redirect('project-admin:home')
if request.method == 'POST':
update_file_metadata(request.POST)
return redirect('project-admin:home')
files = FileMetaData... | c8e91ac49305e3aa7aa33961939c3add23fc5327 | 3,645,866 |
def roundtrip(sender, receiver):
"""
Send datagrams from `sender` to `receiver` and back.
"""
return transfer(sender, receiver), transfer(receiver, sender) | 939d9fd861b89037322fcc7c851d291ab073b520 | 3,645,867 |
import json
def loadHashDictionaries():
"""
Load dictionaries containing id -> hash and hash -> id mappings
These dictionaries are essential due to some restrictive properties
of the anserini repository
Return both dictionaries
"""
with open(PATH + PATH_ID_TO_HASH, "r") as f:
... | de8af6d5e5562869c992e08343aadb77c48933b0 | 3,645,868 |
def preprocess(tensor_dict, preprocess_options, func_arg_map=None):
"""Preprocess images and bounding boxes.
Various types of preprocessing (to be implemented) based on the
preprocess_options dictionary e.g. "crop image" (affects image and possibly
boxes), "white balance image" (affects only image), etc. If se... | 141b170e0d4c6447750e2ece967afec7a92a37ea | 3,645,869 |
def update_comment(id):
"""修改单条评论"""
comment = Comment.query.get_or_404(id)
if g.current_user != comment.author and not g.current_user.can(Permission.COMMENT):
return error_response(403)
data = request.get_json()
if not data:
return bad_request('You must put JSON data.')
comment.... | 59db7122f9139f7fda744284e83045533d6361fb | 3,645,870 |
def resnet18(num_classes, pretrained=False, **kwargs):
"""Constructs a ResNet-18 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
encoder = ResNetEncoder(BasicBlock, [2, 2, 2, 2])
if pretrained:
encoder.load_state_dict(model_zoo.load_url(model_urls... | b342fa322cb26571b5df7e5e8f117ce016a7febf | 3,645,871 |
import html
def display_page(pathname):
"""displays dash page"""
if pathname == '/':
return main.layout
elif pathname == '/explore':
return explore.layout
elif pathname == '/eval':
return eval.layout
elif pathname == '/train':
return train.layout
else:
r... | 3aeb44ca1974b63f63b9ef97526aef20d2d92ddb | 3,645,872 |
def getFilterDict(args):
"""
Function: An entire function just to notify the user of the arguments they've passed to the script? Seems reasonable.
Called from: main
"""
## Set variables for organization; this can be probably be removed later
outText = {}
outAction = ""
userString = ""... | ea175812465fa30866fe90c6461f416c4af1d6b2 | 3,645,873 |
def pointwise_multiply(A, B):
"""Pointwise multiply
Args:
-----------------------------
A: tvm.te.tensor.Tensor
shape [...]
B: tvm.te.tensor.Tensor
shape same as A
-----------------------------
Returns:
-----------------------------
tvm.te.tensor.Tensor
shap... | 37c27cced9cc77f3a3aefef32d56f92f0ceb292f | 3,645,874 |
import traceback
def create_website(self):
"""
:param self:
:return:
"""
try:
query = {}
show = {"_id": 0}
website_list = yield self.mongodb.website.find(query, show)
return website_list
except:
logger.error(traceback.format_exc())
return "" | b7b8faf55095288e5c2d693aeed85f6412449c08 | 3,645,875 |
def _get_sparsity(A, tolerance=0.01):
"""Returns ~% of zeros."""
positives = np.abs(A) > tolerance
non_zeros = np.count_nonzero(positives)
return (A.size - non_zeros) / float(A.size) | 44b7fb501a10551167ad37ffdafaef42c6c849b9 | 3,645,876 |
def findPeaks(hist):
"""
Take in histogram
Go through each bin in the histogram and:
Find local maximum and:
Fit a parabola around the two neighbor bins and local max bin
Calculate the critical point that produces the max of the parabola
(critical point represents orientation... | 99b89d4fd9f35deab141e178aaa107dabf35ccfe | 3,645,877 |
def gradient_descent(x_0, a, eta, alpha, beta, it_max, *args, **kwargs):
"""Perform simple gradient descent with back-tracking line search.
"""
# Get a copy of x_0 so we don't modify it for other project parts.
x = x_0.copy()
# Get an initial gradient.
g = gradient(x, a)
# Compute the norm... | 701097aaebbe15306818593daf501b0f7d622f49 | 3,645,879 |
from typing import Counter
def knn_python(input_x, dataset, labels, k):
"""
:param input_x: 待分类的输入向量
:param dataset: 作为参考计算距离的训练样本集
:param labels: 数据样本对应的分类标签
:param k: 选择最近邻样本的数目
"""
# 1. 计算待测样本与参考样本之间的欧式距离
dist = np.sum((input_x - dataset) ** 2, axis=1) ** 0.5
# 2. 选取 k 个最近邻样本的标... | 8deaec88369d2d0cb42ebdd3961caf891357335b | 3,645,881 |
def all_logit_coverage_function(coverage_batches):
"""Computes coverage based on the sum of the absolute values of the logits.
Args:
coverage_batches: Numpy arrays containing coverage information pulled from
a call to sess.run. In this case, we assume that these correspond to a
batc... | 32674a4528b69b756b3fc5f161dcbfd3ceaba01f | 3,645,884 |
import asyncio
async def create_audio(request):
"""Process the request from the 'asterisk_ws_monitor' and creates the audio file"""
try:
message = request.rel_url.query["message"]
except KeyError:
message = None
LOGGER.error(f"No 'message' parameter passed on: '{request.rel_url}'"... | 6aa90764c167be9a1d980dea0e54243a9467c276 | 3,645,885 |
def reinterpret_axis(block, axis, label, scale=None, units=None):
""" Manually reinterpret the scale and/or units on an axis """
def header_transform(hdr, axis=axis, label=label, scale=scale, units=units):
tensor = hdr['_tensor']
if isinstance(axis, basestring):
axis = tensor['labels... | e19d1a5cf567f72ae261cc0fef69b03e2d8a9696 | 3,645,886 |
def duel(board_size, player_map):
"""
:param board_size: the board size (i.e. a 2-tuple)
:param player_map: a dict, where the key is an int, 0 or 1, representing the player, and the value is the policy
:return: the resulting game outcomes
"""
board_state = init_board_state(board_size)
result... | 3fbcd1477fc90553cdc5371440083c9737b4bf5b | 3,645,887 |
def set_processor_type(*args):
"""
set_processor_type(procname, level) -> bool
Set target processor type. Once a processor module is loaded, it
cannot be replaced until we close the idb.
@param procname: name of processor type (one of names present in
\ph{psnames}) (C++: const char *)
... | 32d827fe0c0d152af98e6bed5baa7a24d372c4f8 | 3,645,888 |
from onnx.helper import make_node
from onnx import TensorProto
def convert_repeat(node, **kwargs):
"""Map MXNet's repeat operator attributes to onnx's Tile operator.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
opset_version = kwargs['opset_version']
if opset_version < 11:
rais... | 120e1ee364bf64b00b504fcdc8d0769a6d02db7b | 3,645,889 |
def my_quote(s, safe = '/'):
"""quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted.
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserve... | c5c28b7779e9cab2488696435832f9f7cbd03e57 | 3,645,890 |
from masci_tools.tools.cf_calculation import CFCalculation, plot_crystal_field_calculation
def test_plot_crystal_field_calculation():
"""
Test of the plot illustrating the potential and charge density going into the calculation
"""
cf = CFCalculation()
cf.readPot('files/cf_calculation/CFdata.hdf'... | 90488103d929929615dc1e5de1531102a9f7b96a | 3,645,892 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.