content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def generate_strokes_until_ambiguity(skeleton_image, pixel, minimum_length = 10):
"""Generates an stroke until ambiguity, unless the current length is less than a predefined length threshold"""
former_skeleton = skeleton_image.copy()
ambiguity_pixel = None
stroke_history = []
stroke_history.append(p... | ab733969446791ab8f7e035204e2c5040529ae36 | 72,511 |
def init_subplot(fig=None, subplot_index=None, is_3d=False):
"""Initialize subplot (given position or automatic stacking)
Parameters
----------
fig : Matplotlib.figure.Figure
The figure to get the handle from (can be None)
subplot_index : int
Index of the subplot, or None
is_3d ... | d228bcec3c9b7a0173a79b4810fadc0e34013563 | 72,512 |
def create_usstock_bundle(code, sids=None, universes=None, free=False, data_frequency=None):
"""
Create a Zipline bundle for US stocks.
This function defines the bundle parameters but does not ingest the actual
data. To ingest the data, see `ingest_bundle`.
Parameters
----------
code : str... | 00b93a490de6030c878f9e7742f4db1fa6083c77 | 72,513 |
import time
from datetime import datetime
def train():
"""Train classification for a number of steps."""
with tf.Graph().as_default():
# Returns and create (if necessary) the global step tensor.
global_step = tf.train.get_or_create_global_step()
# Get images and labels for datasets.
... | ba9e09da094cc63340a4fc06679a621fceedd53a | 72,514 |
def _verify_ffsn_input(x, T, T_c, N_FS, axes):
"""
Verify input values to :py:func:`~pyffs.ffs.ffsn`,
:py:func:`~pyffs.ffs.iffsn`, and return axes values.
Parameters
----------
x : :py: class: `~numpy.ndarray`
(..., N_s1, N_s2, ..., N_sD, ...) input values; either for FFSn or iFFSn.
... | d537d27501a63a8e70c1bcfd5c358cdcc0efad2c | 72,516 |
async def read_doujin(digits: int):
"""Get doujin data by digits."""
doujin = get_doujin(digits)
return doujin | 048274ef2acceebb8cec22579bbea4b82a95dd3b | 72,517 |
def popen4(cmd, mode='r', bufsize=0):
"""Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
child_stdout_and_stderr)``."""
return (__file_object, __file_object) | 06de122386d2f12c5731d67afa9c653fb797231f | 72,519 |
def federated_secure_select(client_keys, max_key, server_val, select_fn):
"""Sends privately-selected values from a server database to clients.
Args:
client_keys: `tff.CLIENTS`-placed one-dimensional fixed-size `int32` keys
used to select values from `database` to load for each client.
max_key: A `t... | bc54f675db13bd6036477877ee68221d6f71b301 | 72,520 |
from pathlib import Path
def test_log_path_(test_app_data_dir) -> Path:
"""Make a test-log directory under the app data directory"""
log_path = test_app_data_dir / Path("test-logs")
print(f"Logging at: {log_path}")
return log_path | c2cf7d51e9c7736cc1d442359cd79684b7f12ccd | 72,522 |
def _List(requests, http, batch_url, errors):
"""Makes a series of list and/or aggregatedList batch requests.
Args:
requests: A list of requests to make. Each element must be a 3-element tuple
where the first element is the service, the second element is the method
('List' or 'AggregatedList'), and... | c985827b508845d31ec8bb65ba61ec5205b532c0 | 72,523 |
def res2net50_48w_2s(pretrained=False, **kwargs):
"""Constructs a Res2Net-50_48w_2s model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = Res2Net(Bottle2neck, [3, 4, 6, 3], baseWidth = 48, scale = 2, **kwargs)
if pretrained:
model.load_state_dic... | 5e163a4269c09799660fdb941dbff857b49d4c55 | 72,524 |
def aggregate_results(tweets, results):
"""
Aggregates results based on actual tweet labeling and the classified sentiment.
@param tweets: the list of labeled tweets.
@param results: the results form the classification.
@return:
"""
#print "INFO -- Aggregating results"
classification_res... | d51bc4b173ca1b4fec632fef68a0f1537a19d799 | 72,525 |
import array
def compute_line_seeds(binary,bottom,top,colseps,scale):
"""Base on gradient maps, computes candidates for baselines
and xheights. Then, it marks the regions between the two
as a line seed."""
t = args.threshold #0.2###############################################################more focu... | e695d087f6588e6643662d7752386b37580d3ce5 | 72,526 |
def convert_raw_tuple(value_tuple, format_string):
"""
Convert a tuple of raw values, according to the given line format.
:param tuple value_tuple: the tuple of raw values
:param str format_string: the format of the tuple
:rtype: list of tuples
"""
values = []
for v, c in zip(value_tupl... | 0090594503532e8b94e6abe6d04f133769ee08fa | 72,527 |
def movie_search(code, input):
"""imdb movie/show title -- displays information about a production"""
try:
# Url-ify
search = web.quote(input.group(2).strip())
# Pull response from API, and load into a JSON based dict()
data = web.json(search_uri % search)
# If we get a... | 3803f5605f910621e2930cd6ccd3e8f88f7ea373 | 72,528 |
from typing import Tuple
from typing import List
def GenerateSecret(
params: InputParams,
original_words: OriginalWords,
key_count: int
) -> Tuple[FuzzyState, List[SecretKey]]:
"""
Returns a FuzzyState and a list of key_count 512-bit keys
This function establishes the orig... | dc203b52f18dd98e6c629961e6ac6fa9c3694ad9 | 72,529 |
def wss_deleteOperationsByID(wss_id):
"""
WaveShaper operations by ID
---
delete:
description: Delete operations configured on a WaveShaper specified by id
produces:
- application/json
parameters:
- name: wss_id
in: path
type: integer
description: id of the WaveShap... | 8fb9dfbf1804eb48ac0ea8552ee2cfc2254b5172 | 72,530 |
def generate_rst(create_rst):
"""Converts Markdown to RST for PyPI"""
md = fs.read_file("README.md")
md = pypi_sanitize_markdown(md)
rst = markdown2rst(md)
rst = pypi_prepare_rst(rst)
changes_md = pypi_sanitize_markdown(fs.read_file("CHANGELOG.md"))
changes_rst = markdown2rst(changes_md)
... | b09a42aa83e37dcef3b3f2a3f0329555075fce0e | 72,531 |
def parse_placement_policies(formatted_placement_policies):
""""Parse a placement policy description from a formatted policy"""
from azure.servicefabric.models import (ServicePlacementNonPartiallyPlaceServicePolicyDescription, # pylint: disable=line-too-long
ServiceP... | 1bbbbe084edd7a4265be5541c7b533a78cc40613 | 72,532 |
def decomp(n):
""" Retorna a decomposição em fatores primos de um inteiro em forma de dicionário onde as chaves são
as bases e o valores os expoentes.
Ex:
>>> decomp(12)
{2: 2, 3: 1}
>>> decomp(72)
{2: 3, 3: 2}
:param n: number
:return: dictionary
"""
expoente = 0
base... | 999d8be04ffd197ebdd14c88b525eb8ca4379bb9 | 72,534 |
def sanitize_type_instance(index_name):
"""
collectd limit the character set in type_instance to ascii and forbids
the '/' character. This method does a lossy conversion to ascii and
replaces the reserved character with '_'
"""
ascii_index_name = index_name.encode('ascii', 'ignore')
# '/' is... | ece5008944a80ec45f20c3c8bf01575f162bb8e0 | 72,535 |
from typing import Optional
def is_valid_output_event(event: metadata_store_pb2.Event,
expected_output_key: Optional[str] = None) -> bool:
"""Evaluates whether an event is an output event with the right output key.
Args:
event: The event to evaluate.
expected_output_key: The exp... | 7ee7ac9899fd26de8c811e351ca6d1a058df947b | 72,536 |
def validWorkspace(uri):
"""Function to check whether workspace is a geodatbase"""
if ".gdb" in str(uri) or ".sde" in str(uri):
return True
else:
return False | 073c1b992eee78dcb939b46215faed57e9bcf96c | 72,537 |
from typing import Optional
def _get_matching_ami(_type: str, version: str, default: bool = True) -> Optional[str]:
"""Gives the matching AMI given the type.
If default is on, then it will return a default AMI in case it does
not find the correct one matching version.
Parameters
----------
_... | 80fca22635f4fe62dcd4a6375750eccc308744ff | 72,538 |
def get_run_zip_file_slug_sets(new_run, old_run_zip_files):
"""
:param old_run_zip_files: A list of run zip files.
:return: A set of provider slugs for each zip file.
"""
data_provider_task_records = new_run.data_provider_task_records.exclude(provider__isnull=True)
all_run_zip_file_slugs = [
... | 3dd2c472bcf3113f2544dcf7b4c13f956714429b | 72,539 |
def fit_predict_one_fold(data, pipeline):
""" Simple strategy for model evaluation based on one folder check
:param data: InputData for validation
:param pipeline: Pipeline to validate
"""
# Train test split
train_input, predict_input = train_test_data_setup(data)
test_target = np.array(pr... | 5d90a39fffaa13a5ae08b0ff9912f48688407e6e | 72,540 |
def targets_vocabulary(vocabulary):
"""Get the targets vocabulary.
Args:
vocabulary: Vocabulary or (inputs_vocabulary, targets_vocabulary) tuple.
Returns:
a Vocabulary
"""
if isinstance(vocabulary, tuple):
vocabulary = vocabulary[1]
return vocabulary | 79a7ad0c5bb5232116e9c4dd9adad26cbe6ccb3f | 72,541 |
def pac_hr(pd):
""" Calculate PAC value using the height ratio.
Parameters
----------
ang: array_like
Phase of the low frequency signal.
amp: array_like
Amplitude envelop of the high frequency signal.
Returns
-------
The pac strength using the height ratio.
Note
... | 5d47155318c36c2708f931087fe582659bff4d3a | 72,542 |
import requests
def sendRequest(url, type="POST", params=None, headers=None):
"""
Send a request to a URL
### Input:
- `url` (str) | the url to send the request to
- `type` (str) | the type of request (GET or POST)
- `params` ... | 7f450b8eedf6405b237730b9f7d6da5277c41e7b | 72,543 |
def create_data_mix(add_noise, seed, N=3, T=1000, M=None):
""" Create a simple data set with a mixture of superGaussian-distributed and
subGaussian-distributed sources (Laplace and uniform distributions).
"""
rng = np.random.RandomState(seed)
S = np.zeros((3, 1000))
S[: int(N // 2), :] = rng.u... | 4751c42e4fdc1a01b2c4c8d54bcedf6981bcab4c | 72,544 |
def delete_album_file(album_file, albumdirectory, msg, options):
"""sanity check - only delete from album directory."""
if not album_file.startswith(albumdirectory):
print >> sys.stderr, (
"Internal error - attempting to delete file "
"that is not in album directory:\n %s") % ... | 193dbc86d243fa2659886b95fbc3f90fca8cd094 | 72,545 |
def index(request):
"""Index Page"""
if request.method != "GET":
return JsonResponse({"error": "GET request required"}, status=405)
# view
return render(request, "index.html") | fedf9c6d1bf258ac5cadd7210b1bdcc8ba64fd49 | 72,546 |
import itertools
def standardize_inputs(source, colgroups=None, mean=None, std=None):
"""
Standardize input features.
Groups of features could be listed in order to be standardized together.
source: Pandas.DataFrame or filename of csv file with features
colgroups: list of lists of groups of featur... | 36fd83179953fc655070cbfddf22481de940db17 | 72,547 |
def podatki_vaje(idVaje):
"""
Vrne vse podatke vaje.
"""
poizvedba = """
SELECT *
FROM intervencija
WHERE id = ?
"""
cur = conn.cursor()
cur.execute(poizvedba, [idVaje])
osnovni_podatki = cur.fetchone()
if osnovni_podatki is None:
return None
i... | 417317ad6cae384d21018864444c332cb443767b | 72,548 |
def extract_milestones(github_issues: list) -> list:
"""Extracts milestone information from parsed issues."""
# Extract individual milestone fields, dedupe
deduped_milestone_names = {
x.get('milestone').get('name') for x in github_issues}
deduped_milestone_descriptions = {
x.get('milestone').get('d... | 236f2f55eeff9de9e149fcb920b642684f3ee1ab | 72,549 |
def format_number(value: float) -> str:
"""
Format a number into a string, where “.0” is removed if number does not have a decimal part.
:param value: The number to format.
"""
return str(int(value) if value % 1 == 0 else value) | 7f34c689a64753c97c664dadf61d57bdf837c8a6 | 72,550 |
def get_span_row_count(span):
"""
Gets the number of rows included in a span
Parameters
----------
span : list of lists of int
The [row, column] pairs that make up the span
Returns
-------
rows : int
The number of rows included in the span
Example
-------
C... | e226e0f78bd6711a7ddbe9c749ed43d1d2bc476c | 72,551 |
def _full_covariance_matrices(points,means,weights,resp,reg_covar,n_jobs=1):
"""
Compute the full covariance matrices
"""
n_components,dim = means.shape
covariance = np.empty((n_components,dim,dim))
for i in range(n_components):
diff = points - means[i]
diff_we... | 26642126eccd021bbc0a515bea90266ff40a9f4d | 72,552 |
def parse_score_qa(output, metric, digits=4):
"""Function for parsing the output from `pyserini.eval.evaluate_dpr_retrieval`. Currently, the implementation is
the same as `parse_score_msmacro`, but we're keeping separate in case they diverge in the future."""
for line in output.split('\n'):
if me... | dbb2179fc1706618cc5a4ccfd88818d32086680b | 72,553 |
def mappings_prepend_dev(mappings):
"""Prepend '/dev/' to 'device' entry of swap/ephemeral virtual type"""
for m in mappings:
virtual = m['virtual']
if (is_swap_or_ephemeral(virtual) and
(not m['device'].startswith('/'))):
m['device'] = '/dev/' + m['device']
return ma... | d6d80e2b9b8d6c7fd5e31f6268d7ce0600d641a1 | 72,554 |
def SortTools_HeapSortOfInteger_Sort(*args):
"""
:param TheArray:
:type TheArray: TColStd_Array1OfInteger &
:param Comp:
:type Comp: TCollection_CompareOfInteger &
:rtype: void
"""
return _SortTools.SortTools_HeapSortOfInteger_Sort(*args) | 48f04e7470e512630bcc1246dcf57cefae86e4bb | 72,556 |
def format_games(teams, schedule_list):
"""
Formats the games for cleaner use.
Args:
teams: full list of NBA teams.
schedule_list: list of all the scheduled matchups for the team.
Returns:
A list of of lists containing schedule games information in the format:
[["T... | 0c6d224120499baae70c1c63a860937b5e597eee | 72,557 |
def get_logbook_by_name(logbook_name, conn):
"""
Get a logbook by name from a persistence backend connection
:param str logbook_name: The name of the logbook to get
:param obj conn: A persistence backend connection
:return obj logbook: The logbook with the specified name
"""
return next(
... | 7ed83cfca3d7f0313046b39032c2b906c4bff410 | 72,558 |
import importlib
def load_middleware(path):
""" Load the middleware python script """
middlewares = O()
loader = importlib.machinery.SourceFileLoader('middleware', path)
middleware = loader.load_module()
for mw in (d for d in dir(middleware) if not d.startswith("__")):
middlewares[mw] = ge... | e142c0c5272c50ccfffbd142968fa12ea204a00e | 72,559 |
import _ctypes
def IMG_LoadTexture_RW(renderer, src, freesrc):
"""Loads an image from a file object to a texture using a given renderer.
This function can load all supported formats, *except* TGA. See
:func:`IMG_LoadTexture` for more information.
Args:
renderer (:obj:`SDL_Renderer`): The... | 4fa7356471689dbd0549b913df93ddeda175cf97 | 72,560 |
def _filter_by_status(tools, address_family, status):
"""Filter sliver tools based on the status of their available interfaces.
Args:
tools: A list of sliver tools to filter by status.
address_family: Address family of the interface to which the status
parameter applies. If None, in... | e9eeef0603e2132ccdb4a2c74f91937dde151977 | 72,561 |
def plot_gains_vs_time(timeArr_hrs, gainsArr, gainType, feed="XX"):
"""
Create a figure showing Amplitude or Phase gains versus time from the
logfile output by GPPLT. Returns a MPL figure object.
"""
# Setup the figure page
fig = plt.figure(figsize=(12.0, 8.0))
# One plot per antenna
... | 4eab60597932b01290a2d8c3f5460b54ad698275 | 72,563 |
def vec2mat(V, order=RESHAPE_ORDER, shape=None):
"""reshape a vector to a square matrix, whos number of rows equals cols
input: any iterable object with size of N**2
"""
if shape is None:
dim = np.sqrt(len(V))
assert dim.is_integer()
shape = (int(dim), int(dim))
return np.re... | afef0f3d8fe5b15fbcf3fedc4c8687b91b80c2f1 | 72,565 |
from pathlib import Path
async def retrieve_player_games_current(
player_id: str = Path(..., regex=ID_REGEX, description=PLAYER_ID_DESC),
skip: int = Query(..., ge=0, description=SKIP_DESC),
limit: int = Query(..., ge=1, le=100, description=LIMIT_DESC),
) -> JSONResponse:
"""Handles /playe... | 301669acbae18f638fb9af6a6343d18a149c5328 | 72,566 |
def mean(x, axis=None, keepdims=False):
"""
Computes the arithmetic mean along a given axis.
Returns the average of the array elements. The average is taken over the flattened array by default, otherwise over
the specified axis.
:param x: Array containing numbers whose mean is desired.
:type x:... | 001bcfa165f241bb6618771af61689ed390cbc97 | 72,567 |
def list_cloud_backups() -> [str]:
"""List available cloud backups
Returns:
list: backups
"""
files = list_filtered_s3_files(S3_BACKUPS_DIR_PATH)
return files | 7cab40b48836fe99d8a974efe0b5c65cff08fc7a | 72,568 |
def check_aspell(original_text):
"""
Set pyenchant broker to Aspell
"""
broker = enchant.Broker()
broker.set_ordering("en_US","aspell")
return check(original_text) | 9c091b13dec2149b258b89012ce2878cf34d42be | 72,569 |
def connections(request: HttpRequest) -> Response:
"""
Method to get or add connection
:param request: HttpRequest
"""
if request.method == "GET":
res = Connections.getConnections()
return Response(res.json())
elif request.method == "POST":
res = Connections.addConnection... | 9c3fd7339b33f1f570da355ae2bd673d197563ee | 72,570 |
import logging
def error_logging_middleware(f):
"""
Logs all exceptions
"""
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
logging.exception(e)
raise
return wrapper | 722113fdba047cfb7c286199f4fee5fbd713df3f | 72,571 |
def get_policy_by_name(policy_name: str) -> iam_resource.Policy:
"""
Get an existing policy by name.
:return: IAM Policy object
"""
# sts provides the account number of the current credentials
account_id = sts_client.get_caller_identity()["Account"]
# policy arns consist of an account id and... | 0614b079995c303d5c5d7896da88727136c6f803 | 72,572 |
def ils_marshmallow_loader(schema_class):
"""Marshmallow loader for JSON requests."""
def json_loader():
try:
return marshmallow_loader(schema_class)()
except MarshmallowErrors as me:
for error in me.errors:
parent_path = [str(x) for x in error['parents']]... | be92cf0414d93f1e0d42d1600add83c06d8b8cad | 72,573 |
def shannon_entropy(c):
"""calculate the Shannon entropy of 1 d data. The unit is bits """
c_normalized = c / float(np.sum(c))
c_normalized_nonzero = c_normalized[np.nonzero(c_normalized)] # gives 1D array
entropy = -sum(c_normalized_nonzero * np.log2(c_normalized_nonzero)) # unit in bits
return ... | f884a4aa0cfa8cf12d2d64f9457a8aef8740a6ce | 72,575 |
def dict_to_dataframe(mechanistic_dict):
"""Function to create dataframe from mechanistic drug targets. Warning it changes the input dictionary."""
item_list = []
for key, value in mechanistic_dict.items():
for element in value:
element["hgnc_id"] = key
item_list.append(eleme... | e8b7ef1e5060433a63307125d4e6cac8131a2f63 | 72,576 |
import time
import torch
def test(model, dataloader):
"""
在一些有标签的测试数据集上测试模型的准确性
Args:
model: 必须在其上执行测试的torch模块
dataloader: 用于在数据集上进行迭代的dataloader对象
Returns:
batch_time: 预测一个批处理的类的平均时间
total_time: 处理整个数据集的总时间
accuracy: 模型对输入数据的准确性
"""
# 切换到评价模式
model.... | 4f9144bb0022f7fad396f4ccd4f4682857745e64 | 72,577 |
import collections
import logging
def _cross_validation_training(feature_maker, feature_names):
"""Finds the best models for features by cross-validation."""
use_implicationals_values = [True, False]
best_configs = collections.defaultdict(lambda: collections.defaultdict(str))
total_num_configs = len(feature_n... | f1010b3af2ab1ae2051aa5e51f5fd53c4ea0d7f8 | 72,578 |
def create_application(db):
"""Return a callable which lets you create applications."""
def _create_application(name, **params):
params.setdefault('client_id', unicode(uuid4()))
params.setdefault('default_scopes', 'read:user')
params.setdefault('redirect_uris', 'http://localhost:10500')... | e6adc89fc5357a910063b710ed73bd300a06130f | 72,579 |
def is_inside_relative_range(value, ref_value, pct):
"""
Parameters
----------
value : numeric
ref_value : numeric
pct : numeric
pct should be smaller than 1.
Returns
-------
boolean
"""
if ref_value * (1 - pct) <= value <= ref_value * (1 + pct):
return True... | 9e60eda7b3ba979c9dc33be890d46394aa954436 | 72,580 |
def unsharp_masking(im, sigma=5):
"""im: numpy.array image
cf. 1.4.1.gauss.py"""
im2 = filters.gaussian_filter(im,sigma)
return im2 - im | 90c892436d304a231f6970d70f82c8671ff44f7e | 72,581 |
from typing import List
def get_label_list(labels: List[List[int]]) -> List[int]:
"""Gets a sorted list of all the unique labels from `labels`.
Args:
labels: A list of lists, each corresponding to the label-sequence of a text.
Returns:
All the unique labels the ever appear in `labels`, g... | be795ff63c1eaccd221289708551a8ddd02b2cc5 | 72,582 |
from typing import Dict
def get_summary_dict(ldap_members: set, grouper_members: set, delta: Delta) \
-> Dict[str, int]:
"""
Return a dict containing summary data for EDS and Grouper queries
:param ldap_members: set containing EDS entries
:param grouper_members: set containing Grouper entries... | b3d356354480efb28618e05f2b3fc3625c966a86 | 72,583 |
def get_loss_gradient_functions(objective):
"""
Helper utility to return the (loss, gradient) function
pair.
"""
if objective == 'huber_hinge':
return huber_hinge.loss, huber_hinge.gradient
raise Exception("Objective not found") | d045b169ee2eda4af309a75f2f9a39a3d3f2dad1 | 72,584 |
def format_message(date_str, node, msg):
"""Format log message"""
message = f"{date_str}: {node.site_name}: {node.location or node.model} ({node.serial}) {msg}"
return message | 53dc7e2716f935a083c36e40ad4887cfe23c0aad | 72,585 |
def coating_brownian(f, materials, wavelength, wBeam, dOpt,
Ic=None, mTi=None):
"""Coating brownian noise for a given collection of coating layers
This function calculates Coating Brownian noise using
Hong et al . PRD 87, 082001 (2013).
All references to 'the paper', 'Eq' and 'Sec'... | 7d3fbe2944f3f932df62c239b38e3e2c53ab0a05 | 72,586 |
def preact_resnet(name, num_classes=10):
"""
Returns suitable Resnet model from its name.
Arguments:
name (str): name of resnet architecture.
num_classes (int): number of target classes.
Returns:
torch.nn.Module.
"""
if name == 'preact-resnet18':
return PreActResN... | 45615c9b9353102867b6ca31498d77490c46b202 | 72,587 |
def _deep_value(*args, **kwargs):
""" Drills down into tree using the keys
"""
node, keys = args[0], args[1:]
for key in keys:
node = node.get(key, {})
default = kwargs.get('default', {})
if node in ({}, [], None):
node = default
return node | fc821b5fe0758b582388c91be4139737970704b3 | 72,588 |
import functools
def settings_getter(func):
"""Ensure settings are loaded appropriately."""
@functools.wraps(func)
def wrapper(*args, **vargs):
Settings.load()
return func(*args, **vargs)
return wrapper | 98e3a63a647d6852ff4555736a77369de3a96608 | 72,590 |
import json
def calculate_number_of_events(client: Client, query: str) -> str:
"""
function that calculates number of events that fulfilling the query parameter
args:
client (Client): Phisher client
query (String): query with the timestamp in a lucene query format
returns:
nu... | fd19af4321baf22a0c34c3f3ea757a1b19bf6cc5 | 72,591 |
def get_secret(secret_key):
"""Given an instance of SecretKey returns several last values of the secret.
First item in the list is the current value of a secret (that can be used to
validate and generate tokens), the rest are previous values (that can be used
to validate older tokens, but shouldn't be used to ... | ec854fba1f2ec77be516ff5df1af614d3e5580e2 | 72,592 |
def bool_arrays_sum(arr_1: np.ndarray, arr_2: np.ndarray) -> np.ndarray:
"""
Calculate integer sum of two arrays.
Resulting array consists only of integers 0, 1 and 2.
>>> arr_1 = np.array([True, False, False])
>>> arr_2 = np.array([True, True, False])
>>> bool_arrays_sum(arr_1, arr_2)
arr... | 73edd0b56072d708a19f68b7fcfea048aa69623b | 72,593 |
def nikto_result(request):
"""
:param request:
:return:
"""
if request.method == 'GET':
scan_id = request.GET['scan_id']
scan_result = nikto_result_db.objects.filter(scan_id=scan_id)
return render(request,
'nikto_scan_result.html',
{'scan_re... | 81db1e710072d3a5f3c843c711ddf02db100e01a | 72,594 |
def generate_embedding():
"""initialize the interface (if needed, depends on the actual implementation), (call at first run)"""
interface.generate_embedding()
return embedding_view() | 6edad0e7a9d674a456cecfbc9a851183285fe72d | 72,595 |
def is_stranded_pp(child):
"""
Whether this predicate has a stranded preposition
E.g., "What is John associated with?"
"""
return is_prep(child) \
and not any([is_pobj(tok) # Doesn't have an object
for tok in child.children]) | b9b0120e0ed68ce34186f5463e30492bffce60a4 | 72,596 |
def remove_negations(ast):
"""
@brief Removes all negations.
@param ast The ast
@return another ast
"""
assert not is_node_op(ast, '->'), \
"Negations can only be removed on implication free AST"
assert ast is not None, "Empty ast"
if is_node_op(ast, '... | c038f8743006d0cee703ca6c4dd8626858686e22 | 72,597 |
def cna_stats(cnarr):
"""Fraction of the mapped genome with altered copy number."""
cnarr = cnarr.autosomes()
denom = cnarr.total_range_size()
if "cn" not in cnarr:
cnarr = do_call(cnarr)
aneuploid = cnarr[cnarr["cn"] != 2]
numer = aneuploid.total_range_size()
frac = numer / denom
... | 6beca5116e67821d4df7ecb36e6a28d069f2b674 | 72,599 |
from re import T
def prod(x, axis=None, keepdims=False):
"""Multiply the values in a tensor, alongside the specified axis.
"""
return T.prod(x, axis=axis, keepdims=keepdims) | 8478cab6c1041eab415f2db736379f46d98d323f | 72,600 |
from typing import Tuple
from typing import Optional
def accumulate_output(
duration: float,
step: float,
patch_collar: float = 0.05,
) -> Operator:
"""Accumulate predictions and audio to infinity: O(N) space complexity.
Uses a pre-allocated buffer that doubles its size once full: O(logN) concat o... | a2867737824630fbf69f50e9164ae41e5189716c | 72,601 |
import tempfile
def create_tmpdir():
"""Create temporary directory where all intermediate files will be placed."""
return tempfile.mkdtemp(prefix='xl-') | 7cac5eb979b3d7150084daf68749b30a3986e52b | 72,602 |
def get_sticker_and_id(sticker):
"""
Gets sticker and it's identifier from the given sticker or of it's identifier.
Parameters
----------
sticker : ``Sticker``, `int`
The sticker, or it's identifier.
Returns
-------
sticker : ``Sticker``, `None`
The sticker if f... | afeb09e9d44d5326aa3f4a3511d7536cb36d2476 | 72,603 |
import scipy
def getRelativisticMaxwellJuttnerDistribution(p,T,n):
"""
Calculates the relativistic Maxwell-Jüttner distribution.
:param float p: Momentum in units of m_e*c
:param float T: Plasma temperature (eV)
:param float n: Plasma density (m^-3)
"""
mc2inEV = scipy.constants.m_e*scipy... | b5f9e68ef96800bb3894c90b5d0f0d1bf8466feb | 72,604 |
def _save_prediction_results(res: dict, recorder: Recorder,
curr_loader: MARSDataLoader, threshold: float, recall_at: float=None) -> int:
"""use result metrics, recorder, test dataset loader to save results to pred file"""
pred_ID = _find_next_pred_ID()
# add additional info
... | a9806d810c992290f8d0004a0f5fbe670d9750aa | 72,605 |
def ovs_vsctl_set(table, record, column, key, value):
"""
This function allows to alter the OVS database. If column is a map, then
caller should also set the key, otherwise the key should be left as an
empty string.
"""
if key is None:
index = column
else:
index = "%s:%s" % (... | c3da6e66d9320d05a91da891e6de1020e9d32092 | 72,608 |
def get_pg_type(f, type_override=None):
"""
:param fields._column f: field to get a Postgres type for
:param type type_override: use the provided type for dispatching instead of the field's own type
:returns: (postgres_identification_type, postgres_type_specification)
:rtype: (str, str)
"""
... | d5f0674d656a9ea57a73b77640cfb10ec0f4cb09 | 72,609 |
import re
def get_aws_local_file(aws_creds_file):
"""
Converting aws config and credentials files into dictionaries
:param aws_creds_file: string
:return: dictionary
"""
aws_config = {}
current_profile = ''
input_file = open(aws_creds_file, 'r')
for line in input_file.readlines():
... | 3c0b323f8dc61f17953d72f9e8adb74ac3e0e828 | 72,611 |
from typing import Optional
def build_get_revoc_reg_delta_request(
submitter_did: Optional[str], revoc_reg_id: str, from_ts: Optional[int], to_ts: int
) -> Request:
"""
Builds a GET_REVOC_REG_DELTA request.
Request to get the delta of the accumulated state of the revocation registry
identified by... | 6d2ae8eea455098390ed1b9f9237b1df5532fb5c | 72,612 |
from typing import Union
from typing import Sequence
def get_shift(
reference_array: np.ndarray,
shifted_array: np.ndarray,
shift_method: str = "modulus",
precision: int = 1000,
support_threshold: Union[None, float] = None,
verbose: bool = True,
) -> Sequence[float]:
"""
Calculate the ... | 4bf2a071f289154e6fffd85d8fe4764a7a087423 | 72,613 |
import threading
def make_collector(name, sleep_time, decay_time, collector_class, *args):
""" other module should use this fn to init a collector, this fn start a thread
to run the collector and return an atomic_ref so outside world can get metrics
collected by this collector """
atomic_ref, instance... | ab51ad2a65b7f0678d532b85a985b70d4dd8b478 | 72,614 |
def make_quant(param, default_unit):
"""Convenience function to intialize a parameter as an astropy quantity.
Parameters
----------
param : float, or Astropy Quantity
Parameter to initialize
default_unit : str
Astropy unit string, sets as default for param.
Returns
-------
... | a6ed42ba9712b235ecbf0062c08601afb3a3a9a4 | 72,616 |
def html_escape(text: str) -> str:
"""Produce entities within text."""
return "".join(html_escape_table.get(c, c) for c in text) | a3cd3eff7698bb0613f4115f2d539521617db06c | 72,617 |
def vit_base_patch32_224(num_classes: int = 1000):
"""
ViT-Base model (ViT-B/32) from original paper (https://arxiv.org/abs/2010.11929).
ImageNet-1k weights @ 224x224, source https://github.com/google-research/vision_transformer.
weights ported from official Google JAX impl:
链接: https://pan.baidu.co... | dc8679a1dbf7ab7d97a9ba263403db77b61ecc91 | 72,618 |
def validate_base10(number):
"""Check if a string is a valid BASE10 representation of an AIC."""
number = compact(number)
if len(number) != 9:
raise InvalidLength()
if not isdigits(number):
raise InvalidFormat()
if number[0] != '0':
raise InvalidComponent()
if calc_check_... | bc2394cf5b50d4f5e46b4b8089f0aec463ed5242 | 72,619 |
def replace_oovs(source_in, target_in, vocabulary, source_out, target_out):
"""Replaces out-of-vocabulary words in source and target text with <unk-N>,
where N in is the position of the word in the source sequence.
"""
def format_unk(pos):
return "<unk-{}>".format(pos)
if target_in is None... | c11412cd67399ec88dd36e3120072500fc39aca5 | 72,620 |
def _bowtie_args_from_config(data):
"""Configurable high level options for bowtie.
"""
config = data['config']
qual_format = config["algorithm"].get("quality_format", "")
if qual_format.lower() == "illumina":
qual_flags = ["--phred64-quals"]
else:
qual_flags = []
multi_mapper... | 57e86765444657812d0bebc9b1a3c3dcb234d300 | 72,621 |
def split_unk(str_, vocab):
"""
将所有不在词表中的符号切分开,尽量保留在词表中的符号
"""
rstring = ""
for c in str_:
if c in vocab.keys():
rstring += c
else:
rstring += " " + c + " "
str_ = rstring
return str_ | c54da92f9e69f32949bba538242ea91cfdb197f9 | 72,622 |
def sum_square_numbers(upper: int) -> int:
"""Calculate the sum of the squares of the integers less than upper."""
n = upper - 1
return n * (2 * n + 1) * (n + 1) // 6 | b576ac0a860ea40a3efae2ced2d2c5d449b975dc | 72,623 |
import requests
from bs4 import BeautifulSoup
def searchAnimation(keyword = None, pageNum = None):
""" 通过关键词搜索动画 返回搜索页的soup """
if keyword == None or keyword == "" :
keyword = "极影字幕社 鬼灭之刃"
page = Formate.pageFormate(pageNum)
keyword = Formate.keywordFormat(keyword)
keywordURL = Constant.b... | fb69cb3a5b1072d4c1a7d0acd2f7542dd917b191 | 72,624 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.