content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import unittest
def load_tests_from_testcase(test_case_class, args):
"""
load tests from testcase class
Args:
test_case_class: TestCase class object
args: parse args
Returns: unittest.TestSuite()
"""
if 'all' in args.case_list:
# Load all test cases
# test_suit... | 1c5384ec9d3296e1c7c18e2848a8f32089ace675 | 11,912 |
def PyTmHMSXtoS(h, m, s, x):
"""
Convert hours-minutes-seconds-milliseconds to seconds as float
Parameters
----------
h: int, hours
m: int, minutes
s: int, seconds
x: float, milliseconds
Returns
-------
float, seconds
"""
return h * 3600.0 + m * 60.0 + s + x | 550362fe48d4e6c8c94b0c885611b607c8e39e63 | 11,913 |
def baby_names_collapsed_from_list(a_baby_names_list):
"""
a_baby_names_list is a list of lists, each element [name, rank]
Collapse list element to a string
"""
print('baby_names_collapsed_from_list')
baby_names_collapsed = []
for baby_element in a_baby_names_list:
baby_names_collap... | f874c1fb205e0a86e46db8a3e2c0002712db82cb | 11,916 |
def HeadingStr(heading):
"""
Gives a heading string given the heading float
"""
headstr = "?"
if heading != None:
if heading < 22.5 or heading >= 337.5:
headstr = "N"
elif heading >=22.5 and heading < 67.5:
headstr = "NE"
elif heading >= 67.5 and heading < 112.5:
headstr = "E"
elif heading >= 112.... | 1f1276e3f8f9c963703ced42d9391d1ee0598e3e | 11,919 |
def polyval(p,x):
"""
Replacement for the polyval routine in numpy. This version doesnt check the
input variables to make sure they are array_like. This means that when
masked arrays are treated correctly when they are passed to this routine.
Parameters
----------
p : a 1D array of coeffi... | 7887e504aef74f35bc014462e9bb0eb2c4548971 | 11,920 |
def get_user_by_email(email, db_model):
"""Take an email from request and return user object if existed.
"""
return db_model.query.filter(db_model.email == email).first() | 656ccd8b7fc66141a1e2023ebcfda84dd1caea16 | 11,921 |
from collections import defaultdict
def E():
"""
Сеть компании состоит из серверов. Серверы соединены друг с другом в кластеры.
Каждый сервер может скачивать файлы только с серверов в его кластере.
Составьте программу, которая сообщать, из каких источников определённый
сервер может скачать необход... | c5ce5e64f2be3c25e63d3f413970b13c1a094725 | 11,922 |
import secrets
def random_key(length: int = 16) -> str:
"""Generate a random key of specified length from the allowed secret characters.
Args:
length: The length of the random key.
"""
secret_allowed_chars = (
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
)... | a50daa81f3a01430a211299ae7123196a4b34264 | 11,923 |
import re
def fetch(name: str, **kwargs):
""" """
func = f"""_fetch_{re.sub("[_-]+dict", "", name.lower()).replace("-", "_")}"""
retval = eval(f"{func}(**kwargs)")
return retval | 62fbe0e478bbb81955e7aa5205b9ddf5197d7fe5 | 11,924 |
import re
def commit_message_contains_query(message, query_terms):
"""
Check if the commit message contains the query terms
@param message: The commit message
@param query_terms: The terms that we look for in the message
@return:
"""
tester = r'\b(' + '|'.join(query_terms) + ')'
has_re... | b701dac00971658be13a6b7207f8685c3388609e | 11,925 |
def get_event_role(bot, guild):
"""Return the event role, if it exists"""
result = bot.db.get_event_role_id(guild.id)
if result:
for role in guild.roles:
if role.id == result.get('event_role_id'):
return role | 85656ee6b65896762197008108c7b09830a5a4a8 | 11,926 |
def laser(asteroid_angles):
"""
Takes list of relative asteroid positions with manhattan distances and
relative angles from (0,1), sorted in order of increasing angle and increasing
distance where angles are equal.
Simulates firing a laser from 0 radians (along (0,1)) to 2 pi radians and
de... | 80947e23f1c01d60d73a2fc2f41fa5304b9b1ab4 | 11,927 |
import os
import re
def parse_captions(path):
"""Parse lines from captions"""
lines = []
for fname in os.listdir(path):
if re.findall(r'\.vtt$', fname):
with open(os.path.join(path, fname), 'r') as f:
get_next = False
for line in f.readlines():
... | c8c52c650578aa03d16982963f4abcf1436dcfe4 | 11,928 |
from typing import Optional
from typing import Dict
from typing import Any
def commit_draft(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
draft_number: int,
title: str,
description: Optional[str] = None,
) -> Dict[str, str]:
"""Execute the OpenAPI `POST /v2/datasets/{own... | 395070863b678892ca1004de20ac1b163d6e2da8 | 11,929 |
def DotProduct_DML(feat, M, query=None,
is_sparse=False, is_trans=False):
""" DotProduct distance with DML.
"""
if query is None:
query = feat
return -query.dot(M).dot(feat.T) | 7a1d1173e351d6f621755fe5dfc64bcbdcc95b97 | 11,930 |
import os
import sys
import pickle
def read_vest_pickle(gname, score_dir):
"""Read in VEST scores for given gene.
Parameters
----------
gname : str
name of gene
score_dir : str
directory containing vest scores
Returns
-------
gene_vest : dict or None
dict cont... | 517f07242240d4767a0f573c2a02446cb363aa70 | 11,931 |
import random
def create_fake_risk(data):
"""
Since the raw data had almost only 'unknown_risk' values and I wanted to
have my visualisations look cool, I decided to do a Diederik Stapeltje and
make up the data myself. ¯\_(ツ)_/¯
"""
risks = []
# for a specific amount of times, add the di... | c42edc03a57913d96701cc8b36c388d42c1c9bfc | 11,932 |
import functools
import os
def section_from_file(fname: str, relpath: bool = True, text_var: str = "text"):
"""Make a decorator for providing a default argument from a text file
Args:
fname (str): Name of the file to be read
relpath (bool): If :data:`True` (default), the file name is interpreted
as... | 261b6b7d846d2435c1dbe8e77f771b97fea5abe6 | 11,933 |
import random
def capnp_id() -> str:
"""
Generates a valid id for a capnp schema.
Returns:
str -- capnp id
"""
# the bitwise is for validating the id check capnp/parser.c++
return hex(random.randint(0, 2 ** 64) | 1 << 63) | 55ae4e112c3ba223168627d7d06fab327a0d4f82 | 11,934 |
def linspace(start,stop,np):
"""
Emulate Matlab linspace
"""
return [start+(stop-start)*i/(np-1) for i in range(np)] | b1be58298ff9983f6e2f6c5156cb4497ef8668d9 | 11,935 |
import pandas
def _coerce_numeric(table):
"""Coerce a table into numeric values."""
for i in range(table.shape[1]):
table.iloc[:, i] = pandas.to_numeric(table.iloc[:, i], errors='coerce')
return table | cba1a224655e3536e361212569b7d6397a58786e | 11,936 |
def generate_wiki_redirect_text(redirect_name: str) -> str:
"""Generate wikitext for redirect."""
return f'#REDIRECT [[{redirect_name}]]' | f6e55fa20004d836ea601a1d3966d070273df237 | 11,938 |
def dnnlib_shadow_submit_convert_path(txt):
"""Not sure what this really does, so just a no-op."""
return txt | 9a883453edeb6171386dca221557eead8f9058b2 | 11,939 |
import re
def read_html(htmlfile):
"""
Reads the HTML file to a string.
Removes some potential trouble makers.
"""
with open(htmlfile, "r") as infile:
html = infile.read()
# Clean out some unnecessary stuff
html = re.sub("<div class=\"wp-about-author.*?</div>", "", html, re... | bb0f724792cd817464a8720199ce7c7035e6b0f1 | 11,941 |
import time
def get_datetime():
"""Return the current datetime in a database compatible format"""
return time.strftime('%Y-%m-%d %H:%M:%S') | 804166ac7f56899733043871ea5ec9fcce474ee7 | 11,944 |
import inspect
def expand_lambda_function(lambda_func):
"""
Returns a lambda function after expansion.
"""
lambda_function = inspect.getsource(lambda_func).split(",")[1].strip()
if lambda_function.endswith(")"):
return lambda_function[:-1]
return lambda_function | 7076ce6bdee4077f6cbf665d686cd28c2420d67e | 11,945 |
def get_dict_from_params_str(params_str):
"""Get the dictionary of kv pairs in a string separated
by semi-colon."""
if params_str:
kvs = params_str.split(";")
params_dict = {}
for kv in kvs:
k, v = kv.strip().split("=")
params_dict[k] = eval(v)
return ... | 611f80b55c090ff5aa6afa78ee4b1b5db074cab0 | 11,946 |
def WENOReconstruct( u_stencil, eps, p ):
"""WENO reconstruction. This reconstructs u_{i+1/2}
given cell averages \\bar{u}_i at each neighboring location.
See `High Order Weighted Essentially Nonoscillatory Schemes for
Convection Dominated Problems'.
Input
-----
u_stencil :
... | aa49be7b069f09c90c9b350d86575376eb5c9fbb | 11,949 |
def read_ssm_params(params, ssm):
"""Build dictionary from SSM keys in the form `ssm://{key}` to value in the
paramater store.
"""
result = ssm.get_parameters(Names=[s[len('ssm://'):] for s in params],
WithDecryption=True)
if result['InvalidParameters']:
raise... | dc4aa3272b8b371621074230bc2ce2b3cad1dd72 | 11,951 |
import re
def is_stable_version(version):
"""
A stable version has no letters in the final component, but only numbers.
Stable version example: 1.2, 1.3.4, 1.0.5
Not stable version: 1.2alpha, 1.3.4beta, 0.1.0rc1, 3.0.0dev
"""
if not isinstance(version, tuple):
version = version.split(... | 995dff30ff81908e0d5a00d88816d874e9bfd626 | 11,953 |
from datetime import datetime
def chart_grouping_as_date(value):
"""Transforms a string YYYYMM or YYYY in a date object"""
value = str(value)
for format in ('%Y', '%Y%m'):
try:
return datetime.strptime(str(value), format).date()
except ValueError:
pass | 92f80be0baea30944ebd90e1377dfa953f5fb7fa | 11,954 |
def impartial(f, *args, **kwargs):
"""
Acts just like Python's functools.partial, except that any arguments
to the returned function are ignored (making it 'impartial', get it?)
"""
def func(*_a, **_k):
return f(*args, **kwargs)
return func | ef512146057ae09546b6e7fac64c2496ac8f7d53 | 11,955 |
import argparse
def get_args() -> argparse.Namespace:
"""
Parse command line arguments.
Returns:
argparse.Namespace: parsed arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("--path", help="full path to top level show folder", required=True)
parser.add_argument(... | 18deeb1debefbe9bde5e793728b111382fdb72bd | 11,956 |
def get_existing_symptoms(journal):
"""Given a journal w/ proper format, aggregates all the symptoms
args:
journal (dict)
returns:
[str]: array of symptom names
"""
symptoms = []
for log in journal['journal']:
symptoms.extend([
symptom['name'] for symptom i... | e8f90ff3344318b53ae91e79d29f572110103959 | 11,958 |
def cal_fps(raw_trajs_frequent_pattern: dict, sd_trajs_frequent_pattern: dict) -> float:
"""
calculate FPS
Args:
raw_trajs_frequent_pattern: frequent patterns of the original trajectory
sd_trajs_frequent_pattern : frequent patterns that generate trajectories
Returns:
FPS
... | 0b877ba77d928d0550f3fb695c0805f9447b4f61 | 11,959 |
def compara_assinatura(ass_main, matriz_ass_input):
"""
Essa funcao recebe duas assinaturas de texto e deve devolver o grau de
similaridade nas assinaturas.
"""
lista_Sab = []
soma_mod = 0
if type(matriz_ass_input[0]) is list:
for lin in range(len(matriz_ass_input)):
for ... | b9dae58c37f06cbcbab577e54e3bbbcf793d7977 | 11,961 |
import os
import pickle
def load_options(run_folder, options_file_name = 'options-and-config.pickle'):
""" Loads the training, model, and noise configurations from the given folder """
with open(os.path.join(run_folder, options_file_name), 'rb') as f:
train_options = pickle.load(f)
noise_confi... | 23af1f8082fbfa509a4c7675bc6dd8d666cbbc87 | 11,962 |
import re
def prune_lines(infile):
""" Discard all lines which don't have the data we're after
Adapted from http://stackoverflow.com/questions/17131353/problems-targeting-carriage-return-and-newlines-with-regex-in-python
"""
result = []
with open(infile, 'r') as text:
lines = text.read... | 0d3bccf996b2afeab3e56cd29e5559235cb34d12 | 11,963 |
def _GetDefiningLayerAndPrim(stage, schemaName):
""" Searches the stage LayerStack for a prim whose name is equal to
schemaName.
"""
# SchemaBase is not actually defined in the core schema file, but this
# behavior causes the code generator to produce correct C++ inheritance.
if schemaName =... | c898b1f1fdd3430b044b556a269b0cdf84a552c1 | 11,964 |
def twoSum(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
# Time Complexity - O(n)
# Space Complexity - O(n)
res = set()
for i in nums:
if i in res:
return True
res.add(k - i)
return False | 93e6d3f4d2d80f28a125b85b3eab5f4601d119d6 | 11,965 |
def unique_by(func, objects):
"""
Sorts by applying func to each item
:param func: Applied to each object to get the sortable result
:param objects: iterable
:return: The sorted objects
"""
seen = set()
def hash(obj):
value = func(obj)
return value not in seen and no... | e3f72626543b0b0234530f936e02a100f00e6cba | 11,967 |
def property_info(info, delimiter=' | '):
"""Returns property info from tupple.
Input tuple must containts flags if property is writable, readable
and deletable.
#!jinja
{# return someone like this: WRITE | READ | DELETE #}
{{ property_info(info) }}
"""
rv = []
if info[... | 0b39c7ba69a05365f0051eab9941fd2ddce02642 | 11,969 |
import re
def clean(s):
"""Strip leading & trailing space, remove newlines, compress space.
Also expand '{NL}' to a literal newline.
:param str s:
:rtype: str
"""
s = s.strip()
s = re.sub(' +', ' ', s)
s = s.replace('\n', '')
s = s.replace('\r', '')
s = s.replace('{NL}', '\n')
... | f2c07984de1766b7a1d0258b29ad8030e87896e8 | 11,971 |
import time
import math
def timeSince(since):
"""
compute the training/evaluate time
"""
now = time.time()
s = now - since
m = math.floor(s / 60)
s -= m * 60
h = math.floor(m / 60)
m -= h * 60
return '%d h %d m %d s'%(h, m, s) | 4fefbf6198bc89ca53eae341c116b0f6e693e8d1 | 11,972 |
import argparse
import sys
def get_options(cmd_args=None):
""" Argument Parser. """
parser = argparse.ArgumentParser(
prog='{}'.format(sys.argv[0]), usage='%(prog)s [options]',
description='SAGA Live Monitoring')
parser.add_argument(
'--tripinfo', type=str, required=True,
... | eab3eff5847defd3e2c68a2924bf2f0410f9a282 | 11,974 |
def get_test_specific_options(test, BLIND=False, ignore_others=True, ignore_labels=None):
""" Function to use for determining test specific options, currently this is tuned to 4CR dataset;
Need to be replaced for specific dataset.
"""
# Need to change when the total test options changed
# Color key ... | 0b56619a7eefadc58921a1d7145afeba9e7b9d74 | 11,975 |
def people():
"""
People in organization
:return: list of users
"""
# users = get_users()
return dict() | ac2c0b1403d9d00fe7fa6c8b631fefcf71c8266b | 11,977 |
def parse_by_category(category, data):
"""
filters database content by category from dumps
:param category: accepts string
:param data: accepts multi-dimensional iterable data type
:return: returns filtered multi-dimensional LIST containing TUPLES
"""
new_dat = []
for entry in data:
... | 255d69580ed666aac38eaa70442ee4e215a7e802 | 11,978 |
def user_to_dict(user):
"""Build a json flask response using the given data.
:Returns: A flask response with json data.
:Returns Type: :py:class:`flask.Response`
"""
data = {}
if user.is_authenticated:
roles = [{'id': r.id, 'description': r.description, 'name': r.name}
f... | aed99bf8ff05dfca0b4bac4b2a674c4e71871c54 | 11,979 |
import numpy
def flatten_training(training_pairs):
"""Convert active label training pairs to two lists.
Args:
:training_pairs: (dict) dictionary of either 'match' or 'distinct', where
'match' is a list of pairs of records which are the same, and
'distinct' is a list of pairs o... | 0813134356eed5478cf61b73cc054cda8fc460c5 | 11,981 |
def replace_extension(filename, new_extension, add_to_end=False):
"""Replaces the extension in the filename with the new_extension."""
dot = filename.rfind(".")
if dot < 0 or filename[dot + 1:] == new_extension or add_to_end:
filename_base = filename
else:
filename_base = filename[:dot]
... | 75b04c37dffb3dd92f3fe12295b18efb52dfa2ef | 11,982 |
from bs4 import BeautifulSoup
def wrap_with_tag(html: str, document_wrapper_class: str) -> str:
"""
Wraps a string of HTML with a div using a given wrapper class
Args:
html (str): The HTML to be wrapped
document_wrapper_class(str): The class with which to wrap the HTML
Returns:
... | 075cf4ef818eb38f2b0a8a16c76fcc5cc11cdec9 | 11,983 |
def slave_entry(slave, programs, filesystems):
"""
Template tag {% slave_entry slave programms %} is used to display a single
slave.
Arguments
---------
slave: Slave object
programs: Array of programs
Returns
-------
A context which maps the slave object to slave an... | 7449eec9d906bfe74245cbdec2a76fd7a2fc8157 | 11,984 |
from pathlib import Path
def get_and_mark_bundle_cache_version(bundle_base: str, *,
previously_bundled: bool) -> int:
"""
Check and return the bundle cache version.
The marker filename is `.bundle_cache_version`.
:param str bundle_base: The bundle directory
... | 74ab1584b60ffb77dbb3709d01ea4df00a448ea4 | 11,986 |
def isinrectbnd(x: int, y: int,
xmin: int, ymin: int,
xmax: int, ymax: int) -> bool:
"""Checks if the x and y values
lie within the rectangular area
defined by xmin, ymin and
xmax, ymax
Args:
x, y: (x,y) coordinates to test
xmin, ymin: min (x, ... | 3f67de8669a258a554a8754786579517a07bc321 | 11,987 |
def remove_prefix(string: str, prefix: str):
"""
Removes a prefix from a string if present.
Args:
string (`str`): The string to remove the prefix from.
prefix (`str`): The prefix to remove.
Returns:
The string without the prefix.
"""
return string[len(prefix) :] if stri... | 598e1b9b863d342e757e54cf94035da63e3ace1f | 11,990 |
def get_params(opt_over, net, net_input, downsampler=None):
"""
Returns parameters that we want to optimize over.
:param opt_over: comma separated list, e.g. "net,input" or "net"
:param net: network
:param net_input: torch.Tensor that stores input `z`
:param downsampler:
:return:
"""
... | b8a3c26b5307c0ba584e3841a2d98f337c618bf8 | 11,991 |
from typing import Optional
from typing import Any
def nested_get(dct: dict, *keys: str) -> Optional[Any]:
"""Multi-level get helper function."""
for key in keys:
dct = dct.get(key, {})
return dct if dct else None | cd881389157d67365793240e1e2e0b39f4bc1726 | 11,995 |
def only_moto(request):
"""Return True if only moto ports are to be used for mock services."""
return request.config.option.only_moto | 1ab211925a411d4999a22e77d819da88b4477ed6 | 11,996 |
def find(sub_str, target_str):
"""[summary]
字符串查找
Arguments:
sub_str {str} -- substring
target_str {str} -- target string
Returns:
bool -- if substring is found in target string
"""
return sub_str in target_str
# in operator用的是Boyer–Moore算法,最坏情况O(mn), 最好情况O(n/m)
... | d26e4ad79eaf913d81126d7647036b857de5ed6d | 11,997 |
def check_faces_in_caption(photo):
"""Checks if all faces are mentioned in the caption."""
comment = photo.comment
if photo.getfaces() and not comment:
return False
for face in photo.getfaces():
parts = face.split(" ")
# Look for the full name or just the first name.
if (... | eed03439df84a1ddd4cb7bcbb269af7c60adfcb5 | 11,998 |
def LfromS(seq):
"""
Compute Schroder function value L from a given sequence.
This performs the calculation by plodding through the algorithm given in
the paper. Humans can easily recognize the relation between elements of S
and length of runs of 0s or 1s in the binary representation of L. Knowing
that, the... | 6adf8c0b6f8e12d7e6a79efcb38c628ef0b29031 | 11,999 |
import random
def contest(other):
"""contests human ability"""
return random.randint(1, 20) > round(other.advantage / 5) | a87cc2ffc7d01f493d99b3808735f7954847caaa | 12,001 |
def get_trader_violation(model, trader_id, trade_type):
"""Get trader violation"""
if (trader_id, trade_type) in model.V_TRADER_TOTAL_OFFER.keys():
return sum(model.V_CV_TRADER_OFFER[trader_id, trade_type, i].value
for i in range(1, 11))
else:
return 0.0 | 1ef4822345bd16e17d0b351148275a288fc281a5 | 12,003 |
def shorter(item):
"""Make a string shorter.
item -- a unicode string."""
if len(item) > 2:
return item[:-2] + u'\u2026' # ellipsis
return item | d3d9f678c5055e43f2120c1779bbd41066c8684d | 12,004 |
def route_con(lst):
"""
Функция для получения списка лучшего пути
:param lst: list -- список кортежей лучшего пути
:return result: list -- список лучшего пути
"""
result = []
for elem in range(len(lst)):
if elem == 0:
result.append(lst[elem][0])
result.append(... | dae6a3613c5908615b1504b9960a6981d84b3224 | 12,005 |
import yaml
import subprocess
def validate_output(output, fmt, mcf):
"""compare values in merp2tbl output with merp -d row for row, non-NA must agree
Parameters
----------
output : dict
as returned by format_output
fmt : str
'tsv' or 'yaml'
mcf : str
path to merp command ... | 2d9e7c89f8280751abfc328042c0ee3bd1572f4a | 12,007 |
def getViolationFromAria2(ariaViolation, constraint, violationList):
"""Descrn: Make a constraint's violation object in the input violation list given an Aria2
violation analysis object.
Inputs: Aria2 violation analysis object, NmrConstraint.DistanceConstraint, NmrConstraint.ViolationList
Outpu... | f89718bb8a2b767e51e9efa657768327548822f1 | 12,009 |
from typing import Dict
import pathlib
def dir_parser(path_to_dir: str) -> Dict[str, Dict[str, str]]:
"""
Parses the given directory, and returns the path, stem and suffix for files.
"""
files = pathlib.Path(path_to_dir).resolve().glob("*.*")
files_data = {}
for file in files:
files_... | 3b6c0ac172ad863470d492aa99713fab3ecf5d99 | 12,011 |
import inspect
def is_redefined_dataclass_with_slots(old: type, new: type) -> bool:
"""Return True if `new` is the `old` dataclass redefined with `__slots__."""
# Must both be dataclasses.
if "__dataclass_fields__" not in old.__dict__ or "__dataclass_fields__" not in new.__dict__:
return False
... | c5c760bca752c0458139419f3c8e519ed8adad66 | 12,012 |
def filter_data(data):
"""
Filters data for years after 2010 and data originating
from Syria.
Inputs:
data (pd.DataFrame): Input data with column "Year" and "Origin"
Returns:
data (pd.DataFrame): Filtered data
"""
if 'Origin' in data.columns:
data = data[(data.Year >... | 2daf6fbd815fcea9dd3c2712363cd99cdca62a34 | 12,013 |
def strrep(strg,x):
""" A função retorna uma string com n repetições;
str, int -> str """
return strg*x | 6e3d59666778af9db781a11e6f48b61010e7de4d | 12,014 |
def task_build():
"""Create full distribution."""
return {
'actions': ['python -m build'],
'task_dep': ['gitclean', 'mo', 'docs'],
} | 7112ab22031299207dfb9c14d2482ef52e975f89 | 12,016 |
def get_positions(structure):
"""Wrapper to get the positions from different structure classes"""
try: # ASE structure
return structure.get_scaled_positions()
except AttributeError:
try: # diffpy structure
return structure.xyz
except AttributeError:
raise Va... | 6428139131de02b577925be9499668642a11a69c | 12,017 |
from typing import List
def parse_comp_internal(
comp_rules: str, top_delim: str, bottom_delim: str, rule_start: str
) -> List[str]:
"""
Do the heavy handling to parse out specific sub-sections of rules.
:param comp_rules: Rules to parse
:param top_delim: Section to parse
:param bottom_delim: ... | 5563e1eb7bbe9d738f550a220a733c6c2d11b509 | 12,019 |
def finish_waiting(event, messageCenter, roomGrid):
"""Events that happen at the end of some input cycle."""
if roomGrid.waitFunction[0] == "move":
location = roomGrid.waitFunction[1]["location"]
if event.location == [-1, -1]:
to_location = roomGrid.lockedSpace
else:
... | c3b74736b875e531af29d5f4c470543c0ca975ec | 12,020 |
import logging
import io
import sys
import types
def _RunMethod(dev, args, extra):
"""Runs a method registered via MakeSubparser."""
logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
result = args.method(dev, *args.positional, **extra)
if result is not None:
if isinstance(result, io... | 34c267aa1379a81bea5c73b0a2fa9f3a9aa9b3d7 | 12,021 |
def fully_connected(input, params):
"""Creates a fully connected layer with bias (without activation).
Args:
input (:obj:`tf.Tensor`):
The input values.
params (:obj:`tuple` of (:obj:`tf.Variable`, :obj:`tf.Variable`)):
A tuple of (`weights`, `bias`). Probably obtained ... | 77815acfe17674bc20035900b75d8e4ddc982855 | 12,022 |
def GetIslandSlug(island_url: str) -> str:
"""该函数接收一个小岛 URL,并将其转换成小岛 slug
Args:
island_url (str): 小岛 URL
Returns:
str: 小岛 slug
"""
return island_url.replace("https://www.jianshu.com/g/", "") | 71e1b609e5bd3c703a4d5d0789fddff117969e69 | 12,023 |
def cec_module_spr_e20_327():
"""
Define SunPower SPR-E20-327 module parameters for testing.
The scope of the fixture is set to ``'function'`` to allow tests to modify
parameters if required without affecting other tests.
"""
parameters = {
'Name': 'SunPower SPR-E20-327',
'BIPV'... | 55593d3a561d6ebafba424f50406128e58406073 | 12,024 |
def get_base_classification(x: str) -> str:
"""
Obtains the base classification for a given node label.
Args:
x: The label from which to obtain the base classification.
Returns:
The base classification.
"""
return x.split('_', 1)[0] | 8122d435af8ac6aef43faab349ee98dca75469d4 | 12,025 |
def check_individuals(ped_individuals, vcf_individuals):
"""
Check if the individuals from ped file is in vcf file
Arguments:
ped_individuals (iterator): An iterator with strings
vcf_individuals (iterator): An iterator with strings
Returns:
bool: if the individuals exis... | e65b24390c8cebff7870e46790cf1c0e9b2d37c6 | 12,026 |
import dill
def load(filename):
"""
Load an instance of a bayesloop study class that was saved using the bayesloop.save() function.
Args:
filename(str): Path + filename to stored bayesloop study
Returns:
Study instance
"""
with open(filename, 'rb') as f:
S = dill.load... | 19ce91d2a4bb552362bd8f8ab67194e1241356d1 | 12,027 |
def des_magnitude_zero_point(bands=''):
"""
Sample from the distribution of single epoch zeropoints for DES
"""
dist = {'g': 26.58, 'r': 26.78, 'i': 26.75, 'z': 26.48, 'Y': 25.40}
return [dist[b] for b in bands.split(',')] | 568b6f17abb0957c22cb6c300af06d72b41e6c73 | 12,028 |
import configparser
import sys
def loadAuth(path):
""" Load guthub api token form file
:param path: File's path
:type path: string
:return: token
:rtype: string
"""
try:
config = configparser.ConfigParser()
config.read(path)
return config['github']['token']
... | 1e8d78124fe5e664bfb5a7532cc71e5f5d90d9cc | 12,031 |
from typing import List
def load_grid_from_string(grid_str: str) -> List[List[int]]:
"""Returns a grid by loading a grid passed as a string."""
array = [int(cell) for cell in grid_str.split()]
grid = [[int(cell) for cell in array[i : i + 3]] for i in range(0, len(array), 3)]
return grid | c3b9a91c9298b54226f5ef532d1948a41dc67eac | 12,032 |
def number(bus_stops):
"""
There is a bus moving in the city, and it takes and drop some people in each bus stop.
You are provided with a list (or array) of integer pairs.
Elements of each pair represent number of people get into bus (The first item)
and number of people get off the bus (The second ... | 382c0112c223a6681508ec3d7a345ec92391657d | 12,033 |
import torch
def omp(X: torch.Tensor, y: torch.Tensor, *,
k=None, device=None) -> torch.Tensor:
"""
y = Xa
:param X: (n_features, n_components)
:param y: (n_features)
:param k: n_nonzero_coefs
:param device: pytorch device
:return: (n_components)
"""
assert X.dim() == 2
... | 5f11464371401e630e0f7a37eedb53d29016bd27 | 12,035 |
import random
def generate_random_color():
"""
Generates the hexadecimal code of a random pastel color
"""
# generates random RGB
r = (random.randrange(1, 256) + 255) / 2
g = (random.randrange(1, 256) + 255) / 2
b = (random.randrange(1, 256) + 255) / 2
# clamp function
clamp = lam... | d6efcb30f1296e031ee764076b2659b0d4a7cd93 | 12,036 |
def fixbackslash(value):
"""Replace backslashes '\' in encoded polylines for Google Maps overlay."""
return value.replace('\\','\\\\') | 20a1e6132c379049e949f50e413c66cf5e67e7dc | 12,037 |
def _filter_tuples(diced_str, to_remove):
"""
Returns *diced_str* with all of the tuples containing any elements of the
*to_remove* iterable filtered out. This is used to drop search terms from
the diced_str once they've been matched. For example:
# start with the output of the _dice doctest
>>... | 625ca421e3b1ec3dd9f5187fe994ee095eff8d30 | 12,038 |
def print_xm_info(xm_dict, name_re):
"""Print a dictionary of xmethods."""
def get_status_string(m):
if not m.enabled:
return " [disabled]"
else:
return ""
if not xm_dict:
return
for locus_str in xm_dict:
if not xm_dict[locus_str]:
conti... | e2564a5fcb7dc435c3ba1fa71fe82532d2b5083e | 12,040 |
def format_multitask_preds(preds):
"""
Input format: list of dicts (one per task, named with task_name), each having a
'predictions' list containing dictionaries that represent predictions for each sample.
Prediction score is represented by the field {task_name}_score in each of those dicts.
... | 470b23f6a5cc6b8e48ce0becfafd62104e016de8 | 12,041 |
def msp(items):
"""Yield the permutations of `items`
items is either a list of integers representing the actual items or a list of hashable items.
The output are the unique permutations of the items.
Parameters
----------
items : sequence
Yields
-------
list
permutation of... | a91f2b80997b73cf7dbcbec88a923f855e117c26 | 12,042 |
def _NormalizeGitPath(path):
"""Given a |path| in a GIT repository (relative to its root), normalizes it so
it will match only that exact path in a sparse checkout.
"""
path = path.strip()
if not path.startswith('/'):
path = '/' + path
if not path.endswith('/'):
path += '/'
return path | f2781ac304d4c15e835fa174d4aa816ea920045f | 12,043 |
def unpack(t, n):
"""Iterates over a promised sequence, the sequence should support random
access by :meth:`object.__getitem__`. Also the length of the sequence
should be known beforehand.
:param t: a sequence.
:param n: the length of the sequence.
:return: an unpackable generator for the eleme... | 4601cc51b2ae1015a31e8dc525756d8f590c2d8b | 12,044 |
import re
def parse_value(expr):
"""Parse text into Python expression.
Args:
expr: String to be converted to Python expression (e.g. a list).
Returns:
Parsed Python expression.
"""
try:
return eval(expr)
except:
return eval(re.sub(r"\s+", ",", expr))
else... | f033e35b77bb3839dc6ccc05e1f96898a1a93c0c | 12,045 |
from typing import List
def pkg_asset_download_urls(url) -> List[str]:
"""
Example URL for release assets:
tarball: https://github.com/ICGC-TCGA-PanCancer/awesome-wfpkgs2/releases/download/fastqc-wf.0.2.0/fastqc-wf.0.2.0.tar.gz
json: https://github.com/ICGC-TCGA-PanCancer/awesome-wfpkgs2/release... | 2e66629efa07c00473f8bfb86f2db816211d24ed | 12,046 |
def _grid_out_property(field_name, docstring):
"""Create a GridOut property."""
def getter(self):
self._ensure_file()
# Protect against PHP-237
if field_name == 'length':
return self._file.get(field_name, 0)
return self._file.get(field_name, None)
docstring += "... | 71bb15738528142d4e410811ba021884ed5bb5ef | 12,047 |
def create_stack_list(input_list):
"""
:param input_list: list (of page visits), duplicates are possible
:return: stack list: loops have been removed, consecutive duplicates also have been removed
"""
# print('#################')
# print(input_list)
stack_list = []
list_of_backward_jump... | d82d4b3825d2d034eb4aad4c39f8c0876fb82c86 | 12,049 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.