content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def annotation_multi_vertical_height(_img, _x, _y_list, _line_color, _text_color, _text_list,
_thickness=1,
_with_arrow=True):
"""
纵向标注多个高度
:param _img: 需要标注的图像
:param _x: 当前直线所在宽度
:param _y_list: 所有y的列表
:param _line... | 2e181eddee2dea969b14dc18f910d4c5f82fb371 | 9,300 |
async def list_(hub, ctx, registry_name, resource_group, **kwargs):
"""
.. versionadded:: 3.0.0
Lists all the replications for the specified container registry.
:param registry_name: The name of the container registry.
:param resource_group: The name of the resource group to which the container r... | aa24ab14278e49da35fe6851d71e6d375f763b4d | 9,301 |
import timeit
def dbrg(images, T, r):
"""
Segmentation by density-based region growing (DBRG).
Parameters
----------
n : int
Number of blurred images.
M : np.ndarray
The mask image.
r : int
Density connectivity search radius.
"""
n = len(images)
M = _ge... | 0fb3aa19252be95d436013025e90f2dd9a12da4e | 9,302 |
from typing import Union
def latest_window_partition_selector(
context: ScheduleEvaluationContext, partition_set_def: PartitionSetDefinition[TimeWindow]
) -> Union[SkipReason, Partition[TimeWindow]]:
"""Creates a selector for partitions that are time windows. Selects latest time window that ends
before th... | bac6fe78b0111cdf6272c7bf08a0d555971c20a5 | 9,303 |
import os
def env_or_val(env, val, *args, __type=str, **kwargs):
"""Return value of environment variable (if it's defined) or a given fallback value
:param env: Environment variable to look for
:type env: ``str``
:param val: Either the fallback value or function to call to compute it
:type val: `... | 6a94c627ec4af63f54f5d3b6627141cb0624e445 | 9,304 |
def html(i):
"""
Input: {
(skip_cid_predix) - if 'yes', skip "?cid=" prefix when creating URLs
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
... | a2effe3ac9cf9fb8678283cb9d23cf574bc54700 | 9,305 |
def multi_particle_first_np_metafit(n):
"""Fit to plots of two-body matrix elements from various normal-ordering
schemes, where only the first n points are taken from each scheme
"""
name = b'multi_particle_first_{}p_metafit'.format(n)
def mpfnp(fitfn, exp_list, **kwargs):
return multi_part... | 384b4d7a1627e554e3ba1583236dbb8fde136b9c | 9,306 |
from typing import Union
from pathlib import Path
from typing import List
from typing import Dict
import json
def readJSONLFile(file_name: Union[str, Path]) -> List[Dict]:
"""
Read a '.jsonl' file and create a list of dicts
Args:
file_name: `Union[str,Path]`
The file to open
Return... | 8e33fad766a255578179828dc76ec793c02f90b9 | 9,307 |
def _dtype_from_cogaudioformat(format: CogAudioFormat) -> np.dtype:
"""This method returns the numpy "data type" for a particular audio format."""
if COG_AUDIO_IS_INT(format):
if COG_AUDIO_FORMAT_DEPTH(format) == COG_AUDIO_FORMAT_DEPTH_S24:
return np.dtype(np.uint8)
elif COG_AUDIO_FO... | d41b01fddd798eaa526e767775138e4a4e3ce718 | 9,308 |
def makeSiteWhitelist(jsonName, siteList):
"""
Provided a template json file name and the site white list from
the command line options; return the correct site white list based
on some silly rules
"""
if 'LHE_PFN' in jsonName:
siteList = ["T1_US_FNAL"]
print("Overwritting SiteWh... | 8f8b11739a30b4338b8dd31afb6c3c57545af6d0 | 9,309 |
import json
import jsonschema
def loadConfig(configFilePath: str) -> {}:
"""Loads configuration"""
config = {}
with open(configFilePath) as configFile:
config = json.load(configFile)
configSchema = {}
with open(CONFIG_SCHEMA_FILE_PATH, "r") as configSchemaFile:
configSchema = json... | d5e1cbd3bc1f61d329f26a40d9dff5b14ca76f22 | 9,310 |
def version_info():
"""
Get version of vakt package as tuple
"""
return tuple(map(int, __version__.split('.'))) | 446a637134484e835f522f2f67c19110796f503d | 9,311 |
from sys import flags
import six
def dacl(obj_name=None, obj_type="file"):
"""
Helper function for instantiating a Dacl class.
Args:
obj_name (str):
The full path to the object. If None, a blank DACL will be created.
Default is None.
obj_type (str):
T... | 8427940cd180eb61a1ba52b4d9459466cda26ca6 | 9,312 |
from typing import List
def max_crossing_sum(lst: List[int], mid: int, n: int) -> int:
"""
Parameter <mid> is the floor middle index of <lst>.
Parameter <n> is the length of the input list <lst>.
Pre: <lst> is a list of integers and len(lst) >= 2.
Post: returns the maximum contiguous crossing sum ... | 3d873907cb7ed0c14152ec3c2e92a742bd52aa85 | 9,313 |
def _kubeconfig_impl(repository_ctx):
"""Find local kubernetes certificates"""
# find and symlink kubectl
kubectl = repository_ctx.which("kubectl")
if not kubectl:
fail("Unable to find kubectl executable. PATH=%s" % repository_ctx.path)
repository_ctx.symlink(kubectl, "kubectl")
# TODO... | 5638af9fd059593b228aab5e6c4eca092759ce31 | 9,314 |
def getPrimaryHostIp():
"""
Tries to figure out the primary (the one with default route), local
IPv4 address.
Returns the IP address on success and otherwise '127.0.0.1'.
"""
#
# This isn't quite as easy as one would think. Doing a UDP connect to
# 255.255.255.255 turns out to be prob... | 127eeb80c21f766c3b877fc6fdfc05aed9bf50ca | 9,315 |
from re import DEBUG
def run(raw_args):
"""
Parse arguments in parameter. Then call the function registered in the
argument parser which matches them.
:param raw_args:
:return:
"""
if "--version" in raw_args:
print("version: ", __version__)
return error.ReturnCode.success.v... | 85c5a8a6ff87e8bee670627f8ce0c16ebb44b083 | 9,316 |
def localize(_bot, _msg, *args, _server=None, _channel=None, **kwargs):
""" Localize message to current personality, if it supports it. """
global messages
# Find personality and check if personality has an alternative for message.
personality = config.get('personality', _server or _current_server, _ch... | ba2300388afee37d4bf40dc2ac9fc6f4f04731fa | 9,317 |
import argparse
def parse_arguments():
"""
Parse the argument list and return the location of a geometry file, the
location of a data file, whether or not to save images with a timestamp of
the four default plot windows and the VisIt session file in the current
directory, and whether or not to ope... | 5ba0e6e65801cfc93cc2864368eb2fac4b75e840 | 9,318 |
def list_events():
"""Show a view with past and future events."""
if "username" not in session:
return redirect("/")
events = actions.get_upcoming_events()
past_events = actions.get_past_events()
return render_template("events.html", count=len(events), past_count=len(past_events),
... | a4ab3207943ccd302aab6a0785de4cc4a4609994 | 9,319 |
import argparse
import os
def create_parser():
"""Create argparser."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--mode', default='local', choices=['local', 'docker'])
parser.add_argument(
'--env-file', action="append", help='Job specific environment file')
parser.ad... | 8064afedf3273e21b69c130d8ba48852490cb6af | 9,320 |
def get_duration(df):
"""Get duration of ECG recording
Args:
df (DataFrame): DataFrame with time/voltage data
Returns:
float: duration of ECG recording
"""
start = df.time.iloc[0]
end = df.time.iloc[-1]
duration = end - start
return duration | 77698afc8ef7af557628d5fea760dc101c3e6112 | 9,321 |
def conv_seq_labels(xds, xhs):
"""description and hedlines are converted to padded input vectors. headlines are one-hot to label"""
batch_size = len(xhs)
assert len(xds) == batch_size
def process_xdxh(xd,xh):
concated_xd = xd+[[3]]+xh
padded_xd = lpadd(concated_xd,maxlend)
concat... | e8a70797ae1fa7eaf50c96bd072614aff6417b80 | 9,322 |
import json
def create_task():
"""Create new post"""
global post_id_counter
body = json.loads(request.data)
title = body.get("title")
link = body.get("link")
username = body.get("username")
if not title or not link or not username:
return json.dumps({"error": "Missing fields in th... | bace1881a104e41d83842992fc7818f2c2a213ac | 9,323 |
def _asklong(*args):
"""_asklong(sval_t value, char format, v(...) ?) -> int"""
return _idaapi._asklong(*args) | f80d4db85461cd3e13de2cfc6006385419729bec | 9,324 |
def describe_bivariate(data:pd.DataFrame,
only_dependent:bool = False,
size_max_sample:int = None,
is_remove_outliers:bool = True,
alpha:float = 0.05,
max_num_rows:int = 5000,
max_size_cats... | 4754b106cab60dd02ab32b0705802d9459c28593 | 9,325 |
import click
import subprocess
def launch(cmd, args=None, separate_terminal=False, in_color='cyan', silent=False, should_wait=True):
"""
Launch a system command
:param cmd: The command to run
:param args: The arguments to pass to that command (a str list)
:param separate_terminal: Should we open a... | 48de0ef8b80973fede05444ec78ab09de6b783b9 | 9,326 |
def devilry_multiple_examiners_short_displayname(assignment, examiners, devilryrole):
"""
Returns the examiners wrapped in HTML formatting tags perfect for showing
the examiners inline in a non-verbose manner.
Typically used for showing all the examiners in an
:class:`devilry.apps.core.models_group... | 4afa278f115a2a99ee2f922ef15dd8507293d3cc | 9,327 |
import seaborn
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb, hex2color
def colormap_with_fixed_hue(color, N=10):
"""Create a linear colormap with fixed hue
Parameters
----------
color: tuple
color that determines the hue
N: int... | 2d6e7d1bc5f919a01bf9871ed9422cd847cc5a99 | 9,328 |
import json
def get_news_blacklist() -> list:
"""Get the users news blacklist from news-blacklist.json.
Returns:
list: List of blacklisted news article titles
"""
try:
with open("news-blacklist.json", encoding="utf-8") as file:
log.info("Getting news blacklist from news-bl... | b25f2c619e5767d8238e95277e691264eb0682df | 9,329 |
def calc_triangular_number(n: int):
"""
A triangular number or triangle number counts objects
arranged in an equilateral triangle.
More info: https://www.mathsisfun.com/algebra/triangular-numbers.html
:param n:
:return:
"""
return int((n * (n + 1)) / 2) | e3bfefd6e0e9451849cee8f6da252ec128285c85 | 9,330 |
def wrap_keepdims(func):
""" Check that output have same dimensions as input. """
# TODO : check if it's working
@wraps(func)
def check_keepdims(X, *args, keepdims=False, **kwargs):
if keepdims:
out = func(X, *args, **kwargs)
return out.reshape(out.shape + (1,))
... | ef0d7a320e9207f50b1c00d9b9359faad47e5850 | 9,331 |
def get_headers(cred=None, filename=None):
"""Return headers for basic HTTP authentication.
Returns:
str: Basic authorization header, including Base64 encoded
username and password.
"""
return {
"Authorization": "Basic {}".format(
get_base64(cred=cred, filename=... | 17a8c941044487a334070d70d9d93071898a31f5 | 9,332 |
def create_xml_content(
segmentation: list[dict],
lang_text: list[str],
split: str,
src_lang: str,
tgt_lang: str,
is_src: bool,
) -> list[str]:
"""
Args:
segmentation (list): content of the yaml file
lang_text (list): content of the transcription or translation txt file
... | 6af6b5fcdaccd5bd81ad202bdb22fad3910afc2b | 9,333 |
def style_string(string: str, fg=None, stylename=None, bg=None) -> str:
"""Apply styles to text.
It is able to change style (like bold, underline etc), foreground and background colors of text string."""
ascii_str = _names2ascii(fg, stylename, bg)
return "".join((
ascii_str,
string,
... | 6d61c33a632c88609cb551ae0a1d55d8ee836937 | 9,334 |
def select_all_genes():
"""
Select all genes from SQLite database
"""
query = """
SELECT GENE_SYMBOL, HGNC_ID, ENTREZ_GENE_ID, ENSEMBL_GENE, MIM_NUMBER FROM GENE
"""
cur = connection.cursor()
cur.execute(query)
rows = cur.fetchall()
genes = []
for row in rows:
... | fb73e890d62f247939c1aa9a1e16a8e5f5a75866 | 9,335 |
def test_enum_handler(params):
""" 测试枚举判断验证
"""
return json_resp(params) | c3a4a9589b5d06813d6afaa55c8f6d9fafa80252 | 9,336 |
def get_staff_timetable(url, staff_name):
"""
Get Staff timetable via staff name
:param url: base url
:param staff_name: staff name string
:return: a list of dicts
"""
url = url + 'TextSpreadsheet;Staff;name;{}?template=SWSCUST+Staff+TextSpreadsheet&weeks=1-52' \
'&days=1-7&... | 0e52604c08bef70d5cfc1fc889c8ced766f49ae5 | 9,337 |
def find_ccs(unmerged):
"""
Find connected components of a list of sets.
E.g.
x = [{'a','b'}, {'a','c'}, {'d'}]
find_cc(x)
[{'a','b','c'}, {'d'}]
"""
merged = set()
while unmerged:
elem = unmerged.pop()
shares_elements = False
for s in merged.copy... | 4bff4cc32237dacac7737ff509b4a68143a03914 | 9,338 |
def read_match_df(_url: str, matches_in_section: int=None) -> pd.DataFrame:
"""各グループの試合リスト情報を自分たちのDataFrame形式で返す
JFA形式のJSONは、1試合の情報が下記のような内容
{'matchTypeName': '第1節',
'matchNumber': '1', # どうやら、Competitionで通しの番号
'matchDate': '2021/07/22', # 未使用
'matchDateJpn': '2021/07/22',
'matchDateWe... | 0dae5f1669c3e1a1a280967bc75780a7b1aa91a0 | 9,339 |
import re
def tokenize(text):
"""Tokenise text with lemmatizer and case normalisation.
Args:
text (str): text required to be tokenized
Returns:
list: tokenised list of strings
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
det... | 56c7dc6ce557257f8716bd502958093eb01a8c50 | 9,340 |
def reinforce_loss_discrete(classification_logits_t,
classification_labels_t,
locations_logits_t,
locations_labels_t,
use_punishment=False):
"""Computes REINFORCE loss for contentious discrete action spaces... | 7296f0647d792ce0698cd48d2b56e30941ca1afb | 9,341 |
import os
def train2(num,base_path=base_path):
"""
this function is used to process train.yzbx.txt format
"""
#train_data_file="/home/zyyang/RS/train.yzbx.txt"
train_data_file=os.path.join(base_path,num,'train.yzbx.txt')
b_data=defaultdict(list)
fi=open(train_data_file,'r')
size=0
maxb=0
for line in fi:
s... | 5cdaed452c2087161a9ccdd7c06735b025aed0db | 9,342 |
import os
import shutil
def analyze(binObj, task='skewer', frange=None, distort=True, CenAlpha=None,
histbin=False, statistic='mean', suffix='temp', overwrite=False,
skewer_index=None, zq_cut=[0, 5], parallel=False, tt_bins=None,
verbose=True, nboot=100, calib_kwargs=None, skewer_k... | 90a04f5c4bb137032a80217a10a9dcfae863f0a8 | 9,343 |
import itertools
def distances(spike_times, ii_spike_times, epoch_length=1.0, metric='SPOTD_xcorr'):
"""Compute temporal distances based on various versions of the SPOTDis, using CPU parallelization.
Parameters
----------
spike_times : numpy.ndarray
1 dimensional matrix containing all spike t... | 3696f33929150ac2f002aa6a78822654eeb50581 | 9,344 |
def format_object_translation(object_translation, typ):
"""
Formats the [poi/event/page]-translation as json
:param object_translation: A translation object which has a title and a permalink
:type object_translation: ~cms.models.events.event.Event or ~cms.models.pages.page.Page or ~cms.models.pois.poi.... | 11499d53d72e071d59176a00543daa0e8246f89a | 9,345 |
def _FormatKeyValuePairsToLabelsMessage(labels):
"""Converts the list of (k, v) pairs into labels API message."""
sorted_labels = sorted(labels, key=lambda x: x[0] + x[1])
return [
api_utils.GetMessage().KeyValue(key=k, value=v) for k, v in sorted_labels
] | 3f2dd78951f8f696c398ab906acf790d7923eb75 | 9,346 |
def gen_unique(func):
""" Given a function returning a generator, return a function returning
a generator of unique elements"""
return lambda *args: unique(func(*args)) | 703dc6f80553fc534ca1390eb2c0c3d7d81b26eb | 9,347 |
def admin_inventory(request):
"""
View to handle stocking up inventory, adding products...
"""
context = dict(product_form=ProductForm(),
products=Product.objects.all(),
categories=Category.objects.all(),
transactions=request.user.account.transact... | ec8f38947ab95f82a26fc6c6949d569a5ec83f7d | 9,348 |
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
print(f'METHOD @ snippet_list= {request.method}')
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return JsonResponse(seriali... | 959245f7d194470c4bccef338ead8d0b35abe1bc | 9,349 |
def generate_submission(args: ArgumentParser, submission: pd.DataFrame) -> pd.DataFrame:
"""Take Test Predictions for 4 classes to Generate Submission File"""
image, kind = args.shared_indices
df = submission.reset_index()[[image, args.labels[0]]]
df.columns = ["Id", "Label"]
df.set_index("Id", inpl... | e5b3f1c65adbe1436d638667cbc7bae9fb8a6a1e | 9,350 |
import numba
def nearest1d(vari, yi, yo, extrap="no"):
"""Nearest interpolation of nD data along an axis with varying coordinates
Warning
-------
`nxi` must be either a multiple or a divisor of `nxo`,
and multiple of `nxiy`.
Parameters
----------
vari: array_like(nxi, nyi)
yi: ar... | f7a9c03b1cca3844a9aad3d954fa2a189134a69f | 9,351 |
def registros():
"""Records page."""
return render_template('records.html') | b72cffbdf966f8c94831da76fd901ce9cba60aac | 9,352 |
def cal_evar(rss, matrix_v):
"""
Args:
rss:
matrix_v:
Returns:
"""
evar = 1 - (rss / np.sum(matrix_v ** 2))
return evar | 21f1d71ba98dafe948a5a24e4101968531ec1e30 | 9,353 |
def split_path(path):
"""
public static List<String> splitPath(String path)
* Converts a path expression into a list of keys, by splitting on period
* and unquoting the individual path elements. A path expression is usable
* with a {@link Config}, while individual path elements are usable with a... | 9e102d7f7b512331165f51e6055daeaf4f56b61a | 9,354 |
import os
from sys import path
import numpy
import math
def load_dataset_RGB(split_th = 0.8, ext='.jpg'):
""" Default: 80% for training, 20% for testing """
positive_dir = '/media/himanshu/ce640fc3-0289-402c-9150-793e07e55b8c/visapp2018code/RGB/data/positive'
negative_dir = '/media/himanshu/ce640fc3-0289... | 90abee394944318f567660276e5dd1b2d577225b | 9,355 |
def imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated_d():
"""Dilated hparams."""
hparams = imagetransformer_base_8l_8h_big_cond_dr03_dan_dilated()
hparams.gap_sizes = [0, 16, 64, 16, 64, 128, 256, 0]
return hparams | b0a56031e06cff42df4cdeab55e01322be8e439d | 9,356 |
def leaveOneOut_Input_v4( leaveOut ):
"""
Generate observation matrix and vectors
Y, F
Those observations are trimed for the leave-one-out evaluation. Therefore, the leaveOut
indicates the CA id to be left out, ranging from 1-77
"""
des, X = generate_corina_features('ca')
X = np.delete... | 0078bda71345d31cf24f4d1c4ceeafa768357ad4 | 9,357 |
import logging
def common_inroom_auth_response(name, request, operate, op_args):
"""
> 通用的需要通过验证用户存在、已登录、身处 Room 的操作。
参数:
- name: 操作名,用于日志输出;
- request: Flask 传来的 request;
- operate: 具体的操作函数,参数为需要从 request.form 中提取的值,返回值为成功后的response json;
- op_args: operate 函数的 参数名 str 组成的列表。
返回:res... | b11607f2d0a6a656c65cf464010f10634389f0bf | 9,358 |
def get_pca(acts, compute_dirns=False):
""" Takes in neuron activations acts and number of components.
Returns principle components and associated eigenvalues.
Args:
acts: numpy array, shape=(num neurons, num datapoints)
n_components: integer, number of pca components to reduce
... | 25620178e340f58b3d13ed0de4ee6d324abcb3ef | 9,359 |
def refresh_lease(lease_id, client_id, epoch, ttl):
"""
Update the timeout on the lease if my_id is the lease owner, else fail.
:param lease_id:
:param client_id:
:param ttl: number of seconds in the future to set the expiration to, can lengthen or shorten expiration depending on current value of l... | 6f26ad7887ab26d7c90dfd2c7881f7b50ec5fa1b | 9,360 |
import os
def checkLastJob(jobsFolder):
"""Count number of folders in folder
:param jobsFolder: directory with jobs
:return: number of created jobs
"""
allFolders = os.listdir(jobsFolder)
jobsFolders = [f for f in allFolders if f.startswith('job')]
jobsCount = len(jobsFolders)
ret... | 17ea83ffc07134d91d66a08ee59ed85b499c8e4d | 9,361 |
def canny(img, low_threshold, high_threshold):
"""Applies the Canny transform"""
#imgCopy = np.uint8(img)
return cv2.Canny(img, low_threshold, high_threshold) | 80e8d4ad99c769887e85577b46f6028ceea0b9f6 | 9,362 |
def pairwise_two_tables(left_table, right_table, allow_no_right=True):
"""
>>> pairwise_two_tables(
... [("tag1", "L1"), ("tag2", "L2"), ("tag3", "L3")],
... [("tag1", "R1"), ("tag3", "R3"), ("tag2", "R2")],
... )
[('L1', 'R1'), ('L2', 'R2'), ('L3', 'R3')]
>>> pairwise_two_tables(
... | aabcccc2ade9b00ed5bdac32f9cc4a7a4cc718c3 | 9,363 |
def augment_stochastic_shifts(seq, augment_shifts):
"""Apply a stochastic shift augmentation.
Args:
seq: input sequence of size [batch_size, length, depth]
augment_shifts: list of int offsets to sample from
Returns:
shifted and padded sequence of size [batch_size, length, depth]
"""
shift_index = ... | 1afd682e1f665d4d0786e729e6789a6459b4457c | 9,364 |
def _SourceArgs(parser):
"""Add mutually exclusive source args."""
source_group = parser.add_mutually_exclusive_group()
def AddImageHelp():
"""Returns detailed help for `--image` argument."""
template = """\
An image to apply to the disks being created. When using
this option, the size o... | dfa44ed54c4efba666f19c850a0eacffe85cafa0 | 9,365 |
def get_all_species_links_on_page(url):
"""Get all the species list on the main page."""
data, dom = get_dom(url)
table = dom.find('.tableguides.table-responsive > table a')
links = []
for link in table:
if link is None or link.text is None:
continue
links.append(dict(
... | 4a63d78b699150c37ccc9aa30d9fa6dae39d801b | 9,366 |
def gen_image_name(reference: str) -> str:
"""
Generate the image name as a signing input, based on the docker reference.
Args:
reference: Docker reference for the signed content,
e.g. registry.redhat.io/redhat/community-operator-index:v4.9
"""
no_tag = reference.split(":")[0]
... | ccaecfe91b5b16a85e3a3c87b83bbc91e54080b1 | 9,367 |
def adaptive_confidence_interval(values, max_iterations=1000, alpha=0.05, trials=5, variance_threshold=0.5):
""" Compute confidence interval using as few iterations as possible """
try_iterations = 10
while True:
intervals = [confidence_interval(values, try_iterations, alpha) for _ in range(trials... | 47c1861384d94a13beaf86eed5ad88a2ad2fb80f | 9,368 |
def get_chat_id(update):
"""
Get chat ID from update.
Args:
update (instance): Incoming update.
Returns:
(int, None): Chat ID.
"""
# Simple messages
if update.message:
return update.message.chat_id
# Menu callbacks
if update.callback_query:
return ... | 1669382fd430b445ea9e3a1306c1e68bf2ec0013 | 9,369 |
def action(fun):
"""Method decorator signaling to Deployster Python wrapper that this method is a resource action."""
# TODO: validate function has single 'args' argument (using 'inspect.signature(fun)')
fun.action = True
return fun | 2720d1d44f325f5c8462c9957365b08de7b7847e | 9,370 |
def chooseCommertialCity(commercial_cities):
"""
Parameters
----------
commercial_cities : list[dict]
Returns
-------
commercial_city : dict
"""
print(_('From which city do you want to buy resources?\n'))
for i, city in enumerate(commercial_cities):
print('({:d}) {}'.for... | 6e39c1922a1560f6d3d442cf5d14b764f2c08437 | 9,371 |
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
"""Reusable code for making a simple neural net layer.
It does a matrix multiply, bias add, and then uses relu to nonlinearize.
It also sets up name scoping so that the resultant graph is easy to read,
and adds a number of summary o... | 38976aa68de06e131f0e2fd8056216ce9bfcba77 | 9,372 |
def move_right_row(row, debug=True):
"""move single row to right."""
if debug:
print(row)
row_del_0 = []
for i in row: # copy non-zero blocks
if i != 0:
row_del_0.append(i)
#print(row_del_0)
row = row_del_0
i = 0
j = len(row_del_0) - 1
while i < j: # com... | b779f2c336a62aaff23f35584460c765a9d7e408 | 9,373 |
def get_validate_platform(cmd, platform):
"""Gets and validates the Platform from both flags
:param str platform: The name of Platform passed by user in --platform flag
"""
OS, Architecture = cmd.get_models('OS', 'Architecture', operation_group='runs')
# Defaults
platform_os = OS.linux.value
... | 3b9150c400ed28e322108ba531c7f4c5ac450da1 | 9,374 |
def get_path_cost(slice, offset, parameters):
"""
part of the aggregation step, finds the minimum costs in a D x M slice (where M = the number of pixels in the
given direction)
:param slice: M x D array from the cost volume.
:param offset: ignore the pixels on the border.
:param parameters: stru... | 06348e483cd7cba012354ecdcadcd0381b0b7dfb | 9,375 |
def generate_cyclic_group(order, identity_name="e", elem_name="a", name=None, description=None):
"""Generates a cyclic group with the given order.
Parameters
----------
order : int
A positive integer
identity_name : str
The name of the group's identity element
Defaults to 'e'
... | ed79547dfde64ece136456a8c5d7ce00c4317176 | 9,376 |
def loadTextureBMP(filepath):
"""
Loads the BMP file given in filepath, creates an OpenGL texture from it
and returns the texture ID.
"""
data = np.array(Image.open(filepath))
width = data.shape[0]
height = data.shape[1]
textureID = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, textu... | dd80584afc644fa23c2aef919a24152ea5b3696e | 9,377 |
def get_pixeldata(ds: "Dataset") -> "np.ndarray":
"""Return a :class:`numpy.ndarray` of the pixel data.
.. versionadded:: 2.1
Parameters
----------
ds : pydicom.dataset.Dataset
The :class:`Dataset` containing an :dcm:`Image Pixel
<part03/sect_C.7.6.3.html>` module and the *Pixel Da... | 418603d30bf272affc0e63615e94d4cce11b1bf2 | 9,378 |
import time
def timeit(method):
""" Timing Decorator Function Written by Fahim Sakri of PythonHive (https://medium.com/pthonhive) """
def timed(*args, **kwargs):
time_start = time.time()
time_end = time.time()
result = method(*args, **kwargs)
if 'log_time' in kwargs:
... | 598667950bc707b72239af9f4e5a3248dbe64d96 | 9,379 |
def allot_projects():
"""
The primary function that allots the projects to the employees.
It generates a maximum match for a bipartite graph of employees and projects.
:return: A tuple having the allotments, count of employees allotted and
total project headcount (a project where two people need to... | 774df8714cd47eb2a7affe34480dfec682010341 | 9,380 |
import requests
def upload_record(data, headers, rdr_project_id):
""" Upload a supplied record to the research data repository
"""
request_url = f"https://api.figsh.com/v2/account/projects/{rdr_project_id}/articles"
response = requests.post(request_url, headers=headers, json=data)
return res... | 7431234757668f9157f90aa8a9c335ee0e2a043b | 9,381 |
def datetime_to_ts(str_datetime):
"""
Transform datetime representation to unix epoch.
:return:
"""
if '1969-12-31' in str_datetime:
# ignore default values
return None
else:
# convert to timestamp
if '.' in str_datetime: # check whether it has milliseconds or no... | 83b40abc6c5ce027cf04cd2335b2f35e235451d0 | 9,382 |
import functools
def is_codenames_player(funct):
"""
Decorator that ensures the method is called only by a codenames player.
Args:
funct (function): Function being decorated
Returns:
function: Decorated function which calls the original function
if the user is a codenames pla... | 814bc929bbd20e8c527bd5c922a25823a4bdbefc | 9,383 |
def same_container_2():
"""
Another reason to use `same_container=co.SameContainer.NEW` to force
container sharing is when you want your commands to share a filesystem.
This makes a download and analyze pipeline very easy, for example, because
you simply download the data to the filesystem in one no... | 06e1a3c70c33ed9b7de46ebabb1d5f2f6bc83266 | 9,384 |
def get(args) -> str:
"""Creates manifest in XML format.
@param args: Arguments provided by the user from command line
@return: Generated xml manifest string
"""
arguments = {
'target': args.target,
'targetType': None if args.nohddl else args.targettype,
'path': args.path,
... | 7b859952d7eda9d6dedd916bb3534d225c3d9593 | 9,385 |
from typing import Callable
def elementwise(op: Callable[..., float], *ds: D) -> NumDict:
"""
Apply op elementwise to a sequence of numdicts.
If any numdict in ds has None default, then default is None, otherwise the
new default is calculated by running op on all defaults.
"""
keys: set... | 4e7dce60d01e8bcec722a5a6d60d15920a6a91c5 | 9,386 |
import torch
def sigmoid_focal_loss(
inputs: torch.Tensor,
targets: torch.Tensor,
alpha: float = -1,
gamma: float = 2,
reduction: str = "none",
) -> torch.Tensor:
"""
Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
Args:
inputs: A float tensor of a... | e792c1bea37bcc26ff323a764fc56e0f4bbd0bc5 | 9,387 |
def arcsin(x):
"""Return the inverse sine or the arcsin.
INPUTS
x (Variable object or real number)
RETURNS
if x is a Variable, then return a Variable with val and der.
if x is a real number, then return the value of arcsin(x).
EXAMPLES
>>> x = Variable(0, name='x')
>>> t = arcsin(x)
>>> print(t.val, t.d... | a5d899dae9b4fc33b6ddf2e2786ec6eee8508541 | 9,388 |
import tqdm
def preprocessing(texts, words, label, coef=0.3, all_tasks=False, include_repeat=True, progressbar=True):
"""
the function returns the processed array for the Spacy standard
"""
train = []
enit = {}
assert 0 < coef <= 1, f"The argument must be in the range (0 < coef <= 1) --> {coe... | f10c27f8ed686d45a1c778bdf557f88ad3f3bdfa | 9,389 |
import numpy
import math
def rotate(
input,
angle,
axes=(1, 0),
reshape=True,
output=None,
order=3,
mode="constant",
cval=0.0,
prefilter=True,
*,
allow_float32=True,
):
"""Rotate an array.
The array is rotated in the plane defined by the two axes given by the
`... | 04b7f3dc66d09c0b69ba97579972e131cc96b375 | 9,390 |
def generate_url_fragment(title, blog_post_id):
"""Generates the url fragment for a blog post from the title of the blog
post.
Args:
title: str. The title of the blog post.
blog_post_id: str. The unique blog post ID.
Returns:
str. The url fragment of the blog post.
"""
... | c846e6203fa4782c6dc92c892b9e0b6c7a0077b5 | 9,391 |
def update_cluster(cluster, cluster_args, args,
api=None, path=None, session_file=None):
"""Updates cluster properties
"""
if api is None:
api = bigml.api.BigML()
message = dated("Updating cluster. %s\n" %
get_url(cluster))
log_message(message, log_fil... | d07e3969e90cbc84f5329845e540c3b1a03d86b5 | 9,392 |
def get_post_by_user(user_id: int, database: Session) -> Post:
"""
"""
post = database.query(Post).filter(
Post.user == user_id).order_by(Post.id.desc()).all()
logger.info("FOI RETORNADO DO BANCO AS SEGUINTES CONTRIBUIÇÕES: %s", post)
return post | 9274caf4d484e68bdc7c852aff6360d9674b2957 | 9,393 |
import yaml
def unformat_bundle(formattedBundle):
"""
Converts a push-ready bundle into a structured object by changing
stringified yaml of 'customResourceDefinitions', 'clusterServiceVersions',
and 'packages' into lists of objects.
Undoing the format helps simplify bundle validation.
:param ... | fcc6067fab89dffa8e31e47da42060ca11a48478 | 9,394 |
def supports_box_chars() -> bool:
"""Check if the encoding supports Unicode box characters."""
return all(map(can_encode, "│─└┘┌┐")) | 82a3f57429d99dc2b16055d2b7103656ec2e05e5 | 9,395 |
def calculate_intersection_over_union(box_data, prior_boxes):
"""Calculate intersection over union of box_data with respect to
prior_boxes.
Arguments:
ground_truth_data: numpy array with shape (4) indicating x_min, y_min,
x_max and y_max coordinates of the bounding box.
prior_boxes:... | 6ac634953a92f1b81096f72209ae5d25d46aa4e6 | 9,396 |
def get_report(analytics, start_date, end_date = 'today'):
"""Queries the Analytics Reporting API V4.
Args:
analytics: An authorized Analytics Reporting API V4 service object.
Returns: The Analytics Reporting API V4 response.
"""
return analytics.reports().batchGet(
body={
'reportRequests': [
... | cac0b27a40f6a648a4d3f41aa9615dc114700f84 | 9,397 |
def write_pinout_xml(pinout, out_xml=None):
"""
write the pinout dict to xml format with no attributes. this is verbose
but is the preferred xml format
"""
ar = []
for k in sort_alpha_num(pinout.keys()):
d = pinout[k]
d['number'] = k
# ar.append({'pin': d})
ar.a... | 7f2fff341b11eb29bf672a4f78b0fc0971a26cbc | 9,398 |
import json
def get_solution(request, level=1):
"""Returns a render of answers.html"""
context = RequestContext(request)
cheat_message = '\\text{Ulovlig tegn har blitt brukt i svar}'
required_message = '\\text{Svaret ditt har ikke utfylt alle krav}'
render_to = 'game/answer.html'
if request.... | f6d5b7c90b656d2302c1aaf2935fc39bcf882a03 | 9,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.