content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def rank2int(rank):
"""Convert a rank/placing string into an integer."""
ret = None
try:
ret = int(rank.replace(u'.',u''))
except Exception:
pass
return ret | 227edc366f1a675a91efb4919139838ea81f13a2 | 658,377 |
def write(path, content):
"""Write to file."""
with open(path, 'a') as _file:
return _file.write(content) | d123d53f4c7c2c389ba39c503501b4e739fc4f7e | 658,378 |
def calc_rating_in_percents(shooters):
"""
Рассчет рейтинга в процентах на основании абсолютных величин
:return:
"""
# поиск максимального рейтинга
max_rating = max(shooters, key=lambda d: d['rating'])['rating']
# теперь посчитаем рейтинг
for shooter in shooters:
shooter['rating_... | 9c69a5031d90c7df5999972c4b9de17d986cd166 | 658,380 |
def slice_up_range(n, num_slices, start=0):
"""
Divides up `range(start,start+n)` into `num_slices` slices.
Parameters
----------
n : int
The number of (consecutive) indices in the range to be divided.
num_slices : int
The number of slices to divide the range into.
start :... | 557f93babcab7bcb84196e0b48d74fbc21e11462 | 658,381 |
from typing import Any
import os
def get_model_id(model: Any, table_name: str, sequence_increase_factor: int) -> int:
"""
Increases the sequence number for a given table by the amount of objects being
imported into that table. Hence, this gives a reserved range of ids to import the converted
slack obj... | f3421e5cd45f5fd1f498e5fec5b93e24bdd2e35b | 658,382 |
def part2(lines):
""" disassemble by hand and translate to python """
return sum(any(b % d == 0 for d in range(2, b)) for b in range(107900, 124901, 17)) | 14417caf07f0b1eaae287f0eaf62cd1ef4f035d8 | 658,383 |
def normalize_image(x):
"""
Normalize an image so its values are between 0.0 and 1.0. This is useful
for plotting the gradient.
"""
# Get the min and max values for all pixels in the input.
x_min = x.min()
x_max = x.max()
# Normalize so all values are between 0.0 and 1.0
x_norm = (x... | d1646ad132bd4931299ffa15da03665f99021ebc | 658,384 |
def get_xy_table_description(table_elt):
"""
Get a table's description.
@param IN table_elt Table XML element
@return The description as a string
"""
description = table_elt.text
return description or "" | be9012e4ea440c1643865d5e2941be737a767aea | 658,385 |
def all_lowercase(title_words):
"""
if the words are all in lowercase
>>> all_lowercase(["a", "b", "c"])
True
>>> all_lowercase(["a", "12b", "c12"])
True
>>> all_lowercase(["a", "12b", "C12"])
False
"""
concat_str = ''.join(title_words)
return concat_str.lower() == concat_st... | e6b97b76eda30e25f87b58aa12340897945139ae | 658,386 |
def PrintIterStatistics():
""" Prints statistics about the current iteration
"""
return True | 8eec4b9986a53da2319a062673ab842d38e13853 | 658,387 |
import sys
import traceback
def trace_error(logger):
"""
Capture & log the error
:param logger:
:return: Formatted error message
"""
exc_type, exc_value, exc_traceback = sys.exc_info()
rtn = traceback.format_exception(exc_type, exc_value, exc_traceback)
logger.error(rtn)
return rt... | 15bf429dcf9cee6d098f6b6b9309fa3d79f3acc9 | 658,388 |
import requests
def get_docket(auth_token, docket_number, court_name, client_matter="", cached=True, normalize=True):
"""
Takes in an authentication token as a string,
a docket number as a string, and the court name as a string,
and returns the docket data as a dictionary.
Optional parameters are... | 4f38c1bd791f76e0a0bc6e732dc89f36178745dc | 658,389 |
def restorecands(datalist, features=['snr1', 'immax1', 'l1', 'm1', 'specstd', 'specskew', 'speckurtosis', 'imskew', 'imkurtosis'],
featureind=['scan', 'segment', 'int', 'dmind', 'dtind', 'beamnum']):
""" Take list of dicts and forms as list of lists in rtpipe standard order
Order of features an... | e6069b7975d925015e61aa33b725ff76c352ec2b | 658,390 |
def configuration(generated_configuration):
"""
We can modify the generated configurations a bit before feeding them to
cookiecutter.
"""
return generated_configuration | 3cee1fdca0953568eafd956cabf742cd312f07fe | 658,391 |
import glob
import os
import shlex
def getFiles(folder, pattern, labelfile):
"""
returns files and associated labels by reading the labelfile
parameters:
folder: inputfolder
pattern: new suffix
labelfiles: contains a list of filename and labels
return: absolute filenames + la... | 9369d3a942e6b7abee3b7e12bfe6920521625b96 | 658,392 |
import os
def file_name_conversion(file_path: str, extension_to_remove=None) -> str:
"""Convert a `/path/to/file.py` to it's usable string name such as `file`.
:param file_path: the absolute path of a file preferable the __file__ constant.
:param extension_to_remove: the string that you find irrelevant a... | f845f22cbe83c5d565fcacad1c33aa32f3e56148 | 658,393 |
def rcv_to_quantified_guard(rcv_guard, rcv_vars, rcv_environment):
"""
Translate a receive guard to an smt guard, where the receive guard is
strengthened by rcv_environment, and the receive variables are existentially quantified
"""
strong_guard = '(and\n{}\n{})'.format(rcv_guard, '\n'.join(rcv_env... | 1e7ee950c096619c0a0b9fac04728b3e4d766aef | 658,394 |
def read_file(filename: str) -> list:
"""deals with a file, reading it and returning a list of domains"""
with open(filename, "r") as f:
domains = f.readlines()
return [d.strip() for d in domains] | ebfb261de38d998cba299546a9ba2b5164a5fadc | 658,395 |
def format_phone_number(phone):
"""
Given a phone number as a string of digits (only), format for presentation.
Local Libya numbers will look like '+218 (0)xx-xxx-xxxx', and Thuraya
numbers will look like '+88216xxxxxxx' (per Elliott, Hipchat, Dec. 30, 2014).
You can also use this from a template:
... | a22fdaee76786bff27610a5cf89f872a77004fd0 | 658,396 |
def maxim(numar1, numar2):
"""Funcție ce determină maximul dintre două numere."""
if numar1 > numar2:
return numar1
elif numar2 > numar1:
return numar2
else:
# Numerele sunt egale
return numar1 | da86e2417a08d45098bc80386d4301e4fbf47ee1 | 658,397 |
def df_retrieve(data,cols_vals):
"""
Retrieves a subset of a dataframe based on equivalence matches
Parameters:
data (pandas.DataFrame): the dataframe from which a subset is to be created from
cols_vals (dict): a dict with the key as the column name and the val as the equivalence val
... | adf45dfe5220a4b9222e216b9fac9fd199b150ba | 658,398 |
def link_command(mwdb, parent, child):
"""
Set relationship for objects
"""
parent_obj = mwdb.query(parent)
child_obj = mwdb.query(child)
parent_obj.add_child(child_obj)
return dict(message="Added relationship {parent} => {child}",
parent=parent_obj.id,
child=... | ce67cfce7787a10623720ec564164051591ccdda | 658,399 |
def process_nlp_response(get_response):
"""
This function takes as input an NLP GET response
and returns a list of concept codes.
Input: get_response - A list of GET responses
Output: codes - A list of concept Codes
"""
keep = ["ICD9CM", "ICD10CM", "RXNORM", "SNOMEDCT_US", "SNOMED", "NCI"]... | 0afb8a28664d51fdbed7a670afbac817795901f1 | 658,401 |
def mclag_domain_id_valid(domain_id):
"""Check if the domain id is in acceptable range (between 1 and 4095)
"""
if domain_id<1 or domain_id>4095:
return False
return True | 2af736ea6116fb83c34ed89dc464d6853a6fc88a | 658,402 |
def package_name_from_url(url):
"""Parse out Package name from a repo git url"""
url_repo_part = url.split('/')[-1]
if url_repo_part.endswith('.git'):
return url_repo_part[:-4]
return url_repo_part | cea90a8928fed1e2380d543b7e118464c3541475 | 658,403 |
def model_and_diffusion_defaults():
"""
Defaults for image training.
"""
return dict(
image_size=64,
num_channels=128,
num_res_blocks=2,
num_heads=4,
num_heads_upsample=-1,
attention_resolutions="16,8",
dropout=0.0,
learn_sigma=False,
... | c390747ca89d2a3894d091597facdea24a59af09 | 658,404 |
from pathlib import Path
def is_empty_directory(path: Path) -> bool:
"""
Returns if path is a directory with no content.
"""
sentinel = object()
return path.is_dir() and next(path.iterdir().__iter__(), sentinel) == sentinel | cda66be499f0fd40716226a765bcc5cd8ddfb1a3 | 658,405 |
def accuracy_score(y_true, y_pred):
"""Accuracy score.
Args:
y_true (array[float]): 1-d array of targets
y_predicted (array[float]): 1-d array of predictions
state_labels (array[float]): 1-d array of state representations for labels
Returns:
score (float): the fraction of c... | 3b25ec7347246aff58add4d5302a81df2851f8e1 | 658,406 |
import os
def get_version():
"""
Get the version of automatminer without worrying about circular imports in
__init__.
Returns:
(str): the version
"""
thisdir = os.path.dirname(os.path.realpath(__file__))
version_reference = os.path.join(thisdir, "../__init__.py")
with open(ve... | ce4cf23a98047d7ed621cd916b9c3b2ad0e70771 | 658,407 |
def _StopOps(from_ops, stop_gradient_ops, pending_count):
"""The set of ops that terminate the gradient computation.
This computes the frontier of the forward graph *before* which backprop
should stop. Operations in the returned set will not be differentiated.
This set is defined as the subset of `from_ops` co... | 63693d9ea9b25b124ed258144211585fa7162970 | 658,409 |
def f_unc(x, A, center, width, offset):
"""
similar to the raw function call, but uses unp instead of np for uncertainties calculations.
:return:
"""
return A / ((x - center)**2 + (width/2)**2) | b221001a2d52d6195c7d8178ad749ffdfe921dab | 658,411 |
import re
def pep8case(txt):
"""
pep8case converts a string using the lower case function
:param txt: a string
:type txt: ``str``
:return: a string with underscores and lowercase letters
:rtype: ``str``
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', txt)
return re.sub('([... | 163a902159edf01d0868119b6c7106a2c886f004 | 658,412 |
import pickle
def load_lookup_tables(paths):
"""
加载lookup tables
Args:
paths: list of str, emb路径
Returns:
lookup_tables: list of dict
"""
lookup_tables = []
for path in paths:
with open(path, 'rb', encoding='utf-8') as file_r:
lookup_tables.append(pickle... | d2aa6cf2a3b5d807725a6632682fd3bfb4c7ae4a | 658,413 |
from datetime import date
import os
def planet_by_month(
year=2016,
month=1,
api_key=None,
token_name="PLANET_API_KEY",
):
"""Gets Planet global mosaic tile url by month. To get a Planet API key, see https://developers.planet.com/quickstart/apis/
Args:
year (int, optional): The year o... | 3c228ddbb3da575c6b432e7e7517d33b48352303 | 658,414 |
def merge_dict(a: dict, b: dict) -> dict:
"""
Merge 2 dictionaries.
If the parent and child shares a similar key and the value of that key is a dictionary, the key will be recursively
merged. Otherwise, the child value will override the parent value.
Parameters
----------
a dict:
P... | cc827b5d8cba295b7eeda0723a3ae2a664c296f9 | 658,415 |
def bracket_level(text, open={'(', '[', '{'}, close={')', ']', '}'}):
"""Return 0 if string contains balanced brackets or no brackets."""
level = 0
for c in text:
if c in open:
level += 1
elif c in close:
level -= 1
return level | 904e91d498540d7753b2c7db5495deaa3acf83b6 | 658,416 |
def spammer_cmd_header(username):
"""Return formatted text for spammer command header.
Args:
username (str): DeviantArt username.
Returns:
str: Formatted text for spammer command header.
"""
return '\n'.join([
'REPORT LINK: https://contact.deviantartsupport.com/en?subOption... | 86630edf06a24de3e246408ea0eb4a5a73097bae | 658,417 |
def placeholder(_: str):
""" Return False. Using this as a command argument annotation will always fail
the command. Useful for groups.
"""
return False | e8e426469c530046211345549407aa6981a336c0 | 658,418 |
def sbs_annotation_converter(x: str) -> str:
"""
Eithers swaps from word -> arrow format for SBS or vice versa.
word: (REF)(ALT)(LEFT)(RIGHT)
arrow: (LEFT)[(REF)>(ALT)](RIGHT)
"""
if '>' in x:
return x[2]+x[4]+x[0]+x[6]
else:
return x[2]+'['+x[0]+'>'+x[1]+']'+x[3] | 462eb604687354150fb6971ef4d1a633655bd8bb | 658,419 |
import numpy
def _conv(obj, dtype=None):
""" Convert an object to the preferred form for input to the odr routine.
"""
if obj is None:
return obj
else:
if dtype is None:
obj = numpy.asarray(obj)
else:
obj = numpy.asarray(obj, dtype)
if obj.shape... | 4284b45293349e3051184ef1036a909a48e2287d | 658,420 |
def _pop_accumulator(func, attr):
"""Return and clear the accumulator of function `_accumultae_ops`"""
ret = getattr(func, attr)
delattr(func, attr)
return ret | 72fb291d08395af0c9a09a885a12829c810c4495 | 658,421 |
def _check_consistency_sizes(list_arrays) :
"""Check if all arrays in list have the same size
Parameters:
-----------
list_arrays: list of numpy arrays
Return
------
bool: True if all arrays are consistent, False otherwise.
"""
if len(list_arrays) == 0 :
return True
re... | 400ed2a038069fb4e267d5b52a0310ebd5c81b15 | 658,422 |
def add_parameters(plot_type,df):
"""[summary]
Args:
plot_type (str): [description]
Returns:
list: [description]
"""
scatter= ('color','size','facet_col','animation_frame','opacity','marginal_x','marginal_y',\
'trendline','log_x','log_y','Add L... | 37e6fea0a1b65c222b9e3e95180ef9037037f150 | 658,423 |
def validate_probability(p: float, p_str: str) -> float:
"""Validates that a probability is between 0 and 1 inclusively.
Args:
p: The value to validate.
p_str: What to call the probability in error messages.
Returns:
The probability p if the probability if valid.
Raises:
... | ec805e54db85b0d288973e0e95d7dead870eba65 | 658,424 |
def get_whos_up(dates_selected):
""" return members_dict['Bob'] = [0, 'Bob', ('middle','Mon 12/24'), ('middle','Tue 12/25'), ]
for use by show_whos_up()
"""
members_dict = {}
p_ord = 0
for event in dates_selected:
member = event['member']
try:
members_dict[member]... | ad81e36ca7ac4052cdbe6133891f37cb413fddb2 | 658,425 |
def remove_newlines(text):
# type: (str) -> str
"""
Remove newlines.
The `name` field serves as a displayable title. We remove newlines and leading and trailing
whitespace. We also collapse consecutive spaces to single spaces.
:param text: Text for newline removal
:return: Single line of t... | 06a06d2756099fc45ffc1345bf0bef44cffa9f78 | 658,426 |
def get_layer_parents(adjList,lidx):
""" Returns parent layer indices for a given layer index. """
return [e[0] for e in adjList if e[1]==lidx] | 883f239e0964aae6fb50b0cbee1490fb9df8d7a4 | 658,427 |
def get_type_from_image(td):
"""We convert a link to an image of a letter to the actual letter."""
src = td.find_elements_by_xpath('img')[0].get_attribute('src')
if 'pIcon' in src:
return 'p'
elif 'nIcon' in src:
return 'n'
elif 'iIcon' in src:
return 'i' | 9a8a265165505bd225d737b8fc996c99914caf5b | 658,429 |
import json
def getData(option1, option2 = None):
"""
## Get data from config.json file.
"""
data = json.load(open('../../client/config/config.json', "r"))
if option2 == None:
req_option = data.get(option1)
else:
req_option = data[option1].get(option2)
return req_... | 143d962cd4b2bd42dad5393dd09ab7e879f70307 | 658,431 |
import glob
def get_dicom_paths():
"""Return DICOM paths to all LIDC direcotries
e.g. ['../images_full/LIDC-IDRI-0001/1.3.6.1.4.1.14519.5.2.1.6279.6001.298806137288633453246975630178/' \
'1.3.6.1.4.1.14519.5.2.1.6279.6001.179049373636438705059720603192']"""
return glob.glob("../images_full/LIDC-... | f6d328a5a2ec44a2427153dd9f695fbda24b6085 | 658,432 |
import torch
def convert_points_from_homogeneous(points, eps=1e-8):
""""
Function that converts points from homogeneous to Euclidean space.
"""
if len(points.shape) < 2:
raise ValueError("Input must be at least a 2D tensor. Got {}".format(
points.shape))
# we check for p... | 61d1a367e07d9d10336031a2725358fcbd849480 | 658,433 |
def calculate(puzzle_input):
"""Tracks Santa's steps"""
x = y = rx = ry = 0
visited = set()
robot = False
for step in puzzle_input:
if step == "^":
if robot:
ry += 1
else:
y += 1
elif step == "v":
if robot:
... | f29875d2e0a1352f2863aad7820911df33844bf7 | 658,434 |
from pathlib import Path
import configparser
import argparse
import codecs
def get_arguments():
"""
Get command line arguments and return them.
"""
home = str(Path.home())
config = configparser.ConfigParser(interpolation=None)
config.read(home + "/.config/cliplayer/cliplayer.cfg")
parser ... | e00a053bea0a1b98f5121008cf0127fae8bd3a00 | 658,435 |
import os
def lemmatize(text, lemmatizer_path=None):
"""This method lemmatize the text. Its used NILC's LematizadorV2a
(http://conteudo.icmc.usp.br/pessoas/taspardo/LematizadorV2a.rar).
Args:
text (str): Text to be lemmatized.
lemmatizer_path (str): Path to lemmatizer, if not passed will ... | 7f90d4c015069fcfbfdab9862f838b0e7126fd97 | 658,436 |
def available_letters(remaining, guess):
"""
Check for available letters.
"""
newstr = ""
for i in remaining:
# print i
# print "Checking " + i
if i == guess:
# print "removing ", guess
# print "new string: ", newstr
newstr
else:
... | 0ffaa7ca558ed18613d15c7d75a00427817f53f8 | 658,438 |
def random_sample(percent=None, return_expectations=None):
"""
A random sample of approximately `percent` patients
"""
return "random_sample", locals() | d4212f29c8861dab3a33c8abead82a5aa6685ef6 | 658,439 |
def public(func):
"""Decorator that marks a function as available for anonymous access.
Useful only in a context of AuthenticatingHandler subclass to mark method as
explicitly open for anonymous access. Without it AuthenticatingHandler will
complain:
class MyHandler(auth.AuthenticatingHandler):
@auth.pu... | 2d6acf540c0a96a11c3681efb286d5893ea077bb | 658,440 |
def verifie_identique(liste):
"""Fonction qui, à l'aide d'une liste, retourne un booléen variant selon si la liste contient au moins deux éléments
identiques.
Paramètre(s):
- liste list: Liste à vérifier, peut posséder un nombre d'élément indéfini sachant que ceux-ci doivent être les
chaîne... | 939b6a8cf24586beecc0f52d2199389b345dba17 | 658,441 |
def extract_bmpstp(filename):
"""
Extracts Bmpstp from filename. Filenames are often of the form:
fort.Bmpstp
or:
fort.(Bmpstp+myid)
"""
ii = int(filename.split('fort.')[1].split('+myid')[0]) # Extract from filename
# Not true?
#if ii >= 100:
# print(... | 14c97713d23c3bbf522084c5dfa5c06bf0d7cf54 | 658,442 |
def max_value(tab):
"""
This function determine the max value of list tab
Parameters :
tab: the list
Returns :
return the max value of list
"""
max_val = 0
for i in tab:
if i > max_val:
max_val = i
return max_val | 0db8284b94b968bd4f309073ba5cd7dccf6f2922 | 658,444 |
def train_transforms(operations, columns):
"""
Train a chain of transformations to the data.
:return: Returns the trained operations for style, although they are also changed in-place.
"""
for name in operations.keys():
col = columns[name]
for op in operations[name]:
op.learn(col)
return operations | 965407c78e73eca600619c51a12ab2362bcf15ff | 658,446 |
import hashlib
import os
def filemd5(filepath):
"""
Get MD5 hash of a file
"""
md5_hash = hashlib.md5()
if os.path.isfile(filepath):
with open(filepath, "rb") as f:
# Read and update hash in chunks of 4K
for byte_block in iter(lambda: f.read(4096), b""):
... | 4aef978c65174907771d922410affeef4876181f | 658,447 |
def intersect_2d(x1, x2):
"""
Given two arrays [m1, n], [m2,n], returns a [m1, m2] array where each entry is True if those
rows match.
:param x1: [m1, n] numpy array
:param x2: [m2, n] numpy array
:return: [m1, m2] bool array of the intersections
"""
if x1.shape[1] != x2.shape[1]:
... | 0be6afa1f0d1cdd9bdf41dde0d938db8e46e308b | 658,448 |
from typing import Any
def flags_to_args(flags: dict[str, Any]) -> dict[str, Any]:
"""
Turn flags dict from docopt into **kwargs-usable dict.
'--'-prefix is removed, dashes are turned into underscores
and keys are lowercased.
When conflicts arise (ie --repo: None vs REPO: "ideaseed"), do a 'or',
... | 32c4b13d4814b8da20f84f27c1f0b1675c91e064 | 658,449 |
def _generate_linux_body(hooks):
"""
Generate linux specific functions.
At the moment it implements load_impls_from_library and the class destructor
to cleanup handles.
"""
# generate destructor to free the library handles opened by load_from_library()
result = [
f"private:",
... | ec45198bce76cc0fa52fc2001e78c9168f08c2f6 | 658,450 |
def createFile(name, paramToValue, numberOfCycles=1):
"""Creates a dictionary storing file information"""
File = {'name': name,
'paramToValue': paramToValue,
'numberOfCycles': numberOfCycles}
return File | 55294fb81152977ff0262c78888fb08986234a0a | 658,451 |
import argparse
def parse_args(wk):
"""
A command line argument parser
:return:
"""
ap = argparse.ArgumentParser()
# passed arguments
ap.add_argument('-p', '--projectName', type=str, default=wk, help='project name & dir name')
ap.add_argument('-g', '--gabarit', type=bool, default=True,... | 5a9295e171a30d3e935520a73693711a87342e40 | 658,452 |
def rol(x, i):
"""Rotate the bottom 32 bits of x left by i bits."""
return ((x << i) | ((x & 0xffffffff) >> (32 - i))) & 0xffffffff | 33ecbe3ed9f0806e14c6abbfb75889e916dfc78b | 658,453 |
import traceback
def _formatException(_, ei):
"""
Format and return the specified exception information as a string.
This implementation builds the complete stack trace, combining
traceback.format_exception and traceback.format_stack.
"""
lines = traceback.format_exception(*ei)
if ei[2]:
... | ce4b571159eb1b1df45323ceebff684eea054359 | 658,454 |
def virial_temp_HB(mass, z):
"""Virial temperature from halo mass according to Haiman & Bryan
(2006ApJ...650....7).
z is the redshift.
Units are Msun and kelvin.
"""
return 1800. * (mass/1e6)**(2./3.) * (1.+z)/21 | 8ce9df3435414491b815f6a1e0f9c8da7d5c6aa1 | 658,455 |
import json
def GetDataFromFile(filename):
"""
Retrives JSON formatted data from a file and loads as a Python object.
Returns False if the requested file is unreadable.
"""
try:
fileObj = open(filename, 'r')
except IOError:
return False
data = json.load(fileObj)
fileObj.close()
return data | 343566b38772a1054b7eda89d388af38f2cb9bf9 | 658,456 |
def is_not_outstanding(invoice):
"""
Return `True` if the given invoice is paid
"""
return invoice.status == 'Paid' | 03c06180a87ec9eb1d9708010e2cf62a88cad03a | 658,457 |
import argparse
import ast
def parse_args():
"""
parse arguments
"""
parser = argparse.ArgumentParser(description="MindSpore Stacked Hourglass")
# Model
parser.add_argument("--nstack", type=int, default=2)
parser.add_argument("--inp_dim", type=int, default=256)
parser.add_argument("--... | 09c8100cbfab9e3da38051e9f9168f82c8019782 | 658,458 |
def tarFilter(tarinfo):
"""
_tarFilter_
Filters what goes into a tarball
"""
if tarinfo.name.endswith(".svn") or tarinfo.name.endswith(".git"):
return None
else:
return tarinfo | a41cec9f5cfba69be17d0c66873d0aab76e5ef1a | 658,459 |
import argparse
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Train a Fast R-CNN network')
# Config the session ID for identify
parser.add_argument('--session', dest='session', default=1, type=int, help='Training session ID')
parser.add_argu... | 5a6b52c6fb7d10111c62123029c655efdcb037d0 | 658,460 |
import torch
def gather(x, idx):
"""
Args:
x: (B, d, N)
idx: (B, N, k)
Returns:
(B, N, K, d)
"""
batch_size, num_dims, num_points = x.size()
k = idx.size(2)
assert x.size(2) == idx.size(1)
device = x.device
idx_base = torch.arange(0, batch_size, device=de... | 0b3c0747c0fbe57028b606e48525265115ab7016 | 658,461 |
from pathlib import Path
def resolve_path(path: Path, database_yml: Path) -> Path:
"""Resolve path
Parameters
----------
path : `Path`
Path. Can be either absolute, relative to current working directory, or
relative to `config.yml`.
database_yml : `Path`
Path to pyannote.d... | 0f371334aec7e4c1ac04f8ffdab961094a01a02f | 658,463 |
def p1evl(x, coef, N):
"""
Evaluates the given polynomial of degree <tt>N</tt> at <tt>x</tt>.
Evaluates polynomial when coefficient of N is 1.0. Otherwise same as
<tt>polevl()</tt>.
Coefficients are stored in reverse order.
The function <tt>p1evl()</tt> assumes that <tt>coef[N] = 1.0</tt> and ... | 3d9bad2039aecc4f26b3eaf5db1675c84cd4e764 | 658,464 |
def external_component(decorated):
"""
A decorator gadget that generates base address variables for each unique
external component as well as a get() function
Usage:
@external_component
function(generator, outfile, ...):
outfile.write( <contents that depend on component base... | 9ad16fb23e3f29097834298c397e66237dc7be95 | 658,466 |
def get_revision_ids_for_credential(credential):
"""
For the given credential, return a list of archive credential IDs.
"""
_range = range(1, credential.revision + 1)
ids = []
for i in _range:
ids.append("{0}-{1}".format(credential.id, i))
return ids | 58b86adce5351c956c056eef17d179989c4172ee | 658,467 |
def inverse_mvr(mean, var):
"""
Inverse function of the negative binomial fixed-dispersion mean-variance
relationship. Vectorized.
Parameters
----------
mean, var : float
The mean and variance of a NB distribution, respectively.
Returns
-------
float
The dispersion ... | 89f83639d5bfb0f7f5f4a7121f747ec2b4f5724e | 658,468 |
def state_from_scratch(args: tuple, kwargs: dict) -> dict:
"""Create pipeline state from (args, kwargs)."""
state = {i: v for i, v in enumerate(args)}
state.update(kwargs)
return state | 26b84c95fcdeae55e903cdfa763bfc59597caedb | 658,469 |
def timestr(seconds):
"""Return time as string M:SS."""
minutes = seconds // 60
seconds = seconds - (minutes * 60)
return f"{minutes}:{seconds:02}" | 2f37ade13839170ad48af401fd80ae171a688070 | 658,470 |
def get_markdown_files(data_path):
"""获取.md.ziw文件列表"""
md_files = list(data_path.glob('**/*.md*.ziw'))
print(f'共发现{len(md_files)}个Markdown文件。')
return md_files | 0307e3d55460148aad274e70cf700d121d107fe1 | 658,471 |
def part1(entries: list) -> int:
"""part1 solver take the entries and return the part1 solution"""
crabs = sorted(entries)
middle_crab = crabs[len(crabs)//2]
return sum(abs(crab - middle_crab) for crab in crabs) | 9ef497d516cb07c393c22aa9153a65366ede5446 | 658,473 |
import torch
def zeros_like(input, *args, **kwargs):
"""
In ``treetensor``, you can use ``zeros_like`` to create a tree of tensors with all zeros like another tree.
Example::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.zeros_like(torch.randn(2, 3)) # the sa... | 13cdc7481cfccab12a2bd5fe20a754442176c447 | 658,474 |
def asyncpg_engine_dsn(db_url: str) -> str:
"""Return Database URL with asyncpg engine.
:param db_url: Base database URL
"""
split = db_url.split(":")
split[0] = f"{split[0]}ql+asyncpg"
return ":".join(split) | 14270d28ab41644da8ed517c83e1cfcf2a1209a5 | 658,475 |
import struct
import socket
def dottedQuadToNum(ip):
"""
convert decimal dotted quad string to long integer
"""
return struct.unpack('I', socket.inet_aton(ip))[0] | 4cb530bbe52ff118b2840164565e9e211cb24ea6 | 658,476 |
def resolve_mro(model, name, predicate):
""" Return the list of successively overridden values of attribute ``name``
in mro order on ``model`` that satisfy ``predicate``. Model classes
(the ones that appear in the registry) are ignored.
"""
result = []
for cls in type(model).__mro__:
... | 8f98e774e908075b84dc1d1c15f961f3879c17ea | 658,477 |
def generate_tags(trip_destination_data, destination_info,
num_destinations, num_existing_destinations,
existing_tags, country_dict):
"""Generates a list of tags, destination tags and trip tags to be inserted
into the database.
Keyword arguments:
trip_destinati... | aa35f998af849eb049489de061d25212483eff47 | 658,479 |
def ping():
"""[ping func provides a health check]
Returns:
[dict]: [success response for health check]
"""
return {"response": "ping to datahub successful"} | f433eaac3d2a3b8fbfd80f7a76b15f2c077432d1 | 658,480 |
from typing import Optional
from typing import List
def _listify(chars: str) -> Optional[List]:
"""
Converts a string into a list of characters.
:param chars: String containing the characters you wish to turn into a list.
:return: List of characters.
"""
return list(chars) | b7b6e2180c41c0f4048ea87011d7667365b2c9e2 | 658,481 |
def islower(text):
"""
Checks if all cased characters in ``text`` are lowercase and there is at least one cased character.
Cased characters are defined by the Unicode standard. All alphabetic characters in the
ASCII character set are cased.
:param text: The string to check
:type text... | daae3011c5c4ceb80dda46ec68b905a5bac06f31 | 658,482 |
def get_holidays_by_category(holiday_list, categories_list, category_string):
"""get all holidays by category"""
filtered_holiday_list = []
category_obj = next(cat for cat in categories_list if cat.name == category_string.strip())
for holiday_item in holiday_list:
if holiday_item.category.name.l... | 9d8acc01e3d40877b2e2c1d30bb59499ebf471e0 | 658,483 |
def startswith(s, prefix):
""" True if the string starts with the specified prefix. """
return s.startswith(prefix) | 656669790d43b90cf2b8a2a15cb4c73b7182d36d | 658,484 |
from typing import Callable
from typing import Any
import asyncio
async def async_on_threadpool(callable_function: Callable, *args: Any) -> Any:
"""Ensures blocking operation runs on shared thread pool"""
return await asyncio.get_event_loop().run_in_executor(
None, callable_function, *args
) | 2494ac2e1e7981ad022bc30816d8560c4c5f119c | 658,485 |
def _section(section_name, section_data):
"""Add opening/closing section_name tags to data."""
opening_tag = ['<' + section_name + '>']
closing_tag = ['</' + section_name + '>']
section = None
if isinstance(section_data, list):
section = opening_tag + section_data + closing_tag
elif isi... | 2f4b89ad5d8c8b7feff799f215f43f5275c67ada | 658,486 |
import os
def fcount(path):
""" Counts the number of files in a directory """
count = 0
for f in os.listdir(path):
if os.path.isfile(os.path.join(path, f)):
count += 1
return count | 4c30d68655abe59749d13c801be23fdd690ae10b | 658,488 |
def sanitize(name):
"""
Sanitize the specified ``name`` for use with breathe directives.
**Parameters**
``name`` (:class:`python:str`)
The name to be sanitized.
**Return**
:class:`python:str`
The input ``name`` sanitized to use with breathe directives (primarily for use
... | 3585902680c05bb681df36ba4083525b808e71de | 658,489 |
def obj_get_name(obj):
"""get_name(obj) return object name."""
return obj.__name__ | c13c1a219c7a00552d0c1b1b51fb205337beb95a | 658,490 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.