content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def args_to_int(args: list) -> tuple:
""" Convert augs to int or return empty """
try:
return tuple([int(i) for i in args])
except ValueError:
return () | 73,100 |
def update_variables_with_types(*, variables: Dict[VarName, VarDecl], types: Dict[VarName, VarType]) -> Dict[VarName, VarDecl]:
"""
:raises TypingError:
"""
updated: Dict[VarName, VarDecl] = {}
for name, decl in variables.items():
if decl.type is None:
t = types[name]
el... | 73,101 |
def copy_labelbox_output_images_to_model_repo_folder(
labelbox_output_folder, model_repo_images_folder, video_source
):
"""copy_labelbox_output_images_to_model_repo_folder
A utility function to copy labelbox output images to model repo images folder
:param labelbox_output_folder: Labelbox output dire... | 73,102 |
def suite():
"""A testsuite that has all the Flask tests. You can use this
function to integrate the Flask tests into your own testsuite
in case you want to test that monkeypatches to Flask do not
break it.
"""
setup_path()
suite = unittest.TestSuite()
for other_suite in iter_suites():
... | 73,103 |
def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
header_filter, extra_arg, extra_arg_before, quiet,
config):
"""Gets a command line for clang-tidy."""
start = [clang_tidy_binary]
if header_filter is not None:
start.append('-hea... | 73,104 |
def setAngledLeftMargin(glyph, font, value):
"""Set the left angled margin to value, adjusted for font.info.italicAngle."""
pen = AngledMarginPen(font, glyph.width, font.info.italicAngle)
g.draw(pen)
isLeft, isRight = pen.margin
glyph.leftMargin += value-isLeft | 73,105 |
def natsort_key(s, number_type=int, signed=False, exp=False):
"""\
Key to sort strings and numbers naturally, not lexicographically.
It also has basic support for version numbers.
For use in passing to the :py:func:`sorted` builtin or
:py:meth:`sort` attribute of lists.
Use natsort_key just lik... | 73,106 |
def _check_sample_weight(sample_weight, X, dtype=None):
"""Validate sample weights.
Note that passing sample_weight=None will output an array of ones.
Therefore, in some cases, you may want to protect the call with:
if sample_weight is not None:
sample_weight = _check_sample_weight(...)
Pa... | 73,107 |
def get_by_name(opname, operators):
"""Return operator class instance by name.
Parameters
----------
opname: str
Name of the sklearn class that belongs to a TPOT operator
operators: list
List of operator classes from operator library
Returns
-------
ret_op_class: class
... | 73,108 |
def snrm2(x, dims, mnl = 0):
"""
Returns the norm of a vector in S
"""
return math.sqrt(sdot(x, x, dims, mnl)) | 73,109 |
def main(samplesheet, input_directory, output_directory, paired, merge):
"""MergeGI is a command line tool to merge and organize sequencing data
(FastQ files) out of a MGI sequencer according to lanes and barcodes.
MGI DNBSEQ G400 sequencer produces FastQ files organized by
flowcell, lanes, barcodes an... | 73,110 |
def test_filters_allowed_keys(test_endpoint):
"""Test that ValueError is raised if invalid filter keys are passed.
Also verify that filter keys do not conflict with assigned parameter keys.
"""
with pytest.raises(ValueError):
test_endpoint.filters = {"{}".format(randstr(12)): random.randint(0, ... | 73,111 |
def log2die_safe(code, message):
"""Log message to STDOUT only and die.
Args:
code: Message code
message: Message text
Returns:
None
"""
# Initialize key variables
output = _message(code, message, True)
print(output)
sys.exit(2) | 73,112 |
def get_tweets(count = 800, output_file=None,verbose=True):
"""
Pulls Tweets from Authenticated Twitter User
Twitter API maxes out at 800 or input count number
"""
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy... | 73,113 |
def import_pkg_operation():
"""This function imports the primary package and returns ``True`` when successful."""
import khoros
return True | 73,114 |
def test_deck_iter():
"""Tests the dunder iter method"""
with pytest.raises(StopIteration):
deck = Deck()
for i in iter(deck):
next(deck)
next(deck) | 73,115 |
def extract():
""" extract data from MongoDB """
# connect mongodb container of the same composer from python
client = pymongo.MongoClient("mongodb")
# get database
db = client.tweets_stream_db
# get collection
collection = db.tweet_stream_json
return collection | 73,116 |
def test_the_appendleft(the_deque):
"""Test the peek left function."""
the_deque.appendleft(1)
the_deque.appendleft(2)
the_deque.appendleft(3)
assert the_deque._new_dll.tail.data == 3
the_deque.popleft()
assert the_deque._new_dll.tail.data == 2 | 73,117 |
def run_cmd(command, **kwargs):
""" Runs a command and returns an array of its results
:param command: String of a command to run within a shell
:returns: Dictionary with keys relating to the execution's success
"""
cwd = kwargs.get('cwd', None)
try:
ret = check_call(command, shell=Tru... | 73,118 |
def generate_group_expected_result(group_config) -> dict:
"""Generate expected result for groups"""
expected_result = {
'group_visible': not group_config['ui_options']['invisible'],
'editable': not group_config['read_only'],
"content": group_config['default'],
}
if group_config['... | 73,119 |
def run_device_analysis_pool(task_func, device_names, processes=None, cwd=None,
walltime=3600):
"""
Use a multiprocessing.Pool to run a device-level analysis task
over a collection of device names. The task_func should be
implemented as pickleable function that takes the de... | 73,120 |
def get_sub_text_from_xml_node( xmlnode, _text=None ):
"""
Concatenates the content at and under the given ElementTree node, such as
text = get_sub_text_from_xml_node( xmlnode )
"""
if _text == None:
_text = []
if xmlnode.text:
_text.append( xmlnode.text )
for nd in xm... | 73,121 |
def resample_to_shape(source_file, region, sp_res, grid, prefix=None,
nan_value=None, dest_nan_value=None, variables=None,
shapefile=None):
"""
Resamples images and clips country boundaries
Parameters
----------
source_file : str
Path to source fi... | 73,122 |
def group_dates(dates):
"""
Groups list of given days day by day.
:param dates: List of dates to group.
:type dates: list
:return:
"""
days = []
times = []
for elem in dates:
if elem.date() not in days:
days.append(elem.date())
times.append([elem.ti... | 73,123 |
def sum_normalization(X, types):
"""
Normalize decision matrix using sum normalization method.
Parameters
----------
X : ndarray
Decision matrix with m alternatives in rows and n criteria in columns
types : ndarray
Criteria types. Profit criteria are represented ... | 73,124 |
def create_facelet_rects(a):
"""Initializes the facelet grid on the canvas."""
offset = ((1, 0), (2, 1), (1, 1), (1, 2), (0, 1), (3, 1))
for f in range(6):
for row in range(3):
y = 10 + offset[f][1] * 3 * a + row * a
for col in range(3):
x = 10 + offset[f][0] ... | 73,125 |
def make_colormap(seq):
"""Return a LinearSegmentedColormap with colors defined as the sequence.
The sequence red to blue can be defined as:
`make_colormap(['red', 'blue'])`
or equivalently
`make_colormap([(1,0,0), 'blue'])`
For more control over color transitions, floats can be included after... | 73,126 |
def error(message) -> NoReturn:
"""Raise SystemExit exception to the stderr."""
sys.exit(f"ERROR: {message}") | 73,127 |
def read_dictionary():
"""
read the dict file into the dict list
"""
with open(FILE, 'r') as f:
for line in f:
words_lst = line.split()
for word in words_lst:
dict_list.append(word) | 73,128 |
def do_magick_identify(input_file):
"""The different informations of an image.
:param input_file: The input file.
:type input_file: jfscripts._utils.FilePath
:return: A directory with the keys `width`, `height` and `colors`.
:rtype: dict
"""
def _get_by_format(input_file, format):
... | 73,129 |
def _run_callback(dir, ejobs):
"""Runs callback script to upload results"""
args = (join(dir, 'callback'), join(dir, 'config'))
args += tuple(join(ejobs, f) for f in _FILES_TO_SEND)
_logger.info('Homework evaluated; sending results')
_logger.debug('calling %s', args)
try:
env = _env_w... | 73,130 |
def is_asciidoc(path):
"""Returns true if the given path is an Asciidoc file."""
# NOTE: Only checking the extension for now.
if path.endswith(".txt"):
return True
return False | 73,131 |
def svn_client_args_to_target_array2(*args):
"""
svn_client_args_to_target_array2(apr_getopt_t os, apr_array_header_t known_targets,
svn_client_ctx_t ctx, svn_boolean_t keep_last_origpath_on_truepath_collision,
apr_pool_t pool) -> svn_error_t
"""
return _client.svn_client_args_to_target_ar... | 73,132 |
def originProblem():
"""
Logic grid puzzle: 'origin' in CPpy
Based on... to check originally, currently part of ZebraTutor
Probably part of Jens Claes' master thesis, from a 'Byron...' booklet
"""
person = ['Mattie', 'Ernesto', 'Roxanne', 'Zachary', 'John']
age = ['109', '110', '111', '112'... | 73,133 |
def write_trip_matrices(trips, skim_dict, skim_stack):
"""
Write trip matrices step.
Adds boolean columns to local trips table via annotation expressions,
then aggregates trip counts and writes OD matrices to OMX. Save annotated
trips table to pipeline if desired.
"""
model_settings = con... | 73,134 |
def do_fiteach(save_cube=None, save_pars=None, show_plot=False):
"""Fits a cube with a gaussian for later use"""
if save_cube is None:
save_cube = 'test.fits'
test_sigma = 10 # in pixel values, each pixel is CDELT3 thick
make_test_cube((100,10,10), save_cube,
sigma=(test_s... | 73,135 |
def prev(y):
"""Reverses next() function from super_cipher.py.
next() generates the next keystream according to the following bit mapping:
current triplet -> next possible triplet : current bit -> next possible bit
0 000 --> (0 000, 4 100) : 0 --> (0, 1)
1 001 --> (0 000, 4 100) : 1 --> (0, 1)
... | 73,136 |
def is_runtime_path_valid(path):
""" Returns True if the given path is a valid runtime path, False
otherwise.
"""
try:
_parse_from_path(path)
return True
except InvalidMetadata:
return False | 73,137 |
def list_role_privileges(role, web_session=None):
"""Lists all privileges of a role.
Args:
role (str): The name of the role.
web_session (object): The webserver session object, optional. Will be
passed in by the webserver automatically
Returns:
The generated shell reque... | 73,138 |
def radar_factory(num_vars, frame='circle'):
"""Create a radar chart with `num_vars` axes.
This function creates a RadarAxes projection and registers it.
Parameters
----------
num_vars : int
Number of variables for radar chart.
frame : {'circle' | 'polygon'}
Shape of frame surr... | 73,139 |
def replaceShapes(path, controls=None, remove=True):
"""
Replaces all the the given control shapes with controls of the same name in the given path file.
If no controls given, will use selected. If none selected, will use all controls in the scene.
Args:
path (string): Path to Maya file to refe... | 73,140 |
def generator_run_to_dict(generator_run: GeneratorRun) -> Dict[str, Any]:
"""Convert Ax generator run to a dictionary."""
return {
"__type": generator_run.__class__.__name__,
"arms": generator_run.arms,
"weights": generator_run.weights,
"optimization_config": generator_run.optimi... | 73,141 |
def preprocess_data_for_dqn(data, reward_model="sparse"):
"""
Creates n_students traces of (s,a,r,s') tuples which can be loaded into the experience replay buffer.
Each student yields one trace
:param data:
:param reward_model: "dense", "sparse" or "semisparse".
If "sparse", then reward = percen... | 73,142 |
def out(json_data):
"""
Output json data in pretty format
"""
print(json.dumps(json_data, indent=4)) | 73,143 |
def find_layer_of_feature(feature, layer_notation='conv'):
"""
This function find the layer correspondent to the given feature in a certain embedding.
It returns the layer name of the feature.
There are two different notations:
- The used by the FNE: vgg16_model/relux_y
- The used by the vgg16 ... | 73,144 |
def get_default_regions():
"""
Current order of precedence
- AWS_DEFAULT_REGION overrides everything else
- region_args come next
- fall back to us-east-1 I guess
"""
env_region = os.environ.get('AWS_DEFAULT_REGION', None)
regions = []
if env_region is not None and env_region:
... | 73,145 |
def connect():
"""Page for connecting to the pi."""
return(str(connect_to_pi.delay({'r': ['VS1_GT1']}))) | 73,146 |
def simulate(n=5):
"""
Simulate data
:param n: int, number of subjects to simulate
:return:
"""
# make data without any offset:
simulated_data = [simulate_raw(make_sine_signal()) for i in range(15)]
raw, weights = list(zip(*simulated_data))
model = fit_srm(raw)
plot_srm(model, we... | 73,147 |
def collect_demo(
scene,
task,
task_id=0,
instance_id=0,
log_path=None,
disable_save=False,
disable_scene_cache=False,
profile=False,
config_file=os.path.join(igibson.example_config_path, "behavior_vr.yaml"),
):
""" """
# HDR files for PBR rendering
hdr_texture = os.path.... | 73,148 |
def get_human_input(player_name, buy_ship, game_stats):
"""
Get input from a human player.
Parameters
----------
player_name : Name of the player to get input from (str).
buy_ships : True, if players buy their boats (bool).
game_stats : stats of the game (dic).
Returns
-------
player_input : input from Huma... | 73,149 |
def install_platformio_core():
""" update platformio version """
cwd = os.getcwd()
python_path = os.path.join(cwd, "platformio_core", "python.exe")
pip_path = os.path.join(cwd, "platformio_core", 'get-pip.py')
cmd = "{0} {1} --no-warn-script-location".format(python_path, pip_path)
logging.info(... | 73,150 |
def _vector_sample_perturbations(
theta: ArrayTree, key: PRNGKey, std: float,
num_samples: int) -> Tuple[ArrayTree, ArrayTree, ArrayTree]:
"""Sample a perturbation with positive and negative pair."""
def _fn(key: PRNGKey) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
pos = _sample_perturbations(thet... | 73,151 |
def solution_detail(request, solution_id):
"""
:param request:
:param solution_id:
:return:
"""
solution_id = solution_id
solution_item = Solution.objects.get_solution_by_id(solution_id)
if not solution_item:
raise Http404
# 获取关键词
solution_keywords = solution_item.keyword... | 73,152 |
def _execute_query(sql_raw, params, qry_type):
""" Handles executing queries based on the `qry_type` passed in.
Returns False if there are errors during connection or execution.
if results == False:
print('Database error')
else:
print(results)
You cannot use `if no... | 73,153 |
def index(page=None):
"""
preview_data = Preview.query.all()
# print(preview_data) # [<Preview 17>]
first_preview_id = Preview.query.order_by(Preview.id.asc()).first().id # <Preview 17>
# first_preview_id = Preview.query.order_by(Preview.id.asc()) # sql
# print(first_preview_id.id)
return... | 73,154 |
def conv2d_w(x, W):
"""conv2d returns a 2d convolution layer with full stride."""
# return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
return wavecomp_ops_module.wave_conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') | 73,155 |
def _validate_decrypt_query_parameter(decrypt, scope, is_admin, user_db):
"""
Validate that the provider user is either admin or requesting to decrypt value for
themselves.
"""
is_user_scope = scope == USER_SCOPE or scope == FULL_USER_SCOPE
if decrypt and (not is_user_scope and not is_admin):
... | 73,156 |
def loadmshid(mesh, fptr, ltag):
"""
LOADMSHID: load the MSHID data segment from file.
"""
data = ltag[1].split(";")
if (len(data) > 1):
mesh.mshID = data[1].strip().lower()
return | 73,157 |
def interpolate_colors(colors, flat=False, num_colors=256):
""" given a list of colors, create a larger list of colors interpolating
the first one. If flatten is True a list of numers will be returned. If
False, a list of (r,g,b) tuples. num_colors is the number of colors wanted
in the final list """
... | 73,158 |
def test_encode(morse):
"""Test Morse.encode().
:param morse: Morse object
:type morse: enigma.morse.Morse
"""
# TODO Need to test spaces too
morse.encode("test")
assert morse.morse == "- . ... - " | 73,159 |
def test_get_delay():
"""Test various scenarios and return values for get_delay."""
current_time_string = str(datetime.datetime.now())[:16].replace(" ", "T")
delay = get_delay(current_time_string)
assert delay <= 0
assert delay >= -60 | 73,160 |
def vcv_cart2local(vcv_cart, lat, lon):
"""Transforms a VCV from the Cartesian to the local reference frame. If
only a column vector of variances is supplied then they are assumed to be
uncorrelated and only the column vector of variances is returned.
See Section 4.4.1 of the DynAdjust User's Guide v1.... | 73,161 |
def test_prepare_dutchf3_patch_step_1():
"""check a complete run for the script in case further changes are needed
"""
# setting a value to SECTION_STRIDE as needed to test the values
SECTION_STRIDE = 1
DIRECTION = "inline"
# use a temp dir that will be discarded at the end of the execution
... | 73,162 |
def create_instance(test_id, config, args):
"""
Invoked by TestExecutor class to create a test instance
@test_id - test index number
@config - test parameters from, config
@args - command line args
"""
return TestSessions(test_id, config, args) | 73,163 |
def test_build_page(pages, cli):
"""Test building a page."""
page = pages.joinpath("single_page.ipynb")
html = pages.joinpath("_build", "_page", "single_page", "html")
index = html.joinpath("index.html")
result = cli.invoke(commands.build, [page.as_posix(), "-n", "-W", "--keep-going"])
assert re... | 73,164 |
def run():
"""
Run the training and makes predictions.
"""
run_id = int(datetime.timestamp(datetime.now()))
writer = SummaryWriter(f"runs/{run_id}")
start_time = datetime.now()
epochs = 5
with trange(epochs + 1) as t:
for epoch in t:
try:
t.set_d... | 73,165 |
def process_decoded_keypoints_2d(decoded_tensors,
keypoint_names_2d,
include_keypoint_scores_2d,
common_module=common):
"""Processes decoded 2D keypoint tensors.
Args:
decoded_tensors: A dictionary for decoded te... | 73,166 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Hive switches."""
if discovery_info is None:
return
session = hass.data.get(DATA_HIVE)
devs = []
for dev in discovery_info:
devs.append(HiveDevicePlug(session, dev))
add_entities(devs) | 73,167 |
def test_init():
"""Tests whether KQMLModule can be initialized."""
KQMLModule(testing=True, name='testmodule') | 73,168 |
def compute_propagation(w, phi):
"""
Propagation term
"""
# Compute derivatives x and y
wx = compute_derivative(w, np.array([[-1, 1]]))
wy = compute_derivative(w, np.array([[-1], [1]]))
# Get max and min of wx
wx_max = np.maximum(wx, 0)
wx_min = np.minimum(wx, 0)
# Get max ... | 73,169 |
def dict2PCA(fit_dict, test_dict=None, dim=2, pca=None):
"""
Dimensionality Reduction by PCA with dict data
example of dict data is below:
fit_dict = {"aa": [[ndarray with shape (Na, D)]],
"bb": [[ndarray with shape (Nb, D)]],...}
Args:
fit_dict (... | 73,170 |
def test_trigger_start_process_jobs(add_jobs, handler):
""" Test the triggering of start process jobs. """
# create dummy applications and processes
proc_list, _ = add_jobs
process_1, process_2, process_3 = proc_list
# update context
for process, stopped in zip(proc_list, [True, False, True]):
... | 73,171 |
def totree(expr):
"""Simplifies ``expr`` (:py:class:`Expr <histbook.expr.Expr>`) to contain only constants (:py:class:`Const <histbook.expr.Const>`), names (:py:class:`Name <histbook.expr.Name>` and :py:class:`Predicate <histbook.expr.Predicate>`), and function calls (:py:class:`Call <histbook.expr.Call>`)."""
... | 73,172 |
def pipe_singlemod_clustering(
f_gene, f_cell, f_mat,
flist_selected_cells, flist_res,
resolutions,
npc=50,
kforleiden=30,
):
"""
"""
# read input
gc_mat = snmcseq_utils.load_gc_matrix(f_gene, f_cell, f_mat)
for f_selected_cells, f_res in zip(flist_selec... | 73,173 |
def decimal_to_short(code):
"""
Convert an ICD9 code from decimal format to short format.
"""
parts = code.split(".")
parts[0] = _zero_pad(parts[0])
return "".join(parts) | 73,174 |
def total() -> int:
"""
:return: int: Return sum of number of grains in each of the 64 squares, i.e. 2^64 - 1
"""
# The sum of the geometric series 1 + 2 + 4 + 8... 64 terms is 2^64 - 1
return 2**64 - 1 | 73,175 |
def normalize_property_ref(value: rdltypes.PropertyReference, owner_node: node.Node) -> str:
"""
Hash of relative path from owner of the property to the target component's
property
"""
path = "%s->%s" % (value.node.get_rel_path(owner_node), value.name)
md5 = hashlib.md5(path.encode('utf-8')).hex... | 73,176 |
def needs_db(function):
""" A function wrapper that provides access to the database. """
@wraps(function)
def wrapper(*args, **kwargs):
db_session = Session()
output = function(db_session, *args, **kwargs)
db_session.close()
return output
return wrapper | 73,177 |
def deluser(name, username, **kwargs):
"""
Remove a user from a group
Args:
name (str):
The name of the group to modify
username (str):
The name of the user to remove from the group
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Ex... | 73,178 |
def unambig_variants(variants, idos_list):
"""Create 'unambiguos' variants for a stop name that equals a city name, depending
on the type of the stop (bus, train or city public transit)."""
# get the right additions list
additions = ADDITIONS.get(idos_list, ADDITIONS['MHD'])
if len(variants) > 1: #... | 73,179 |
async def test_reset_password(
auth_client: AuthClient,
example_user: SignUpUser,
):
"""
Can reset password using the password reset email
"""
sent = await auth_client.send_password_reset_email(example_user.email)
assert isinstance(sent, ResetResponse)
assert sent.email == example_user.e... | 73,180 |
def run(challenges, timeout, seed, logfunc):
""" Challenge launcher for replay services
This will setup fds for all challenges according to:
https://github.com/CyberGrandChallenge/cgc-release-documentation/blob/master/newsletter/ipc.md
Args:
challenges (list): List of absolute paths to all cha... | 73,181 |
def show_cmaps(*args, **kwargs):
"""
Generate a table of the registered colormaps or the input colormaps
categorized by source. Adapted from `this example \
<http://matplotlib.org/stable/gallery/color/colormap_reference.html>`__.
Parameters
----------
*args : colormap-spec, optional
Col... | 73,182 |
def makeRst(prefix, section, app, exampleByIdentifier, schema_store):
"""
Generate the sphinx documentation associated with a L{klein} application.
:param bytes prefix: The URL prefix of the URLs in this application.
:param unicode section: The section of documentation to generate.
:param klein.K... | 73,183 |
def read_accession_file(f):
"""
Read an open accession file, returning the list of accession numbers it
contains.
This automatically skips blank lines and comments.
"""
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
yield lin... | 73,184 |
def test_httpurl_cp_url(url_v6_txt, url_test_path) -> "AutoURI":
"""Test copying local_v6_txt to the following destination storages:
url_test_path: url -> url
This will fail as intended since URL is read-only.
"""
u = HTTPURL(url_v6_txt)
basename = os.path.basename(url_v6_txt)
f... | 73,185 |
def test_least_squares():
""" This test will construct second order cone constraints """
prob = problems.least_squares(10, 5)[1]
data = prob.get_problem_data(cp.SCS)
out = newton_admm(data, data['dims'])
cvx_out = prob.solve()
assert np.allclose(out['info']['fstar'], cvx_out), _s(
out['... | 73,186 |
def downgrade():
"""Migrations for the downgrade."""
statement = sa.text("""
UPDATE db_dblink SET label='_result' WHERE label = 'return';
""")
op.get_bind().execute(statement) | 73,187 |
def Run(benchmark_spec):
"""Measure the boot time for all VMs.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
Returns:
A list of sample.Sample objects with individual machine boot times.
"""
vm = benchmark_spec.vms[0]
if 'all' no... | 73,188 |
def inputs(n_devices, dataset_name, data_dir=None, input_name=None,
n_chunks=0, append_targets=False):
"""Make Inputs for built-in datasets.
Args:
n_devices: how many devices to build the inputs for.
dataset_name: a TFDS or T2T dataset name. If it's a T2T dataset name, prefix
with "t2t_".
... | 73,189 |
def ansi_render_approx(s, width = 80, height = 2000):
"""
Does an approximated render of how a string would look on a vt100
terminal
The string can contain ANSI escape sequences, which the
:module:`pyte` engine can render so a string such as
>>> s = '\x1b[23;08Hi\x1b[23;09H\x1b[23;09Hf\x1b[23;... | 73,190 |
def ycbcr2rgb(ycbcr, *, channel_axis=-1):
"""YCbCr to RGB color space conversion.
Parameters
----------
ycbcr : (..., 3, ...) array_like
The image in YCbCr format. By default, the final dimension denotes
channels.
channel_axis : int, optional
This parameter indicates which a... | 73,191 |
def test_non_interface_glue(create):
"""Test non-interface gluing with implementation."""
impl = create(InterfaceRealizationItem)
clazz = create(ClassItem, UML.Class)
glued = allow(impl, impl.head, clazz)
# connecting head to non-interface item is disallowed
assert not glued | 73,192 |
def confirm_licenses_package(access_token, resource_server, pickup_number):
# type: (str, str, str) -> int
"""
Sends the confirmation to the server that the license package was retrieved.
Returns the response code in case of success.
"""
response = requests.post(
resource_server + "/exte... | 73,193 |
def loss(logits, labels):
"""Calculates the loss from the logits and the labels.
Args:
logits: Logits tensor, float - [batch_size, NUM_CLASSES].
labels: Labels tensor, int32 - [batch_size].
Returns:
loss: Loss tensor of type float.
"""
# Convert from sparse integer labels in the range [0, NUM_CL... | 73,194 |
def import_data(directory, only_main_ipc):
"""Imports preprocessed patent files with patent text and ipcs from txt files in given hierarchical directory.
Parameters
----------
directory : string
Path of hierarchical directory with preprocessed patent txt files
Returns
-------
result_df : pandas DataFrame
... | 73,195 |
def get_douban_url(detail_soup):
"""-"""
detail_soup = detail_soup.find('a', title='豆瓣链接')
if detail_soup:
return detail_soup['href']
return '' | 73,196 |
def generate_gitlab_yaml_for_noop(rust_workspace: str) -> str:
"""Return a string with the Gitlab YAML pipeline config for no-op builds."""
rust_workspace = os.path.abspath(rust_workspace)
gitlab_ci_config = load_gitlab_ci_config(rust_workspace)
out = io.StringIO()
generate_gitlab_yaml(set(), gitl... | 73,197 |
def all_recording_days(path, day_format):
"""
Iterates through the provided directory path and returns an array of all
day directories that match the provided format.
"""
dirpath, dirnames, filenames = next(os.walk(path))
return __dirnames_matching_format(dirnames, day_format) | 73,198 |
def _check_tensors(tensors, tensors_name):
"""Helper function to check the type and length of tensors."""
_check_type(tensors, tensors_name, (list, tuple))
if len(tensors) < 2:
raise ValueError('At least 2 tensors are required.') | 73,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.