content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def basic_style(color=None, size=None, opacity=None, stroke_color=None, stroke_width=None):
"""Helper function for quickly creating a basic style.
Args:
color (str, optional): hex, rgb or named color value.
Defaults is '#FFB927' for point geometries and '#4CC8A3' for lines.
size (in... | e607c9f04e085367900393804f7ce119524da81c | 42,255 |
def git_errors_message(git_info):
"""Format a list of any git errors to send as slack message"""
git_msg = [
{
"color": "#f2c744", "blocks": [
{
"type": "divider"
},
{
"type": "section", "text": {"type": ... | 192c1f5c85c4615828873795eb8f71d8ced4080e | 42,256 |
import sqlite3
def get_avg_score(num_moves=None, num_trials=None):
"""Get the average score for a specified configuration of num_moves and num_trials
Args:
num_moves (int, optional): The value for num_moves which printed trials must match. Defaults to None.
num_trials (int, optional): The val... | e75c7865b7bd49edf9fd2b73561734482e28cfd2 | 42,257 |
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words=break_words(sentence)
return sort_words(words) | 23d0f3b5b554ddb405e79c95b1e663cb50ec4047 | 42,258 |
from iotbx.pdb import fetch
def get_pdb_file(file_name, print_out=True):
""" (file_name) -> file_path
This function will check if a pdb file_name exist.
If it is not, it will either fetch it from the RCSB website
or find it on LBLs pdb mirror folder
:param file_name (str): a pdb file name
:return file_na... | 1e28309f4c3fcb59295ec305c32e8cff46f5014e | 42,259 |
def create_knx_exposure(
hass: HomeAssistant, xknx: XKNX, config: ConfigType
) -> KNXExposeSensor | KNXExposeTime:
"""Create exposures from config."""
address = config[KNX_ADDRESS]
expose_type = config[ExposeSchema.CONF_KNX_EXPOSE_TYPE]
attribute = config.get(ExposeSchema.CONF_KNX_EXPOSE_ATTRIBUTE)
... | b3bb96eba5968e3e3b85719c7324d216de451029 | 42,260 |
def normalize_vector(v):
"""
Takes in a vector in list form, concatenates it to form a single vector,
normalizes it to unit length, then returns it in list form together with its norm.
"""
norm_val = np.linalg.norm(np.concatenate(v))
norm_v = [a / norm_val for a in v]
return norm_v, norm_val | 99c8755a53169967eceac997df662d19a436301f | 42,261 |
def clean_data(df):
"""Clean categories and merge to messages
Args:
df => DataFrame of merged categories and messages csv files
Returns:
df => Dataframe of cleaned categories and dropped duplicates
"""
categories = pd.Series(df.categories).str.split(';', expand=True)
row = catego... | 45c3bdb4aa0fef4b5e5a2f8665ddfc10dd846e2f | 42,262 |
def vote():
"""
/vote
description: Seconds the proposal
vote: Vote on a Referendum either "yes" or "no"
ref_index: the value returned from /get_ref or use PropIndex
Request payload
{
'spider_id' : 'xxxx',
'phrase' : '...',
'ref_index' : '4',
'vote': 'ye... | 7a92a6276accbf471882c97c4503fb8ed61179f8 | 42,263 |
def getAllModules():
"""
Returns a list of all modules that should be checked.
@rtype: list of L{pcmodules.PyCheckerModule}
"""
modules = []
for module in pcmodules.getPCModules():
if module.check:
modules.append(module)
return modules | c8a2112138b663471023228fd7499fd36e015389 | 42,264 |
from pathlib import Path
def load_matrix_flexible(matrix_file: str) -> ndarray:
"""Load a matrix data from .tiff, .npy or .txt file."""
path = Path(matrix_file)
if path.suffix in (".tiff", ".tif"):
return load_img(matrix_file)
elif path.suffix == ".npy":
return np.load(matrix_file)
... | 4cc33e1d545568b12f138682386092770777add6 | 42,265 |
import torch
def sp2torch(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx.data)
shape = torch.Siz... | 5546a8d0ee691818e65186f08494176ce6ccc781 | 42,266 |
def Distribution_of_masses(**kwds):
"""
输出双黑洞质量的分布。(ratio_step 不能小于 0.01,可以通过增大 doa=100 提高精度)
Input:
共有三种输入方式,如下面的例子:
Eg1: mass1_scope = (5,75), mass2_scope = (5,75), mass_step = 2
Eg2: mass1_scope = (5,75), mass_step = 2, ratio_scope = (0.1,1), ratio_step = 0.1
Eg3: Mass_scope = (5, 30... | aaef2ddcf589f9a299685344f1ee076e469150bf | 42,267 |
def DecodePublic(curve, bb):
"""
Decode a public key from bytes. Invalid points are rejected. The
neutral element is NOT accepted as a public key.
"""
pk = curve.Decode(bb)
if pk.is_neutral():
raise Exception('Invalid public key (neutral point)')
return pk | 7bf8d7eb129fe640475fbf404354c204f3242954 | 42,269 |
def parse_result_page(html):
"""
"""
dfs = []
for df in pd.read_html(html, thousands=' '):
grouper = df.columns[0]
value_cols = df.columns[1:].tolist()
df.columns = ["group"] + value_cols
df_long = pd.melt(df, id_vars="group", value_vars=df.columns[1:],
... | e539531e8832c0a80992e4239d792e00b8e1ac31 | 42,270 |
def _read_schema(proto_path):
"""Reads a TF Metadata schema from the given text proto file."""
result = schema_pb2.Schema()
with open(proto_path) as fp:
text_format.Parse(fp.read(), result)
return result | 2f9301d1ce0e478a83fee6c433702bf25092d591 | 42,271 |
def compact(it):
"""Filter false (in the truth sense) elements in iterator."""
return filter(bool, it) | 0d84d2e7c35447969bfb3b357389e416c71b40bd | 42,272 |
def session_capabilities(session_capabilities):
"""Log browser (console log) and performance (request / response headers)
data.
They will appear in `Links` section of pytest-html's html report.
"""
session_capabilities["loggingPrefs"] = {
"browser": "ALL",
"performance": "ALL"
}
return session... | ab87146f815dffa905a60d143f7aebf4a64d3ad0 | 42,274 |
def find_nearest(arr, val):
"""Find index(es) of "nearest" value(s).
Parameters
----------
arr : array_like (ND)
The array to search in (nd). No need to be sorted.
val : scalar or array_like
Value(s) to find.
Returns
-------
out : tuple
The index (or tuple if nd... | 3c2271efc6178332a885f80d419b319fd2cb21e5 | 42,275 |
def calculate_overlap_rate(inventor_class_nbr_group_count_dict):
"""
计算交叠率
:param inventor_class_nbr_group_patent_count:
:return:
"""
#发明家的总数
inventor_cnt = len(inventor_class_nbr_group_count_dict.keys())
#无法分组的发明家数量
cant_group_inventor = 0
for inventor, class_nbr_group_count_dic... | 0c59c8ffaf8407b4f1ede86c8a3b5b4202f211fc | 42,276 |
import ast
def _parse_mock_imports(mod_ast, expanded_imports):
"""Parses a module AST node for import statements and resolves them against
expanded_imports (such as you might get from _expand_mock_imports).
If an import is not recognized, it is omitted from the returned dictionary.
Returns a dictionary suit... | 50cb8e4e2469b7bf63deacf0a5085afcded0b5e3 | 42,277 |
from typing import Union
def to_numpy(array: Union[pa.Array, pa.ChunkedArray]):
"""For non-chunked arrays, need to pass zero_copy_only=False."""
if isinstance(array, pa.ChunkedArray):
return array.to_numpy()
return array.to_numpy(zero_copy_only=False) | c2fcb61b79056183e0606ace886bc2a0f3c1d7a1 | 42,278 |
def get_model(inputs, max_length, dim=25):
"""
input - vocabulary size, a number of unique words in
our data set
max_length - the maximum length of each sequence of words
(a document)
dim - word embedding dimension, the lenght of word vector
that will be produced... | 1901225c5dc078f49f7c9b6a1a3c41cf0f6c8d95 | 42,280 |
def calc_field_size(field_type, length):
"""
Рассчитывает размер данных поля
:param field_type: Тип поля
:type field_type: string
:param length: Длина поля
:type length: int
:return: Длина поля в байтах
:rtype: int
"""
if field_type == 'B':
return length
elif field_t... | 677b28d03d02e45d2f7a771c3c895c16060c229a | 42,281 |
def local_channel(obj):
"""
Return the parallel region local channel number `obj` is executing in.
The channel number is in the range of zero to ``local_max_channel(obj)``.
Args:
obj: Instance of a class executing within Streams.
Returns:
int: Parallel region local channel num... | 315c8a0c1a3f908e756672a752ae053e540fbe61 | 42,282 |
def import_results(file_name):
"""Import scientific instrument data. The routine is as follows:
1. Read in all the excel sheets at one time.
2. Get the sample name.
3. Get and tidy the compound data from the compound sheet.
4. Add the analyte names and measurements to a list of resul... | 018827e5ea14cb3db436e081ebc7a328bd603281 | 42,283 |
def SortByName(list_response):
"""Return the list_response sorted by name."""
return sorted(list_response, key=lambda x: x.name) | 5cb48e536790c9f246aebe2a38bba77f329c5ae9 | 42,284 |
def calculateTetTwt(C):
"""Calculate tetanus/twitch ratio.
Calculate the tetanus/twitch ratio for every sigmoid with
parameter c in vector C.
Parameters
----------
C : 1-D array, float
Sequence of values to be used as parameter of a sigmoid function.
Returns
------... | 66c2f8ebea6f62dc2c74f8017ffc830f00170e90 | 42,285 |
from typing import Optional
def jwt_encode(
payload: dict[str, any],
secret: Optional[str] = None,
algo: Optional[str] = None,
) -> str:
"""Encode payload into a JWT"""
return jwt.encode(
payload,
secret or current_app.config["SECRET_KEY"],
algorithm=algo or current_app.con... | fac8b91962f4d187853f167a671052cd28f5d4bb | 42,286 |
def specs_free_photoz_info(my_photoz_info):
"""specs_free_photoz_info(user_pz_info my_photoz_info)"""
return _ccllib.specs_free_photoz_info(my_photoz_info) | c428f32113d2de0aaaa22f216d2ecb09fcd281fa | 42,287 |
from Bio.File import _IndexedSeqFileDict
def index(filename, format=None, key_function=None, **kwargs):
"""Indexes a search output file and returns a dictionary-like object.
- filename - string giving name of file to be indexed
- format - Lower case string denoting one of the supported format... | 8cb3ff1455b01ef9a462a726395aad587cf3c358 | 42,288 |
def equal_two_arrays(array1, array2, eps, tolerance, throwError=True):
"""
This function will compare the values of two python tuples. First, if the values are below
eps which denotes the significance level that we care, no comparison is performed. Next,
False is returned if the different between any ... | 781e567860bc6058c34ee5b689eeebfcaa49d009 | 42,289 |
def additive_attention(query, memory, mem_mask, hidden_size,
ln=False, proj_memory=None, num_heads=1,
dropout=None, scope=None):
"""
additive attention model
:param query: [batch_size, dim]
:param memory: [batch_size, seq_len, mem_dim]
:param mem_mask: [... | 13c24facf1ea585de54c5bf8d98c9e7294e9dda3 | 42,290 |
def radec_to_xyz(ra_deg, dec_deg):
""" Convert RA and Dec to xyz positions on a unit sphere.
Parameters
----------
ra_deg, dec_deg : float or arrays of floats, shape (N,)
RA and Dec in degrees.
Returns an array of floats with shape (N, 3).
"""
ra = np.asarray(ra_deg) * RAD_PER_DE... | ba9d34a71abed2c9185a0d7ae2c296d77a246497 | 42,291 |
from sampling import MetropolisGauss
def sample_hybrid_zprior_xmetro(network, niter, nprior, nmetro, prior_std=1.0, noise=0.02, z0=None, x0=None,
mapper=None, verbose=0):
""" Samples iteratively using Prior MCMC in z-space and Metropolis MCMC in z-space
Parameters
-------... | 30417bfd27a1b1793cc063a220113290fe20d9aa | 42,292 |
def multiplex_modularity(B, mu, membership):
"""Calculates a multiplex modularity score.
Calculates the modularity from a given modularity matrix and membership
vector.
Args:
B (scipy.sparse.csr_matrix): An n by n sparse modularity matrix where
n is the number of vertices across al... | c4bdb8ebd60179eee1e4ee217ace2ff31bd090f1 | 42,293 |
import re
def unindent(string):
"""Remove the initial part of whitespace from string.
>>> unindent("1 + 2 + 3\\n")
'1 + 2 + 3'
>>> unindent(" def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> unindent("\\n def fun():\\n return 42\\n")
'def fun():\\n return 42'
>>> u... | 1179d4d4a67380b95d46b3234e4b09fb83f36041 | 42,294 |
def unpackdict(table, field, keys=None, includeoriginal=False,
samplesize=1000, missing=None):
"""
Unpack dictionary values into separate fields. E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar'],
... [1, {'baz': 'a', 'quux': 'b'}],
... ... | faee5dab08972b942a0ec1d966584e0b1ea27aae | 42,295 |
from typing import Collection
def is_collection(path):
"""Check if the collection exists"""
return Collection.find(path) is not None | 3c44153649f78794e5233fef8523de45690ed692 | 42,296 |
def download_file(url, download_dir: str):
"""
https://stackoverflow.com/a/53153505/12988588
"""
response = calls.ping_url(url)
filename = url.split("/")[-1]
if len(download_dir) > 0:
os_makedirs(download_dir, exist_ok=True)
out_filepath = os_path.join(download_dir, filename)
wi... | e74a0b08f0892befdea5bf7cab0d218e25511932 | 42,297 |
from typing import Union
from typing import Tuple
import math
def conv2d_padding_size(
h_w_in: Union[int, Tuple[int, int]],
h_w_out: Union[int, Tuple[int, int]],
kernel_size: int = 1,
stride: int = 1,
dilation: int = 1,
) -> Tuple[Tuple[int, int], Tuple[int, int]]:
"""
:param h_w_in:
... | f0fa3b515f495b9f8b385c97f13adcded00d623f | 42,298 |
def register_user(email, name, password, password2):
"""
Register the user to the database
:param email: the email of the user
:param name: the name of the user
:param password: the password of user
:param password2: another password input to make sure the input is correct
:return: an error ... | 3f898d5a13610ebc8a0f31902dae6d0be268b003 | 42,299 |
def GetIntervalVarFromMatlab(doc:NexDoc, MatrixName):
"""Imports the specified matrix containing intervals from Matlab."""
return NexRun("GetIntervalVarFromMatlab", locals()) | 74c9e836f08972dedab768af0fb348b65b22a121 | 42,300 |
def get_display_backend_size():
"""Function to get the display backend size resolution
:return : display resolution size as x,y
:rtype : integer
"""
xc, yc = default_display_backend_size.split('x')
x = int(xc)
y = int(yc)
return x, y | 2f111dac7d49c9db79fb6319e14c2745b6bba8ea | 42,301 |
from typing import Sequence
from typing import Optional
from typing import Mapping
from typing import Tuple
def _skip_block(
lines: Sequence[bytes],
sline: int,
scol: int,
sstr: bytes,
estr: bytes,
skips: Optional[Mapping[bytes, SkipFun]] = None,
) -> Optional[Tuple[int, int]]:
"""A generi... | 83f7618be5543776a2d4e21876fecd41b2f8c39b | 42,302 |
def get_database_connection(file_path, timeout=0.0):
"""
Gets a Connection to an Sqlite Database
:param timeout: how long in seconds the driver will attempt to execute a statement before aborting.
:param file_path: path to the sqlite database
:return: a connection to the database
"""
db_co... | 87a23c2df027d52cfa22a3bc0545b6fb441858eb | 42,303 |
def cartesian_product(p_dict):
"""
Compute Cartesian product on parameter dict:
In:
{"number": [1,2,3], "color": ["orange","blue"] }
Out:
[ {"number": 1, "color": "orange"},
{"number": 1, "color": "blue"},
{"number": 2, "color": "orange"},
{"number": 2, "col... | 36009609a77083a24bdf720f89c0bde1227db9c8 | 42,304 |
def normalize(vector, pre_computed=None):
"""Return the normalized version of a vector.
Parameters
----------
vector : np.array
pre_computed : float, optional
The pre-computed norm for optimization. If not given, the norm
will be computed.
"""
n = pre_computed if pre_compute... | ab0c2690ddacc29c43faafbc1b503e324373edba | 42,305 |
def account_unlock(account, token):
"""
Unlock account
Note that if you call account_lock, you must always unlock account,
otherwise it will be locked until process restart
"""
if config.keep_integrity:
with lock_account_token:
l = account_lockers.get(account.upper())
... | 528b9dc2a995d85b886400d4d8b0c90b63afb274 | 42,307 |
def activate_detection(timeout: int = 10000) -> str:
"""Active sound detection
Parameter:
timeout: duration of detection default 10 sec
(value in milisec)
"""
msg = 'Sound detected in the room !'
no_sound_msg = "No sound detected in the room."
# waiting for edge cases for sete... | f0af4701ae27d4e00f4a15e61caea55e355a99b6 | 42,308 |
async def get_ohlcv(ticker: str = "KRW-BTC",
interval: str = "day",
count: int = 200,
to: str = None,
contain_req: bool = False) -> tuple or DataFrame:
"""Candle data request
Args:
ticker (str, optional): Coin's ticker. De... | d391ee4f131598bae9dcb1d816fc755b93e87695 | 42,309 |
def reset_window_environment() -> BoxLayout:
"""Remove PythonHere app widgets and styles."""
# import Window inside function to avoid early loading of the app config
from kivy.core.window import Window # pylint: disable=import-outside-toplevel
for widget in Window.children:
widget.clear_widget... | 47bbb3cfb994c9c6bfae0a0c83c4c8c15701da1d | 42,310 |
from typing import Iterable
from typing import Callable
from typing import Iterator
import math
def partition_sequentially(
items: Iterable[_T],
*,
key: Callable[[_T], str],
size_target: int,
size_max: int | None = None,
) -> Iterator[list[_T]]:
"""Stably partitions the given items into batche... | 7cd9f2db83c145f1b7b3d6cf75c33508f710cf31 | 42,311 |
import torch
def quad_kappa_loss(input, targets, y_pow=1, eps=1e-15):
"""
https://github.com/JeffreyDF/kaggle_diabetic_retinopathy/blob/master/losses.py#L22
:param input:
:param targets:
:param y_pow:
:param eps:
:return:
"""
batch_size = input.size(0)
num_ratings = 5
asse... | f7aab107d9264384f04f1b8ba331223adcb495aa | 42,312 |
def clamp_remaining(max_timeout: float) -> float:
"""Return the remaining timeout clamped to a max value."""
timeout = remaining()
if timeout is None:
return max_timeout
return min(timeout, max_timeout) | e16b1ccb3c6168aa82159e34d477e9ff3efba306 | 42,314 |
def is_tag_exists(
lf_client,
account_id: str,
key: str,
) -> bool:
"""
Check if an Lake Formation tag exists or not
Ref: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lakeformation.html#LakeFormation.Client.get_lf_tag
"""
try:
lf_client.get_lf_tag(C... | 9f323ee97d4dfc67b183f5bcdc46229fd328eff6 | 42,315 |
def browse_repository(script, project, repository):
"""
Gets the list of repositories for the specified project
:param script: A TestScript instance
:type script: TestScript
:param project: The project for the repository
:type project: str
:param repository: The repository to browse
:typ... | c3c98c625b3ed0e1de3e795861eb29c9825ef5e8 | 42,316 |
import collections
def build_node_statistics(nodes, images):
"""Build a dictionary of cache statistics about a group of nodes."""
# Generic statistics applicable to all groups of nodes.
node_statistics = {
'provisioned': len(list(filter(lambda n: n.provisioned, nodes))),
'not provisioned':... | 6f1b6a7128a088168f3d31054458275d5f13df53 | 42,318 |
from typing import Union
from typing import Sequence
def track_local_coordinate_systems(
markers: TimeSeries,
/,
segments: Union[str, Sequence[str]],
*,
method: int = 1) -> TimeSeries:
"""
Create local coordinate system definitions based on static markers.
Paramete... | b7a2d7f113eec550e0c59f3be1eab1bc99d9e188 | 42,319 |
def select_white(image):
"""
Threshold to select a white color objects
:param image: Undistorted image
:return: Thresholded image
Ref: Udacity reviewer suggestion
"""
lower = np.array([210, 210, 210])
upper = np.array([255, 255, 255])
mask = cv2.inRange(image, lower, upper)
retur... | f51995cf0d74668c383c280e2169817dbfa31d87 | 42,320 |
def is_libpsp():
"""Was libbinding successfully loaded in this module?"""
return __is_libpsp__ | 73844759e0b4f9dbd36bdd2f1c2b9709ce387b2f | 42,321 |
def run_batch(args: dict) -> int:
"""Runs a batch operation for the given arguments."""
batcher.run_project(
project_directory=args.get('project_directory'),
log_path=args.get('logging_path'),
output_directory=args.get('output_directory'),
shared_data=load_shared_data(args.get('s... | 1ad412c206e6bb67c8754476ec6cf24ba1a4c0a1 | 42,322 |
from re import S
def prepare(statement, variables, extra_data={}):
"""
Set variable in statement and return the prepared statement
"""
template = Template(statement)
data = extra_data.copy()
for variable in variables:
if variable == S.LOGIN_VARIABLE:
data[variable] = Settin... | cbc570f4ec020ee87674267f8746bdcbff7880e9 | 42,323 |
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
""" Returns public key in bitcoins 'bin' encoding. """
if not ishash(private_key_bin):
raise ValueError('private_key_bin format mismatch. maybe hex encoded?')
return keys.PrivateKey(private_key_bin).public_key.to_bytes() | 541b3791017df8b72825ee647f436ac4adf32618 | 42,324 |
def single_value_rnn_regressor(num_units,
sequence_feature_columns,
context_feature_columns=None,
cell_type='basic_rnn',
num_rnn_layers=1,
optimizer_type='SGD',
... | c1af7a4fa74d8f66052fba9a2a221d441a0b2d43 | 42,325 |
import torch
import copy
def k_fold(
n_splits,
epochs,
batch_size,
transforms,
criterion,
model,
dataset,
device):
"""
Perform K-fold cross validation.
Parameters
----------
n_splits: int
Number of splits to make of the data.... | e4c596756f1980c6c32150caffb17ec5be0cd0f1 | 42,326 |
def render_instruction(name, content):
""" Render an arbitrary in-line instruction with the given name and
content """
return ':{}: {}'.format(name, content) | 2200ab1c865dbad871395476fc2227cc8995b3d1 | 42,327 |
def check_nan_columns(df: pd.DataFrame) -> pd.Series:
"""Check whether the columns of the DataFrame object contain missing
values.
Arguement:
df: the DataFrame object to be checked whether its columns contain the
missing values
Return:
_: the Series object whose values are True ... | 414c7ad9a7387a01bc7c6e74a8304f9c5cb9f45f | 42,328 |
def site_time() -> Timestamp:
"""Wrapper for site server time."""
return _site.server_time() | 737a92448b4aa72eb491b6b6d5e294c8ec025768 | 42,329 |
def contract_id(owner_id, nonce):
"""
Compute the contract id of a contract
:param owner_id: the account creating the conctract
:param nonce: the nonce of the contract creation transaction
"""
return hash_encode("ct", decode(owner_id) + _int(nonce)) | 9bc6352acf7ed5279f6ac492f9b519a05222fb22 | 42,330 |
def json_patch_link(url, title, description):
"""Generate a json patch Link object."""
return serializers.Link(
url=url,
title=title,
description=description + " (Using an RFC6902 JSON Patch)",
action="patch",
) | a7cf77287fc32f3bba3c2a2372520de07437d0c3 | 42,331 |
import json
def sign_up_post(request: HttpRequest, *args, **kwargs):
"""用户邮箱验证注册。"""
body = json.loads(request.body)
if keys_missed(body, ['email', 'password', 'code']):
response = HttpResponse(MSG_BAD_REQUEST, status=400)
else:
exists = User.objects.filter(email=body['email'])
... | abf60ec83a77703e21b70b18312859687e3b1bae | 42,332 |
def balanced_decomp_unsafe(sequence, open_to_close):
"""
Same as :func:`balanced_decomp` but assumes that ``sequence`` is valid
balanced sequence in order to execute faster.
"""
gen = generate_balance_unsafe(sequence, open_to_close)
bal_curr, tok_curr = next(gen)
pop_open = sequence[0:1]
... | 524dc6074c06e5d3927789b8a3ee15afafe8376d | 42,333 |
def parse(args: list = None) -> dict:
"""
Parses the command line arguments and returns a dictionary containing the
results.
:param args:
The command line arguments to parse. If None, the system command line
arguments will be used instead.
"""
parser = ArgumentParser(description... | 93c8abb53b855dbcbad02809528746b58367bc62 | 42,334 |
def GetPlayerNames(player_ids):
"""Loads player_ids into Steam Account cache.
This will take in a list of account ids and load the Steam Accounts into db cache from the Steam API.
Args:
player_ids (list): List of SteamID64s to lookup.
Returns:
dict. Returns dict of player_i... | f06507c61eafd9eb23410ac439a9c5606943e4dd | 42,335 |
def _verify_node(cmd):
"""Verify that the node command exists and is at least the minimum supported
version of node.
Parameters
----------
cmd : string
Node command to verify (i.e 'node')."""
try:
out, err, return_code = get_output_error_code([cmd, '--version'])
except OSErr... | 1d84124c75d35316da011f00e194e5693b538ff9 | 42,336 |
def random_crop_info(h, w, border_ratio):
"""
:return:
random cropsize 原尺寸 * random scale [0.9, 1.0, 1.1]
random center 设置 border 随机取中心
"""
# h,w: ori image size
if np.random.random() < 1.0:
# random scale
random_scale = np.random.choice(np.arange(0.8, 1.2, 0.1))
... | 5646717cf910eedf98df124978b401984f2e1e43 | 42,337 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
entry_data = hass.data[DOMAIN].pop(entry.entry_id)
vlc = entry_data[DATA_VLC]
awa... | 08c25c611b677435339b13b64bc268b7e5607390 | 42,338 |
def _create_pem_projected_volume(cert_secret_name):
"""
Create volume for pem certificate
"""
items = [client.V1KeyToPath(key="tls.crt", path="keystore.pem"),
client.V1KeyToPath(key="ca.crt", path="truststore.pem"),
client.V1KeyToPath(key="tls.key", path="key.pem")]
sec_pro... | c7fa4198b3f35e832a6c35fafc41d48df88c1e4d | 42,339 |
def assign_random(scores, vector_quotas=None, pi_init=None, sigma_init=None, envy_init=None):
"""
Assigns refugee at random
Inputs:
assignment: A NxM matrix describing assignment
scores: The scoring matrix describing refugee-locality integration scores
refugee: The index of the refuge... | bf8db44acd672f7145444cf296496b9f2ca3b787 | 42,340 |
def get_alerts(alert_id=None, filt=None):
"""In short: Get one or many alerts.
The client uses the get_alerts command to get alert information.
If the command sent by the client was valid, the connector will
reply with a list of alerts to the client.
"""
root = etree.Element("get_alerts")
i... | 84f7389d12b103d7ec0ad4c8bde9a66d7ecdac03 | 42,341 |
def similar(app_id, detailed=False, hl="en", gl="us"):
"""Sends a GET request, follows the redirect, and retrieves a list of
applications similar to the specified app.
:param app_id: the app to retrieve details from, e.g. 'com.nintendo.zaaa'
:param detailed: if True, sends request per app for its full ... | 4e3532f4b9d9f3857c67ada633576052bd2aef6a | 42,342 |
def gcd(x, y):
"""
greatest common divisor
"""
while y != 0:
(x, y) = (y, x % y)
return x | 5ed0e0cd20e6a73bca895fc4ea76ea65f71fb9f3 | 42,343 |
def parse_agent_req_file(contents):
"""
Returns a dictionary mapping {check-package-name --> pinned_version} from the
given file contents. We can assume lines are in the form:
datadog-active-directory==1.1.1; sys_platform == 'win32'
"""
catalog = {}
for line in contents.splitlines():
... | 7d3516327ffaf147ee85c150921c876ba5ee2980 | 42,344 |
def evaluate_metrics_stopping(model_list, metric_name, bigger_is_better, search_criteria, possible_model_number):
"""
This function given a list of dict that contains the value of metric_name will manually go through the
early stopping condition and see if the randomized grid search will give us the correct... | 69665b6b4406519075d029bbb86de38aacc98f31 | 42,345 |
def svn_wc_external_item2_create(*args):
"""svn_wc_external_item2_create(apr_pool_t pool) -> svn_error_t"""
return _wc.svn_wc_external_item2_create(*args) | ea103aff72e382d14440d638bbd3f4fecbe81665 | 42,346 |
def __get_recruiter_hamburger_menu_items():
"""
allows multiple templates to pull the same menu list items from one source of truth
Returns(str): html5 list elements for the hamburger menu
"""
return \
"<li><a href='/jobs'><span class='glyphicon glyphicon-briefcase'></span> Jobs</a... | 31556527b117d2fca8c86ae4750b63df7d9f34e2 | 42,347 |
def SampleSum(dists, n):
"""Draws a sample of sums from a list of distributions.
dists: sequence of Pmf or Cdf objects
n: sample size
returns: new Pmf of sums
"""
pmf = Pmf(RandomSum(dists) for i in range(n))
return pmf | 76dce20f47ebc598ca8ce007712b2abc15ce4a4f | 42,348 |
def transform(shape, from_crs, to_crs):
"""Transform a shape from one crs to another."""
project = partial(pyproj.transform, from_crs, to_crs)
return s_transform(project, shape) | 2ae02747dd75df7cf435ea2d8fe106ee270d326b | 42,349 |
from heapq import heappush, heappop
def optimum_policy2D():
"""
This algorithm keeps track of all the paths through the grid. It
always expands the least expensive path, thus avoiding unnecessary
work on paths that are too expensive to follow.
A path starts at the initial position. Each time a ne... | ef09e2a598ce3620c95246cb06a9843748c8cb7d | 42,350 |
def make_etag(hasher):
"""Build etag function based on `hasher` algorithm."""
def etag(buf):
h = hasher()
for chunk in buf:
h.update(chunk)
return '"' + h.hexdigest() + '"'
return etag | 31963ebacf886298a60e383d2a0c278293a59012 | 42,351 |
def Siamese(vocab_size=41699, d_model=128, mode='train'):
"""Returns a Siamese model.
Args:
vocab_size (int, optional): Length of the vocabulary. Defaults to len(vocab).
d_model (int, optional): Depth of the model. Defaults to 128.
mode (str, optional): 'train', 'eval' or 'predict', pre... | 85e0d572e5b39ef3ef907d01e082b507a3470997 | 42,352 |
def indexof(ilist, item):
""" returns the index of item in the list """
i = 0
for list_item in ilist:
list_item = list_item.strip()
if list_item == item:
return i
i += 1
print("ERROR failed to parse config, can't find item:", item)
exit(-4) | e6b24d8b6455433f7b6afd824045fbec0dfabfc6 | 42,353 |
def im(data):
"""
imshow puts eta (first axis) on y-axis inverts the y-axis resulting in a plot like
W |
|
eta |
|
E v -------->
N xi S
So flipping brings us to
W |
|
eta |
|
E v -------->
S xi N
And rotation to
N |
|
xi |
|
S v -------->
E xi W
"""
retur... | 4e173bb1c9fcc7708d7a3cf9e0cc5103bd4be7d9 | 42,354 |
def update_loc_dict(new_file_name, file_name="loc_dict"):
"""
Updates loc_dict with locations new file and saves it as python object.
:param new_file_name: string, name of file with new data
:param file_name: string, name of file to update, default "loc_dict"
:return loc_dict: dictionary, keys - loc... | 5167092aada49252643f1c3012c36213ff0ea6bc | 42,355 |
def make_1397(pc, target_list, skill_id, skill_lv, damage_list, color_list):
"""スキル使用結果通知(対象:自分)"""
if not target_list:
target_list = ()
damage_list = ()
color_list = ()
else:
assert len(target_list) == len(damage_list)
assert len(damage_list) == len(color_list)
i = len(target_list)
result = pack_short(s... | fd06bd507e930063495d4a1d91e17b47b5eb5cab | 42,356 |
def _contains(shape, x, y):
"""
Try to use the shape's contains method directly on XY.
Does not currently work on anything.
"""
raise NotImplementedError()
return shape.contains((x, y)) | 146178e2ac8101b306228a89de2d72493ec7a270 | 42,357 |
from typing import Optional
def _api_tier_validator(value: str) -> Optional[str]:
"""
Determines if input value is a valid API tier
"""
try:
KrakenAPITier(value.upper())
except ValueError:
return "No such Kraken API Tier." | 0d618afa4aff17ba3c4e1a097ac218976e777abf | 42,358 |
def ecdf(x):
""" Generate empirical CDF
"""
n = len(x)
xs = np.sort(x)
ys = np.arange(1, n+1)/n
return xs, ys | 41f990dbfdf2dcf80dcaaf8db6600f6c0f727bcd | 42,359 |
def _get_pyramid(img, num_scales, pooling_fn=tf.nn.avg_pool2d):
"""Generates a pyramid from the input image/tensor at different scales.
This function behaves similarly to `tfg.image.pyramid.split()`. Instead of
using an image resize operation, it uses average pooling to give each
input pixel equal weight in c... | 845c541901a448d0fb3cc3a042bd9f4f6d666954 | 42,360 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.