content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
def to_document(model, document_class):
"""Convert a model object to a database document.
:param BaseModel model: The model object to convert. This instance must have a to_dict() method that returns
a dictionary of the model data.
:param class document_class: The type of the docume... | e021bd8912226a80042d47382630574d28ac3d9f | 34,600 |
def get_lightcurve(meteor_array):
""" Calculates the sum of column level values of a given array. For croped meteor image this gives its lightcurve.
"""
ncols = len(meteor_array[0])
lightcurve = []
for i in range(ncols-1):
lightcurve.append(np.sum(meteor_array[:, i:i+1]))
return lightc... | 3b231653d31444f274f867f7bb52fb5d73c376b3 | 34,601 |
def __neighcom(node, graph, status, threshold) :
"""
Compute the communities in the neighborood of node in the graph given
with the decomposition node2com
"""
weights = {}
for neighbor, datas in graph[node].iteritems() :
if (neighbor != node) :
#
#if distance(neig... | 36377dfd418fde5de34d2c815733be49748957b2 | 34,602 |
import six
def wheel_is_compatible(filename):
"""
Return True if the wheel is compatible, False otherwise.
"""
data = parse_wheel_name(filename)
if ("py2.py3" in data["python_tag"]) or ("py3.py2" in data["python_tag"]):
# only here to skip elif/else
pass
elif six.PY3:
i... | 2de1d1c27629bbed863d6de6dd995da57f3bda0d | 34,603 |
import numpy
def _njit_itakura_mask(sz1, sz2, max_slope=2.):
"""Compute the Itakura mask without checking that the constraints
are feasible. In most cases, you should use itakura_mask instead.
Parameters
----------
sz1 : int
The size of the first time series
sz2 : int
The siz... | c0905f4159aca4fc9b2c3448545770fa0019967f | 34,604 |
def flush_deferred_until(ctx, u, until):
"""
Flush the deferred actions where the run_at is before 'until'.
NOTE: These actions are NOT run, they are just deleted.
:param ctx: The database context.
:param until: datetime Flush deferred actions with run_at times older than this.
Returns a list of... | a18007a3786fb7370b646ebf2af8d97e5ee57954 | 34,605 |
def add_kl_to_loss(kl, loss, jacobian_dict):
"""Adds the KL to the optimized loss and updates jacobians accordingly."""
if kl is None:
return loss, jacobian_dict
loss += kl
jacobian_dict = utils.add_grads_to_jacobians(jacobian_dict, kl)
return loss, jacobian_dict | 695627ca17fddf7126b8bcca50c11f6680b0152e | 34,606 |
def _unicodeToBuiltInType(input_to_convert):
"""
Convert a string into a string, a float or an int depending on the string
:param input_to_convert: unicode or string element to convert
:Example:
>>> _unicodeToBuiltInType("1")
1
>>> _unicodeToBuiltInType("1.0")
1.0
>>> _unicodeToBuiltInType("a")
'a'
... | 1023ed1c22d71daef8277f2f0b7d1b642656fc09 | 34,607 |
def fxa_oauth_token(request):
"""Return OAuth token from authorization code.
"""
state = request.validated['querystring']['state']
code = request.validated['querystring']['code']
# Require on-going session
stored_redirect = request.registry.cache.get(state)
# Make sure we cannot try twice ... | 1581ea350b18d70c10255a988ad1b2375e80f2f0 | 34,608 |
def minimaxav_score(profile, committee):
"""
Return the Minimax AV (MAV) score of a committee.
Parameters
----------
profile : abcvoting.preferences.Profile
A profile.
committee : iterable of int
A committee.
Returns
-------
int
The ... | 7bc9b4c81088341ca4f9fe2e5e03d71e36463504 | 34,609 |
def set_lipid(path, lipid):
"""
Establish save directory of cutoff test data.
"""
save_dir = "{}/PyLipID_cutoff_test_{}".format(path, lipid)
fig_dir = check_dir(save_dir, "Figures", print_info=False)
return fig_dir | a5ec6ab7af2f1006e96fd6ecb54eb3a6e8c45501 | 34,610 |
import re
def format_bucket(bucket, appid):
"""兼容新老bucket长短命名,appid为空默认为长命名,appid不为空则认为是短命名"""
if not isinstance(bucket, string_types):
raise CosClientError("bucket is not string")
if not bucket:
raise CosClientError("bucket is required not empty")
if not (re.match(r'^[A-Za-z0-9][A-Za-... | 1d322982fd29d1f380d6bc19c319abefa23d4d7c | 34,611 |
def model(pretrained=False, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
"""
model = VGG(make_layers(cfg['O'], di... | ae38f9ad96f226152c47029c25bb1cbd40774c0e | 34,612 |
def get_location_from_uri(uri):
"""
Given a URI, return a Location object that has had an appropriate
store parse the URI.
:param uri: A URI that could come from the end-user in the Location
attribute/header
Example URIs:
https://user:pass@example.com:80/images/some-id
... | 574c7cbf4fbe5b6e87a95e9ccdc283fbf7182337 | 34,613 |
def Coding(incoming_msg):
"""
Function to retrieve a meme on brooklyn99.
:param incoming_msg: The incoming message object from Teams
:return: A text or markdown based reply
"""
# our test search
search_term = "coding"
return SearchGif(incoming_msg, search_term) | 1163ba5393dd15ac9a1004bb57defdcf45d07dcb | 34,614 |
def false_pos(pred_labels, true_labels, groups):
"""
Calculates the number of elements in a group with a positive prediction but negative true label.
:math: :math:`\\hat{Y} = 1, Y=0`
:return: dictionary of total false positive predictions for each group
"""
if isinstance(pred_labels, Tens... | 1e58ff4e5becf2beeea620fe232c800b8ad00009 | 34,615 |
def merge_mesh(mesh1: Mesh, mesh2: Mesh) -> Mesh:
"""Merge two meshes into a single mesh
Keyword arguments:
mesh1 -- First mesh
mesh2 -- Second mesh
"""
m1_vertices = list(mesh1.absolute_vertices())
m2_vertices = list(mesh2.absolute_vertices())
mesh = Mesh()
mesh.material = deepcopy... | 71507c155446f9afd8ce017699a6ad859c4ba94b | 34,616 |
def traverse(tree, it):
"""
Traverse tree until a leaf node is reached, and return its symbol.
This function consumes an iterator on which next() is called during each
step of traversing.
"""
nd = tree
while 1:
nd = nd.child[next(it)]
if not nd:
raise ValueError("... | 5f4be6c4fedfe4220855c0ec12547a9f9eb2ac87 | 34,617 |
def deposit_create():
"""Create a new deposit."""
return render_template(
"invenio_app_rdm/records/deposit.html",
forms_config=get_form_config(createUrl=("/api/records")),
searchbar_config=dict(searchUrl=get_search_url()),
record=new_record(),
files=dict(
defa... | 66a79bb5e09c4f5934d19c1e5b5534645cf20fa8 | 34,618 |
def load_synthetic_mammogram(image_path):
"""Load a synthetic mammogram from file
:param image_path: path to the image one disk.
:returns: ndarray -- the image as an ndarray
"""
img, image_header = load(image_path)
img = np.invert(img)
img = img.astype('float64')
img = skimage.transform... | 6a35d963153f119b6f39eabb4f83235e35b0e934 | 34,619 |
def setUnitStatus(unitID: bytes, status: bytes) -> bytes:
"""
Sets the status for a unit
:param unitID:
:param status:
:return:
"""
return wrap(b"g" + b"E" + b"U" + unitID + status) | 04d34052d4ff5f337d8dcb972efebf36d289baa4 | 34,620 |
import re
import json
def _parsing_dayprice_json(pageNum=0):
"""
处理当日行情分页数据,格式为json
Parameters
------
pageNum:页码
return
-------
DataFrame 当日所有股票交易数据(DataFrame)
"""
url = ct.SINA_DAY_PRICE_URL%pageNum
request = urllib2.Request(url)
text = urllib2.urlop... | d32a628a879796d56ed6a8eba288d1066ae416b7 | 34,621 |
def get_cammoun_schaefer(vers='fsaverage5', data_dir=None, networks='7'):
"""
Returns Cammoun 2012 and Schaefer 2018 atlases as dictionary
Parameters
----------
vers : str, optional
Which version of the atlases to get. Default: 'fsaverage5'
data_dir : str or os.PathLike, optional
... | 2a05cadcaef9f4ec2c24b027346a1cc658971924 | 34,622 |
def sql_schemas(dict_kwargs=None) -> SearchStrategy[dict[str, Table]]:
"""
Build objects describing multiple tables in a SQLite3 database.
"""
if dict_kwargs is None:
dict_kwargs = {}
return dictionaries(keys=sql_identifiers(), values=tables(), **dict_kwargs) | 3cd11aa9fa26fd6692f193459d34e352d4b78b5b | 34,623 |
import random
def select_rand_pen(t_s: int, t_d: int, t_e: int, p: np.array) -> int:
"""
Simulate Multi Query Read Scheduling by sampling at random according to the inverse of the
penalty function.
@see selectRand
:param t_s: int
start time of the interval [t_s, t_e]
:param t... | 8106e2aab0ca4573415bde25450074c7518a9884 | 34,624 |
from typing import OrderedDict
import array
def _height_fit_fun(parameters,
names,
heights_dict, # in um
radius, # in um
data_dict=None, # in units [1, nm/mV, pN/nm]
errors_dict=None, # in units [1, nm/mV, pN/nm]
... | ecc219a253f0e644e34e6435cd161a6a090e4d99 | 34,625 |
import ctypes
import array
import warnings
def _get_bytes_pointer(inp):
"""Returns pointer to bytes-like input
"""
if isinstance(inp, np.ndarray):
assert inp.dtype == np.uint8
# https://stackoverflow.com/q/60848009/5133167
if not inp.flags["C_CONTIGUOUS"]:
# Make a cont... | db754acc506a7370aa3c9c29d87cdca12e3703ef | 34,626 |
def no_trajectory_xml():
"""Emulates a XML response for no trajectory case"""
STREAM = b'<INST nbVeh="0" val="1.00"><CREATIONS><CREATION entree="Ext_In" id="0" sortie="Ext_Out" type="VL"/></CREATIONS><SORTIES/><TRAJS/><STREAMS/><LINKS/><SGTS/><FEUX/><ENTREES><ENTREE id="Ext_In" nb_veh_en_attente="1"/></ENTREES... | abd90b9f87beb39b04bbf8fc889c952d81d4e7f8 | 34,627 |
from typing import Dict
from typing import List
def get_scalars(tensors: Dict[str, tf.Tensor], names: List[str] = None, pattern: str = None) -> Dict[str, tf.Tensor]:
"""Retrieve scalars from tensors.
Parameters
----------
tensors : Dict[str, tf.Tensor]
Dictionary
names : List[str], option... | 0d4524925f62715d429b5def6ea0d3582eb07714 | 34,628 |
def rle_encoding(x):
"""
Run-length encoding stolen
from https://www.kaggle.com/rakhlin/fast-run-length-encoding-python
Args:
x (np.ndarray): ndarray of size (height, width) representing the mask of an image
Returns:
run_lengths (list): List of predicted road pixels
if x[i,j] ... | 3a38de0b83bc25067f4adab26dc8b8287de0a66d | 34,629 |
from typing import List
import os
def _setup_multi_seed_no_changes_experiment(
experiment_path: str, seeds: List[int]
) -> List[str]:
"""Method for constructing paths in case of seed variation but no config changes.
Args:
experiment_path: overall experiment path.
seeds: list of seeds over... | e01c59d4f9d42ac873cb1c60d594b48ee5b5608f | 34,630 |
import re
def normalize_date(date):
"""normalze date
Returns:
[string] -- [normalized result date]
"""
char = re.compile('[年月./]')
date=date.group(0)
date = char.sub('-',date)
if '日' in date:
date=date.replace('日','')
return date | 11197775c975fd09aa54a12de47b5e113d99f954 | 34,631 |
def get_rendersetup_layer(layer):
"""Return render setup layer name.
This also converts names from legacy renderLayer node name to render setup
name.
Note: `defaultRenderLayer` is not a renderSetupLayer node but it is however
the valid layer name for Render Setup - so we return that as is.
... | 098e6286e018b4057498aa8afe66a28dde473ed8 | 34,632 |
from typing import List
import math
def grid(topology: Topology, template: AgentTemplate) -> List[AgentState]:
"""
Generate agents on every integer location within the `topology` bounds.
Args:
topology: the `context.globals()["topology"]` value.
template: an agent definition, or a functio... | 852a58136b55302d336aeb727387767b9241b17a | 34,633 |
def formatNumber(number, numberOfDigits):
"""
The function formatNumber() return a string-representation of a number
with a number of digits after the decimal separator.
If the number has more digits, it is rounded.
If the number has less digits, zeros are added.
@param number: the number to fo... | 04bb35fc3f7bab847709c48c6acdb72260a038eb | 34,634 |
def get_plugin_manager(name="DEFAULT"):
"""Return the Collection Plugin manager for events logging.
:param name: the name of the logger to be associated with the plugin.
:type name: str
:returns: the Logger plugin manager
:rtype: LoggerPluginManager
"""
global _logger_plugin_managers
t... | a830db601e18323c50818b989543b0e7f0df24a1 | 34,635 |
from foreshadow.smart import SmartTransformer
from foreshadow.concrete import StandardScaler
def smart_child():
"""Get a defined SmartTransformer subclass, TestSmartTransformer.
Note:
Always returns StandardScaler.
"""
class TestSmartTransformer(SmartTransformer):
def pick_transform... | d9a01815887ce33276dfe8b2feb2fddaf3e41cbd | 34,636 |
def compute_species_interaction_weights(
model: CommunityModel, df: pd.DataFrame, alpha: float = 1.0
) -> Array:
"""Compute interaction between two species. The values lie between -1 (negative
interaction) and + 1 postitive interaction. Be :math:`p_{ij}` the number of
metabolites produced by i and consu... | 575fa13797cfffa646757b8ac56dc3d132adf256 | 34,637 |
def unsupported_sequence_terminals(request):
"""Terminals that emit warnings for unsupported sequence-awareness."""
return request.param | 6a85fcd35d3d4813ec14c530b867171518cb584e | 34,638 |
def get_timed_data_sheet(wb,fkeys,pkeys,date_nums,ras,decs,azs,elevs):
"""
See if the timed data sheet exist and create it if not
A timed data sheet is basically the power VtoF data as a function
of time (rows) and frequency/polarization (columns). This initiates
the sheet but does not fill it. fill_map_sh... | bbd46286e0ff1efc25089d46f81d8b31e3687f38 | 34,639 |
from pathlib import Path
from typing import List
from typing import Tuple
def rtconvert(*, in_file: Path, reference_series: Path, out_file: Path, struct_names: List[str],
struct_colors: List[str], fill_holes: List[bool], roi_interpreted_types: List[str],
modelId: str, manufacturer: str, in... | 80ee5e84bd67509367fa051b242ee4ff08e76017 | 34,640 |
def get_diamond_prediction(diamond_data, protein_accession):
"""Retrieve DIAMOND prediction data from dbCAN overview.txt file.
:param diamond_data, str, output data from DIAMOND written in the overview.txt
:param protein_accession, str
Return a CazymeProteinPrediction instance.
"""
# check if ... | 03f3feacd5263d0bc1d81b496bc2b9f537b14604 | 34,641 |
def train_batch(b, verbose=False):
"""
:param b: contains:
:param imgs: the image, [batch_size, 3, IM_SIZE, IM_SIZE]
:param all_anchors: [num_anchors, 4] the boxes of all anchors that we'll be using
:param all_anchor_inds: [num_anchors, 2.0] array of the indices into the concatenat... | 20f6c84803ef6ad5e148a8a5c0e8f172d8587a3f | 34,642 |
def convert_image_idx_to_padded_string(n, numCharacters=6):
"""
Converts the integer n to a padded string with leading zeros
"""
t = str(n)
return t.rjust(numCharacters, '0') | 71309d7765e3fdc740f50db8f46b4e5b71eb512d | 34,643 |
from astroNN.config import ENVVAR_WARN_FLAG
import os
def gaia_env():
"""
Get Gaia environment variable
:return: Path to Gaia Data
:rtype: str
:History: 2017-Oct-26 - Written - Henry Leung (University of Toronto)
"""
_GAIA = os.getenv('GAIA_TOOLS_DATA')
if _GAIA is None and ENVVAR_WAR... | 4fab0f9cd97edca13f273f051ddc60523122edaf | 34,644 |
import math
def compute_frequency(occurrence_count):
"""
frequency is too coarse.
taking the log from it is going
to smooth it somehow
:param occurrence_count:
:return:
"""
return round(math.log(occurrence_count), 2) | e797bf26feee3379a781b3eefe8a988700728c8f | 34,645 |
def determineCalibrants(functions):
""" Automatically determine suitable calibrant peaks.
This function is part of the automated peak detection
functionality, where it attempts to determine the most suitable
n number of calibrations (n is the user defined setting of minimum
number of peaks for cali... | 3a45b14c2fcf1e48f35735ffa3b5f18d4ac05395 | 34,646 |
from datetime import datetime
import spwd
import crypt
def check_pw(user, password):
"""Check the password matches local unix password on file"""
# log the username & password
# in openssh-server, if user is invalid, password must be overwrite.
# source code:
# badpw[] = "\b\n\r\177INCORRECT";
... | c1a1bb9f9ce59d25eb453158be1ac28d40ac926e | 34,647 |
def get_error_stats(errors, tokens):
""" Returns a dictionary recording each error and its
frequency in the document.
Uses the FreqDist function from NLTK.
`errors` generated with the `identify_errors` function.
References:
:func:`nltk.FreqDist`
:func:`identify_errors`
Args:
... | 0be0b111ad9343e7ea3c740a4f4c6cf4b72f3755 | 34,648 |
def extended_figure(*args, **kwargs):
"""
Creates an Extended_Figure object.
Parameters
----------
*args: *list
Any argument accepted by matplotlib.pyplot.figure
**kwargs: **dict
Any keyword argument accepted by matplotlib.pyplot.figure
Returns
-------
fig: Extended... | bf9e8c00d35496b1ce74b7726ae61abe7c39ff00 | 34,649 |
async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook from Locative."""
try:
data = WEBHOOK_SCHEMA(dict(await request.post()))
except vol.MultipleInvalid as error:
return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY)
device = data[ATT... | 80cc23ab06066be8641fc3c9c7a0d321f0e22be2 | 34,650 |
def mat2flat(H):
"""
Converts an homography matrix with shape `[1, 3, 3]` to its corresponding flattened
homography transformation with shape `[1, 8]`.
"""
H = tf.reshape(H, [-1, 9])
return (H / H[:, 8:9])[:, :8] | 46896c0a3179df2e2678e26f3508de7b889bbc7a | 34,651 |
import sys
def predict_current_location():
"""Predict location label for current wifi signals."""
# read from sensors
signals = get_signals()
# read from model
x_train = get_feature_matrix()
y_train = get_labels()
x_signal = get_signal_matrix(x_train, signals)
# classify signal
try... | 82c256299988f8ffcaa6fa155e1ae9db44d3baf7 | 34,652 |
def fibonacci_peak(cam,focus,ak,bk,aoi,hysteresis,tolerance):
"""Fibonacci peak search taken from E. Krotkov: "Focusing" P.233"""
# cam: camera already opened
# focus: focus from used LenseController
# ak: start step no.
# bk: stop step no.
# aoi: area of interest in form [x1,y1,x2,y2]
# hysteresis: offse... | 7fdae0cc8b3e2ba6ed8d5b40091258e4e1bb47eb | 34,653 |
def convert_params_to_string(params: dict) -> str:
""" Create a string representation of parameters in PBC format
"""
return '\n'.join(['%s %s' % (key, value) for (key, value) in params.items()]) | d121ea62f14333ad7f02727a7a6777b8880fef45 | 34,654 |
import time
def get_series_nuclear_data(self, summary, sidx, **kwargs):
"""Function for parallelized single-pixel nuclear data retrieval.
Args:
summary (list): list of summaries.
sidx (int): series index.
**kwargs: ncores.
Returns:
np.array: series nuclear data.
"""
# Se... | 29720e83df11623bdafd2f268b2a9da21a830ce4 | 34,655 |
def _encode_as_png(data, profile, dst_transform):
"""
Uses rasterio's virtual file system to encode a (3, 512, 512)
array as a png-encoded bytearray.
Parameters
-----------
data: ndarray
(3 x 512 x 512) uint8 RGB array
profile: dictionary
dictionary of kwargs for png writing... | 535ece2c1375c0b2fe96f67547b012050bd9de9b | 34,656 |
def arch_from_macho(cputype, cpusubtype):
"""Converts a macho arch tuple into an arch string."""
arch = ffi.new('SymbolicMachoArch *')
arch[0].cputype = cputype & 0xffffffff
arch[0].cpusubtype = cpusubtype & 0xffffffff
try:
return str(decode_str(rustcall(lib.symbolic_arch_from_macho, arch)))... | 204815ecb1d4ab2d2d7aae4ac13522e37f68e7f9 | 34,657 |
import PyMOTW
import os
def get_doc_dir(module_name):
"""Return the local directory containing documentation for the module."""
package_path = PyMOTW.__path__[0]
doc_dir = os.path.join(package_path, DOCS_DIR, module_name)
return doc_dir | 1c25325a3ed221a70f0327f059295bc0b872c53c | 34,658 |
def interpret_keypress():
"""
See whether a number was pressed (give terminal bell if so) and return
value. Otherwise returns none. Tries to handle arrows as a single
press.
"""
press = getch()
if press == "Q":
raise Exception("Exiting expo by user request from pressing Q")
i... | bc3b2e25b3c15c49daf6f7a3907e41bb04aa8d5e | 34,659 |
def generate_numbers(limit):
"""
@param:
limit - length of the sequence of natural numbers to be generated
@return:
list_of_numbers - list of the generated sequence
"""
if limit <= 0:
raise ValueError('Invalid limit specified')
list_of_numbers = list()
for... | f0cd027f6978be01b80c4a86914ecc8d3444d251 | 34,660 |
from gdcdatamodel import models, validators
import os
def graph_connect():
"""Load config and connect to graph, return graph and models."""
if ('DICTIONARY_URL' in os.environ):
url = os.environ['DICTIONARY_URL']
datadictionary = DataDictionary(url=url)
print('created datadictionary fro... | fc4f14c24c825da94a2031e959a1a37dd7669d33 | 34,661 |
def get_supplier(supplier_id):
"""
Read a single Supplier
This endpoint will return a Supplier based on it's id
"""
app.logger.info("Request for supplier with id: %s", supplier_id)
supplier = Supplier.find(supplier_id)
if not supplier:
raise NotFound("Supplier with id '{}' was not fo... | b358bfcaad48c6fbfb98ca6b64f799da6fe8eb78 | 34,662 |
import warnings
def se_diversity(gen, k=None, n_jobs=1, fp_type='morgan',
dist_threshold=0.65, normalize=True):
"""
Computes Sphere exclusion diversity i.e. fraction of diverse compounds according to a pre-defined
Tanimoto distance.
:param k:
:param gen:
:param n_jobs:
:... | 2be39404b8ae143efb7a37a78e753c1978676374 | 34,663 |
def get_root_y(c_sys: CompositeSystem) -> Gate:
"""returns root of Y gate.
Parameters
----------
c_sys : CompositeSystem
CompositeSystem containing gate.
Returns
-------
Gate
root of Y gate.
Raises
------
ValueError
CompositeSystem is not 1quit.
Val... | 572deeb46a8a23d37a7138716b983d91136dc34b | 34,664 |
def sanitize_sql(sql, keep_transaction=False):
"""Sanatize the sql string
"""
# remove comments
string = remove_comments(sql)
# remove transactionals
if not keep_transaction:
string = remove_transactional(string)
# remove new lines
string = remove_newlines(string)
# remove... | 9ef3c12b823f9eabc4f6b61fe389ea68db6c209d | 34,665 |
def create_whimsy_computation_lambda_empty():
"""Returns a lambda computation and type `( -> <>)`."""
value = computation_factory.create_lambda_empty_struct()
type_signature = computation_types.FunctionType(None, [])
return value, type_signature | 741629cd80ba4bbaf27af22d4061226176dfc683 | 34,666 |
def fire_weather_index(isi, bui):
"""Fire weather index.
Parameters
----------
isi : array
Initial spread index
bui : array
Build up index.
Returns
-------
array
Build up index.
"""
fwi = np.where(
bui <= 80.0,
0.1 * isi * (0.626 * bui ** 0.809... | bae3f683a2870c36ce1b3c0c6f33d872968f851c | 34,667 |
from typing import Optional
import logging
def read_file(filename: str) -> Optional[str]:
"""
Read a common file and return its content.
Returns
-------
content
The file content
"""
try:
with open(filename, 'r') as f:
content = f.read
return content
... | 46ceb903af8b655edf85588d31987e02a7667ef4 | 34,668 |
def power(b, e):
"""
@purpose: Using a binary list to calculate power of two integers
@param:
b: The base number
e: The exponent
@precondition: A valid positive base and exponent are input
@postcondition: The power of b^e is print out
@Complexity:
Best Case: O(1) if expon... | f510642c8b3eee9eac231b33d2e5260855c4bbf2 | 34,669 |
def get_all_items():
"""Get all items"""
items = Item.query.all()
items_list = []
for item in items:
item_object = {
'id': item.id,
'subject': item.subject,
'status' : item.status,
'url': item.url,
'requestor': item.requestor,
... | 0dadd886096f8a3bcea2413830c70a89b4eb06fb | 34,670 |
def usergenerator(no1, no2, no3, no4, mode):
"""
生成中文拼音和随机字母组成的用户名
:param no1 表示声母:
:param no2 表示韵母:
:param no3 表示第一位随机字母:
:param no4 表示第二位随机字母:
:param mode 选择姓名的次序:
:return 返回用户名:
"""
list1 = ['b', 'p', 'm', 'f', 'd',
't', 'n', 'l', 'g', 'k',
'h', 'j... | 0875297000dc00bb3a6ba46844993047137261ec | 34,671 |
def verify_input(json_data):
"""
Verifies the validity of an API request content
:param json_data: Parsed JSON accepted from API call
:type json_data: dict
:return: Data for the the process function
"""
# callback_uri is needed to sent the responses to
if 'callback_uri' not in json_dat... | 77f609923bd774732c1233413633b077d47e5919 | 34,672 |
def detail_slug_dct(slug):
"""
Function to localize Slug's detail properties.
:param slug: model Slug
:return: dictionary with Slug's detail properties localized
"""
return _detail_slug_form.fill_with_model(slug) | 13d7f41c706a45bf4534cc8be9f2be14e31bc6bd | 34,673 |
import warnings
def is_myst_available():
"""Whether the myst-parser package is available."""
if myst_parser is None:
return False
major, minor = myst_parser.__version__.split(".")[:2]
if int(major) < 1 and int(minor) < 8:
warnings.warn("The installed myst-parser version is less than th... | 15b54b642e2a4096438f41b12ac2c6b83b651716 | 34,674 |
def CreateTrimmedSurface(trimSource, surfaceSource, multiple=False):
"""
Constructs a Brep using the trimming information of a brep face and a surface.
Surface must be roughly the same shape and in the same location as the trimming brep face.
Args:
trimSource (BrepFace): BrepFace which contains... | 5b317a6c64c3607feb3338844a505e3b62fde970 | 34,675 |
import sys
from datetime import datetime
def limits_exceeded():
"""
Check to see if we are about to exceed the maximum recursion depth. Also check to
see if emulation is taking too long (if needed).
"""
# Check to see if we are approaching the recursion limit.
level = len(getouterframes(curr... | 6ea9bcbd6b37faa470121601d9927357e5d37438 | 34,676 |
def formatdatetime(datatimes):
"""
格式化日期时间为指定格式
:param datatimes: 数据库中存储的datetime日期时间,也可以是字符串形式(2021-09-23 11:22:03.1232000)
:return: 格式化后的日期时间如:2021-09-23 11:22:03
"""
if datatimes:
try:
if isinstance(datatimes, str):
if "." in datatimes:
... | 8346fe27eb27994a647837c8b280e04e178c91d4 | 34,677 |
def get_difference(stocks: pd.DataFrame) -> pd.DataFrame:
"""Calculates the gains or loss for each stock."""
stocks = stocks.astype({"closing_price": "float", "initial_value": "float"})
stocks["gain_loss"] = stocks["closing_price"] - stocks["initial_value"]
stocks["gain_loss"] = stocks["gain_loss"].ro... | 141caa895a6d5761e41f0656307c851c64df2df5 | 34,678 |
import math
def random_mini_batches(X, Y, batch_size=64, seed=0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (number of examples, input size)
Y -- true "label" vector of shape (number of examples, number of features)
batch_size -- size of the min... | ee6eec6d90a61f33c44fa01ced15e9a718a4a58e | 34,679 |
def stelab(pobj: ndarray, vobs: ndarray) -> ndarray:
"""
Correct the apparent position of an object for stellar
aberration.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/stelab_c.html
:param pobj: Position of an object with respect to the observer.
:param vobs:
Veloc... | ebdead6d87c4f916afcca8897758fb189fa4a58a | 34,680 |
import tqdm
import torch
def train(train_loader, model, args, optimizer, scheduler, epoch, device, writer=None):
"""Train for one epoch on the training set"""
# switch to train mode
model.train()
print('\nEpoch: %d' % epoch)
train_loss = 0
total = 0
correct = 0
for j, (input,... | 55f25cf0d7ed93a973443442ad93ba5ed0eea0ba | 34,681 |
def add_noise(input_image, noise, multiple_image_std, size=224):
"""Transformation of a single image by adding noise.
If a random gaussian distribution of noisy is specified (noise='r_normal'),
the standard deviation of the noise added is based upon the dynamic range of
the image weighed by multiple_image_std ... | 99f290f498b6abea5d592787ee60a137d805ff33 | 34,682 |
from datetime import datetime
import sys
def get_measures_slot(dbs: Databases, topic: str, timespan: int):
"""
Return
------
a list of measures found in the timespan
None if upper limit of the time window is reached
"""
# Fetch first doc inserted
start_timestamp = get_first_doc(dbs, t... | 8196a4d420535bebbb2ef4423af176862308bb03 | 34,683 |
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False,
metric=None, **metric_kwargs):
"""
Compute several Topic Models in parallel using the "gensim" package. Calculate the models using a list of varying
parameters `... | 01ad43f2ab07dbbd3c64e2a9bc8ee3b7f5fddfad | 34,684 |
from re import T
def n_step_bootstrapped_returns(r_t: T, discount_t: T, v_t: T, targets: T, lambda_t: T, seq_len: int, n: int) -> T:
"""Computes strided n-step bootstrapped return targets over a sequence.
The returns are computed according to the below equation iterated `n` times:
Gₜ = rₜ₊₁ + γₜ₊₁ [(1 - λₜ... | ec729b840a47f4d37eff65f5e7c36a7467237fc2 | 34,685 |
import requests
import json
def questions (category, token):
"""Contacts API and retrieves questions + answers based on category"""
# Retrieve questions and answers from API
try:
response = requests.get(f"https://opentdb.com/api.php?amount=1&category={category}&type=multiple&token={token}")
... | 7ff86a66e82dd442fc57b68ac02a7b793336d290 | 34,686 |
async def reset_clean_filter_timer(obj):
"""Reset the Clean Filter indicator timer."""
return await obj["madoka"].reset_clean_filter_timer.update(ResetCleanFilterTimerStatus()) | a746aa0ce2527dc3a135c4ab71d8841f133b85bb | 34,687 |
def getFigureSpec(iteration: int, perceptual: bool):
"""
Get 2x2 Figure And Axis
Parameters
----------
iterations : int
perceptual : bool
If true, generate the axis of perceptual loss
Return
------
fig, axis : matplotlib.figure.Figure, matplotlib.axes.Axes
The plott... | 2003ce5d4ddfa316ba5bd56bfb5150d9c96b96ab | 34,688 |
def ldr_vartime_blockedby_pp_hat(arr_rate, pp_mean_svctime, pp_cap, pp_cv2_svctime):
"""
Approximate unconditional variance of time blocked in ldr waiting for a pp bed.
Modeling pp as an M/G/c queue and using approximation by Whitt.
"""
pp_svcrate = 1.0 / pp_mean_svctime
vartime = qng.ggm_qwait... | 4ec8a552473c07fb65a2b044fda906a01c7b7f1c | 34,689 |
def identify_crossing_events(df):
"""Identifies pore crossing events in data frame of domain indices.
Given a data frame of domain indices alongside time stamps and particle IDs,
this function identifies crossing events, i.e. a particle moving from one
side of the membrane to the other THROUGH THE PORE... | 583469263c319db59724e56a46c6f422486a230b | 34,690 |
from datetime import datetime
import calendar
import time
def timecode(acutime):
"""
Takes the time code produced by the ACU status stream and returns
a ctime.
Args:
acutime (float): The time recorded by the ACU status stream,
corresponding to the fractional day of th... | 41e5298777e1685041018e8aeee046a758ee4912 | 34,691 |
def calc_timedelta_in_years(start, end) -> float:
"""Computes timedelta between start and end dates, in years
To use this function, start and end dates should come
from a series of daily frequency.
Args:
start: start date
end: end date
Returns:
float: time delta in ... | 1833b69492b9c16a2b657da658f2f17dce2c3884 | 34,692 |
def resolve_field(ctx, parent_type, source, field_asts):
"""A wrapper function for resolving the field, that catches the error
and adds it to the context's global if the error is not rethrowable."""
field_ast = field_asts[0]
field_name = field_ast.name.value
field_def = get_field_def(ctx.schema, pa... | ee070b2d8a3a6dfdb4e9d60345964c2aa8f7f93d | 34,693 |
def listen(recognizer, mic, keywords, uses_google_api):
"""
Listens for a set of (keyword, priority) tuples and returns the response
:param recognizer: speech_recognition Recognizer object
:param mic: speech_recognition Microphone object
:param keywords: Iterable of (keyword, priority) tuples
:... | 1af6674edc6709da7a81e72cbfa84ec2df1eff64 | 34,694 |
from pynetio import Netio
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Netio platform."""
host = config.get(CONF_HOST)
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
port = config.get(CONF_PORT)
if not DEVICES:
hass.htt... | 955a9b62f19eb4478c19339456cd74037f4ffdca | 34,695 |
def extract_username(message: Message) -> str:
"""
Extracts the appropriate username depending on whether
* it was mentioned in an Entity,
* it's accessible on message.author.id (discord)
* it's accessible on message.author (pyttman dev mode)
:param message:
:return: str
"""
... | 58a181abce89306b65228fd3f51c63925b5a467b | 34,696 |
def application(app_plan, custom_application, request, lifecycle_hooks):
"""
Creates an application with a application plan defined in the specified fixture
"""
application = custom_application(rawobj.Application(blame(request, "limited_app"), app_plan),
hooks=lifecy... | 6519af0a6aea26b4f4d7a39c325a06c9c993fda6 | 34,697 |
def reward_user_required(view_func):
"""
Decorator for views that checks that the user is logged in and can use
reward points.
"""
def check_user(user):
return can_reward_points_be_used_by(user)
return user_passes_test(check_user)(view_func) | aa499dc61d35537fc7e74404e0ead227da46a461 | 34,698 |
def dnv_registry_listing_soup(alphabetLetter, output_file_base):
"""
A method for collecting the list of ships that are in the DNV registry. From this list a list of available dnv-ids can be generated.
:param alphabetLetter: A capital letter of the alphabet
:param output_file_base: The base_name of the ... | 942404c074113b424f38a12af97619843b6109cb | 34,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.