content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_default_accept_image_formats():
"""With default bentoML config, this returns:
['.jpg', '.png', '.jpeg', '.tiff', '.webp', '.bmp']
"""
return [
extension.strip()
for extension in config("apiserver")
.get("default_image_handler_accept_file_extensions")
.split(",... | 9f2e8514ed1dcc4d533be0e3f2e501a9a9784abb | 3,654,860 |
import copy
def cells_handler(results, cl):
"""
Changes result cell attributes based on object instance and field name
"""
suit_cell_attributes = getattr(cl.model_admin, 'suit_cell_attributes', None)
if not suit_cell_attributes:
return results
class_pattern = 'class="'
td_pattern ... | c49bdb89597e191d0c6b65df1b58a80ac6bd5f9e | 3,654,862 |
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:lastdot]... | f6418ff17f3d480b22abac1146d946a5f990cb3c | 3,654,863 |
from typing import Union
from typing import List
def _split_on_parenthesis(text_in: Union[str, list[str]]) -> List[str]:
"""Splits text up into a list of strings based on parenthesis locations."""
if isinstance(text_in, list):
if None in text_in:
return text_in
text_list = text_in
... | 7c7994590838c0293869786841eb7f97c60b16e8 | 3,654,864 |
import requests
def getExternalIP():
""" Returns external ip of system """
ip = requests.get("http://ipv4.myexternalip.com/raw").text.strip()
if ip == None or ip == "":
ip = requests.get("http://ipv4.icanhazip.com").text.strip()
return ip | 77847063a2da7c6484dd6e569786a012b3a0a62f | 3,654,866 |
def intersection_indices(a, b):
"""
:param list a, b: two lists of variables from different factors.
returns a tuple of
(indices in a of the variables that are in both a and b,
indices of those same variables within the list b)
For example, intersection_indices([1,2,5,4,6],[3,5,1,2... | 55264faaa4fd5e6dc5365b675ebd3b7f6a1e1280 | 3,654,867 |
def test_extract_requested_slot_from_entity_with_intent():
"""Test extraction of a slot value from entity with the different name
and certain intent
"""
# noinspection PyAbstractClass
class CustomFormAction(FormAction):
def slot_mappings(self):
return {"some_slot": self.from_... | 0b457700781183f275a8512e16bac53aa058d762 | 3,654,868 |
def graph_cases(selenium, host):
"""
Factory method that allows to draw preconfigured graphs and manipulate them
with a series of helpful methods.
:type selenium: selenium.webdriver.remote.webdriver.WebDriver
:type host: qmxgraph.server.Host
:rtype: GraphCaseFactory
:return: Factory able to... | 2df048d35a337e8d335844b7a1bb98db77816e5d | 3,654,869 |
def figure_8():
"""
Notes
-----
Colors from Bang Wong's color-blind friendly colormap. Available at:
https://www.nature.com/articles/nmeth.1618
Wong's map acquired from David Nichols page. Available at:
https://davidmathlogic.com/colorblind/.
"""
# choosing test sample and network... | 2a72f24673b96b577fc4f4a23a1869740e90c3ec | 3,654,870 |
import re
def check_threats(message):
"""Return list of threats found in message"""
threats = []
for threat_check in get_threat_checks():
for expression in threat_check["expressions"]:
if re.search(expression, message, re.I | re.U):
del threat_check["expressions"]
... | 091d370e4a2e6cbdf674d6dde73bf616b994498b | 3,654,871 |
def data_processing_max(data, column):
"""Compute the max of a column."""
return costly_compute_cached(data, column).max() | 299075ea3e1953abe0ffbd71afb42525c6270c49 | 3,654,872 |
from typing import Sequence
def type_of_target(y):
"""Determine the type of data indicated by the target.
Note that this type is the most specific type that can be inferred.
For example:
* ``binary`` is more specific but compatible with ``multiclass``.
* ``multiclass`` of integers is mor... | 2c721ab04cdba3209794a21b2b25fe10485be106 | 3,654,873 |
from typing import List
def extract_data_from_csv_stream(client: Client, alert_id: str,
attachment_id: str, delimiter: bytes = b'\r\n') -> List[dict]:
"""
Call the attachment download API and parse required fields.
Args:
client (Client): Cyberint API client.
... | 992679004ae94da2731b04eaf41918a755d8306a | 3,654,874 |
import re
def validate_password(password, password_repeat=None):
"""
Validate user password.
:param password: password as string
:param password_repeat: repeat password
:return: False - valid password
"""
if password_repeat:
if password != password_repeat:
return "Passw... | 2987a1bec151e173156ab6a72345864c84dcb61c | 3,654,875 |
def get_large_circuit(backend: IBMBackend) -> QuantumCircuit:
"""Return a slightly larger circuit that would run a bit longer.
Args:
backend: Backend on which the circuit will run.
Returns:
A larger circuit.
"""
n_qubits = min(backend.configuration().n_qubits, 20)
circuit = Qua... | a35a9ee67d6268911f49936095a703b4fd227a56 | 3,654,876 |
import torch
def top_k(loc_pred, loc_true, topk):
"""
count the hit numbers of loc_true in topK of loc_pred, used to calculate Precision, Recall and F1-score,
calculate the reciprocal rank, used to calcualte MRR,
calculate the sum of DCG@K of the batch, used to calculate NDCG
Args:
loc_pr... | 8796312e1fa4d43fb992c0dd7903070a9e061e1b | 3,654,878 |
def enviar_contacto(request):
"""
Enviar email con el formulario de contacto
a soporte tecnico
"""
formulario = ContactoForm()
if request.method == 'POST':
formulario = ContactoForm(request.POST)
if formulario.is_valid():
mail = EmailMessage(subject='HPC Contacto',
... | 2f17e0cd0fbd5c5df345484c5fe08a420272785a | 3,654,879 |
def dict_depth(d):
"""
递归地获取一个dict的深度
d = {'a':1, 'b': {'c':{}}} --> depth(d) == 3
"""
if isinstance(d, dict):
return 1 + (max(map(dict_depth, d.values())) if d else 0)
return 0 | 16f4164fdea08af9d5846a5866428c81848726b9 | 3,654,880 |
def apercorr(psf,image,objects,psfobj,verbose=False):
"""
Calculate aperture correction.
Parameters
----------
psf : PSF object
The best-fitting PSF model.
image : string or CCDData object
The input image to fit. This can be the filename or CCDData object.
objects : table
... | bc4bb936801fe06a55648ed9a11545eacb24fd7d | 3,654,881 |
from typing import Dict
from typing import Tuple
def product_loading_factor_single_discount(skus: str, product_list: Dict[str, object], product: Dict[str, int], product_name: str, rules: list) -> Tuple[int, str]:
"""
Single product loading factor for calculating discounts with one rule
Parameters
---... | 44e12d02be7c8b54d1ea64ef2dc3cbec29a870bc | 3,654,882 |
import re
def clean_text(page):
"""Return the clean-ish running text parts of a page."""
return re.sub(_UNWANTED, "", _unescape_entities(page)) | 8042cc5049b2d8b6646c10655b84c5552e315274 | 3,654,883 |
def calculate_recall(tp, n):
"""
:param tp: int
Number of True Positives
:param n: int
Number of total instances
:return: float
Recall
"""
if n == 0:
return 0
return tp / n | b8a36488af59e036acdb50821716ae34287e6b8f | 3,654,884 |
def authenticate_user_password(password : 'bytes', encryption_dict : 'dict', id_array : 'list'):
"""
Authenticate the user password.
Parameters
----------
password : bytes
The password to be authenticated as user password.
encryption_dict : dict
The dictionary containing all... | b608a921fb02cedf9da9d8ea8e0d8f8139a6a9bd | 3,654,885 |
def date_to_num(date):
"""Convert datetime to days since 1901"""
num = (date.year - 1901) * 365.25
num += [
0, 31, 59.25, 90.25, 120.25,
151.25, 181.25, 212.25, 243.25,
273.25, 304.25, 334.25
][date.month - 1]
num += date.day
return int(num) | 88e342e0fc80a5998df8e5f1ab0002e0f7fe808e | 3,654,886 |
from typing import Tuple
def load_world(filename: str, size: Tuple[int, int], resolution: int) -> np.array:
"""Load a preconstructred track to initialize world.
Args:
filename: Full path to the track file (png).
size: Width and height of the map
resolution: Res... | 8ccf97efb83b3c365fb95a2732d0737100d5f254 | 3,654,887 |
import torch
def generate_image(model, img_size, n_flow, n_block, n_sample, temp=0.7, ctx=None, label=None):
"""Generate a single image from a Glow model."""
# Determine sizes of each layer
z_sample = []
z_shapes = calc_z_shapes(3, img_size, n_flow, n_block)
for z in z_shapes:
z_new = tor... | bee9c45cbbd028351e580729da51092604f87288 | 3,654,888 |
def quote_spaces(arg):
"""Generic function for putting double quotes around any string that
has white space in it."""
if ' ' in arg or '\t' in arg:
return '"%s"' % arg
else:
return str(arg) | e0171c3b0eee18c7fcc44cbdfe007949feabba9a | 3,654,889 |
from pathlib import Path
import requests
import shutil
def download_file(url) -> Path:
"""Better download"""
name = Path(urlparse(unquote(url)).path).name
with mktempdir() as tmpdir:
@backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_time=30)
def get():
... | 5ff6c05e5e1eb3379918c65d945d57af7e8d56be | 3,654,891 |
def creategui(handlerfunctions):
"""Initializes and returns the gui."""
gui = GUI(handlerfunctions)
# root.title('DBF Utility')
return gui | 17be3bae6eb105aca770327898a01027271e6f9c | 3,654,892 |
import torch
def rank_src_trgs(enc_dec_gen, src_list, trg_list):
"""
"""
batch_size = len(trg_list)
x, y = enc_dec_gen.encode_inputs(src_list,
trg_list,
add_bos=True,
add_eos=True)
... | f5472889489676e21a7bec032e13ef99c850f2da | 3,654,893 |
def plugin_poll(handle):
""" Extracts data from the sensor and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a sensor reading in a JSON document, as a Python dict, if it is av... | c3d7b32b6816c81d244f689ce4185d1dcd9a16fe | 3,654,894 |
import torch
def ltria2skew(L):
"""
assume L has already passed the assertion check
:param L: lower triangle matrix, shape [N, 3]
:return: skew sym A [N, 3, 3]
"""
if len(L.shape) == 2:
N = L.shape[0]
# construct the skew-sym matrix
A = torch.zeros(N, 3, 3).cuda() # [N... | 6e74c181fc8efcdc28ba35578f31fb6f2a7fa1bb | 3,654,896 |
def gamma_contrast(data_sample, num_patches=324, num_channel=2, shape_data=None,
gamma_range=(0.5, 1.7), invert_image=False, per_channel=False,
retain_stats=False):
"""Performs gamma contrast transformation"""
epsilon = 1e-7
data_sample_patch = []
gamma_range_tenso... | 373f3f7e602de69c1cbce328ec3ff1322a44d013 | 3,654,897 |
def _converge(helper, rcs, group):
"""
Function to be passed to :func:`_oob_disable_then` as the ``then``
parameter that triggers convergence.
"""
return group.trigger_convergence(rcs) | 8aab701dc7e29d83d6c8ab8b71c37837feb72847 | 3,654,898 |
def HybridClientFactory(jid, password):
"""
Client factory for XMPP 1.0.
This is similar to L{client.XMPPClientFactory} but also tries non-SASL
autentication.
"""
a = HybridAuthenticator(jid, password)
return xmlstream.XmlStreamFactory(a) | 283d9182c0e7bce254bc9f04cd42c15b9e3aed46 | 3,654,899 |
def home():
"""Home page."""
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash('You are logged in.', 'success')
redirect_url = request.args.get('next') or url_for('user.mem... | 4bed46f095b31a61746c382460b6f477a4aa215e | 3,654,900 |
def countingsort(A):
"""
Sort the list A. A has to be a list of integers.
Every element of the list A has to be non-negative.
@param A: the list that should get sorted
@return the sorted list
"""
if len(A) == 0:
return []
C = [0] * (max(A)+1)
B = [""] * le... | ebdaac4580f910873f77878978b57e193334a4ea | 3,654,901 |
import math
def calc_obstacle_map(ox, oy, resolution, vr):
"""
Build obstacle map according to the distance of a
certain grid to obstacles. Treat the area near the
obstacle within the turning radius of the vehicle
as the obstacle blocking area and mark it as TRUE.
"""
min_x = round(min(ox))
min_y = ro... | 87d44c5eb799bf3b2ea64ac0717b8d7f260a4a37 | 3,654,902 |
import itertools
def dilate(poly,eps):
"""
The function dilates a polytope.
For a given polytope a polytopic over apoproximation of the $eps$-dilated set is computed.
An e-dilated Pe set of P is defined as:
Pe = {x+n|x in P ^ n in Ball(e)}
where Ball(e) is the epsilon neighborhood with no... | 0ae4d8ea9cb6977939e4d3bed6454ed55e8855cf | 3,654,903 |
def read_files_to_vardf(map_df, df_dict, gridclimname, dataset, metadata,
file_start_date, file_end_date, file_delimiter,
file_time_step, file_colnames,
subset_start_date, subset_end_date, min_elev, max_elev, variable_list=None):
"""
# r... | 31bc460eb0035d3bbd51f266c96a53f537495a53 | 3,654,904 |
import pickle
def read_file(pickle_file_name):
"""Reads composite or non-composite class-activation maps from Pickle file.
:param pickle_file_name: Path to input file (created by
`write_standard_file` or `write_pmm_file`).
:return: gradcam_dict: Has the following keys if not a composite...
gr... | 3f2f7fb1a5a904f494e64f840f6a8d6ae207c900 | 3,654,905 |
import string
def tacodev(val=None):
"""a valid taco device"""
if val in ('', None):
return ''
val = string(val)
if not tacodev_re.match(val):
raise ValueError('%r is not a valid Taco device name' % val)
return val | 4cffd52f9e7673ad45e697aadfbb3515ecd3d209 | 3,654,906 |
def decode_layout_example(example, input_range=None):
"""Given an instance and raw labels, creates <inputs, label> pair.
Decoding includes.
1. Converting images from uint8 [0, 255] to [0, 1.] float32.
2. Mean subtraction and standardization using hard-coded mean and std.
3. Convert boxes from yxyx [0-1] to x... | a54b26a8b4d82a6a9e5bc093f9f59b7a74450916 | 3,654,908 |
import plotly.figure_factory as ff
def bact_plot(samples, bacteroidetes, healthiest_sample):
"""
Returns a graph of the distribution of the data in a graph
==========
samples : pandas.DataFrame
The sample data frame. Must contain column `Bacteroidetes` and
`Firmicutes` that contai... | d21bb3bd534f92cc6eed3bb467fe355abcf1afd2 | 3,654,909 |
def xdraw_lines(lines, **kwargs):
"""Draw lines and optionally set individual name, color, arrow, layer, and
width properties.
"""
guids = []
for l in iter(lines):
sp = l['start']
ep = l['end']
name = l.get('name', '')
color = l.get('color')
arrow = l.g... | bebeb2d400ed8c779281b67f01007e953f15460f | 3,654,911 |
def _emit_params_file_action(ctx, path, mnemonic, cmds):
"""Helper function that writes a potentially long command list to a file.
Args:
ctx (struct): The ctx object.
path (string): the file path where the params file should be written.
mnemonic (string): the action mnemomic.
cmds (list<string>): th... | adafb75e24b2023ad2926e4248e8b2e1e6966b8e | 3,654,912 |
import gettext
def annotate_validation_results(results, parsed_data):
"""Annotate validation results with potential add-on restrictions like
denied origins."""
if waffle.switch_is_active('record-install-origins'):
denied_origins = sorted(
DeniedInstallOrigin.find_denied_origins(parsed_... | 659ec92f98c2678de2ee8f2552da77c5394047c5 | 3,654,913 |
import textwrap
def ignore_firstline_dedent(text: str) -> str:
"""Like textwrap.dedent(), but ignore first empty lines
Args:
text: The text the be dedented
Returns:
The dedented text
"""
out = []
started = False
for line in text.splitlines():
if not started and no... | 04bde49e72e07552f2f88e9112546d00b85a2879 | 3,654,915 |
def read_file(filename):
"""
Read a file and return its binary content. \n
@param filename : filename as string. \n
@return data as bytes
"""
with open(filename, mode='rb') as file:
file_content = file.read()
return file_content | 2417aa5cfa0d43303f9f6103e8b1fee9e8d652e2 | 3,654,916 |
def getdictkeys(value):
"""
Returns the ordered keys of a dict
"""
if type(value) == dict:
keys = list(value.keys())
keys.sort(key=toint)
return keys
return [] | adf49dbfa46f5174aa1435756c6e099b08b7c6c9 | 3,654,917 |
def exp_lr_scheduler(optimizer, epoch, init_lr=5e-3, lr_decay_epoch=40):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
lr = init_lr * (0.1**(epoch // lr_decay_epoch))
if epoch % lr_decay_epoch == 0:
print('LR is set to {}'.format(lr))
for param_group in optimizer.... | 520a7960ee589e033920cf182d75ea896cc8b8b7 | 3,654,918 |
def random_shadow(image):
"""
Function to add shadow in images randomly at random places, Random shadows meant to make the Convolution model learn
Lanes and lane curvature patterns effectively in dissimilar places.
"""
if np.random.rand() < 0.5:
# (x1, y1) and (x2, y2) forms a line
... | 118fbffa04bbd3551eff3f4298ba14235b00b7c3 | 3,654,920 |
def build_channel_header(type, tx_id, channel_id,
timestamp, epoch=0, extension=None,
tls_cert_hash=None):
"""Build channel header.
Args:
type (common_pb2.HeaderType): type
tx_id (str): transaction id
channel_id (str): channel id
... | cfd7524de77a61fe75d3b3be58e2ebde4d743393 | 3,654,921 |
def get_character(data, index):
"""Return one byte from data as a signed char.
Args:
data (list): raw data from sensor
index (int): index entry from which to read data
Returns:
int: extracted signed char value
"""
result = data[index]
if result > 127:
result -= ... | 5a08102cb9dc8ae7e2adcab9b5653b77ee2c6ae3 | 3,654,922 |
def df_to_embed(df, img_folder):
""" Extract image embeddings, sentence embeddings and concatenated embeddings from dataset and image folders
:param df: dataset file to use
:param img_folder: folder where the corresponding images are stored
:return: tuple containing sentence embeddings, image embedding... | cda55f06a74c1b0475bc6a9e35e657b4f3ce0392 | 3,654,923 |
import random
def generate_player_attributes():
"""
Return a list of 53 dicts with player attributes
that map to Player model fields.
"""
# Get player position distribution
position_dist = get_position_distribution()
# Get player attribute distribution
attr_dist = get_attribute_distri... | 57c16d998348b9db1384dc98412bd69e62d0c73d | 3,654,925 |
def colour_from_loadings(loadings, maxLoading=None, baseColor="#FF0000"):
"""Computes colors given loading values.
Given an array of loading values (loadings), returns an array of
colors that graphviz can understand that can be used to colour the
nodes. The node with the greatest loading uses baseColor... | 8bd65e5b4aa54558d3710a8518bbbe6400559046 | 3,654,926 |
def determineDocument(pdf):
""" Scans the pdf document for certain text lines and determines the type of investment vehicle traded"""
if 'turbop' in pdf or 'turboc' in pdf:
return 'certificate'
elif 'minil' in pdf:
return 'certificate'
elif 'call' in pdf or 'put' in pdf:
return '... | e6c5adc10168321fd6a534dd8e9fbf2e8ccb1615 | 3,654,927 |
from typing import Any
import pickle
def deserialize_api_types(class_name: str, d: dict) -> Any:
"""
Deserializes an API type. Allowed classes are defined in:
* :mod:`maestral.core`
* :mod:`maestral.model`
* :mod:`maestral.exceptions`
:param class_name: Name of class to deserializ... | f9c3962a1c18bd6dfb385af37e90b5062d1e0eef | 3,654,929 |
from click.testing import CliRunner
def runner() -> CliRunner:
"""Fixture for invoking command-line interfaces."""
return testing.CliRunner() | 39f241b8192a3c06750e850c8c953822e4db5634 | 3,654,930 |
import math
def give_color_to_direction_dynamic(dir):
"""
Assigns a color to the direction (dynamic-defined colors)
Parameters
--------------
dir
Direction
Returns
--------------
col
Color
"""
dir = 0.5 + 0.5 * dir
norm = mpl.colors.Normalize(vmin=0, vmax=... | ece62af230cda4870df099eae50a26b72848b2de | 3,654,932 |
def prune_arms(active_arms, sample_arms, verbose=False):
"""Remove all arms from ``active_arms`` that have an allocation less than two standard deviations below the current best arm.
:param active_arms: list of coordinate-tuples corresponding to arms/cohorts currently being sampled
:type active_arms: list ... | bd82f77503a9f0fa6a49b9f24ce9846849544b00 | 3,654,935 |
def prepare_string(dist, digits=None, exact=False, tol=1e-9,
show_mask=False, str_outcomes=False):
"""
Prepares a distribution for a string representation.
Parameters
----------
dist : distribution
The distribution to be stringified.
digits : int or None
The p... | 09abba1e5027049b9a43cb83e8de6f95daf5b431 | 3,654,936 |
def verifier(func):
"""
Creates a `Verifier` by given specifier.
Parameters
----------
func: callable, [callable], (str, callable), [(str, callable)]
The specifier of `Verifier` which can take various forms and determines the attributes and behaviors of `Verifier`.
When it is declar... | 665bc9cf5039e568fb2325a1cf0a25f72311eab8 | 3,654,937 |
def get_add_diff_file_list(git_folder):
"""List of new files.
"""
repo = Repo(str(git_folder))
repo.git.add("sdk")
output = repo.git.diff("HEAD", "--name-only")
return output.splitlines() | af6ff7ffb076fb382aaa946e11e473f2f45bad0e | 3,654,939 |
def has_read_perm(user, group, is_member, is_private):
""" Return True if the user has permission to *read*
Articles, False otherwise.
"""
if (group is None) or (is_member is None) or is_member(user, group):
return True
if (is_private is not None) and is_private(group):
return False
... | 6c1bc51abd50a5af76e16e7723957c758822c988 | 3,654,941 |
def normalize_df(dataframe, columns):
"""
normalized all columns passed to zero mean and unit variance, returns a full data set
:param dataframe: the dataframe to normalize
:param columns: all columns in the df that should be normalized
:return: the data, centered around 0 and divided by it's standa... | 39b23a6f11794323f1d732396021d669410c7de1 | 3,654,943 |
import json
def PeekTrybotImage(chromeos_root, buildbucket_id):
"""Get the artifact URL of a given tryjob.
Args:
buildbucket_id: buildbucket-id
chromeos_root: root dir of chrome os checkout
Returns:
(status, url) where status can be 'pass', 'fail', 'running',
and url looks like:
... | c74b7c5a120d3d489e6990bd03e74bb0d22fea27 | 3,654,944 |
def frozenset_code_repr(value: frozenset) -> CodeRepresentation:
"""
Gets the code representation for a frozenset.
:param value: The frozenset.
:return: It's code representation.
"""
return container_code_repr("frozenset({",
"})",
... | b4a3b283c7d21d0ae888c588471f9dea650215fb | 3,654,945 |
def SRMI(df, n):
"""
MI修正指标
Args:
df (pandas.DataFrame): Dataframe格式的K线序列
n (int): 参数n
Returns:
pandas.DataFrame: 返回的DataFrame包含2列, 是"a", "mi", 分别代表A值和MI值
Example::
# 获取 CFFEX.IF1903 合约的MI修正指标
from tqsdk import TqApi, TqSim
from tqsdk.ta import SR... | 29726385da068446cd3dd3ee13f8d95b88c36245 | 3,654,946 |
def get_purchase_rows(*args, **kwargs):
"""
获取列表
:param args:
:param kwargs:
:return:
"""
return db_instance.get_rows(Purchase, *args, **kwargs) | 505ace358b619a736bc7a71139e307110cd7c27d | 3,654,947 |
def depart_delete(request):
""" 删除部门 """
nid = request.GET.get('nid')
models.Department.objects.filter(id=nid).delete()
return redirect("/depart/list/") | 753c01771ad59b789f324a0cb95e94dcf9e48e9d | 3,654,948 |
def create_condor_scheduler(name, host, username=None, password=None, private_key_path=None, private_key_pass=None):
"""
Creates a new condor scheduler
Args:
name (str): The name of the scheduler
host (str): The hostname or IP address of the scheduler
username (str, optional): The u... | d47c8c69fea249139698564b52520d95fbb1a75f | 3,654,949 |
def dot_to_underscore(instring):
"""Replace dots with underscores"""
return instring.replace(".", "_") | cf9441702ffb128678a031eabb4fa48be881cae5 | 3,654,951 |
def get_birthday_weekday(current_weekday: int, current_day: int,
birthday_day: int) -> int:
"""Return the day of the week it will be on birthday_day,
given that the day of the week is current_weekday and the
day of the year is current_day.
current_weekday is the current day of ... | 5b4ba9f2a0efcdb9f150b421c21bb689604fbb11 | 3,654,952 |
def _check(err, msg=""):
"""Raise error for non-zero error codes."""
if err < 0:
msg += ': ' if msg else ''
if err == _lib.paUnanticipatedHostError:
info = _lib.Pa_GetLastHostErrorInfo()
hostapi = _lib.Pa_HostApiTypeIdToHostApiIndex(info.hostApiType)
msg += 'U... | 2f0b2ccd055bbad814e48b451eb72c60e62f9273 | 3,654,954 |
def make_flood_fill_unet(input_fov_shape, output_fov_shape, network_config):
"""Construct a U-net flood filling network.
"""
image_input = Input(shape=tuple(input_fov_shape) + (1,), dtype='float32', name='image_input')
if network_config.rescale_image:
ffn = Lambda(lambda x: (x - 0.5) * 2.0)(imag... | ff8c90b3eecc26384b33fd64afa0a2c4dd44b82d | 3,654,956 |
def FRAC(total):
"""Returns a function that shows the average percentage of the values from
the total given."""
def realFrac(values, unit):
r = toString(sum(values) / len(values) / total * 100)
r += '%'
if max(values) > min(values):
r += ' avg'
return [r]
retu... | 41946163d5c185d1188f71d615a67d72e6eaee4f | 3,654,957 |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if len(ints) == 0: return (None, None)
low = ints[0]
high = ints[0]
for i in ints:
if i < low:
low = i
... | 14c7d4cc73947c8de38bb598e295d9a1b4b7e5f6 | 3,654,958 |
def gen_sweep_pts(start: float=None, stop: float=None,
center: float=0, span: float=None,
num: int=None, step: float=None, endpoint=True):
"""
Generates an array of sweep points based on different types of input
arguments.
Boundaries of the array can be specified usin... | fb67623acfea433331babf7b7e1217cfa4e9e7ae | 3,654,959 |
def set_lang_owner(cursor, lang, owner):
"""Set language owner.
Args:
cursor (cursor): psycopg2 cursor object.
lang (str): language name.
owner (str): name of new owner.
"""
query = "ALTER LANGUAGE \"%s\" OWNER TO \"%s\"" % (lang, owner)
executed_queries.append(query)
cu... | 07cf4a33ca766a8ccf468f59d33318bab88c4529 | 3,654,960 |
def rstrip_tuple(t: tuple):
"""Remove trailing zeroes in `t`."""
if not t or t[-1]:
return t
right = len(t) - 1
while right > 0 and t[right - 1] == 0:
right -= 1
return t[:right] | a10e74ea4a305d588fbd1555f32dda1d4b95266e | 3,654,961 |
def _calc_active_face_flux_divergence_at_node(grid, unit_flux_at_faces, out=None):
"""Calculate divergence of face-based fluxes at nodes (active faces only).
Given a flux per unit width across each face in the grid, calculate the net
outflux (or influx, if negative) divided by cell area, at each node that
... | 82c485935a3190c07ab12f7c838d52f5fecb78d0 | 3,654,962 |
from typing import NoReturn
def get_line(prompt: str = '') -> Effect[HasConsole, NoReturn, str]:
"""
Get an `Effect` that reads a `str` from stdin
Example:
>>> class Env:
... console = Console()
>>> greeting = lambda name: f'Hello {name}!'
>>> get_line('What is your na... | 47c58bb6ab794fdf789f0812dc1dc6d977106b60 | 3,654,964 |
def reconstruct_wave(*args: ndarray, kwargs_istft, n_sample=-1) -> ndarray:
"""
construct time-domain wave from complex spectrogram
Args:
*args: the complex spectrogram.
kwargs_istft: arguments of Inverse STFT.
n_sample: expected audio length.
Returns:
audio (numpy)
"... | 8624602efe1ab90304da05c602fb46ac52ec86e0 | 3,654,965 |
def perfect_score(student_info):
"""
:param student_info: list of [<student name>, <score>] lists
:return: first `[<student name>, 100]` or `[]` if no student score of 100 is found.
"""
#
first = []
student_names = []
score = []
print (student_info)
for name in student_info:
... | ac7580cce134627e08764031ef2812e1b70ba00f | 3,654,966 |
def get_composite_component(current_example_row, cache, model_config):
"""
maps component_id to dict of {cpu_id: False, ...}
:param current_example_row:
:param cache:
:param model_config:
:return: nested mapping_dict = { #there can be multiple components
component_id = { #componen... | 201db2016ea59cbf4a20ce081813bfd60d58bf67 | 3,654,968 |
def presigned_url_both(filename, email):
"""
Return presigned urls both original image url and thumbnail image url
:param filename:
:param email:
:return:
"""
prefix = "photos/{0}/".format(email_normalize(email))
prefix_thumb = "photos/{0}/thumbnails/".format(email_normalize(email))
... | 7f37cf388ef944d740f2db49c5125435b819e0e8 | 3,654,969 |
def check_if_event_exists(service, new_summary):
"""
Description: checks if the event summary exists using a naive approach
"""
event_exists = False
page_token = None
calendarId = gcalendarId
while True:
events = (
service.events().list(calendarId=calendarId, pageToken=pa... | c6cc8bd3e4548cda11f9eaad6fd2d3da7a5c7e20 | 3,654,970 |
def retry(func, *args, **kwargs):
"""
You can use the kwargs to override the 'retries' (default: 5) and
'use_account' (default: 1).
"""
global url, token, parsed, conn
retries = kwargs.get('retries', 5)
use_account = 1
if 'use_account' in kwargs:
use_account = kwargs['use_account... | 7749fcd63f8d795692097b0257adde4147ecb569 | 3,654,971 |
def eval_f(angles, data=None):
"""
function to minimize
"""
x1, x2, d, zt, z, alpha, beta, mask, b1, b2 = data
thetaxm, thetaym, thetazm, thetaxp, thetayp, thetazp = angles
rm = rotation(thetaxm, thetaym, thetazm)
rp = rotation(thetaxp, thetayp, thetazp)
x1r = rm.dot(x1.T).T
x2r = rp... | 622c18d21224ab40d597a165bff3e0493db4cdcc | 3,654,972 |
def clamp(min_v, max_v, value):
"""
Clamps a value between a min and max value
Args:
min_v: Minimum value
max_v: Maximum value
value: Value to be clamped
Returns:
Returns the clamped value
"""
return min_v if value < min_v else max_v if value > max_v else value | 1a9aaf3790b233f535fb864215444b0426c17ad8 | 3,654,973 |
def collatz(n):
"""Sequence generation."""
l = []
while n > 1:
l.append(n)
if n % 2 == 0:
n = n / 2
else:
n = (3 * n) + 1
l.append(n)
return l | 69d993147604889fe6b03770efbfa6fb7f034258 | 3,654,974 |
def generate_anchors(base_size=16, ratios=[0.5, 1, 2],
scales=2 ** np.arange(3, 6), stride=16):
"""
Generate anchor (reference) windows by enumerating aspect ratios X
scales wrt a reference (0, 0, 15, 15) window.
"""
base_anchor = np.array([1, 1, base_size, base_size]) - 1
... | 083bfad62fac67e0f7fb02251bc3db7904629bd5 | 3,654,976 |
import re
def number_format(number_string, fill=2):
"""
add padding zeros to make alinged numbers
ex.
>>> number_format('2')
'02'
>>> number_format('1-2')
'01-02'
"""
output = []
digits_spliter = r'(?P<digit>\d+)|(?P<nondigit>.)'
for token in [m.groups() for m in re.find... | ee44167b4597fbe7c9f01fa5b26e02d7608c3677 | 3,654,977 |
def box_postp2use(pred_boxes, nms_iou_thr=0.7, conf_thr=0.5):
"""Postprocess prediction boxes to use
* Non-Maximum Suppression
* Filter boxes with Confidence Score
Args:
pred_boxes (np.ndarray dtype=np.float32): pred boxes postprocessed by yolo_output2boxes. shape: [cfg.cell_size * cfg.c... | 07be8b953b82dbbcc27daab0afa71713db96efc1 | 3,654,978 |
from functools import reduce
def many_hsvs_to_rgb(hsvs):
"""Combine list of hsvs otf [[(h, s, v), ...], ...] and return RGB list."""
num_strips = len(hsvs[0])
num_leds = len(hsvs[0][0])
res = [[[0, 0, 0] for ll in range(num_leds)] for ss in range(num_strips)]
for strip in range(num_strips):
... | 0842ecb4a42560fb6dae32a91ae12588152db621 | 3,654,979 |
def _convert_paths_to_flask(transmute_paths):
"""flask has it's own route syntax, so we convert it."""
paths = []
for p in transmute_paths:
paths.append(p.replace("{", "<").replace("}", ">"))
return paths | f8ea95e66c68481f0eb5a6d83cf61d098806f6be | 3,654,980 |
def check_isup(k, return_client=None):
"""
Checks ping and returns status
Used with concurrent decorator for parallel checks
:param k: name to ping
:param return_client: to change return format as '{k: {'comments': comments}}'
:return(str): ping ok / -
"""
if is_up(k):
comments ... | 8ebb346eb74cb54aa978b4fff7cd310b344ece50 | 3,654,981 |
def percent_uppercase(text):
"""Calculates percentage of alphabetical characters that are uppercase, out of total alphabetical characters.
Based on findings from spam.csv that spam texts have higher uppercase alphabetical characters
(see: avg_uppercase_letters())"""
alpha_count = 0
uppercase_count =... | 61ccf42d06ffbae846e98d1d68a48de21f52c299 | 3,654,982 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.