content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def make_word_dict():
"""read 'words.txt ' and create word list from it
"""
word_dict = dict()
fin = open('words.txt')
for line in fin:
word = line.strip()
word_dict[word] = ''
return word_dict | a4213cf5ff246200c7a55a6d1525d6fd6067e31f | 3,637,100 |
def voidobject(key_position: int, offset: int) -> HitObject:
"""
引数から判定のないヒットオブジェクト(シングルノーツのみ)のHitObjectクラスを生成します
引数
----
key_position : int
-> キーポジション、1から入れる場合はkey_assetから参照したものを入れてください
offset : int
-> (配置する)オフセット値
戻り値
------
HitObject
-> 空ノーツのHitObjectクラス
"""
return HitObject(key_position, max_off... | d7d47204bfb09592811fa85c4aa71e3e80bfa7bc | 3,637,101 |
def mock_user_save():
"""Функция-пустышка для эмуляции исключения во время записи пользователя."""
def user_save(*args, **kwargs):
raise IntegrityError
return user_save | 144ad41b9b9a2d477d622b6c2284c36514581ea1 | 3,637,102 |
def index():
"""首页"""
banners = Banner.query_used()
page = request.args.get("page", 1, type=int) # 指定的页码
per_page = current_app.config["MYZONE_ARTICLE_PER_PAGE"] # 每页的文章数
pagination = Article.query_order_by_createtime(page, per_page=per_page) # 创建分页器对象
articles = pagination.items # 从分页器中获取查询... | ba3f6a558e4edb60025ef01832bb5ff5a1fb7f7a | 3,637,103 |
def create_temporal_vis(ldf, col):
"""
Creates and populates Vis objects for different timescales in the provided temporal column.
Parameters
----------
ldf : lux.core.frame
LuxDataFrame with underspecified intent.
col : str
Name of temporal column.
Returns
----... | 9a52600c1aac10a76b85b63c2879341dcc14b415 | 3,637,104 |
from collections import Iterable
import numpy
import os
def load(inputs):
"""load(inputs) -> data
Loads the contents of a file, an iterable of files, or an iterable of
:py:class:`bob.io.base.File`'s into a :py:class:`numpy.ndarray`.
**Parameters:**
``inputs`` : various types
This might represent sev... | f8b8e258dd15cdcd911e90c501c3d6ccf8c07aea | 3,637,105 |
def num_neighbours(skel) -> np.ndarray:
"""Computes the number of neighbours of each skeleton pixel.
Parameters
----------
skel : (H, W) array_like
Input skeleton image.
Returns
-------
(H, W) array_like
Array containing the numbers of neighbours at each skeleton pixel and ... | aad9f1de0f192777ebc41e603cd6ac47aa3cd49f | 3,637,106 |
def FakeSubject(n=300, conc=0.1, num_reads=400, prevalences=None):
"""Makes a fake Subject.
If prevalences is provided, n and conc are ignored.
n: number of species
conc: concentration parameter
num_reads: number of reads
prevalences: numpy array of prevalences (overrides n and conc)
"... | 91230288344c55cd4417175560ec7b3e714d9f98 | 3,637,107 |
from datetime import datetime
import pytz
def build_results_candidate_people():
"""
Return DataFrame containing results, candidates, and people joined
"""
people = pd.read_csv('data/people.csv')
candidates = pd.read_csv('data/candidates.csv')
results = pd.read_csv('data/results.csv')
res... | 5e330b026b3546e728f9a06df33eaf8fc429775c | 3,637,108 |
def div(lhs: Value, rhs: Value) -> Value:
""" Divides `lhs` by `rhs`. """
return lhs.run() // rhs.run() | 73cb05b536c94e56331054e92e7d9fb84f75fdb5 | 3,637,109 |
def get_seat_total_per_area(party_id: PartyID) -> dict[AreaID, int]:
"""Return the number of seats per area for that party."""
area_ids_and_seat_counts = db.session \
.query(
DbArea.id,
db.func.count(DbSeat.id)
) \
.filter_by(party_id=party_id) \
.outerjoi... | 35aced1f8e149a06f54ed43f41b80f796608316b | 3,637,110 |
def toCamelCase(string: str):
"""
Converts a string to camel case
Parameters
----------
string: str
The string to convert
"""
string = str(string)
if string.isupper():
return string
split = string.split("_") # split by underscore
final_split = []
for... | 5197ad3353f2e88ccf1dfca62aeae59260e016e7 | 3,637,111 |
def aggregate_testsuite(testsuite):
""" Compute aggregate results for a single test suite (ElemTree node)
:param testsuite: ElemTree XML node for a testsuite
:return: AggregateResult
"""
if testsuite is None:
return None
tests = int(testsuite.attrib.get('tests') or 0)
failures = int... | 3b7ff5b353e0f6efffed673e1dcb463f00a0e708 | 3,637,112 |
def rowwidth(view, row):
"""Returns the number of characters of ``row`` in ``view``.
"""
return view.rowcol(view.line(view.text_point(row, 0)).end())[1] | f8db1bf6e3d512d1a2bd5eeb059af93e8ac3bc5f | 3,637,113 |
import sys
from SocketServer import BaseServer
from socketserver import BaseServer
from wsgiref import handlers
def patch_broken_pipe_error():
"""
Monkey patch BaseServer.handle_error to not write a stack trace to stderr
on broken pipe: <http://stackoverflow.com/a/22618740/362702>
"""
try:
exc... | ababd5aea1d5f5f18bb6d087b972971c98bc979f | 3,637,114 |
import json
def dry_query(event, *args):
"""Handles running a dry query
Args:
url: dry_query?page&page_length&review_id
body:
search: search dict <wrapper/input_format.py>
Returns:
{
<wrapper/output_format.py>
}
"""
# try:
body = json.l... | 0c69da353d958e9628e31dce68fe6bcafd482f2c | 3,637,115 |
def fixed_prior_to_measurements(coords, priors):
"""
Convert the fixed exchange and met conc priors to measurements.
"""
fixed_exchange = get_name_ordered_overlap(coords, "reaction_ind", ["exchange", "fixed_x_names"])
fixed_met_conc = get_name_ordered_overlap(coords, "metabolite_ind", ["metabolite",... | 3dab3eddb5f785dd04bba4caddbc631a0cdfd187 | 3,637,116 |
def get_batch_size():
"""Returns the batch size tensor."""
return get_global_variable(GraphKeys.BATCH_SIZE) | 4b030738c78fa5a06d27a2aee62f15ff3e6be347 | 3,637,117 |
from altdataset import CSVDataset
def get_dataloader(config: ExperimentConfig, tfms: Tuple[List, List] = None):
""" get the dataloaders for training/validation """
if config.dim > 1:
# get data augmentation if not defined
train_tfms, valid_tfms = get_data_augmentation(config) if tfms is None e... | d314a0bf6f7c9707ce46127e06bc8c22183246f1 | 3,637,118 |
def retournerTas(x,numéro):
"""
retournerTas(x,numéro) retourne la partie du tas x qui commence à
l'indice numéro
"""
tasDuBas = x[:numéro]
tasDuHaut = x[numéro:]
tasDuHaut.reverse()
result = tasDuBas + tasDuHaut
# print(result)
return result | 579798cf5fe8bec02109bfd46c5a945faee1a42c | 3,637,119 |
import configparser
import os
def path_complete(self, text, line, begidx, endidx):
"""
Path completition function used in various places for tab completion
when using cmd
"""
arg = line.split()[1:]
# this is a workaround to get default extension into the completion function
# may (hopeful... | 11ac96eea265afbeb36e79d088a3e14bbc60fdd8 | 3,637,120 |
def nback(n, k, length):
"""Random n-back targets given n, number of digits k and sequence length"""
Xi = random_state.randint(k, size=length)
yi = np.zeros(length, dtype=int)
for t in range(n, length):
yi[t] = (Xi[t - n] == Xi[t])
return Xi, yi | 37ec70fdc60104fc5a99c6ba13923a2e3d56f0a4 | 3,637,121 |
def makeStateVector(sys, start_time=0):
"""
Constructs the initial state vector recursively.
Parameters
----------
sys: inherits from control.InputOutputSystem
start_time: float
Returns
-------
list
"""
x_lst = []
if "InterconnectedSystem" in str(type(sys)):
for... | e184d476c9ba94d88ee462c95987cabc31e459d0 | 3,637,122 |
def make_random_tensors(spec_structure, batch_size = 2):
"""Create random inputs for tensor_spec (for unit testing).
Args:
spec_structure: A dict, (named)tuple, list or a hierarchy thereof filled by
TensorSpecs(subclasses).
batch_size: If None, we will have a flexible shape (None,) + shape. If <= 0
... | dd2569def0863b1e9722de9c6175e680353ccf56 | 3,637,123 |
def simulate(robot, task, opt_seed, thread_count, episode_count=1):
"""Run trajectory optimization for the robot on the given task, and return the
resulting input sequence and result."""
robot_init_pos, has_self_collision = presimulate(robot)
if has_self_collision:
return None, None ... | 13c069282636e7b4215654d958621ed418bc40a8 | 3,637,124 |
import time
def config_worker():
"""
Enable worker functionality for AIO system.
:return: True if worker-config-complete is executed
"""
if utils.get_system_type() == si_const.TIS_AIO_BUILD:
console_log("Applying worker manifests for {}. "
"Node will reboot on completio... | 4ab82a2988a70ec9fe2f2ab6aa45099b7237b07a | 3,637,125 |
def convert_dict_to_df(dict_data: dict):
"""
This method is used to convert dictionary data to pandas data frame
:param dict_data:
:return:
"""
# create df using dict
dict_data_df = pd.DataFrame.from_dict([dict_data])
# return the converted df
return dict_data_df | 550e33b0b3bacbdfb3abeb8019296be2c647000e | 3,637,126 |
def sec2msec(sec):
"""Convert `sec` to milliseconds."""
return int(sec * 1000) | f1b3c0bf60ab56615ed93f295e7716e56c6a1117 | 3,637,127 |
import aiohttp
async def _request(session:aiohttp.ClientSession, url:str, headers:dict[str,str]) -> str:
"""
获取单一url的愿望单页面
"""
async with session.get(url=url, headers=headers, proxy=PROXY) as resp:
try:
text = await resp.text()
except Exception as err:
text = ""... | f891736d4598adc0005c096e12ab43d41544ab36 | 3,637,128 |
def get_pretrained_i2v(name, model_dir=MODEL_DIR):
"""
Parameters
----------
name
model_dir
Returns
-------
i2v model: I2V
"""
if name not in MODELS:
raise KeyError(
"Unknown model name %s, use one of the provided models: %s" % (name, ", ".join(MODELS.keys(... | 75657f039763ae73219eae900061a426ed2b11fd | 3,637,129 |
def object_get_HostChilds(obj):
"""Return List of Objects that have set Host(s) to this object."""
# source:
# FreeCAD/src/Mod/Arch/ArchComponent.py
# https://github.com/FreeCAD/FreeCAD/blob/master/src/Mod/Arch/ArchComponent.py#L1109
# def getHosts(self,obj)
hosts = []
for link in obj.InLis... | dccba2ef151207ebaa42728ee1395e1b0ec48e7d | 3,637,130 |
import torch
def collate_fn(batch):
"""
Collate function for combining Hdf5Dataset returns
:param batch: list
List of items in a batch
:return: tuple
Tuple of items to return
"""
# batch is a list of items
numEntries = [];
allTensors = [];
allLabels = [];
for... | b49ec88b4de844787d24140f5ef99ad9a573c6e3 | 3,637,131 |
def test_psf_estimation(psf_data, true_psf_file, kernel=None, metric='mean'):
"""Test PSF Estimation
This method tests the quality of the estimated PSFs
Parameters
----------
psf_data : np.ndarray
Estimated PSFs, 3D array
true_psf_file : str
True PSFs file name
kernel : int... | 10feef6a483cfa6345561dcf5d1717a466a78c7d | 3,637,132 |
def EulerBack(V_m0,n_0,m_0,h_0,T,opcion,t1,t2,t3,t4,I1,I2,h_res=0.01):
"""
:param V_m0: Potencial de membrana inicial
:param n_0: Probabilidad inicial de n
:param m_0: Probabilidad inicial de m
:param h_0: Probabilidad inicial de h
:param T: Temperatura indicada por el usuario
:param opcion:... | 33660894f80d3060206da3ddbb96d40b8453fc72 | 3,637,133 |
def wiggle(shape, scope, offset, seed=0):
"""Shift points/contours/paths by a random amount."""
if shape is None: return None
functions = { "points": wiggle_points,
"contours": wiggle_contours,
"paths": wiggle_paths}
fn = functions.get(scope)
if fn is None: retu... | 0cd587646013810ca512de5d327c2fdc24b110f5 | 3,637,134 |
def parseAndDisplay(line, indentLevel):
"""Indents lines."""
if line.startswith("starting "):
printArgumentLine(indentLevel, line)
indentLevel += 1
elif line.startswith("ending "):
indentLevel -= 1
printArgumentLine(indentLevel, line)
else:
printLine(indentLevel, ... | 14c9ebe27140aa77f5f7980e1da2bec30e7ccf8b | 3,637,135 |
def insert_question(question):
"""
Insert a particular question
@param: question - JSON object containing question data to be inserted
"""
return db.questions.insert_one(question) | f4d22a137a1e7d9fbe43a1e03414d551cceb27c9 | 3,637,136 |
def sequence_vectorize(train_texts, val_texts):
"""Vectorizes texts as sequence vectors.
1 text = 1 sequence vector with fixed length.
# Arguments
train_texts: list, training text strings.
val_texts: list, validation text strings.
# Returns
x_train, x_val, word_index: vectoriz... | f32c40ca2f8bc6d2c78f8093ccf94fee192b87c8 | 3,637,137 |
def parse_preferences(file, preferences):
"""Parse preferences to the dictionary."""
for line in open(file, "r").readlines():
# all lower case
line = line.lower()
# ignore comment lines
if line[0] == "!" or line[0] == "#" or not line.split():
continue
key ... | 09c0251cd34cfbb6c9342eccd697a08259c744c6 | 3,637,138 |
def func_hex2str(*args):
"""字符串 -> Hex"""
return func_hex2byte(*args).decode('utf-8') | 732f333cd942ecd8bee4ac4b974f0301e0c69baf | 3,637,139 |
import os
def warm_since():
"""Return the date when the current warm version of the fn started.
"""
if is_warm() == 'warm':
ts = os.path.getmtime(warm_file())
return ts | e46ddfdcb24ede5e5754ec7d61d34ff82f6a1b88 | 3,637,140 |
import collections
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
with open(vocab_file, "r", encoding="utf-8") as reader:
tokens = reader.readlines()
for index, token in enumerate(tokens):
token = token.rstrip("\n")
vocab[token] = ind... | 801833664a67e5d6e62dfb5379cabeb1b1b5058c | 3,637,141 |
from typing import List
def triage(routes: List[Route]) -> Route:
"""
This function will be used to determine which route to use
"""
eva = {}
for i, route in enumerate(routes):
stored_route: StoredRoute = route.pop("stored_route")
reg_path = stored_route["path"]
segments = ... | 625b143c3284526b71d21a7c0113e892df92ed3a | 3,637,142 |
def upsert_object(data, cursor=None):
"""
Upsert an object in the repository.
"""
cursor = check_cursor(cursor)
data = _set_object_defaults(data, cursor)
cursor.execute('''
INSERT INTO objects (pid_id, namespace, state, owner, label, versioned,
log, created,... | de0de4a48bf4f1d846938e174bb5a5300dd49083 | 3,637,143 |
import torch
def sparsity_line(M,tol=1.0e-3,device='cpu'):
"""Get the line sparsity(%) of M
Attributes:
M: Tensor - the matrix.
tol: Scalar,optional - the threshold to select zeros.
device: device, cpu or gpu
Returns:
spacity: Scalar (%)- the spacity of the matr... | b8675a768c8686571d1f7709d89e3abeb5b56a80 | 3,637,144 |
def geospace(lat0, lon0, length, dx, strike):
""" returns a series of points in geographic coordinates"""
pts_a = []
npts = length // dx + 1
for idx in range(npts):
# convert to lat, lon
new = convert_local_idx_to_geo(idx, lat0, lon0, length, dx, strike)
pts_a.append(new)
ret... | 78a380b59768cf83eca8edba5f1e21a0b6b61636 | 3,637,145 |
def linearOutcomePrediction(zs, params_pred, scope=None):
"""
English:
Model for predictions outcomes from latent representations Z,
zs = batch of z-vectors (encoder-states, matrix)
Japanese:
このモデルにおける、潜在表現Zから得られる出力の予測です。
zs = ベクトル z のバッチ(袋)です。 (encoder の状態であり、行列です)
(恐らく、[z_0, z_1, z_2, ... | 3e92fe0c0d16d8565066216c1da96b6fdbeb8dc9 | 3,637,146 |
from datetime import datetime
import collections
def _check_flag_value(flag_value):
"""
Search for a given flag in a given blockette for the current record.
This is a utility function for set_flags_in_fixed_headers and is not
designed to be called by someone else.
This function checks for valid ... | 2e4da676ad7abf95aa157aaca5aae80975b893e2 | 3,637,147 |
def logout():
""" Logout a user """
session.pop('user_id', None)
session.pop('player_id', None)
return redirect(url_for('index')) | d7d375e28a3e432c42b845cccf0adecb37cf46e1 | 3,637,148 |
def get_available_gpus():
"""Returns a list of available GPU devices names. """
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == "GPU"] | 9c62204fa1bdc8ad22fd56ecad14bde895a08ec6 | 3,637,149 |
import math
def tgamma ( x ) :
"""'tgamma' function taking into account the uncertainties
"""
fun = getattr ( x , '__tgamma__' , None )
if fun : return fun()
return math.gamma ( x ) | 35c73e2e0a9945cb38beffb6376dd7b7bc6443e9 | 3,637,150 |
def detect_peaks_by_channel(traces, peak_sign, abs_threholds, n_shifts):
"""Detect peaks using the 'by channel' method."""
traces_center = traces[n_shifts:-n_shifts, :]
length = traces_center.shape[0]
if peak_sign in ('pos', 'both'):
peak_mask = traces_center > abs_threholds[None, :]
f... | c5024e73e103ba50c6d011067849eafb519d7ca7 | 3,637,151 |
def multi_gauss_psf_kernel(psf_parameters, BINSZ=0.02, NEW_BINSZ=0.02, **kwargs):
"""Create multi-Gauss PSF kernel.
The Gaussian PSF components are specified via the
amplitude at the center and the FWHM.
See the example for the exact format.
Parameters
----------
psf_parameters : dict
... | 07705bcebb02c622c8f1a4cddcad8781ebfa08fa | 3,637,152 |
from typing import List
from typing import Optional
from typing import Union
def Wavefunction( # type: ignore # pylint: disable=function-redefined
param: List[List[int]],
broken: Optional[Union[List[str], str]] = None) -> 'Wavefunction':
"""Initialize a wavefunction through the fqe namespace
... | d5646e26c908c2c824095f20e82cf9418c6115a6 | 3,637,153 |
def extractFiles(comment):
"""Find all files in a comment.
@param comment: The C{unicode} comment text.
@return: A C{list} of about values from the comment, with no duplicates,
in the order they appear in the comment.
"""
return uniqueList(findall(FILE_REGEX, comment)) | af795598e9f5be973d0e7df771d11d064590881f | 3,637,154 |
def showModelsStatic(ptcode,codes, vols, ss, mm, vs, showVol, clim, isoTh, clim2,
clim2D, drawMesh=True, meshDisplacement=True, drawModelLines=True,
showvol2D=False, showAxis=False, drawVessel=False, vesselType=1,
meshColor=None, **kwargs):
""" show one to four models in multipanel figure.
Input:... | ca596d74af7e826c3efdee9e8ffaf192b85e1703 | 3,637,155 |
def rint_compute(input_x):
"""rint compute implementation"""
res = akg.lang.cce.round(input_x)
res = akg.lang.cce.cast_to(res, input_x.dtype)
return res | f1797518d6b4a7d117ee894c5c0ff26bb4eb09f9 | 3,637,156 |
def _solequal(sol1, sol2, prec):
"""
Compare two different solutions with a given precision.
Return True if they equal.
"""
res = True
for sol_1, sol_2 in zip(sol1, sol2):
if np.ndim(sol_1) != 0 and np.ndim(sol_2) != 0:
res &= _dist(sol_1, sol_2) < prec
elif np.ndim... | 29361d34cf1d1703fa60c8df77132d15e4e1e849 | 3,637,157 |
import os
def get_template_filepath(filename, basepath="templates"):
"""
Get the full path to the config templates, using a relative path to where the shippy script is stored
:param filename: (str) Name of the template file to look for
:param basepath: (str) Base directory to search for templates. De... | f1972c3366590449d9d747b1d03153e6fb0f1f2b | 3,637,158 |
def clip_rows(data, ord=2, L=1):
"""
Scale clip rows according the same factor to ensure that the maximum value of the
norm of any row is L
"""
max_norm = get_max_norm(data, ord=ord)
print("For order {0}, max norm is {1}".format(ord, max_norm))
normalized_data = data.copy()
modified = ... | 64ed166a88eee193f5b6c157bb2d0f37f02af150 | 3,637,159 |
from typing import Pattern
def extrapolate_to_zero_linear(pattern):
"""
Extrapolates a pattern to (0, 0) using a linear function from the most left point in the pattern
:param pattern: input Pattern
:return: extrapolated Pattern (includes the original one)
"""
x, y = pattern.data
step = x[... | ca148be4a104a0eaff5b765de3a847bdf9c052be | 3,637,160 |
import random
def findKthSmallest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def partition(left, right, pivot_index):
pivot = nums[pivot_index]
# 1. move pivot to end
nums[pivot_index], nums[right] = nums[right], nums[pivot_index]
... | d82176bd9539cf36416c5dc3c7da53a99f2a8f62 | 3,637,161 |
def racetrack_AP_RR_TF(
wavelength,
sw_angle=90,
radius=12,
couplerLength=4.5,
gap=0.2,
width=0.5,
thickness=0.2,
widthCoupler=0.5,
loss=[0.99],
coupling=[0],
):
"""This particular transfer function assumes that the coupling sides of the
ring resonator are straight, and t... | e6bc912970333b901bf70e573a8b9194f6255de5 | 3,637,162 |
import os
def _get_event_data(tr, tt_model, phase, acc_type, depth_unit="km"):
"""
Update a sac trace to a obspy trace and update trace header,
and calculate theoretical traveltime of a specific model and phase
:param tr:
:param tt_model:
:param phase:
:param acc_type:
:param depth_un... | b967626328b1348f83882ac8a253c858a43ecdd5 | 3,637,163 |
from typing import Union
from typing import Iterator
import tqdm
def consume_chunks(generator: Union[PandasTextFileReader, Iterator], progress: bool = True, total: int = None):
"""Transform the result of chained filters into a pandas DataFrame
:param generator: iterator to be transformed into a dataframe
... | 60198262341e9bd6dd5170cb98439c5b9975a238 | 3,637,164 |
def lang_not_found(s):
"""Is called when the language files aren't found"""
return s + "⚙" | 064d73e10d6e2aa9436557b38941ed2eb020d7bb | 3,637,165 |
def _get_corr_matrix(corr, rho):
"""Preprocessing of correlation matrix ``corr`` or
correlation values ``rho``.
Given either ``corr`` or ``rho`` (each may be an array,
callable or process instance), returns the corresponding,
possibly time-dependent correlation matrix,
with a ``shape`` attribut... | 8241c0245cbd4b8554c31deb28179556c9da8cd1 | 3,637,166 |
import copy
def init_lqr(hyperparams):
"""
Return initial gains for a time-varying linear Gaussian controller
that tries to hold the initial position.
"""
config = copy.deepcopy(INIT_LG_LQR)
config.update(hyperparams)
x0, dX, dU = config['x0'], config['dX'], config['dU']
dt, T = confi... | a1afcfecc263674856d662b6fe8023b9bf6bda90 | 3,637,167 |
def sequence_exact_match(true_seq, pred_seq):
"""
Boolean return value indicates whether or not seqs are exact match
"""
true_seq = strip_whitespace(true_seq)
pred_seq = strip_whitespace(pred_seq)
return pred_seq["start"] == true_seq["start"] and pred_seq["end"] == true_seq["end"] | 574ad0a7ad0a31875c298824fc1230bdf662f356 | 3,637,168 |
def same_variable(a, b):
"""
Cette fonction dit si les deux objets sont en fait le même objet (True)
ou non (False) s'ils sont différents (même s'ils contiennent la même information).
@param a n'importe quel objet
@param b n'importe quel objet
@return ``True`` ... | 0c33a33e01e5457c7216982df580abc90db47d2f | 3,637,169 |
def format_level_2_memory(memory, header=None):
"""Format an experiment result memory object for measurement level 2.
Args:
memory (list): Memory from experiment with `meas_level==2` and `memory==True`.
header (dict): the experiment header dictionary containing
useful information fo... | ebb8b0ca2e34ac93aaec01efe05a8a4d5de785d5 | 3,637,170 |
from .objectbased.conversion import to_polar
def convert_objects_to_polar(rendering_items):
"""Apply conversion to turn all Objects block formats into polar."""
return list(apply_to_object_blocks(rendering_items, to_polar)) | df7206530e60d3765b1eaf7a3d6b45a41efc50c0 | 3,637,171 |
from typing import Tuple
import ast
def find_in_module(var_name: str, module, i: int = 0) -> Tuple[str, ast.AST]:
"""Find the piece of code that assigned a value to the variable with name *var_name* in the
module *module*.
:param var_name: Name of the variable to look for.
:param module: Module to se... | 7cb6e6bd17018e72953273e53c2fe5f9ac73f2c2 | 3,637,172 |
def empty(shape,
dtype="f8",
order="C",
device=None,
usm_type="device",
sycl_queue=None):
"""Creates `dpnp_array` from uninitialized USM allocation."""
array_obj = dpt.empty(shape,
dtype=dtype,
order=order,
... | 3229a4a99a1073c9bee636d630a818d5c91a3c97 | 3,637,173 |
def solve2(input_data):
"""use scipy.ndimage"""
data_array = np.array(parse(input_data))
# boundaries of objects must be 0 for scipy label
# convert 0 in data to -1 and 9 to 0
data_array[data_array == 0] = -1
data_array[data_array == 9] = 0
labels, _ = label(data_array)
_, counts = n... | 0ba8767020388c33a068b10f89b9cacd51f9e85d | 3,637,174 |
import math
def yolox_semi_warm_cos_lr(
lr,
min_lr_ratio,
warmup_lr_start,
total_iters,
normal_iters,
no_aug_iters,
warmup_total_iters,
semi_iters,
iters_per_epoch,
iters_per_epoch_semi,
iters,
):
"""Cosine learning rate with warm up."""
min_lr = lr * min_lr_ratio
... | ac6b1850031a5c36f8de2c7597c374bc401aaee3 | 3,637,175 |
def builder(obj, dep, denominator=None):
""" A func that modifies its obj without explicit return. """
def decorate(func):
tasks.append(Builder(func, obj, dep, denominator))
return func
return decorate | 8b9d9887324c6aa931efcf905db56ded606c6d84 | 3,637,176 |
import json
import phantom.rules as phantom
import re
def regex_split(input_string=None, regex=None, strip_whitespace=None, **kwargs):
"""
Use a regular expression to split an input_string into multiple items.
Args:
input_string (CEF type: *): The input string to split.
regex: The reg... | 88cf444895792d5f8077485357b510554c4845f1 | 3,637,177 |
def on_segment(p, r, q, epsilon):
"""
Given three colinear points p, q, r, and a threshold epsilone, determine if
determine if point q lies on line segment pr
"""
# Taken from http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment
cr... | b8517fc9d3c6d916cac698913c35ba4e5d873697 | 3,637,178 |
def groupby_times(df, kind, unit=None):
"""Groupby specific times
Parameters
----------
df : pandas.DataFrame
DataFrame with `pandas.TimedeltaIndex` as index.
kind : {'monthly', 'weekly', 'daily', 'hourly', 'minutely', 'all'}
How to group `df`.
unit : str (optional)
What... | 81d5a17e3f89b36a0ce88867ce6d04cd1602a0b4 | 3,637,179 |
def pid_to_path(pid):
"""Returns the full path of the executable of a process given its pid."""
ps_command = "ps -o command " + pid
ps_output = execute(ps_command)
command = get_command(ps_output)
whereis_command = "whereis " + command
whereis_output = execute(whereis_command)
path = get_path(whe... | 942a5756f9b4aecb51472efce558f86d0b9c8d67 | 3,637,180 |
def get_script_histogram(utext):
"""Return a map from script to character count + chars, excluding some common
whitespace, and inherited characters. utext is a unicode string."""
exclusions = {0x00, 0x0A, 0x0D, 0x20, 0xA0, 0xFEFF}
result = {}
for cp in utext:
if ord(cp) in exclusions:
... | 657e60bc1a8d6c7b436cf4f8700041abe41721ea | 3,637,181 |
def ja_nein_vielleicht(*args):
"""
Ohne Argumente erstellt diese Funktion eine Ja-Nein-Vielleicht Auswahl. Mit
einem Argument gibt es den Wert der entsprechenden Auswahl zurück.
"""
values = {
True: "Vermutlich ja",
False: "Vermutlich nein",
None: "Kann ich noch nicht sagen"
... | a4e58ab3f2dc9662e1c054ddfd32ff1ae988b438 | 3,637,182 |
def ebic(covariance, precision, n_samples, n_features, gamma=0):
"""
Extended Bayesian Information Criteria for model selection.
When using path mode, use this as an alternative to cross-validation for
finding lambda.
See:
"Extended Bayesian Information Criteria for Gaussian Graphical Mode... | e5183ee7a4b0f4edc7509afb7217e4203a73919a | 3,637,183 |
def _process_cli_plugin(bases, attrdict) -> dict:
"""Process a CLI plugin, generate its hook functions, and return a new
attrdict with all attributes set correctly.
"""
attrdict_copy = dict(attrdict) # copy to avoid mutating original
if cli.Command in bases and cli.CommandExtension in bases:
... | 999f5011532ae67626ff5a7f416efcfad447c127 | 3,637,184 |
def get_group(yaml_dict):
"""
Return the attributes of the light group
:param yaml_dict:
:return:
"""
group_name = list(yaml_dict["groups"].keys())[0]
group_dict = yaml_dict["groups"][group_name]
# Check group_dict has an id attribute
if 'id' not in group_dict.keys():
prin... | db9e027594d3a9a9e0a1838da62316cfe6e0c380 | 3,637,185 |
def plot_time(
monitors,
labels,
savefile,
title="Average computation time per epoch",
ylabel="Seconds",
log=False,
directory=DEFAULT_DIRECTORY,
):
"""Plots the computation time required for each step as a horizontal bar
plot
:param monitors: a list of monitor sets: [(training,... | 7723be1933bd9f2dd84e1ebec7364b4cbe942601 | 3,637,186 |
def average_gradients(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradi... | fc2a8692046fe32884cb75d405d21fce6301a88d | 3,637,187 |
def recommend(model):
"""
Generate n recommendations.
:param model: recommendation model
:return: tuple(recommendations made by model, recommendations made by primitive model, recall, coverage)
"""
n = 10
hit = 0 # used for recall calculation
total_recommendations = 0
all_recommend... | 07d5e538cbfafd60bee7030fd31e6c9b5d178cfa | 3,637,188 |
def GetTrace(idp_name, package_name, version, launcher_activity, proxy_port, \
change_account=True, with_access_token=True, revoke_access_token=True, reset=False, \
uiconfig='uiaction.json', user='Eve1', port='4723', system_port=8200, tracefile='eveA.trace', \
emulator_name=None, snapshot_tag=None):
"""... | 5d4d02046ff7042e4a40becaccf85761d7f725b6 | 3,637,189 |
def drop_nondominant_term(latex_dict: dict) -> str:
"""
given
x = \\langle\\psi_{\\alpha}| \\hat{A} |\\psi_{\\beta}\\rangle
return
x = \\langle\\psi_{\\alpha}| a_{\\beta} |\psi_{\\beta} \\rangle
>>> latex_dict = {}
>>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]... | 6f53dcce5e17761d6ab9f7f0a772dcd81d91b33e | 3,637,190 |
def template_introduce():
"""
This function constructs three image carousels for self introduction.
Check also: faq_bot/model/data.py
reference
- `Common Message Property <https://developers.worksmobile.com/kr/document/100500805?lang=en>`_
:return: image carousels type message content.... | f0b6585512b8419932c1be38831057508a4454eb | 3,637,191 |
def assign_distance_to_mesh_vertex(vkey, weight, target_LOW, target_HIGH):
"""
Fills in the 'get_distance' attribute for a single vertex with vkey.
Parameters
----------
vkey: int
The vertex key.
weight: float,
The weighting of the distances from the lower and the upper target, ... | 5859ef6535d394d098a92603b2a3e6ac7c619e51 | 3,637,192 |
import hashlib
def _get_user_by_email_or_username(request):
"""
Finds a user object in the database based on the given request, ignores all fields except for email and username.
"""
if 'email_or_username' not in request.POST or 'password' not in request.POST:
raise AuthFailedError(_('There was... | 7bf8ced15acd226b647f0b2e272699c41c3432bc | 3,637,193 |
def timer(save=False, precision=3):
""" Timer Decorator with Logging """
def decorator(function):
@wraps(function)
def inner(*args, **kwargs):
start = default_timer()
value = function(*args, **kwargs)
end = default_timer()
if save:
... | c7331dfb8528ffd1694fed6c98652309a0650307 | 3,637,194 |
def get_minsize_assignment(N, min_comm_size):
"""Create membership vector where each community contains at least
as a certain number of nodes.
Parameters
----------
N : int
Desired length of membership vector
min_comm_size : int
Minimum number of nodes each community should have... | e708b81a2b16d9885a0625d275fedcf001308c00 | 3,637,195 |
def _combine_plots(
p1, p2, combine_rules=None,
sort_plot=False, sort_key=lambda x_y: x_y[0]
):
"""Combine two plots into one, following the given combine_rules to
determine how to merge the constants
:param p1: 1st plot to combine
:param p2: 2nd plot to combine
:param combine_rules:... | 93665498ba30af51020300f774ba5f0cfc2684ce | 3,637,196 |
def shape_of(array, *, strict=False):
"""
Return the shape of array. (sizes of each dimension)
"""
shape = []
layer = array
while True:
if not isinstance(layer, (tuple, list)):
break
size = len(layer)
shape.append(size)
if not size:
break
... | c6e889338761897c1e036bef29cd73bd430608aa | 3,637,197 |
def return_state_dict(network):
"""
save model to state_dict
"""
feat_model = {k: v.cpu() for k, v in network["feat_model"].state_dict().items()}
classifier = {k: v.cpu() for k, v in network["classifier"].state_dict().items()}
return {"feat_model": feat_model, "classifier": classifier} | c0bcd9bd84f7c722c7de5f52d12cf6762a86e1e0 | 3,637,198 |
def get_elevation_data(lonlat, dem_path):
"""
Get elevation data for a scene.
:param lon_lat:
The latitude, longitude of the scene center.
:type lon_lat:
float (2-tuple)
:dem_dir:
The directory in which the DEM can be found.
:type dem_dir:
str
"""
datafi... | b7876bbae41bb6fbadbeff414485a2edff2646bf | 3,637,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.