content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def create_decode_network(width=width, height=height, Din=Din, Dout=Dout, d_range=d_range):
"""
data flow with traffic on:
input IO ->
tag horn ->
(pre-fifo valve) ->
FIFO ->
(post-fifo valve) ->
TAT ->
AER_tx ->
neurons ->
AER_rx ->
(neuron output valve) ->
PAT ... | bce65caa463bea8a582426bfe9fac08617fca812 | 8,504 |
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
return cv2.Canny(img, low_threshold, high_threshold) | df3ede87458939e7648090517828e2056cd9cfd6 | 8,505 |
def dGcthetalnorm(w: Wilson, cthetal):
"""Normalized distribution 1D cthetal"""
return tauBp / Btaul * dGcthetal(w, cthetal) | b925c6dad2dd6327f3fe250771c19018ecedcf14 | 8,507 |
from typing import Optional
def user_deposit_address_fixture(
deploy_smart_contract_bundle_concurrently: FixtureSmartContracts,
) -> Optional[UserDepositAddress]:
""" Deploy UserDeposit and fund accounts with some balances """
services_smart_contracts = deploy_smart_contract_bundle_concurrently.services_s... | 496f27fd9576191e91ac90c6e17c2b07fae629ab | 8,508 |
def vonNeumann(t, rho, H):
"""(quantum Liouville-)von Neumann equation"""
H = H(t)
rho = rho.reshape(H.shape)
rho_dot = -1j*(np.dot(H, rho) - np.dot(rho, H))
return rho_dot.flatten() | e00f9cdadacf36ba40240018d4b1dac1a7ebbba3 | 8,509 |
def nicer_array(a, mm_cutoff=0.3):
"""
Returns a scaled array, the scaling, and a unit prefix
Example:
nicer_array( np.array([2e-10, 3e-10]) )
Returns:
(array([200., 300.]), 1e-12, 'p')
"""
if np.isscalar(a):
x = a
elif len(a) == 1:
x = a[0... | e5abe6b45a4c80d8eb84d9f9f5aed1b11f19684e | 8,511 |
import uuid
import pickle
def build_playground():
"""
build a playground based on user's input building and algorithm type
input: userid, algorithm, target building
output: none
"""
userid, building, algo_type = request.form['userid'], request.form['building'], request.form['algo_type']
us... | 31b73b3c505d27dca07569dc95c31d78822da452 | 8,512 |
def menuItemDirective(_context, menu, for_,
action, title, description=u'', icon=None, filter=None,
permission=None, layer=IDefaultBrowserLayer, extra=None,
order=0, item_class=None):
"""Register a single menu item."""
return menuItemsDirective(_... | 9ca19bd71cef30db9f8cd2a1154154965cf31b7d | 8,513 |
def getQueueStatistics ():
"""
Returns a 4-tuple containing the numbers of identifiers in the
Crossref queue by status: (awaiting submission, submitted,
registered with warning, registration failed).
"""
q = ezidapp.models.CrossrefQueue.objects.values("status").\
annotate(django.db.models.Count("status"... | 2693365e24dc28b57ddbc8db5315779acee2d617 | 8,514 |
from typing import List
from typing import Union
def create_compressed_generator(
original_generator: CompressorArg,
compressed_cse_list: List[List[Union[List[uint64], List[Union[bytes, None, Program]]]]],
) -> BlockGenerator:
"""
Bind the generator block program template to a particular reference blo... | c2eb437caefa53452df61e1f5b4115ab4220a323 | 8,516 |
def run_mcmc(meas, x, nsamples, covm=None, scales=None):
"""
Sample the likelihood space with a Markov Chain Monte Carlo.
:param meas: TemplateMeasurement
measurement whose spectrum likelihood space is to be probe
:param x: [float]
parameter values where to start the chain
:param co... | 79f7806d3c5c84693dfbfcd6d4236734ec7921de | 8,517 |
def get_vlan_list(dut, cli_type="click"):
"""
Get list of VLANs
Author : Prudvi Mangadu (prudvi.mangadu@broadcom.com)
:param dut:
:param cli_type:
:return:
"""
st.log("show vlan to get vlan list")
rv = show_vlan_config(dut, cli_type=cli_type)
vlan_list = list(set([eac['vid'] for... | 5ce768bc8a30fa73fb2f4930384197535584de64 | 8,518 |
def begin_organization_creation_task(registered_id):
"""
Asynchronously create our tenant schema. Email owner when process completes.
"""
# Run the sub-routine for taking the OrganizationRegistration object
# creating our Tenant from it.
call_command('populate_organization', str(registered_id)) ... | fcaccc4e44def7a0d5ce83ac179899d0b288ac9c | 8,519 |
import itertools
def rewrite_blockwise(inputs):
"""Rewrite a stack of Blockwise expressions into a single blockwise expression
Given a set of Blockwise layers, combine them into a single layer. The provided
layers are expected to fit well together. That job is handled by
``optimize_blockwise``
... | dc80aa6c55d3ac6fafe780e5c58f3961d5d92b66 | 8,520 |
def sort_drugs(processed_data, alpha_sort, **kwargs):
"""
Sorts all drug names, as primary keys of processed data dictionary. Sorting
is governed by primary criteria of decreasing cost, then secondary criteria
of alphabetical order. Secondary criteria ignores unsafe characters if
"alpha_sort" is Tru... | aa3727dc52f0204c7c39807982a998cc03fabd2d | 8,521 |
def log_k2ex_and_get_msg(ex, prefix, topology):
""" LOG K2 exception and extracted message. Return NLS message """
LOG.exception(ex)
detail = {}
k2msg = _("None")
if isinstance(ex, K2Error) and ex.k2response:
detail['Request_headers'] = ex.k2response.reqheaders
detail['Response_heade... | a1a827ac38980e593e58236ce8d60eb01b957050 | 8,522 |
def fetch_ticket(identifier):
"""Return data of ticket with given identifier as pandas dataframe."""
try:
return pd.read_csv(f'./data/tickets/{identifier}.csv')
except:
return None | 46d776eab0e7867dd14079147a6101c9b8fddfa5 | 8,523 |
import torch
def dice_loss(logits, targets, smooth=1.0):
"""
logits: (torch.float32) shape (N, C, H, W)
targets: (torch.float32) shape (N, H, W), value {0,1,...,C-1}
"""
outputs = F.softmax(logits, dim=1)
targets = torch.unsqueeze(targets, dim=1)
targets = torch.zeros_like(logits).scatter_(dim=1, index=target... | 4ac40e87fe048dbc3232bb82c7fa16d9c03a8439 | 8,524 |
import math
def make_axis_angle_matrix(axis, angle):
"""construct a matrix that rotates around axis by angle (in radians)"""
#[RMS] ported from WildMagic4
fCos = math.cos(angle)
fSin = math.sin(angle)
fX2 = axis[0]*axis[0]
fY2 = axis[1]*axis[1]
fZ2 = axis[2]*axis[2]
fXYM = axis[0]*axis... | 1bef075e63b26559184025a69f47d8c1b6dccf1d | 8,527 |
def get_agent_type_from_project_type():
""" use project type to determine agent type """
if 'METRIC' in if_config_vars['project_type']:
if if_config_vars['is_replay']:
return 'MetricFileReplay'
else:
return 'CUSTOM'
elif if_config_vars['is_replay']:
return 'Lo... | a2ea351fcba68dde4db2b9200636c937a58ab960 | 8,528 |
import traceback
def close_server(is_rebooting = False):
"""
Close the Unity server and tell clients to react appropriately.
Set `is_rebooting` to handle cases like domain reload when Unity is expected to come back shortly.
Returns True if the server was closed by this call, False if it was already ... | 77fbd9ecd8ed7489d4f5763c5bb417c7cb5ddb15 | 8,529 |
import types
def dict_decode(node_dict: dict) -> Node:
"""Convert a dictionary to an `Entity` node (if it has a `type` item)."""
if "type" not in node_dict:
return node_dict
node_type = node_dict.pop("type")
class_ = getattr(types, node_type, None)
if class_ is None:
return node_... | 00b790e431cdf080c0a6220c2913fd511983904d | 8,530 |
from datetime import datetime
def compute_purges(snapshots, pattern, now):
"""Return the list of snapshots to purge,
given a list of snapshots, a purge pattern and a now time
"""
snapshots = sorted(snapshots)
pattern = sorted(pattern, reverse=True)
purge_list = []
max_age = pattern[0]
... | 710a65ef7068d57470fb72ff171a1f1eb3480d65 | 8,531 |
import logging
def design_partial_factorial(k: int, res: int) -> DataFrame:
"""
design_partial_factorial
This function helps design 2 level partial factorial experiments. These experiments are often
described using the syntax l**(k-p) where l represents the level of each factor, k represents
the ... | a9c93cf696c33f0eb74cb092d1f340d5732dc994 | 8,532 |
def get_trending_queries(filename):
"""Extract trends from a file."""
f = open(filename, 'r')
trend_tuples_list = []
for line in f:
trend_tuples_list.append(tuple((line.strip()).split(',')))
f.close()
return trend_tuples_list | 6f5828d4bf0092c0a43804ca7ffb9ee4aa67e607 | 8,534 |
def get_bio(x, lang='en'):
"""Get the one-sentence introduction"""
bio = x.loc[16][lang]
return bio | 8c9ddabd2e6ada790af2b85a3fb656291f3ee5bd | 8,535 |
import io
def create_tf_example(filename, source_id, encoded_jpeg, annotations, resize=True):
"""
This function creates a tf.train.Example in object detection api format from a Waymo data frame.
args:
- filename [str]: name of the original tfrecord file
- source_id [str]: original image s... | b757fc1e4d51fac5722eb170357ea36388d40d5d | 8,536 |
import re
def format_oids(oids_parameters):
"""
Format dictionary OIDs to ``cryptography.x509.oid.NameOID`` object list
:param oids_parameters: CA Object Identifiers (OIDs).
The are typically seen in X.509 names.
Allowed keys/values:
``'country_name': str (two letters)``,
... | 08641ffb1c431c13e23f2b9498ce1cb1a896f955 | 8,537 |
def Phases(*args):
"""Number of phases"""
# Getter
if len(args) == 0:
return lib.Generators_Get_Phases()
# Setter
Value, = args
lib.Generators_Set_Phases(Value) | d1610c5b2ab19cf2b3018850fe685bb9fcbc11ad | 8,538 |
import requests
def create_channel(logger: Logger,
connection: komand.connection,
team_id: str,
channel_name: str,
description: str) -> bool:
"""
Creates a channel for a given team
:param logger: (logging.logger)
:param conne... | 6cdd37a7fdc131433f9f75ba10e523bc719a34aa | 8,539 |
def activate_user(username):
"""Activate a user account."""
user = annotator.credentials.find_one({'username': username})
if not user['active']:
annotator.credentials.update_one(user, {'$set': {'active': True}})
flash("User {0} activated successfully".format(username), 'success')
else:
... | 58b70edc4a098a7409e1c2e62f9710b3da3c95af | 8,541 |
def query_all():
"""Queries all matches in Elasticsearch, to be used further for suggesting
product names when a user is not aware of them.
"""
query_all = {
"query": {"match_all": {}},
}
return query_all | 9d15297cf82d813ff0a0688f5c25e2ca6fa145d3 | 8,542 |
def _mesh_homogeneous_cell(cell_vect, mesh_path):
"""Generate a simple mesh for a homogeneous cell.
cell_vect: np.array 2x2 colonnes = vecteurs periodicité
"""
name = mesh_path.stem
geometry.init_geo_tools()
geometry.set_gmsh_option("Mesh.MshFileVersion", 4.1)
# Mesh.Algorithm = 6; Frontal... | 98c63d7764bcca7baad81de1fe7c3fac16ff6ffd | 8,543 |
from typing import Dict
from typing import Union
from typing import Optional
from typing import List
from typing import Tuple
from typing import cast
from typing import Any
import json
def fetch_incidents(client: Client, max_incidents: int,
last_run: Dict[str, Union[Optional[int], Optional[str]]],... | e273d69611331c9f2eb5b2c0c9c27e805c9d7e4f | 8,545 |
import collections
def extractWordFeatures(x):
"""
Extract word features for a string x. Words are delimited by
whitespace characters only.
@param string x:
@return dict: feature vector representation of x.
Example: "I am what I am" --> {'I': 2, 'am': 2, 'what': 1}
"""
# BEGIN_YOUR_CO... | dd5247dbf7ef69043b200acbefec996107de00f7 | 8,546 |
def delete_user(user_id):
"""
Delete user specified in user ID
Note: Always return the appropriate response for the action requested.
"""
user = mongo_mgr.db.user.find_one({'_id': user_id})
if user:
user.deleteOne({'_id': user_id})
result = {'id': user_id}
else:
resul... | b3244aeafcddd6c5be1d209c89ef7ed7969da989 | 8,547 |
from operator import and_
import logging
def query_attention_one(**kwargs):
"""
查询当前用户是否关注指定的物件
:param kwargs: {'user_id': user_id, 'object_id': object_id}
:return: 0 or 1
"""
session = None
try:
session = get_session()
results = session.query(func.count('*')).filter(and_(A... | 44db7006eec38c2524fe5a74dba46086c63c79c5 | 8,548 |
def _dict_empty_map_helper(values, empty, delim, av_separator, v_delimiter,
parser):
"""
A helper to consolidate logic between singleton and non-singleton mapping.
Args:
values: The value to parse.
empty: The empty representation for this value in CoNLL-U format.
... | cb5550eb606beb47f31236b827e78f2a7fc4ba40 | 8,549 |
def get_restricted_area(path1, path2, restricted_pos1, restricted_pos2, time_step):
"""Computes the restricted area and the start- and end-time steps for both agents.
* start time-step: The first time step where an agent occupies a position within the restricted
area.
* end time-step... | 39104a44e8d5354799e45feb1ba6371f3423fecc | 8,551 |
def FR_highpass(freq: np.ndarray, hp_freq: float,
trans_width: float) -> np.ndarray:
"""Frequency responce for highpass filter
Parameters
----------
``freq``: np.ndarray
frequency array
``hp_freq``: float
highpass frequency
``trans_width``: float
widt... | a57058a3fdf257ee68efe0c99d668e4f5b4fbf60 | 8,553 |
def _rexec(params):
"""Start a subprocess shell to execute the specified command and return its output.
params - a one element list ["/bin/cat /etc/hosts"]
"""
# check that params is a list
if not isinstance(params, list) or len(params) == 0:
return "Parameter must be a not empty list"
command = p... | e8338dc94b177f5d39d5307a88da7aa040a3a7e1 | 8,554 |
def _get_compose_template(manifest):
"""
Build the service entry for each one of the functions in the given context.
Each docker-compose entry will depend on the same image and it's just a static
definition that gets built from a template. The template is in the artifacts
folder.
"""
artifac... | 659e28f97c76a386a20c85fadaa3d0bbd6d88a90 | 8,555 |
def _ParsePackageNode(package_node):
"""Parses a <package> node from the dexdump xml output.
Returns:
A dict in the format:
{
'classes': {
<class_1>: {
'methods': [<method_1>, <method_2>]
},
<class_2>: {
'methods': [<method_1>, <method_2>]
... | 89eefebb82848acad23a9703b87177f626fbbdf5 | 8,556 |
def greet(lang):
"""This function is for printing a greeting in some
selected languages: Spanish, Swedish, and German"""
if lang == 'es':
return 'Hola'
elif lang == 'ge':
return 'Hallo'
elif lang == 'sv':
return 'Halla'
else:
return 'Hello' | dcbe0fb39e735666b36780ee8d06b457e0a9541e | 8,557 |
def add_hook(
show_original=False,
show_transformed=False,
predictable_names=False,
verbose_finder=False,
):
"""Creates and adds the import hook in sys.meta_path"""
callback_params = {
"show_original": show_original,
"show_transformed": show_transformed,
"predictable_name... | efda58094ab2bb218dca8babcdbf0a74b97e0cd8 | 8,558 |
def correlate_two_dicts(xdict, ydict, subset_keys=None):
"""Find values with the same key in both dictionary and return two arrays of corresponding values"""
x, y, _ = correlate_two_dicts_verbose(xdict, ydict, subset_keys)
return x, y | 93287a57c7bf4e8cb03384531ffbca9c6d6e7cfc | 8,559 |
def find_gateways(unicast_gateway, session, apic) -> tuple:
"""Search for ACI Gateways and get configurations"""
get_gateway = get_subnets(session, apic)
aps = []
epgs = []
l3Outs = []
gateways = []
location, bridge_domain, uni_route, scope, unkwn_uni, tenant, bd_vrf, iplearn = None, "Doe... | 7c2f841e9fd3822c03f8b4ea38581bcaba1b60d2 | 8,560 |
import torch
def hamming_dist(y_true, y_pred):
"""
Calculate the Hamming distance between a given predicted label and the
true label. Assumes inputs are torch Variables!
Args:
y_true (autograd.Variable): The true label
y_pred (autograd.Variable): The predicted label
Returns:
... | 0edda102820626b824861ac0f05d4d77f5def432 | 8,561 |
from typing import Tuple
def tuple_action_to_int(
action: Tuple[int, int], slot_based: bool, end_trial_action: bool
) -> int:
"""Converts tuple action to integer."""
stone, potion = action
num_special_actions = 2 if end_trial_action else 1
if stone < 0:
return stone + num_special_actions
if slot_bas... | d1f616706910822670b0d14d6a19f3f9dbddf145 | 8,563 |
def warpImage(imIn, pointsIn, pointsOut, delaunayTri):
"""
变换图像
参数:
===========
imIn:输出图像
pointsIn:输入点
pointsOut:输出点:
delaunayTri:三角形
返回值:
============
imgOut:变形之后的图像
"""
pass
h, w, ch = imIn.shape
imOut = np.zeros(imIn.shape, dtype=imIn.dtype)
for j in ... | f672cf4e6cad968c6f42747f128b436e9b00c466 | 8,565 |
import re
def rmchars(value):
"""Remove special characters from alphanumeric values except for period (.)
and negative (-) characters.
:param value: Alphanumeric value
:type value: string
:returns: Alphanumeric value stripped of any special characters
:rtype: string
>>> import utils
... | 63428103f7da4184c6d9f33a9d05b02ce17f2448 | 8,566 |
def ema(x):
"""
[Definition] 以period为周期的指数加权移动平均线
[Category] 技术指标
"""
return 'ema(%s,%s)' %(x, pe.gen_param('ema', 'period')) | d5490340520f57c9083ae82d6fd1cadd2fc92208 | 8,567 |
from typing import Set
def tokenized(phrase: str) -> Set[str]:
"""Split a phrase into tokens and remove stopwords."""
return set(normalize(phrase).split()) - STOPWORDS | 3a01f5ea316de0f5b27506d1ff7f2358273616a2 | 8,568 |
async def server_error(request, exc):
"""
Return an HTTP 500 page.
"""
template = '500.html'
context = {'request': request}
return templates.TemplateResponse(template, context, status_code=500) | a11be57885b0f0f9107b190bafdebc6f13908f84 | 8,570 |
def return_post():
""""
Returns the post-processing plugins.
:param: None
:return: POST_PROCESSING_PLUGINS
"""
return POST_PROCESSING_PLUGINS | 9c7469f8ec336217abdfdb46db8a0c511789a4bf | 8,571 |
import base64
def numpy_to_b64str(img):
"""
Converts a numpy array into a base 64 string
Args:
img (np.array):
Returns:
str: base 64 representation of the numpy array/image.
"""
img = img[..., ::-1] # flip for cv conversion
_, img = cv2.imencode('.jpg', img) # strips he... | a6af378a26dd3adac08568f49a5d8d74954feddc | 8,573 |
def lennard_jones(r, epsilon, sigma, index=(12, 6)):
"""
General pair potential resembling a Lennard Jones model. Default indexes
values are for a typical LJ potential, also called 12-6 potential.
Parameters
----------
r : float or np.ndarray
Distance between interacting particles. It c... | c16856d1960f1b2542305e4048d8e9fe5e866210 | 8,574 |
def get_unique_name(x, mult=0, extra=''):
"""
Returns a unique key composed of inchikey and multiplicity
>>> mol = get_mol('[O][O]')
>>> get_unique_name(mol)
'MYMOFIZGZYHOMD-UHFFFAOYSA-N3'
"""
mol = get_mol(x, make3D=True)
if mult == 0:
mult = mol.spin
return mol.write("inchi... | a9a58078fb2af1c0542dcf77f522154dd2c3a374 | 8,575 |
def get_individual_user(user_id: int) -> JSONResponse:
"""
Lists all information belonging to one user.
:param user_id: the id of the user
:return: status code and response data
"""
user = _get_db()["users"].find_one({"user_id": user_id})
return JSONResponse(status_code=status.HTTP_200_OK, c... | dfa8d5cdfa8dd8363c550c79d18924a0b5a5764b | 8,576 |
from typing import Union
from typing import List
from typing import Optional
from typing import Tuple
def portfolio_averages(
df: pd.DataFrame,
groupvar: str,
avgvars: Union[str, List[str]],
ngroups: int = 10,
byvars: Optional[Union[str, List[str]]] = None,
cutdf: pd.DataFrame = None,
wtva... | 23c902aafd341a7bbd8e6fc8b005e3cdb5a10f82 | 8,577 |
def get_zero_crossing_rate(y, get_mean=True):
"""
Compute the Zero Crossing Rate (ZCR)
:param y: np.ndarray [shape=(n,)]
Sampling rate of y
:param get_mean: bool
Whether to instead return the mean of ZCR over all frames
:return: np.ndarray [shape=(1,t)] or float
ZCR for each frame, or th... | 782cd302acc69065d26837e45fb882714fa6b927 | 8,579 |
import math
def UF9(x):
"""
adapted from
https://github.com/Project-Platypus/Platypus/blob/master/platypus/problems.py
"""
nvars = len(x)
count1 = 0
count2 = 0
count3 = 0
sum1 = 0.0
sum2 = 0.0
sum3 = 0.0
E = 0.1
for j in range(3, nvars+1):
yj = x[j-1]... | 577b36653517e09cef764528920773ea51c5ed60 | 8,581 |
def antiderivate(values, ax_val, index, Nper, is_aper, is_phys, is_freqs):
"""Returns the anti-derivate of values along given axis
values is assumed to be periodic and axis is assumed to be a linspace
Parameters
----------
values: ndarray
array to derivate
ax_val: ndarray
axis v... | 9280187e907e16f1b2b00a1e86acd43538adcbe4 | 8,583 |
def renumber_labels(label_img):
""" Re-number nuclei in a labeled image so the nuclei numbers are unique and consecutive.
"""
new_label = 0
for old_label in np.unique(label_img):
if not old_label == new_label:
label_img[label_img == old_label] = new_label
new_label += 1
... | 4a37f151ba5a4e3066ce3656903b587f38deafea | 8,584 |
def __virtual__():
"""
Return virtual name of the module.
:return: The virtual name of the module.
"""
return __virtualname__ | 3f1a19fab2561ae1fb464d76a13e7a0b75af5c93 | 8,587 |
def getsamplev3(qcode):
"""Get a sample object of a given identifier
in API V3 style
Returns: A sample (v3) object
"""
scrit = SampleSearchCriteria()
scrit.withCode().thatEquals(qcode)
fetch_opt = SampleFetchOptions()
fetch_opt.withProperties()
fetch_opt.withSpace()
result = a... | 513de42ffd13f6b9abe74753e568e8db2fa473e3 | 8,588 |
def k892_distribution(mass):
"""Calculate normalized relativistic Breit-Wigner distribution value for K(892) at given mass"""
if k892_distribution.norm is None:
k892_distribution.norm = _norm(_k892_distribution_unnormalized)
return _k892_distribution_unnormalized(mass) / k892_distribution.norm | 38175808a7f9acf178604bf64935f0beeb3f7631 | 8,589 |
def ProcessMoleculesUsingSingleProcess(Mols, PAINSPatternMols, Writer, WriterFiltered):
"""Process and filter molecules using a single process."""
NegateMatch = OptionsInfo["NegateMatch"]
OutfileFilteredMode = OptionsInfo["OutfileFilteredMode"]
Compute2DCoords = OptionsInfo["OutfileParams"]["Comput... | fe81953ce311724005c27ea309aa238578c4fd1c | 8,590 |
def UDiv(a: BitVec, b: BitVec) -> BitVec:
"""Create an unsigned division expression.
:param a:
:param b:
:return:
"""
return _arithmetic_helper(a, b, z3.UDiv) | fb3e300a96afdbf17fa7e6fff02379790b2dfd02 | 8,591 |
def _pressure_level_widths(tro3_cube, ps_cube, top_limit=0.0):
"""Create a cube with pressure level widths.
This is done by taking a 2D surface pressure field as lower bound.
Parameters
----------
tro3_cube : iris.cube.Cube
`Cube` containing `mole_fraction_of_ozone_in_air`.
... | 53dd14f6e0b1fda249ecd10d0ad30cfb4e076d5a | 8,592 |
def load_model_configurations(sender):
"""
Iterates through setting MODELS_CRUD_EVENT searching for the sender
model configurations.
:param sender: Django Model
:return dict
"""
for model_config in settings.MODELS_CRUD_EVENT:
model = model_config['model']
app, model = model.r... | e32d441de47f9bb1a78f93854e1c0436819c148b | 8,593 |
from typing import Optional
def get_user_by_private_or_public_nickname(nickname: str) -> Optional[User]:
"""
Gets the user by his (public) nickname, based on the option, whether his nickname is public or not
:param nickname: Nickname of the user
:return: Current user or None
"""
user: User = ... | 1dc43337c8e1372a32ed471ef8285544107cd22b | 8,594 |
def expose(window, context, name, monitor):
"""REST HTTP/HTTPS API to view tuples from a window on a stream.
Embeds a Jetty web server to provide HTTP REST access to the collection of tuples in `window` at the time of the last eviction for tumbling windows, or last trigger for sliding windows.
Example wit... | ca3cf81c91ee89210da6989fdecce727d44273a1 | 8,595 |
import re
def get_order_args():
"""
Get order arguments, return a dictionary
{ <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) }
Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
"""
orders = {}
for arg in request.args:
re_match = re.findall... | a5e57f95479e15c8167434ff34c51cc80fc43f45 | 8,596 |
def version_info(): # pragma: no cover
"""
Get version of nameko_kafka package as tuple
"""
return tuple(map(int, __version__.split('.'))) | 8fe39c50a43e40a589abb51f56e2c7c503026712 | 8,597 |
def StrokePathCommandAddCapType(builder, capType):
"""This method is deprecated. Please switch to AddCapType."""
return AddCapType(builder, capType) | 4e7f852cde4993994ab5f7cf3e1b57700eaff7d3 | 8,598 |
def process_images(dummy_request):
"""Downloads and processes all images uploaded before resize logic fix deployment"""
global n_global_resized
media_bucket = storage_client.bucket(MEDIA_BUCKET)
process_global_images(db_pool, media_bucket)
process_user_images(db_pool, media_bucket)
retur... | ea3734ce797305f7305880b02d2696c3ca8a21c7 | 8,599 |
def _filename_pattern(ext):
"""Returns an re matching native or tfrecord files of format `ext`."""
return r".*\.{}(\.tfrecord)?(\.gz)?".format(ext) | 6ec5a86dbba2432293451ca7dff0a0d1d5091bf0 | 8,600 |
def assemble_remote_url():
"""
组装目标服务器URL, 即生成 parse.remote_url 的值
:rtype: str
"""
if parse.is_external_domain:
# 请求的是外部域名 (external domains)
scheme = 'https://' if parse.is_https else 'http://'
return urljoin(scheme + parse.remote_domain, parse.remote_path_query)
else:
... | f0e14ddb42636f12f4fafa31af4a87b3f91a4e05 | 8,601 |
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(drawbot.views.blueprint)
app.register_blueprint(user.views.blueprint)
return None | 936c17a95ddc013ec9f0c6c232a689245fc313d0 | 8,602 |
def write_attribute(xml_elem, elem: str=None, attrib: str=None, txt: str=None):
""" Write new text to a xml attribute.
Elem can be used to refer to a subelement of the current xml_elem
Args:
xml_elem: The current xml element
elem (str): The requested element tag name
attrib (str): ... | d2ee296b6926a71ef2ffaf9fd9d47128f66e8806 | 8,603 |
def _ndarray_feature(x: np.ndarray) -> tf.train.Feature:
"""Create an ndarray feature stored as bytes."""
x_bytes = x.tostring()
feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[x_bytes]))
return feature | 03ad22f7d943d24574c92a494c915c28611a8d12 | 8,604 |
import re
def get_img_compliance_level(profile):
""" Try to figure out the IIIF Image API compliance level given the
`profile` value from a info.json.
"""
patt_iiif = re.compile('level([0-2])\.json$')
patt_stan = re.compile('#level([0-2])$')
def get_from_str(s):
m = None
... | 7970a795ea1b79bfea3df0e5a306e2d0286a61de | 8,605 |
def _extract_protocol_layers(deserialized_data):
"""
Removes unnecessary values from packets dictionaries.
:param deserialized_data: Deserialized data from tshark.
:return: List of filtered packets in dictionary format.
"""
packets_filtered = []
for packet in deserialized_data:
packe... | 3c3a899909c5278b29ffb402ccb4d8dde24fce3a | 8,606 |
from typing import Optional
from operator import gt
def calculate_affinity(
adata: AnnData,
level: int = 1,
block_key: Optional[str] = 'nsbm',
group_by: Optional[str] = None,
state: Optional = None,
neighbors_key: Optional[str] = 'neighbors',
adjacency: Optional[sparse.spmatrix] = None,
... | e2eec0e9f45199d6cc1559d71dfbf629dba61621 | 8,607 |
def numpy_dtypes_for_minmax(request):
"""
Fixture of numpy dtypes with min and max values used for testing
cummin and cummax
"""
dtype = request.param
min_val = (
np.iinfo(dtype).min if np.dtype(dtype).kind == "i" else np.finfo(dtype).min
)
max_val = (
np.iinfo(dtype).max... | d2ad3676549f427c134b38106a93145c54114052 | 8,609 |
def solve(topics):
"""Solve."""
a_words, b_words = get_dicts(topics)
candidates = []
original = []
duplicates = []
for a, b in topics:
# print(a, b)
# print(a_words[a], b_words[b])
if not (a_words[a] == 1 or b_words[b] == 1):
candidates.append((a, b))
... | bb78da10ff6bb939bc0de9e0cc51a036c2a0e8b9 | 8,610 |
def get_package_plugin(package_type):
"""
Get a plugin for a specific package
Parameters
----------
package_type: str
The package type to fetch
Returns
-------
InvirtualEnvPlugin:
The invirtualenv plugin for the specific package_type
"""
for plugin in installed_... | a1d97a6d1c4248f7a1bfeade8e734bcc0af3aceb | 8,611 |
def validate_basic_message(msg):
"""Validate basic messages.
This example just uses basic assertions but you could easily use a schema
library to get more sophisticated validators.
"""
assert msg.type == TYPE
assert "~l10n" in msg
assert "sent_time" in msg
assert "content" in msg
re... | df6b1541adf86a295e6592f26d72ab2109617f6b | 8,613 |
def _filter_event_queryset(queryset, params, srs=None):
"""
Filter events queryset by params
(e.g. self.request.query_params in EventViewSet)
"""
# Filter by string (case insensitive). This searches from all fields
# which are marked translatable in translation.py
val = params.get('text', No... | 35103268d301239d4c884d50ab5321ebb22ed235 | 8,614 |
import re
def process_user(enrollment, section):
"""Handle getting assignments for a single user
Args:
enrollment (canvasapi.enrollment.Enrollment): Canvas <Enrollment> object
section (canvasapi.section.Section): Canvas <Section> object
Returns:
[list]: formatted list for writing... | 88b471433d99c659eabac82a797530def3baf8f2 | 8,615 |
def op(name,
data,
bucket_count=None,
display_name=None,
description=None,
collections=None):
"""Create a histogram summary op.
Arguments:
name: A unique name for the generated summary node.
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_count: O... | 368b5f0af59352e5f283566d9008c413d38692c9 | 8,616 |
def read_as_str(file):
"""
读取文件,并返回读取到的内容
"""
try:
with open(file, 'r') as f:
return f.read()
except IOError:
return "" | 934bec1e47e0f9af09be7f4d695a8ddf09004f3f | 8,617 |
def has_xml_header(filepath):
"""
Return True if the first line of the file is <?xml
:param filepath:
:return:
"""
return True | 21fdbdf36cf08ca18d8a0f0d7f7d2201b243c558 | 8,618 |
def shikaku(givens):
"""Solver for Shikaku minipuzzles."""
sym = grilops.make_number_range_symbol_set(0, SIZE * SIZE - 1)
sg = grilops.SymbolGrid(LATTICE, sym)
rc = grilops.regions.RegionConstrainer(
LATTICE,
solver=sg.solver,
rectangular=True
)
shifter = Shifter(sg.solver)
for p in LAT... | e380ce634b342a19ecd466576e8e5d3ff28ccc25 | 8,619 |
def invert_qgniw(qh,phi,phih,k,l,f0):
""" Calculate the streamfunction given the potential vorticity.
The algorithm is:
1) Calculate wave potential vorticity
2) Invert for wave, pw, and vortex stremfunctions, pv.
3) Calculate the geostrophic stremfunction... | b90c5f76c2be93d0a45b8c260e7a7228094ff4c0 | 8,621 |
def package_ref_key(package_name, ref):
"""Returns ndb.Key corresponding to particular PackageRef."""
assert is_valid_package_ref(ref), ref
return ndb.Key(PackageRef, ref, parent=package_key(package_name)) | 270b69baa1309bf29a054736ca6f898f23839ee3 | 8,622 |
def conv2d_backprop_input(dout, x_size, weight, stride=1, pad=0):
"""Backpropagation input for conv2d."""
filter_num, _, filter_h, filter_w = weight.shape
dout = dout.transpose(0, 2, 3, 1).reshape(-1, filter_num)
col_w = weight.reshape(filter_num, -1).T
dcol = np.dot(dout, col_w.T)
dx = col2im(d... | 3749398101de25ec4f7b83c8a52754d18d0e8872 | 8,623 |
def fine_license_ratio(license_data, fine_data, column_name1=None, column_name2=None,year=None):
"""Get ratio of fines to licenses issued in a given year
Parameters:
-----------
license_data: DataFrame
Any subset of the Professional and Occupational Licensing dataframe
fine_data: DataFrame
Any subset of... | 97dad8c4f5c78b1291016e1cd9fa9c5f8ef20beb | 8,625 |
def import_obj(obj_path, hard=False):
"""
import_obj imports an object by uri, example::
>>> import_obj("module:main")
<function main at x>
:param obj_path: a string represents the object uri.
:param hard: a boolean value indicates whether to raise an exception on
impor... | fe6bc0cd8fff5c0d5b1ba9fc0e153b2004b09755 | 8,626 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.