content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _get_stops() -> None:
"""Import stop words either from a text file or stopwords corpus"""
global stops
import Settings
filename=Settings.dir_name + 'patentstops.txt'
if filename:
f = File(filename).openText()
for line in f.readlines():
stops += line.split()
f... | 5,345,400 |
def failed_revisions_for_case_study(
case_study: CaseStudy, result_file_type: MetaReport
) -> tp.List[str]:
"""
Computes all revisions of this case study that have failed.
Args:
case_study: to work on
result_file_type: report type of the result files
Returns:
a list of fail... | 5,345,401 |
def _removeTwoSentenceCommonNode(syncSrc1, syncSrc2, matchListT1, matchListT2, prefix):
"""
Identify and remove a node that appears to be in both of the target sentences,
and is also a currently active link
"""
raise DeprecationWarning, "Now finding split points before individual pairs"
# a usef... | 5,345,402 |
def bytes_load(path):
"""Load bytest from a file."""
with open(path, 'rb') as f:
return f.read() | 5,345,403 |
def get_relationship_length_fam_mean(data):
"""Calculate mean length of relationship for families DataDef 43
Arguments:
data - data frames to fulfill definiton id
Modifies:
Nothing
Returns: added_members
mean_relationship_length - mean relationship length of families
"""
families... | 5,345,404 |
def create_jar(jar_file, entries):
"""
Create JAR from given entries.
:param jar_file: filename of the created JAR
:type jar_file: str
:param entries: files to put into the JAR
:type entries: list[str]
:return: None
"""
# 'jar' adds separate entries for directories, also for empty o... | 5,345,405 |
def convert_hapmap(input_dataframe, recode=False, index_col=0):
""" Specifically deals with hapmap and 23anMe Output
"""
complement = {'G/T': 'C/A', 'C/T': 'G/A', "G/A" : "G/A", "C/A": "C/A", "A/G" : "A/G",
"A/C": "A/C"}
dataframe = input_dataframe.copy()
if recode:
recode = data... | 5,345,406 |
def visualize_labels(
labels, title="Visualization of labels", mode: str = "lines"
) -> None:
"""
Plot labels.
Parameters
----------
title: str
Title of the plot.
mode: str
Determines the drawing mode for this scatter trace. If
the provided `mode` includes "text" th... | 5,345,407 |
def to_base64(message):
"""
Returns the base64 representation of a string or bytes.
"""
return b64encode(to_bytes(message)).decode('ascii') | 5,345,408 |
def create_alerts():
"""
Function to create alerts.
"""
try:
# validate post json data
content = request.json
print(content)
if not content: raise ValueError("Empty value")
if not 'timestamp' in content or not 'camera_id' in content or not 'class_id' in content... | 5,345,409 |
def read_envs():
"""Function will read in all environment variables into a dictionary
:returns: Dictionary containing all environment variables or defaults
:rtype: dict
"""
envs = {}
envs['QUEUE_INIT_TIMEOUT'] = os.environ.get('QUEUE_INIT_TIMEOUT', '3600')
envs['VALIDATION_TIMEOUT'] = os.environ.get('VALIDATIO... | 5,345,410 |
def generate(env):
"""Add Builders and construction variables for rmic to an Environment."""
env['BUILDERS']['RMIC'] = RMICBuilder
env['RMIC'] = 'rmic'
env['RMICFLAGS'] = SCons.Util.CLVar('')
env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpa... | 5,345,411 |
def get_platform():
""" Get system platform metadata.
"""
detected_os = platform.system()
detected_distro = platform.platform()
if detected_os == "Darwin":
return PlatformDescription(detected_os=detected_os,
detected_distro=detected_distro,
... | 5,345,412 |
def load_catalog_npy(catalog_path):
"""
Load a numpy catalog (extension ".npy")
@param catalog_path: str
@return record array
"""
return numpy.load(catalog_path) | 5,345,413 |
def pgd(fname, n_gg=20, n_mm=20, n_kk=20, n_scale=1001):
"""
:param fname: data file name
:param n_gg: outer iterations
:param n_mm: intermediate iterations
:param n_kk: inner iterations
:param n_scale: number of discretized points, arbitrary
:return:
"""
n_buses, Qmax, Qmin, Y, V_... | 5,345,414 |
def test_bingmdx_tr_sanity():
""" test bingmdx_tr sanity. """
assert bingmdx_tr("test") # '试验;检测;考试;测验'
assert "试验" in bingmdx_tr("test") | 5,345,415 |
def find_first_empty(rect):
"""
Scan a rectangle and find first open square
@param {Array} rect Board layout (rectangle)
@return {tuple} x & y coordinates of the leftmost top blank square
"""
return _find_first_empty_wrapped(len(rect[0]))(rect) | 5,345,416 |
def parseArticle(text: str) -> str:
"""
Parses and filters an article. It uses the `wikitextparser` and custom logic.
"""
# clear the image attachments and links
text = re.sub("\[\[Податотека:.+\]\][ \n]", '', text)
text = wikipedia.filtering.clearCurlyBrackets(text)
# replace everythi... | 5,345,417 |
def plot_spectrum(x, y, filename, title, con_start_vel, con_end_vel, sigma_tau):
"""
Output a plot of opacity vs LSR velocity to a specified file.
:param x: The velocity data
:param y: The opacity values for each velocity step
:param filename: The file the plot should be written to. Should be
... | 5,345,418 |
def exp2(input, *args, **kwargs):
"""
Computes the base two exponential function of ``input``.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.exp2(ttorch.tensor([-4.0, -1.0, 0, 2.0, 4.8, 8.0]))
tensor([6.2500e-02, 5.0000e-01, 1.0000e+00, 4.0000... | 5,345,419 |
def list_default_storage_policy_of_datastore(
datastore,
host=None,
vcenter=None,
username=None,
password=None,
protocol=None,
port=None,
verify_ssl=True,
):
"""
Returns a list of datastores assign the storage policies.
datastore
Name of the datastore to assign.
... | 5,345,420 |
def action_stats(env, md_action, cont_action):
"""
Get information on `env`'s action space.
Parameters
----------
md_action : bool
Whether the `env`'s action space is multidimensional.
cont_action : bool
Whether the `env`'s action space is continuous.
Returns
-------
n_actions_per_dim : list of length (action_dim... | 5,345,421 |
def count(pred: Pred, seq: Seq) -> int:
"""
Count the number of occurrences in which predicate is true.
"""
pred = to_callable(pred)
return sum(1 for x in seq if pred(x)) | 5,345,422 |
def lambda_k(W, Z, k):
"""Coulomb function $\lambda_k$ as per Behrens et al.
:param W: Total electron energy in units of its rest mass
:param Z: Proton number of daughter
:param k: absolute value of kappa
"""
#return 1.
gammak = np.sqrt(k**2.0-(ALPHA*Z)**2.0)
gamma1 = np.sqrt(1.-(ALPHA... | 5,345,423 |
def tryJsonOrPlain(text):
"""Return json formatted, if possible. Otherwise just return."""
try:
return pprint.pformat( json.loads( text ), indent=1 )
except:
return text | 5,345,424 |
def test_get_yesterday_alias():
"""Test getting date object for 'yesterday' alias"""
assert helpers.get_date_object_for_alias('yesterday') == date(2021, 12, 31) | 5,345,425 |
def create_signaling(args):
"""
Create a signaling method based on command-line arguments.
"""
if args.signaling == "apprtc":
if aiohttp is None or websockets is None: # pragma: no cover
raise Exception("Please install aiohttp and websockets to use appr.tc")
if not args.sign... | 5,345,426 |
def fitswrite(img, imgname, **kwargs):
"""
Write FITS image to disk.
Parameters
----------
img : numpy array
2D or 3D numpy array
imgname : string
Name of the output FITS image
Optional Keywords
-----------------
header : pyFITS header
F... | 5,345,427 |
def signup(DB_MAN: DB_manager, DB_CONN: Connection) -> None:
"""This function represents a view to the signup page.
Args:
DB_MAN (DB_manager): database manager.
DB_CONN (Connection): database connection.
"""
# signup form to retrieve the information from the user.
st.subheader("Sig... | 5,345,428 |
def get_corpus_gene_adjacency(corpus_id):
"""Generate a nugget table."""
corpus = get_corpus(corpus_id)
data = get_gene_adjacency(corpus)
return jsonify(data), 200 | 5,345,429 |
def get_pool_health(pool):
""" Get ZFS list info. """
pool_name = pool.split()[0]
pool_capacity = pool.split()[6]
pool_health = pool.split()[9]
return pool_name, pool_capacity, pool_health | 5,345,430 |
def resize_short(img, target_size):
""" resize_short """
percent = float(target_size) / min(img.shape[0], img.shape[1])
resized_width = int(round(img.shape[1] * percent))
resized_height = int(round(img.shape[0] * percent))
resized_width = normwidth(resized_width)
resized_height = normwidth(resi... | 5,345,431 |
def _scale(aesthetic, name=None, breaks=None, labels=None, limits=None, expand=None, na_value=None, guide=None,
trans=None, **other):
"""
Create a scale (discrete or continuous)
:param aesthetic
The name of the aesthetic that this scale works with
:param name
The name of the ... | 5,345,432 |
def test_del_alarm():
"""Tests del_alarm method
"""
#WARNING: This test will clear all the alarms that have been saved
test_alarm1 = {"title":"test_alarm1","content":"content"}
test_alarm2 = {"title":"test_alarm2","content":"content"}
test_alarm3 = {"title":"test_alarm3","content":"content"}
... | 5,345,433 |
def logsubexp(x, y):
"""
Helper function to compute the exponential
of a difference between two numbers
Computes: ``x + np.log1p(-np.exp(y-x))``
Parameters
----------
x, y : float or array_like
Inputs
"""
if np.any(x < y):
raise RuntimeError('cannot take log of nega... | 5,345,434 |
async def test_exception_handling():
"""Test handling of exceptions."""
send_messages = []
user = MockUser()
refresh_token = Mock()
conn = websocket_api.ActiveConnection(
logging.getLogger(__name__), None, send_messages.append, user, refresh_token
)
for (exc, code, err) in (
... | 5,345,435 |
def is_sequence_of_list(items):
"""Verify that the sequence contains only items of type list.
Parameters
----------
items : sequence
The items.
Returns
-------
bool
True if all items in the sequence are of type list.
False otherwise.
Examples
--------
>... | 5,345,436 |
def sum_fib_dp(m, n):
"""
A dynamic programming version.
"""
if m > n: m, n = n, m
large, small = 1, 0
# a running sum for Fibbo m ~ n + 1
running = 0
# dynamically update the two variables
for i in range(n):
large, small = large + small, large
# note that (i + 1)... | 5,345,437 |
def fibo_dyn2(n):
"""
return
the n-th fibonacci number
"""
if n < 2:
return 1
else:
a, b = 1, 1
for _ in range(1,n):
a, b = b, a+b
return b | 5,345,438 |
def upload_model(source, destination, tmpfile):
"""Uploads a file to the bucket."""
urllib.request.urlretrieve(source, tmpfile)
storage_client = storage.Client()
bucket = storage_client.get_bucket(BUCKET_NAME)
blob = bucket.blob("/".join([FOLDER_NAME, destination]))
blob.upload_from_filename(tmpfile) | 5,345,439 |
def test_get_offline_wikis(fs):
"""Local wiki names are found."""
fs.create_file("/data1/frwiki-20201020-md5sums.txt")
fs.create_file("/data2/enwiki-20201020-md5sums.txt")
wct = ww.CorporaTracker(local_dirs=["/data1", "/data2"], online=False, verbose=False)
assert len(wct.list_local_wikis()) == 2
... | 5,345,440 |
def build_all(box, request_list):
"""
box is [handle, left, top, bottom] \n
request_list is the array about dic \n
****** Attention
before running the function, you should be index.
After build_all, function will close the windows about train troop
"""
# get the ... | 5,345,441 |
def select_results(results):
"""Select relevant images from results
Selects most recent image for location, and results with positive fit index.
"""
# Select results with positive bestFitIndex
results = [x for x in results['items'] if x['bestFitIndex'] > 0]
# counter_dict schema:
# counter... | 5,345,442 |
def dc_session(virtual_smoothie_env, monkeypatch):
"""
Mock session manager for deck calibation
"""
ses = endpoints.SessionManager()
monkeypatch.setattr(endpoints, 'session', ses)
return ses | 5,345,443 |
def is_available(_cache={}):
"""Return version tuple and None if OmnisciDB server is accessible or
recent enough. Otherwise return None and the reason about
unavailability.
"""
if not _cache:
omnisci = next(global_omnisci_singleton)
try:
version = omnisci.version
... | 5,345,444 |
def pitch_info_from_pitch_string(pitch_str: str) -> PitchInfo:
"""
Parse a pitch string representation. E.g. C#4, A#5, Gb8
"""
parts = tuple((c for c in pitch_str))
size = len(parts)
pitch_class = register = accidental = None
if size == 1:
(pitch_class,) = parts
elif size == 2:... | 5,345,445 |
def test_multiple_meta() -> None:
"""Test parsing multiple meta."""
docstring = parse(
"""
Short description
Parameters
----------
spam
asd
1
2
3
Raises
------
bla
herp
yay
... | 5,345,446 |
def dump_one_page(title: str, page_id: str, content: str):
"""
保存文章
$title: 文章标题
$page_id: 文章的 id
$content: 文章的 html 文档
"""
print(f"\n***[SAVING {page_id}]***")
html_file = f"files/{title} - {page_id}.html"
md_file = f"files/{title} - {page_id}.md"
print(f"Saving the article to {... | 5,345,447 |
def determine_word_type(tag):
"""
Determines the word type by checking the tag returned by the nltk.pos_tag(arr[str]) function.
Each word in the array is marked with a special tag which can be used to find the correct type of a word.
A selection is given in the dictionaries.
Args:
tag : String tag from the nltk... | 5,345,448 |
def get_normalized_map_from_google(normalization_type, connection=None, n_header_lines=0):
"""
get normalized voci or titoli mapping from gdoc spreadsheets
:param: normalization_type (t|v)
:param: connection - (optional) a connection to the google account (singleton)
:param: n_header_lines - (optio... | 5,345,449 |
def parse_file(fname, is_true=True):
"""Parse file to get labels."""
labels = []
with io.open(fname, "r", encoding="utf-8", errors="igore") as fin:
for line in fin:
label = line.strip().split()[0]
if is_true:
assert label[:9] == "__label__"
lab... | 5,345,450 |
def main(event, context):
"""
Args:
package: Python Package to build and deploy
return:
execution_arn: ARN of the state machine execution that is building the package
"""
packages = get_config.get_packages()
execution_arns =[]
for package in packages:
client = boto3.... | 5,345,451 |
def make_mesh(object_name, object_colour=(0.25, 0.25, 0.25, 1.0), collection="Collection"):
"""
Create a mesh then return the object reference and the mesh object
:param object_name: Name of the object
:type object_name: str
:param object_colour: RGBA colour of the object, defaults to a shade of g... | 5,345,452 |
def _OptionParser():
"""Returns the options parser for run-bisect-perf-regression.py."""
usage = ('%prog [options] [-- chromium-options]\n'
'Used by a try bot to run the bisection script using the parameters'
' provided in the auto_bisect/bisect.cfg file.')
parser = optparse.OptionParser(usa... | 5,345,453 |
def calc_radiance(wavel, Temp):
"""
Calculate the blackbody radiance
Parameters
----------
wavel: float or array
wavelength (meters)
Temp: float
temperature (K)
Returns
-------
Llambda: float or arr
monochromatic radianc... | 5,345,454 |
def load_config(filename):
"""
Returns:
dict
"""
config = json.load(open(filename, 'r'))
# back-compat
if 'csvFile' in config:
config['modelCategoryFile'] = config['csvFile']
del config['csvFile']
required_files = ["prefix", "modelCategoryFile", "colorFile"]
for... | 5,345,455 |
def _JMS_to_Fierz_III_IV_V(C, qqqq):
"""From JMS to 4-quark Fierz basis for Classes III, IV and V.
`qqqq` should be of the form 'sbuc', 'sdcc', 'ucuu' etc."""
#case dduu
classIII = ['sbuc', 'sbcu', 'dbuc', 'dbcu', 'dsuc', 'dscu']
classVdduu = ['sbuu' , 'dbuu', 'dsuu', 'sbcc' , 'dbcc', 'dscc']
if... | 5,345,456 |
def get_parsed_args() -> Any:
"""Return Porcupine's arguments as returned by :func:`argparse.parse_args`."""
assert _parsed_args is not None
return _parsed_args | 5,345,457 |
def get_license_description(license_code):
"""
Gets the description of the given license code. For example, license code '1002' results in 'Accessory Garage'
:param license_code: The license code
:return: The license description
"""
global _cached_license_desc
return _cached_license_desc[lic... | 5,345,458 |
def db_keys_unlock(passphrase) -> bool:
"""Unlock secret key with pass phrase"""
global _secretkeyfile
try:
with open(_secretkeyfile, "rb") as f:
secretkey = pickle.load(f)
if not secretkey["locked"]:
print("Secret key file is already unlocked")
return Tr... | 5,345,459 |
def list_domains():
"""
Return a list of the salt_id names of all available Vagrant VMs on
this host without regard to the path where they are defined.
CLI Example:
.. code-block:: bash
salt '*' vagrant.list_domains --log-level=info
The log shows information about all known Vagrant e... | 5,345,460 |
def get_old_options(cli, image):
""" Returns Dockerfile values for CMD and Entrypoint
"""
return {
'cmd': dockerapi.inspect_config(cli, image, 'Cmd'),
'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'),
} | 5,345,461 |
def line_crops_and_labels(iam: IAM, split: str):
"""Load IAM line labels and regions, and load line image crops."""
crops = []
labels = []
for filename in iam.form_filenames:
if not iam.split_by_id[filename.stem] == split:
continue
image = util.read_image_pil(filename)
... | 5,345,462 |
def convert(chinese):
"""converts Chinese numbers to int
in: string
out: string
"""
numbers = {'零':0, '一':1, '二':2, '三':3, '四':4, '五':5, '六':6, '七':7, '八':8, '九':9, '壹':1, '贰':2, '叁':3, '肆':4, '伍':5, '陆':6, '柒':7, '捌':8, '玖':9, '两':2, '廿':20, '卅':30, '卌':40, '虚':50, '圆':60, '近':70, '枯':80, '无'... | 5,345,463 |
def computeZvector(idata, hue, control, features_to_eval):
"""
:param all_data: dataframe
:return:
"""
all_data = idata.copy()
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
m_indexes = list(all_data[hue].unique().astype('str'))
query_one = ""
for el in contr... | 5,345,464 |
def getjflag(job):
"""Returns flag if job in finished state"""
return 1 if job['jobstatus'] in ('finished', 'failed', 'cancelled', 'closed') else 0 | 5,345,465 |
def describe_snapshot_schedule(VolumeARN=None):
"""
Describes the snapshot schedule for the specified gateway volume. The snapshot schedule information includes intervals at which snapshots are automatically initiated on the volume. This operation is only supported in the cached volume and stored volume archite... | 5,345,466 |
def json_parse(ddict):
"""
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/test_json/test_functions.json
https://github.com/arita37/mlmodels/blob/dev/mlmodels/dataset/json/benchmark_timeseries/gluonts_m5.json
"deepar": {
"model_pars": {
"model_uri" : "model... | 5,345,467 |
def read_viz_icons(style='icomoon', fname='infinity.png'):
""" Read specific icon from specific style
Parameters
----------
style : str
Current icon style. Default is icomoon.
fname : str
Filename of icon. This should be found in folder HOME/.dipy/style/.
Default is infinity... | 5,345,468 |
def mock_config_entry() -> MockConfigEntry:
"""Return the default mocked config entry."""
return MockConfigEntry(
title="12345",
domain=DOMAIN,
data={CONF_API_KEY: "tskey-MOCK", CONF_SYSTEM_ID: 12345},
unique_id="12345",
) | 5,345,469 |
def get_mnist_loader(batch_size, train, perm=0., Nparts=1, part=0, seed=0, taskid=0, pre_processed=True, **loader_kwargs):
"""Builds and returns Dataloader for MNIST and SVHN dataset."""
transform = transforms.Compose([
transforms.Grayscale(),
transforms.ToTensor(),
... | 5,345,470 |
def gradients_summary(y, x, norm=tf.abs, name='gradients_y_wrt_x'):
"""Summary gradients w.r.t. x.
Sum of norm of :math:`\\nabla_xy`.
:param y: y
:param x: w.r.t x
:param norm: norm function, default is tf.abs
:param name: name of gradients summary
:return: None
"""
grad = tf.reduc... | 5,345,471 |
def read_data(filename):
"""
Reads orbital map file into a list
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip().split('\n')
f.close()
return data | 5,345,472 |
def _form_factor_pipi(
self, s: Union[float, npt.NDArray[np.float64]], imode: int = 1
) -> Union[complex, npt.NDArray[np.complex128]]:
"""
Compute the pi-pi-V form factor.
Parameters
----------
s: Union[float,npt.NDArray[np.float64]
Square of the center-of-mass energy in MeV.
imode:... | 5,345,473 |
def lecture():
"""
lecture()
Lee archivos "tmdb_5000_credits.csv" y "tmdb_5000_movies.csv"
para luego transformarlos en pandas.DataFrame.
Parameters
----------
None.
Returns
-------
credits, movies : [pandas.DataFrame, panda... | 5,345,474 |
def string_to_epoch(s):
"""
Convert argument string to epoch if possible
If argument looks like int + s,h,md (ie, 30d), we'll pass as-is
since pushshift can accept this. Per docs, pushshift supports:
Epoch value or Integer + "s,m,h,d" (i.e. 30d for 30 days)
:param s: str
:return: int | st... | 5,345,475 |
def spline_filter(Iin, lmbda=5.0):
"""Smoothing spline (cubic) filtering of a rank-2 array.
Filter an input data set, `Iin`, using a (cubic) smoothing spline of
fall-off `lmbda`.
"""
intype = Iin.dtype.char
hcol = array([1.0,4.0,1.0],'f')/6.0
if intype in ['F','D']:
Iin = Iin.astype... | 5,345,476 |
def set_logging_level(level=logging.INFO):
"""Sets the log level for the global logger
:param level: Log level to set
:type level: str
"""
logger.setLevel(level)
ch.setLevel(level) | 5,345,477 |
def _construct_aline_collections(alines, dtix=None):
"""construct arbitrary line collections
Parameters
----------
alines : sequence
sequences of segments, which are sequences of lines,
which are sequences of two or more points ( date[time], price ) or (x,y)
date[time] may be ... | 5,345,478 |
def is_mergeable(*ts_or_tsn):
"""Check if all objects(FermionTensor or FermionTensorNetwork)
are part of the same FermionSpace
"""
if isinstance(ts_or_tsn, (FermionTensor, FermionTensorNetwork)):
return True
fs_lst = []
site_lst = []
for obj in ts_or_tsn:
if isinstance(obj... | 5,345,479 |
def fetch_file(url, config):
"""
Fetch a file from a provider.
"""
# pylint: disable=fixme
# FIXME: the handled checking should be in each handler module (possibly handle_file(parsed_url,
# config) => bool)
parsed_url = urllib.parse.urlparse(url)
if parsed_url.scheme == 'github':
... | 5,345,480 |
def query_for_account(account_rec, region):
""" Performs the public ip query for the given account
:param account: Account number to query
:param session: Initial session
:param region: Region to query
:param ip_data: Initial list. Appended to and returned
:return: update ip_data list
"""... | 5,345,481 |
def main():
"""Invoke the command-line entrypoint."""
mecha(prog_name="mecha") | 5,345,482 |
def filter_list_of_dicts(list_of_dicts: list, **filters) -> List[dict]:
"""Filter a list of dicts by any given key-value pair.
Support simple logical operators like: '<,>,<=,>=,!'. Supports
filtering by providing a list value i.e. openJobsCount=[0, 1, 2].
"""
for key, value in filters.items():
... | 5,345,483 |
def test_database_init():
"""Test creating a fresh instance of the database."""
db = DB(connect_url=TEST_URL)
db.init() | 5,345,484 |
def construct_pos_line(elem, coor, tags):
"""
Do the opposite of the parse_pos_line
"""
line = "{elem} {x:.10f} {y:.10f} {z:.10f} {tags}"
return line.format(elem=elem, x=coor[0], y=coor[1], z=coor[2], tags=tags) | 5,345,485 |
def compute_pcs(predicts, labels, label_mapper, dataset):
"""
compute correctly predicted full spans. If cues and scopes are predicted jointly, convert cue labels to I/O labels depending on the
annotation scheme for the considered dataset
:param predicts:
:param labels:
:return:
"""
def ... | 5,345,486 |
def echoError(msg):
"""colored cli feedback"""
click.echo(click.style(msg, fg="red")) | 5,345,487 |
def pentomino():
"""
Main pentomino routine
@return {string} solution as rectangles separated by a blank line
"""
return _stringify(
_pent_wrapper1(tree_main_builder())(rect_gen_boards())) | 5,345,488 |
def do_login(request, username, password):
""" Check credentials and log in """
if request.access.verify_user(username, password):
request.response.headers.extend(remember(request, username))
return {"next": request.app_url()}
else:
return HTTPForbidden() | 5,345,489 |
def _interpolate(format1):
"""
Takes a format1 string and returns a list of 2-tuples of the form
(boolean, string) where boolean says whether string should be evaled
or not.
from <http://lfw.org/python/Itpl.py> (public domain, Ka-Ping Yee)
"""
from tokenize import Token
... | 5,345,490 |
def approxIndex(iterable, item, threshold):
"""Same as the python index() function but with a threshold from wich values are considerated equal."""
for i, iterableItem in rev_enumerate(iterable):
if abs(iterableItem - item) < threshold:
return i
return None | 5,345,491 |
def delete_important_words(word_list, replace=''):
"""
randomly detele an important word in the query or replace (not in QUERY_SMALL_CHANGE_SETS)
"""
# replace can be [MASK]
important_word_list = set(word_list) - set(QUERY_SMALL_CHANGE_SETS)
target = random.sample(important_word_list, 1)[0]
... | 5,345,492 |
def prot(vsini, st_rad):
"""
Function to convert stellar rotation velocity vsini in km/s to rotation period in days.
Parameters:
----------
vsini: Rotation velocity of star in km/s.
st_rad: Stellar radius in units of solar radii
Returns
------
Prot: Period of rota... | 5,345,493 |
def dialog_sleep():
"""Return the time to sleep as set by the --exopy-sleep option.
"""
return DIALOG_SLEEP | 5,345,494 |
def required_overtime (db, user, frm) :
""" If required_overtime flag is set for overtime_period of dynamic
user record at frm, we return the overtime_period belonging to
this dyn user record. Otherwise return None.
"""
dyn = get_user_dynamic (db, user, frm)
if dyn and dyn.overtime_perio... | 5,345,495 |
def get_best_fit_member(*args):
"""
get_best_fit_member(sptr, offset) -> member_t
Get member that is most likely referenced by the specified offset.
Useful for offsets > sizeof(struct).
@param sptr (C++: const struc_t *)
@param offset (C++: asize_t)
"""
return _ida_struct.get_best_fit_member(*arg... | 5,345,496 |
def convert_time(time):
"""Convert given time to srt format."""
stime = '%(hours)02d:%(minutes)02d:%(seconds)02d,%(milliseconds)03d' % \
{'hours': time / 3600,
'minutes': (time % 3600) / 60,
'seconds': time % 60,
'milliseconds': (time % 1) * 1000}
return st... | 5,345,497 |
def Returns1(target_bitrate, result):
"""Score function that returns a constant value."""
# pylint: disable=W0613
return 1.0 | 5,345,498 |
def task_imports():
"""find imports from a python module"""
base_path = pathlib.Path("youtube_dl_gui")
pkg_modules = ModuleSet(base_path.glob("**/*.py"))
for name, module in pkg_modules.by_name.items():
yield {
"name": name,
"file_dep": [module.path],
"actions... | 5,345,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.