content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def resolve_path_traits(thistrait, value, cwd):
"""Resolve a BasePath-derived trait given an interface spec."""
return _recurse_on_path_traits(_resolve_path, thistrait, value, cwd) | 72,300 |
def test_tuning_transe():
"""Function to test the tuning function."""
tunning_function('transe') | 72,301 |
def return_value(controller_fun):
"""
返回参数
:param controller_fun: 控制层函数
:return:
"""
def __decorator(*args, **kwargs):
ret_value = {
"version": server_config.version,
"success": 0,
"message": u"fail query"
}
ret_data, code = controller... | 72,302 |
def coherence_masking(src_ds, coherence_ds, coherence_thresh):
"""
Perform coherence masking on raster in-place.
Based on gdal_calc formula provided by Nahidul:
gdal_calc.py -A 20151127-20151209_VV_8rlks_flat_eqa.cc.tif
-B 20151127-20151209_VV_8rlks_eqa.unw.tif
--outfile=test_v1.tif --ca... | 72,303 |
def rodada14():
"""
P: é a definição para o indice que será usado caso o usuário use a ajuda do pulo. Ele define qual a pergunta que
será escolhida.
pergunta: É definido o nivel, a variável sorteio faz a escolha da pergunta e após essa escolha é selecionada o
indice 0 (Lembra... | 72,304 |
def buffer_toggle(
openings: Observable[Any], closing_mapper: Callable[[Any], Observable[Any]]
) -> Callable[[Observable[_T]], Observable[List[_T]]]:
"""Projects each element of an observable sequence into zero or
more buffers.
.. marble::
:alt: buffer_toggle
---a-----------b----------... | 72,305 |
def reverse(*args, **kwargs):
"""Now this is a crazy and silly hack, but it is basically here to
enforce that an empty path always takes precedence over an article_id
such that the root article doesn't get resolved to /ID/ but /.
Another crazy hack that this supports is transforming every wiki url
... | 72,306 |
def _Start(callback):
"""Grab a lock on job:analyze_analytics and call RunOnce. If we get a return value, write it to the job summary."""
client = db_client.DBClient.Instance()
job = Job(client, 'analyze_analytics')
if options.options.require_lock:
got_lock = yield gen.Task(job.AcquireLock)
if got_lock... | 72,307 |
def locale_get(handle, name):
"""
Gets the locale
Args:
handle (UcscHandle)
name (string): name of ldap provider
Returns:
AaaLocale : Managed Object OR None
Example:
locale_get(handle, name="test_locale")
"""
dn = ucsc_base_dn + "/locale-" + name
retur... | 72,308 |
def euler38():
"""Solution for problem 38."""
# '123456789' will be decomposed in at least two elements,
# the smallest being 4 at most characters long
sol = 0
digits = {str(d) for d in range(1, 10)}
for n in range(10000):
s = ""
for i in itertools.count(1):
s += str(... | 72,309 |
def clone_or_update_repos():
"""Clone the relevant repos from scratch or update them if they exist and
if directed to do so by the user."""
message = """Before building the release, we clone or update the release repositories.
However, if you have had to run the script multiple times today and no files
have... | 72,310 |
def builtin_swap(a, b):
"""Modify the stack: ( a b -- b a )."""
return (b, a) | 72,311 |
def package_version(split: bool = False) -> Union[str, Tuple[str, str]]: # pragma: no cover
"""Get current package version.
Args:
split: Flag indicating whether to return the package version as a
single string or split into a tuple of components.
Returns:
Package version string... | 72,312 |
def _add_method(class_re, method_name, file_name=None):
"""
Loads a file ./ocrd_page_user_methods/{{ method_name }}.py and defines a MethodSpec applying to class_re
"""
source = []
if not file_name:
file_name = method_name
with codecs.open(join(dirname(__file__), 'ocrd_page_user_methods'... | 72,313 |
def makeServoSpeedPacket(ID, maxSpeed):
"""
Run servo between 0.0 to 1.0, where 1.0 is 100% (full) speed.
"""
if 0.0 > maxSpeed > 1.0:
raise Exception('makeServoSpeed: max speed is a percentage (0.0-1.0)')
speed = int(maxSpeed*1023)
pkt = makeWritePacket(ID, xl320.XL320_GOAL_VELOCITY, le(speed))
return pkt | 72,314 |
def checkPaintingContext():
"""
Checks the painting context to check that everything is in order
"""
resetContext = False
if cmds.artAttrCtx("artAttrColorPerVertexContext", exists=True):
resetContext = False
mel.eval("PaintVertexColorTool;") # make sure the paint vertex context exists
... | 72,315 |
def validate_load():
"""Validates that rows have been inserted into the star schema."""
redshift = PostgresHook("redshift")
for query in sql_queries.validate_queries:
records = redshift.get_records(query)
if len(records) < 1 or len(records[0]) < 1:
raise ValueError(f"Data qualit... | 72,316 |
def rotate_translate(vertices: np.ndarray, translation: Union[np.array, List[float]], angle: Union[float, int])\
-> np.ndarray:
"""
First rotates the list of vertices around the origin and then translates the list of vertices.
:param vertices: array of 2D vertices [[x_0, y_0], [x_1, y_1], ...]
... | 72,317 |
def Cleanup(benchmark_spec):
"""Cleanup MLPerf on the cluster.
Args:
benchmark_spec: The benchmark specification. Contains all data that is
required to run the benchmark.
"""
mnist_benchmark.Cleanup(benchmark_spec) | 72,318 |
def check_set_dimension():
"""
Validate a SetDimension and return all errors and warnings.
:returns: A list of 'errors' and a list of 'warnings'
"""
return list(), list() | 72,319 |
def test_periodic_fee_allowance(cluster):
"""
check periodic fee allowance with no expiration
"""
transaction_coins = 100
fee_coins = 10
period = 5
period_limit = 11
number_of_periods = 3
fee_granter_address = cluster.address("community")
fee_grantee_address = cluster.address("... | 72,320 |
def slater(name):
"""In quantum chemistry, Slater's rules provide numerical values for the
effective nuclear charge concept. In a many-electron atom, each electron is
said to experience less than the actual nuclear charge owing to shielding
or screening by the other electrons.
Parameters
------... | 72,321 |
def reidentify_by_pokeblink(rng:Xorshift, rawintervals:List[float], search_max=3*10**4, search_min=0, eps=0.1, dt = 0.01)->Tuple[Xorshift, float, float]:
"""Reidentify Xorshift state via intervals of Pokemon blinks
Args:
rng (Xorshift): _description_
rawintervals (List[float]): _description_
... | 72,322 |
def read_gNB(
*,
db: Session = Depends(deps.get_db),
gNB_id: str = Path(..., description="The gNB id of the gNB you want to retrieve"),
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get gNB by ID.
"""
gNB = crud.gnb.get_gNB_id(db=db, id=gNB_id)
if n... | 72,323 |
def __api_operation_prep(log, arguments):
"""
API Operation Common Functionality
"""
# Parse the user data
example_user_config_json = """
{
'user': <username>,
'username': <username>,
'user_name': <username>,
'user_id': <userid>
'tenant_name': <tenantname>... | 72,324 |
def get_powGen(solar_cf_file, wind_cf_file):
""" Retrieve all necessary information from powGen netCDF files: RE capacity factors and corresponding lat/lons
Capacity factors are in matrix of shape(lats, lon, 8760 hrs) for 1 year
...
Args
----------
`solar_cf_file` (str): file path to... | 72,325 |
def make_batch(points: [np.ndarray], sdfs: [np.ndarray], number_sample: int) -> {str: torch.Tensor}:
"""Make two list of points and sdfs on to GPU.
Args:
points: The list of the points.
sdfs: The list of the signed distance fields.
number_sample: The number points to be sampled on the s... | 72,326 |
def run_server(argv: str):
"""
Run server
"""
os.system(f"uvicorn app.main:app --reload {argv}") | 72,327 |
def test_call_at(loop):
"""Verify that loop.call_at works as expected."""
def mycallback():
nonlocal was_invoked
was_invoked = True
was_invoked = False
loop.call_at(loop.time() + .1, mycallback)
loop.run_until_complete(asyncio.sleep(.5))
assert was_invoked | 72,328 |
def simple_plot(cfg):
"""
a simple plot
"""
data={}
nax = 1
cont = np.loadtxt(cfg.fcont)
cont_cali = np.loadtxt(cfg.fcont+"_cali", usecols=(0, 1, 2))
data["cont"]=[cont, cont_cali]
for i, fl in enumerate(cfg.fline):
nax+=1
line = np.loadtxt(fl)
line_cali = np.loadtxt(fl+"_cali", usecol... | 72,329 |
def h5File(path, mode='r'):
""" open a HSDS domain or HDF5 file based on the path.
if path starts with "hdf5://", use HSDS, otherwise
use h5py on a regular file path """
if path.startswith("hdf5://"):
f = h5pyd.File(path, mode=mode)
else:
f = h5py.File(path, mode=mode)
re... | 72,330 |
def _build_galaxy_loc_line(env, dbkey, file_path, config, prefix, tool_name):
"""Prepare genome information to write to a Galaxy *.loc config file.
"""
if tool_name:
str_parts = []
tool_conf = _get_tool_conf(env, tool_name)
loc_cols = LocCols(config, dbkey, file_path)
# Compo... | 72,331 |
def test_expr_returns_a_unary_node():
"""Expr should return only num node when it's given."""
parser = Parser(Lexer("-1"))
node = parser.expr()
assert isinstance(node, UnaryOp)
assert node.token == Token(MINUS, "-")
assert node.expr.token == Token(INTEGER_CONST, 1) | 72,332 |
def norx_failure():
"""
Failed ```norx```.
"""
message = request.args.get('m')
response = make_response(
render_template(
"norx.html",
success=False,
message=message
)
)
response.headers.set('Irbox-Success', 'false')
... | 72,333 |
def full(shape, fill_value, dtype=None):
"""Main code for operation full.
Arguments:
shape: a tuple of integers
fill_value: a scalar value
dtype: either a string (e.g. 'int32')
or a numpy dtype (e.g. np.int32)
Returns:
an array
"""
if dtype is None:
... | 72,334 |
def imageStats(im_mat, save_flag=0, disp_flag=0):
"""
This function generates statistical image products for a given set of
images and corresponding extrinsics/intrinsics. The statistical image
products are the timex, brightest, variance, darkest.
All images must have the same dimensions.
Attr... | 72,335 |
def pil_to_numpy(pil_image: PILImage.Image) -> np.ndarray:
"""
Convert a Pillow image to a Numpy array.
Parameters
----------
pil_image : PILImage
Pillow image to convert
Returns
-------
image
Array representation of Pillow image.
"""
return np.asarray(pil_image... | 72,336 |
def search_sequence_numpy(arr, seq):
"""Find sequence positions within array.
Parameters
----------
arr : int array, shape (n_tokens_arr)
Token array, where n_tokens_arr is the number of tokens in the array.
seq : int array, shape (n_tokens_seq)
oken sequence to be located within t... | 72,337 |
def download_artifacts(file_name, file_type, file_extension, file_url):
"""
get run artifacts
Arguments:
file_name (str): file name
file_type (str): file type
file_extension (str): file extension
file_url (str): file url
"""
work_directory = os.getcw... | 72,338 |
def gradcam_distillation(gradients_a, gradients_b, activations_a, activations_b, factor=1):
"""Distillation loss between gradcam-generated attentions of two models.
References:
* Dhar et al.
Learning without Memorizing
CVPR 2019
:param base_logits: [description]
:param list... | 72,339 |
def cmd_import(image_archive_path, *, tag=None):
"""Import an image archive into the repo.
This is a no-op if the image has been imported (i.e., an image in
the repo has the same ID).
For images having the same name and version, it is an error to have
different IDs.
"""
oses.assert_root_pr... | 72,340 |
def main():
"""Get a pylint error description by an error code."""
parser = argparse.ArgumentParser(
description=(
'Get a verbose description of a pylint error by an error code.'
)
)
parser.add_argument(
'code',
metavar='error code',
type=str,
... | 72,341 |
def ffn_handle_intermediate_parabola_layer(man, element, weights, bias, num_out_neurons, num_in_neurons, predecessors, use_area_heuristic):
"""
handle the intermediate FFN Parabolic layer
Parameters
----------
man : ElinaManagerPtr
Pointer to the ElinaManager.
element : ElinaAbstrac... | 72,342 |
def fixture_duthosts(enhance_inventory, ansible_adhoc, tbinfo, request):
"""
@summary: fixture to get DUT hosts defined in testbed.
@param ansible_adhoc: Fixture provided by the pytest-ansible package.
Source of the various device objects. It is
mandatory argument for the class constructors.... | 72,343 |
async def test_internal_session(aresponses):
"""Test JSON response is handled correctly."""
aresponses.add(
"opendata.rdw.nl",
f"/resource/{Dataset.PLATED_VEHICLES}.json",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/json"}... | 72,344 |
def generateReactions(database, reactants, products=None, only_families=None):
"""
Generate the reactions (and associated kinetics) for a given set of
`reactants` and an optional set of `products`. A list of reactions is
returned, with a reaction for each matching kinetics entry in any part of
the d... | 72,345 |
def create_runs(args, elements, n_runs, num_classes, classe=None, sample=None, sample_is_support=True, elements_per_class=[]):
"""
Define runs either randomly or by specifying one sample to insert either as a query or as a support
"""
if classe == None and sample == None:
runs = list(zip(*[defin... | 72,346 |
def nordic2Arrival(data, arrival_id):
"""
Function for converting a nordic file into a Arrival string
:param NordicData data: NordicData object to be converted
:param int arrival_id: arrival id of the assoc
:param int origin_id: origin id of the origin
:returns: arrival_string
"""
arriv... | 72,347 |
def realpath(rpath):
"""Path relative to project-root -> Real path relative to project-root.
This resolves symlinks.
"""
return relpath(os.path.realpath(join(rpath))) | 72,348 |
def _build_discrete_cmap(cmap, levels, extend, filled):
"""
Build a discrete colormap and normalization of the data.
"""
import matplotlib as mpl
if not filled:
# non-filled contour plots
extend = "max"
if extend == "both":
ext_n = 2
elif extend in ["min", "max"]:
... | 72,349 |
def _granted(provides, needs):
"""Check if user provided permissions and necessary permissions match."""
current_app.logger.debug("Provides %s and needs: %s", provides, needs)
return provides and not set(provides).isdisjoint(set(needs)) | 72,350 |
def is_jsonable_array(obj: Any) -> bool:
"""Return `True` if ``obj`` is a jsonable array"""
cls = obj if isinstance(obj, type) else type(obj)
return isinstance(getattr(cls, PHERES_ATTR, None), ArrayData) | 72,351 |
def sort_lines(file: str) -> None:
"""Sorts lines in file."""
if os.path.isfile(file):
with open(file, encoding=DEFAULT_CHARSET) as src_file:
temp_list = sorted(set(src_file.readlines()))
with open(file, 'w', encoding=DEFAULT_CHARSET) as src_file:
for line in temp... | 72,352 |
def deep_Q_Learning(alpha, gamma, epsilon, episodes, max_steps, n_tests, render = False, test=False):
"""
@param alpha learning rate
@param gamma decay factor
@param epsilon for exploration
@param max_steps for max step in each episode
@param n_tests number of test episodes
"""
env = gym.make('Deterministic-... | 72,353 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
""" Set up Solis sensor. """
inverter_name = config.get(CONF_NAME)
portal_domain = config.get(CONF_PORTAL_DOMAIN)
portal_username = config.get(CONF_USERNAME)
portal_password = config.get(CONF_PASSWORD)
portal_plantid = c... | 72,354 |
def deploy_env(
filename: str,
skip_images: bool,
debug: bool,
username: Optional[str] = None,
password: Optional[str] = None,
) -> None:
"""Deploy a Orbit Workbench environment based on a manisfest file (yaml)."""
if debug:
enable_debug(format=DEBUG_LOGGING_FORMAT)
filename = fi... | 72,355 |
def readFASTA(text, results=dict()):
"""
@param text in FASTA format
@param results dict where results will be put. A new dict by default.
@return dictionnary with new entry like {sequence_name: sequence_str}
@note call this function only if biopython can't be used instead
"""
string = ''
... | 72,356 |
def get_choices_from_model(model_name, only_active=True):
"""
Return the values of a model as choices to be used in the form.
Args:
model_name: (str) The name of the model inside the ``configuration`` app
only_active: (bool) If True, a filter is set to return only instances of
the... | 72,357 |
def load_dictionaries_list():
"""loading the list of credentials dictionaries"""
dictionaries_list = [f for f in listdir(config_params.CREDENTIALS_DICTIONARIES_FOLDER)
if (isfile(join(config_params.CREDENTIALS_DICTIONARIES_FOLDER, f)) and f.lower().endswith('.dic'))]
return dictionaries_... | 72,358 |
def getDbLogger():
"""
This function will return the logger for CEES database queries.
"""
return getLogger(DB_LOGGER) | 72,359 |
def calc_class_accuracy_metrics(ref_samples, pred_samples, cls_area=None, cls_names=None):
"""
A function which calculates a set of classification accuracy metrics for a set
of reference and predicted samples. Optionally, the area classified for each
class can be provided allowing further metrics to be ... | 72,360 |
def _files_to_copy(directory):
"""Retrieve files that should be remotely copied.
"""
with utils.chdir(directory):
image_redo_files = reduce(operator.add,
[glob.glob("*.params"),
glob.glob("Images/L*/C*"),
... | 72,361 |
def parse(input_text, check_duplicate_keys=False):
"""Parses the input as JSON and returns its contents.
It supports Scalyr's extensions to the Json format, including comments and
binary data. Specifically, the following are allowed:
- // and /* comments
- Concatenation of string literals using ... | 72,362 |
def constFactor(i, transform):
"""经过 transform 变换后的密度矩阵第 i 个对角元表达式中的常数项
"""
return np.real(
np.conj(tensorElement(transform, i, 0)) *
tensorElement(transform, i, 0)) | 72,363 |
def positional_encoding_2d(d_model, height, width, device):
"""
reference: wzlxjtu/PositionalEncoding2D
:param d_model: dimension of the model
:param height: height of the positions
:param width: width of the positions
:return: d_model*height*width position matrix
"""
if d_model % 4 != ... | 72,364 |
def default_get_input_layer_fn(problem_type, feature_columns):
"""Default implementation of get_input_layer_fn."""
def _input_layer_fn(features,
is_training,
scope_name="Phoenix/Input",
lengths_feature_name=None):
with tf.compat.v1.variable_sco... | 72,365 |
def initiate_validator_exit(state: BeaconState,
index: ValidatorIndex) -> BeaconState:
"""
Initiate exit for the validator with the given ``index``.
Return the updated state (immutable).
"""
validator = state.validator_registry[index]
validator = validator.copy(
... | 72,366 |
def wait_for_test_db():
"""Pings the localstack db with describe requests
for {some time} waiting for it to come up...
"""
print('####################################')
print('Waiting for database to start.......')
print('####################################')
def try_request(retries):
... | 72,367 |
def test_task_state_trigger_serialization():
"""
Asserts that the TaskStateTrigger correctly serializes its arguments
and classpath.
"""
trigger = TaskStateTrigger(
TEST_DAG_ID,
TEST_TASK_ID,
TEST_STATES,
[DEFAULT_DATE],
TEST_POLL_INTERVAL,
)
classpath... | 72,368 |
def SHAPE_FUNCTIONS(TYPE_ELEMENT, N_NODESELEMENT, ISO_COORDINATES):
"""
This function creates the matrix of the derivatives of the shape functions
Input:
TYPE_ELEMENT | Type element in Finito algorithm | Integer
| 0 - Frame bar element ... | 72,369 |
def build_app(conf):
""" Build application with the given information
:param conf: Configuration
:return: application
"""
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = conf.SQLALCHEMY_DATABASE_URL
app.config["TESTING"] = conf.TESTING
app.config["SQLALCHEMY_TRA... | 72,370 |
def _json2dicts_mp(proc_id, filename, user_count_filename, uc_dict_filename, params, overwrite=False):
"""Processes a file as downloaded from the reddit data webpage: http://files.pushshift.io/reddit/comments/
For each file it creates two files. One with a dictionary from user -> count and one from user_catego... | 72,371 |
def test_inline_links_528():
"""
Test case 528: (part 3) However, links may not contain other links, at any level of nesting.
"""
# Arrange
source_markdown = """](uri2)](uri3)"""
expected_tokens = [
"[para(1,1):]",
"[image(1,1):inline:uri3::[foo](uri2)::::[[foo](u... | 72,372 |
def two_props_hypothesis(values1: np.ndarray,
values2: np.ndarray,
alternative: str = "two-sided") -> tuple:
"""z test for comparing two proportions
Args:
values1 (np.array): sample 1 binary(0/1) values
values2 (np.array): sample 2 binaray(0/1) ... | 72,373 |
def compare_text(text1, text2):
"""
Compare two markdown texts and return the diff as annotated HTML.
"""
d1 = _markdown(text1)
d2 = _markdown(text2)
sm = difflib.SequenceMatcher(lambda x: x == " ", d1, d2)
output = []
for opcode, a0, a1, b0, b1 in sm.get_opcodes():
if opcode =... | 72,374 |
def share_bi123_f15_v1(s: [Dict, OrderedDict]):
"""股票15分钟123"""
v = Factors.Other.value
freq = Freq.F15.value
for f_ in [freq]:
if f_ not in s['级别列表']:
warnings.warn(f"{f_} not in {s['级别列表']},默认返回 Other")
return v
# # 平多仓因子
# # -----------------------------------... | 72,375 |
def RunSingleCommand(command_and_env):
"""Runs a single command, and returns the return code and any info from
the run.
"""
command, env = command_and_env
try:
proc = subprocess.Popen(
shlex.split(command), stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=env)
... | 72,376 |
def test_get_total_sum_transferred_trustline_update(
ethindex_db_for_currency_network,
currency_network: CurrencyNetworkProxy,
accounts,
wait_for_ethindex_to_sync,
):
"""Test getting the sum transferred for transfer occurring while opening a trustline"""
sender = accounts[0]
receiver = accou... | 72,377 |
def test_namespace_auto_generate():
"""Test if AutoNamespace can generate new options dynamically."""
ns = namespace.AutoNamespace(
type=boolopt.BoolOption, test_1=boolopt.BoolOption()
)
assert ns.test_1 is None
ns.test_1 = True
assert ns.test_1 is True
ns.test_2 = False
assert n... | 72,378 |
def get_sample_interval(info, chan_info):
"""
Get sample interval for one channel
"""
if info['system_id'] in [1, 2, 3, 4, 5]: # Before version 5
sample_interval = (chan_info['divide'] * info['us_per_time'] *
info['time_per_adc']) * 1e-6
else:
sample_inter... | 72,379 |
def get_input_artifact_location(job):
"""
Returns the S3 location of the input artifact.
"""
input_artifact = job["data"]["inputArtifacts"][0]
input_location = input_artifact["location"]["s3Location"]
input_bucket = input_location["bucketName"]
input_key = input_location["objectKey"]
r... | 72,380 |
def run_sparse_network(name, network, intersect_z_vals, intersect_pts,
intersect_ray_batch, use_random_lightdirs, **kwargs):
"""Runs a single network."""
if name.startswith('bkgd'):
intersect_light_ray_batch, intersect_raw = network_query_fn_helper_nodirs(
network=network,
... | 72,381 |
def get(key):
"""get cache value"""
path = getpath(key)
if os.path.exists(path):
return open(path).read() | 72,382 |
def _load_individual_image(f_image, downscale_size, bool_crop=False, crop_size=None):
"""
Loads an individual image into numpy array and perform resizing
:param f_image: absolute path to a single image
:param downscale_size: desired final size of the loaded images, e.g. (256, 256)
:return: individu... | 72,383 |
def appdomconf(appdom, appname):
"""
Return domain specific application configuration
"""
conf = appdom['applications']
for sub in appname.split('.'):
conf = conf[sub]
return conf | 72,384 |
def ForwardDirLocation(build_tool_version_name):
"""Returns location of directory for forward compatibility testing."""
return os.path.join(ThisScriptDir(), '..', 'RSTestForward',
build_tool_version_name) | 72,385 |
def call_action(action, monitorSelected):
"""Calls a action function, depending on the spoken action."""
global MONITOR_SELECTED
MONITOR_SELECTED = monitorSelected
action() | 72,386 |
def test_set_locale_selector_invalid_type():
"""
sets the given function as locale selector which has an invalid type.
it should raise an error.
"""
with pytest.raises(InvalidLocaleSelectorTypeError):
locale_services.set_locale_selector(None) | 72,387 |
def wm_delete_window():
"""A top-level is being closed. Is the program over?"""
cue(); task_closetop(top()) | 72,388 |
def write_run_dict(run_dict, file_name, run_id=FAKE_RUN_ID):
"""Write a dictionary-stored run to a file. The input
is actually a dictionary of dictinoary. The outer
dictionary is a set of query-specific results
indexed by the query id. And the internal dictionary
is a set of document sco... | 72,389 |
def make_fcnet_with_skips(input_, sizes, skip_conns, vocab_size, l2_penalty):
"""
Adds skip connections between layers based on the parameter `skip_conns`,
which should be a list of pairs. A connection will be added from the
output of the source layer to the output of the target layer. The outputs
will be sum... | 72,390 |
def watch_workflows(api, session, **kwargs):
"""
Watch workflows events and save data in database.
Parameters
----------
api : kubernetes.client.apis.custom_objects_api.CustomObjectsApi
session : sqlalchemy.orm.session.Session
"""
w = watch.Watch()
log_level = kwargs.get("log_level... | 72,391 |
def submatrix(tensor: Union[np.ndarray, tf.Tensor], row: int, column: int) -> tf.Tensor:
""" A submatrix of a matrix is obtained by deleting any collection of rows and/or columns.
For example, from the following 3-by-3 matrix, we can construct a 2-by-2 submatrix by
removing row 3 and column 2:
... | 72,392 |
def UDS_SessionEnumerator(sock, session_range=range(0x100), reset_wait=1.5):
""" Enumerates session ID's in given range
and returns list of UDS()/UDS_DSC() packets
with valid session types
Args:
sock: socket where packets are sent
session_range: range for session ID's
re... | 72,393 |
def remove_gap_traces(st):
"""Searches for gaps in seismic data and removes affected traces from
stream.
Parameters
----------
st : Stream
Obspy object containing seismic traces read from disk.
Returns
-------
st : Stream
Obspy object containing seismic traces read from... | 72,394 |
def get_turbot_vpc_subnets(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, turbot_account, api_version):
""" Gets the current turbot vpc configuration for an account
:return: Returns the current turbot VPC configuration
"""
api_method = "GET"
api_url... | 72,395 |
def nfl_scraper(first_season="", last_season="", out_path=""):
"""
Access NFL data from ESPN API
Parameters:
first_season (str): First season (Year)
last_season (str): Last season (Year)
fname (str): Name given to newly written json file
out_path (str): Directory/folder file will be written... | 72,396 |
def read_query(query_filename):
"""
Read a query from file and return as a string
Parameters
----------
query_filename: str name of the query. It will be looked for in the queries folder of this project
Returns
-------
query: str the query with placeholders for the query parameters, as ... | 72,397 |
def AddInstallAPKOption(option_parser):
"""Adds apk option used to install the APK to the OptionParser."""
option_parser.add_option('--apk',
help=('DEPRECATED The name of the apk containing the'
' application (with the .apk extension).'))
option_parser.a... | 72,398 |
def hanoi(n, a, b, c):
"""
>>> hanoi(5, "a", "b", "c")
[('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('b', 'a'), ('c', 'a'), ('b', 'c'), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b'), ('c', 'a'), ('c', 'b'), ('a', 'b'), ('c', 'a'), ('b', 'c'), ... | 72,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.