content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def p_nonempty_name_list(p):
"""name_list : ID
| name_list COMMA ID
"""
p[0] = processList(p, 3) | 6,400 |
def count_infected(pop):
"""
counts number of infected
"""
return sum(p.is_infected() for p in pop) | 6,401 |
def esum(expr_iterable):
"""
Expression sum
:param term_iterable:
:return:
"""
var_dict = {}
constant = 0
for expr in expr_iterable:
for (var_name, coef) in expr.var_dict.items():
if coef not in var_dict:
var_dict[var_name] = coef
else:
... | 6,402 |
def _prompt(func, prompt):
"""Prompts user for data. This is for testing."""
return func(prompt) | 6,403 |
def fsflow():
"""
fsflow()
Defined at ../src/fsflow.f lines 93-211
"""
_min3p.f90wrap_fsflow() | 6,404 |
def show_trace(func, *args, **kwargs):
# noinspection PyShadowingNames
"""
Display epic argument and context call information of given function.
>>> @show_trace
>>> def complex_function(a, b, c, **kwargs):
...
>>> complex_function('alpha', 'beta', False, debug=True)
calling haystack.sub... | 6,405 |
def download(token, data_dir, file=None):
"""
Download produced data files from Zenodo
token : Your Access Toekn, get it from
https://zenodo.org/account/settings/applications/tokens/new/
data_dir : Provide the files' names you want to save data in
file : Name of the particular file you w... | 6,406 |
def record_editor(project_path: Path, debug: bool = False) -> List[Path]:
"""
Records ezvi running for each instructions file in a project.
The files to record a found using `fetch_project_editor_instructions()`.
Args:
project_path (Path): The path towards the project from which the
`e... | 6,407 |
def to_percent__xy(x, y):
"""
To percent with 2 decimal places by diving inputs.
:param x:
:param y:
:return:
"""
return '{:.2%}'.format(x / y) | 6,408 |
def test_compute_distances13(adata_cdr3, adata_cdr3_mock_distance_calculator):
"""Test for #174. Gracefully handle the case when there are IR."""
adata_cdr3.obs["IR_VJ_1_junction_aa"] = np.nan
adata_cdr3.obs["IR_VDJ_1_junction_aa"] = np.nan
adata_cdr3.obs["has_ir"] = "False"
# test both receptor arm... | 6,409 |
def test_update_auto_refresh(ctx):
""" Test the ViewContext.update_auto_refresh method. """
# reset parameter because called in constructor
del ctx.parameters[AUTO]
# test call with default valid value
ctx.update_auto_refresh()
assert not ctx.parameters[AUTO]
# reset parameter
del ctx.pa... | 6,410 |
def generic_constructor(value, name=None, strict=False, allow_downcast=None):
"""SharedVariable Constructor"""
return SharedVariable(type=generic, value=value, name=name, strict=strict,
allow_downcast=allow_downcast) | 6,411 |
def u_scheme(tree, neighbours):
"""Calculates the u-:ref:`scheme <presolve>`.
"""
unique_neighbours = torch.sort(neighbours, 1, descending=True).values
unique_neighbours[:, 1:][unique_neighbours[:, 1:] == unique_neighbours[:, :-1]] = -1
pairs = torch.stack([tree.id[:, None].expand_as(neighbours), u... | 6,412 |
def find_and_open_file(f):
"""
Looks in open windows for `f` and focuses the related view.
Opens file if not found. Returns associated view in both cases.
"""
for w in sublime.windows():
for v in w.views():
if normpath(f) == v.file_name():
w.focus_view(v)
... | 6,413 |
def stochastic_fit(input_data: object) -> FitParams:
"""
Acquire parameters for the stochastic input signals.
"""
params = FitParams(0.000036906289210966747, 0.014081285145600045)
return params | 6,414 |
def unconfigure_radius_automate_tester(device, server_name, username):
""" Unconfigure Radius Automate Tester.
Args:
device (`obj`): Device object
server_name ('str'): Radius server name
username ('str'): Identity Username to query radius server
Return:
None
Raise:
... | 6,415 |
def sort_features_by_normalization(
normalization_parameters: Dict[int, NormalizationParameters]
) -> Tuple[List[int], List[int]]:
"""
Helper function to return a sorted list from a normalization map.
Also returns the starting index for each feature type"""
# Sort features by feature type
sorted... | 6,416 |
def main():
"""Main method that retrieves the devices"""
# Calculate Execution Time - Start
now = datetime.datetime.now()
print("Current date and time when script starts: " + now.strftime("%Y-%m-%d %H:%M:%S"))
# Connect to Switch
conn_pre = paramiko.SSHClient()
conn_pre.set_missing_hos... | 6,417 |
def block_sort():
"""
Do from here: https://en.wikipedia.org/wiki/Block_sort
:return: None
"""
return None | 6,418 |
def improve_dictionary(file_to_open):
"""Implementation of the -w option. Improve a dictionary by
interactively questioning the user."""
kombinacija = {}
komb_unique = {}
if not os.path.isfile(file_to_open):
exit("Error: file " + file_to_open + " does not exist.")
chars = CONFIG["glob... | 6,419 |
def prep_ground_truth(paths, box_data, qgt):
"""adds dbidx column to box data, sets dbidx in qgt and sorts qgt by dbidx
"""
orig_box_data = box_data
orig_qgt = qgt
path2idx = dict(zip(paths, range(len(paths))))
mapfun = lambda x : path2idx.get(x,-1)
box_data = box_data.assign(dbidx=box_... | 6,420 |
def top_1_pct_share(df, col, w=None):
"""Calculates top 1% share.
:param df: DataFrame.
:param col: Name of column in df representing value.
:param w: Column representing weight in df.
:returns: The share of w-weighted val held by the top 1%.
"""
return top_x_pct_share(df, col, 0.01, w) | 6,421 |
def containsdupevalues(structure) -> bool or None:
"""Returns True if the passed dict has duplicate items/values, False otherwise. If the passed structure is not a dict, returns None."""
if isinstance(structure, dict):
# fast check for dupe keys
rev_dict = {}
for key, value in structure.... | 6,422 |
def test_energy_one_socket(fs_one_socket, sensor_param):
"""
Create a sensor with given parameters (see printed output) and get energy of monitored devices
The machine contains only one socket
Test:
- return value of the function
"""
sensor = Sensor(sensor_param.devices, sensor_param.sock... | 6,423 |
def only_letters(answer):
"""Checks if the string contains alpha-numeric characters
Args:
answer (string):
Returns:
bool:
"""
match = re.match("^[a-z0-9]*$", answer)
return bool(match) | 6,424 |
def get_initial_conditions(scenario, reporting_unit):
""" Retreive the initial conditions from a given reporting unit. """
feature = dict(
geometry=json.loads(reporting_unit.polygon.json),
type='Feature',
properties={}
)
# Collect zonal stats from rasters
bps_stats, bps_ras... | 6,425 |
def test_input1():
"""input1"""
run('input1.txt', ' 1:foo boo', 0) | 6,426 |
def is_finally_visible_func(*args):
"""
is_finally_visible_func(pfn) -> bool
Is the function visible (event after considering 'SCF_SHHID_FUNC' )?
@param pfn (C++: func_t *)
"""
return _ida_funcs.is_finally_visible_func(*args) | 6,427 |
def _losetup_list():
"""
List all the loopback devices on the system.
:returns: A ``list`` of
2-tuple(FilePath(device_file), FilePath(backing_file))
"""
output = check_output(
["losetup", "--all"]
).decode('utf8')
return _losetup_list_parse(output) | 6,428 |
def test_compartmentModel_fit_model_returns_bool(preparedmodel):
"""Test whether the fit routine reports sucess of fitting
"""
return_value = preparedmodel.fit_model()
assert (isinstance(return_value, bool)) | 6,429 |
def gaussian_product_center(a,A,b,B):
"""
"""
A = np.array(A)
B = np.array(B)
return (a*A+b*B)/(a+b) | 6,430 |
def test_gms_get_assertions_on_dataset_field():
"""lists all assertion urns including those which may not have executed"""
dataset_urn = make_dataset_urn("postgres", "fooTable")
field_urn = make_schema_field_urn(dataset_urn, "col1")
response = requests.get(
f"{GMS_ENDPOINT}/relationships?directi... | 6,431 |
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None
): # pylint: disable=unused-argument
"""Setup binary_sensor platform."""
name = discovery_info[CONF_NAME]
entities = []
for resource in discovery_info[CONF_RESOURCES]:
sensor_type = resource.lower... | 6,432 |
def starting(date):
"""validate starting"""
validate_time(date)
validate_time_range(date) | 6,433 |
def test_stack_describe_contains_local_stack() -> None:
"""Test that the stack describe command contains the default local stack"""
runner = CliRunner()
result = runner.invoke(describe_stack)
assert result.exit_code == 0
assert "default" in result.output | 6,434 |
def comparison_plot(cn_see,
option='corr',
plot_orientation='horizontal',
cbar_orientation='vertical',
cbar_indiv_range=None,
title=True,
title_suffix='',
titles_='',
... | 6,435 |
def read_yaml_file(yaml_path):
"""Loads a YAML file.
:param yaml_path: the path to the yaml file.
:return: YAML file parsed content.
"""
if is_file(yaml_path):
try:
file_content = sudo_read(yaml_path)
yaml = YAML(typ='safe', pure=True)
return yaml.safe_lo... | 6,436 |
async def test_parse_gcj02_position(caplog):
"""Test conversion of GCJ02 to WGS84 for china."""
account = await get_mocked_account(get_region_from_name("china"))
vehicle = account.get_vehicle(VIN_F48)
vehicle_test_data = {
"properties": {
"vehicleLocation": {
"addres... | 6,437 |
def _InUse(resource):
"""All the secret names (local names & remote aliases) in use.
Args:
resource: Revision
Returns:
List of local names and remote aliases.
"""
return ([
source.secretName
for source in resource.template.volumes.secrets.values()
] + [
source.secretKeyRef.name
... | 6,438 |
def filter_dwnmut(gene_data):
"""Removes the variants upstream to Frameshift/StopGain mutation.
Args:
- gene_data(dictionary): gene_transcript wise variants where
there is at least one Frameshift/Stopgain
mutation.
Return... | 6,439 |
def format_scwgbs_file(file_path):
"""
Format a scwgbs file to a more usable manner
:param file_path: The path of the file to format
:type file_path: str
:return: A dict where each key is a chr and the value is an array with all the scwgbs reads
:rtype: dict
"""
chr_dict = extract_cols(f... | 6,440 |
def connect_signals():
"""
Hooks up all the event handlers to our callbacks above.
"""
review_request_published.connect(review_request_published_cb,
sender=ReviewRequest)
review_published.connect(review_published_cb, sender=Review)
reply_published.connect(rep... | 6,441 |
def test_manifest_v2_all_pass(_, setup_route):
"""
Run a valid manifest through all V2 validators
"""
validators = get_all_validators(False, "2.0.0")
for validator in validators:
# Currently skipping SchemaValidator because of no context object and config
if isinstance(validator, v2_... | 6,442 |
def ls_generator_loss(scores_fake):
"""
Computes the Least-Squares GAN loss for the generator.
Inputs:
- scores_fake: PyTorch Tensor of shape (N,) giving scores for the fake data.
Outputs:
- loss: A PyTorch Tensor containing the loss.
"""
loss = None
#############################... | 6,443 |
def test_d3_4_28v03_d3_4_28v03i(mode, save_output, output_format):
"""
Tests the simpleType dateTimeStamp and its facets pattern, used in
lists
"""
assert_bindings(
schema="ibmData/valid/D3_4_28/d3_4_28v03.xsd",
instance="ibmData/valid/D3_4_28/d3_4_28v03.xml",
class_name="Roo... | 6,444 |
def rmsd(predicted, reference):
"""
Calculate root-mean-square deviation (RMSD) between two variables.
Calculates the root-mean-square deviation between two variables
PREDICTED and REFERENCE. The RMSD is calculated using the
formula:
RMSD^2 = sum_(n=1)^N [(p_n - r_n)^2]/N
where p is the p... | 6,445 |
def _get_ranks_for_sequence(logits: np.ndarray,
labels: np.ndarray) -> List[float]:
"""Returns ranks for a sequence.
Args:
logits: Logits of a single sequence, dim = (num_tokens, vocab_size).
labels: Target labels of a single sequence, dim = (num_tokens, 1).
Returns:
An a... | 6,446 |
def eval_model_on_grid(model, bbox, tx, voxel_grid_size, cell_vox_min=None, cell_vox_max=None, print_message=True):
"""
Evaluate the trained model (output of fit_model_to_pointcloud) on a voxel grid.
:param model: The trained model returned from fit_model_to_pointcloud
:param bbox: The bounding box defi... | 6,447 |
def create_gop(mpeg_file_object: IO[bytes]) -> bytes:
"""Create an index that allows faster seeking.
Note: as far as I can tell, this is not a standard GOP / group of pictures
structure. It is an index that maps frame numbers to stream offsets.
This is referred to as `GOPList` in MoonShell:
misctoo... | 6,448 |
def add_path_arguments(parser) -> None:
"""Adds common presubmit check options to an argument parser."""
parser.add_argument(
'paths',
nargs='*',
type=Path,
help=(
'Paths to which to restrict the presubmit checks. '
'Directories are expanded with git ls-f... | 6,449 |
def beam_search(model, test_data_src, beam_size, max_decoding_time_step):
""" Run beam search to construct hypotheses for a list of src-language sentences.
@param model : Model
@param test_data_src (List[List[str]]): List of sentences (words) in source language, from test set.
@param beam_size (int): be... | 6,450 |
def main():
"""
Example of partial loading of a scene
Loads only some objects (by category) and in some room types
"""
logging.info("*" * 80 + "\nDescription:" + main.__doc__ + "*" * 80)
settings = MeshRendererSettings(enable_shadow=True, msaa=False)
if platform == "darwin":
settings... | 6,451 |
def filter_months(c, months):
"""Filters the collection by matching its date-time index with the specified months."""
indices = find_all_in(get_months(c), get_months(months))
return take_at(c, indices) | 6,452 |
def kmode_fisher(ks,mus,param_list,dPgg,dPgv,dPvv,fPgg,fPgv,fPvv,Ngg,Nvv, \
verbose=False):
"""
Fisher matrix for fields g(k,mu) and v(k,mu).
Returns F[g+v] and F[g]
dPgg, dPgv, dPvv are dictionaries of derivatives.
fPgg, fPgv, fPvv are fiducial powers.
"""
from orphics.stat... | 6,453 |
def main(args):
"""
Downloads the necessary catalogues to perform the 1- and 2-halo
conformity analysis
"""
## Reading all elements and converting to python dictionary
param_dict = vars(args)
## ---- Adding to `param_dict` ----
param_dict = add_to_dict(param_dict)
## Checking for c... | 6,454 |
def detect_device(model):
"""
Tries to determine the best-matching device for the given model
"""
model = model.lower()
# Try matching based on prefix, this is helpful to map e.g.
# FY2350H to FY2300
for device in wavedef.SUPPORTED_DEVICES:
if device[:4] == model[:4]:
return device
... | 6,455 |
def re_identify_image_metadata(filename, image_names_pattern):
"""
Apply a regular expression to the *filename* and return metadata
:param filename:
:param image_names_pattern:
:return: a list with metadata derived from the image filename
"""
match = re.match(image_names_pattern, filename)
... | 6,456 |
def test_superoperator_to_kraus_fixed_values(superoperator, expected_kraus_operators):
"""Verifies that cirq.kraus_to_superoperator computes the correct channel matrix."""
actual_kraus_operators = cirq.superoperator_to_kraus(superoperator)
for i in (0, 1):
for j in (0, 1):
input_rho = np... | 6,457 |
def train():
"""given 20 players, run the tournament to make qlearner learn
with variable tournament parameters"""
players = setup_opponents()
#players = [axl.Random(), axl.Random(), axl.Random(), axl.Random(), axl.Random(), axl.Random(), axl.Random(), axl.Random(), axl.Random(), axl.Random(), axl.Rand... | 6,458 |
def load_config(config_file: str) -> dict:
"""
Function to load yaml configuration file
:param config_file: name of config file in directory
"""
try:
with open(config_file) as file:
config = yaml.safe_load(file)
except IOError as e:
print(e)
sys.exit... | 6,459 |
def LoginGoogleAccount(action_runner,
credential='googletest', # Recommended credential.
credentials_path=login_utils.DEFAULT_CREDENTIAL_PATH):
"""Logs in into Google account.
This function navigates the tab into Google's login page and logs in a user
using credenti... | 6,460 |
async def test_application_state(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_device: RokuDevice,
mock_roku: MagicMock,
) -> None:
"""Test the creation and values of the Roku selects."""
entity_registry = er.async_get(hass)
entity_registry.async_get_or_create(
SELE... | 6,461 |
def remove(filepath_list):
"""移除中间文件"""
for path in filepath_list + [CONCAT_FILE]:
if os.path.exists(path):
os.remove(path) | 6,462 |
async def admin_cmd_make_role_menu(message : discord.Message, args : str, isDM : bool):
"""Create a reaction role menu, allowing users to self-assign or remove roles by adding and removing reactions.
Each guild may have a maximum of cfg.maxRoleMenusPerGuild role menus active at any one time.
Option reaction... | 6,463 |
def PSF_Moffat(alpha,beta,x,y):
""" Compute the PSF of the instrument with a Moffat function
Parameters
-----------
alpha: float
radial parameter
beta: float
power indice of the function
x: float
position along the x axis
y: float
position along the y axi... | 6,464 |
def _tf_range_for_stmt(iter_,
extra_test,
body,
get_state,
set_state,
init_vars,
basic_symbol_names,
composite_symbol_names,
opts):
""... | 6,465 |
def _import_class(module_and_class_name: str) -> type:
"""Import class from a module, e.g. 'text_recognizer.models.MLP'"""
module_name, class_name = module_and_class_name.rsplit(".", 1) # splits into 2 elements at "."
module = importlib.import_module(module_name)
class_ = getattr(module, class_name) # g... | 6,466 |
def mark_task(func):
"""Mark function as a defacto task (for documenting purpose)"""
func._is_task = True
return func | 6,467 |
def dict_diff(left: Map, right: Map) -> t.List[t.Dict]:
"""Get the difference between 2 dict-like objects
Args:
left (Map): The left dict-like object
right (Map): The right dict-like object
The value returned is a list of dictionaries with keys ["path", "left", "right"]
which contain t... | 6,468 |
def make_slack_message_divider() -> dict:
"""Generates a simple divider for a Slack message.
Returns:
The generated divider.
"""
return {'type': 'divider'} | 6,469 |
def sandbox_multibranch(log_dir, request):
"""Multi-branch sandbox fixture. Parameterized by map of branches.
This fixture is identical to `sandbox` except that each node_id is
mapped to a pair (git revision, protocol version). For instance,
suppose a mapping:
MAP = { 0: ('zeronet', 'alpha'), 1:... | 6,470 |
def ensure_access(file):
"""Ensure we can access a directory and die with an error if we can't."""
if not can_access(file):
tty.die("Insufficient permissions for %s" % file) | 6,471 |
def username():
""" Return username from env. """
return os.environ["USER"] | 6,472 |
def get_history(filename: str, extension: int = 0) -> str:
"""
Returns the HISTOR header lines.
Args:
filename: image filename.
extension: image extension number.
Returns:
string containing all HISTORY lines.
"""
filename = azcam.utils.make_image_filename(filename)
... | 6,473 |
def product_detail(request, product_id):
""" A view to show one product's details """
product = get_object_or_404(Product, pk=product_id)
review_form = ReviewForm()
reviews = Review.objects.filter(product_id=product_id).order_by('-created_at')
context = {
'product': product,
're... | 6,474 |
def deserialize_response_content(response):
"""Convert utf-8 encoded string to a dict.
Since the response is encoded in utf-8, it gets decoded to regular python
string that will be a json string. That gets converted to python
dictionary.
Note: Do not use this method to process non-json response.co... | 6,475 |
def _remove_header_create_bad_object(remove, client=None):
""" Create a new bucket, add an object without a header. This should cause a failure
"""
bucket_name = get_new_bucket()
if client == None:
client = get_client()
key_name = 'foo'
# remove custom headers before PutObject call
... | 6,476 |
def SpawnObjectsTab():
"""This function creates a layout containing the object spawning functionality.
Returns:
str : The reference to the layout.
"""
### Create main Layout for the tab
mainTab = cmds.columnLayout(adjustableColumn=True, columnAttach=('both', 20))
cmds.separator(height... | 6,477 |
def train_val_test_split(relevant_data: List[str], seed: int = 42) -> Tuple[List[str], List[str], List[str]]:
"""Splits a list in seperate train, validate and test datasets.
TODO: add params for train / val / test sizes
:param relevant_data: The list to be divided, generaly a list of filenames.
:dtype... | 6,478 |
def create_boxplots_ratio_3(arr1, arr2, arr3, labels, m, n, lambda_max, title,
ticks, no_vars, range_1, range_2, region,
function_type, func_evals):
"""Create boxplots."""
plt.figure(figsize=(5, 5))
plt.ylim(range_1, range_2)
bpl = plt.boxplo... | 6,479 |
def getShdomDirections(Y_shdom, X_shdom, fov=math.pi/2):
"""Calculate the (SHDOM) direction of each pixel.
Directions are calculated in SHDOM convention where the direction is
of the photons.
"""
PHI_shdom = np.pi + np.arctan2(Y_shdom, X_shdom)
PSI_shdom = -np.pi + fov * np.sqrt(X_shdo... | 6,480 |
def twos_comp(val, bits):
"""returns the 2's complement of int value val with n bits
- https://stackoverflow.com/questions/1604464/twos-complement-in-python"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
val = val - (1 << bits) # compute negative value
r... | 6,481 |
def get_batch(source, i, cnf):
"""
Gets a batch shifted over by shift length
"""
seq_len = min(cnf.batch_size, len(source) - cnf.forecast_window - i)
data = source[i : i + seq_len]
target = source[
i + cnf.forecast_window : i + cnf.forecast_window + seq_len
].reshape(-1)
return d... | 6,482 |
def test_list_language_min_length_2_nistxml_sv_iv_list_language_min_length_3_1(mode, save_output, output_format):
"""
Type list/language is restricted by facet minLength with value 7.
"""
assert_bindings(
schema="nistData/list/language/Schema+Instance/NISTSchema-SV-IV-list-language-minLength-3.x... | 6,483 |
def verify_df(df, constraints_path, epsilon=None, type_checking=None,
repair=True, report='all', **kwargs):
"""
Verify that (i.e. check whether) the Pandas DataFrame provided
satisfies the constraints in the JSON ``.tdda`` file provided.
Mandatory Inputs:
*df*:
... | 6,484 |
def logical_and(image1, image2):
"""Logical AND between two videos. At least one of the videos must have
mode "1".
.. code-block:: python
out = ((image1 and image2) % MAX)
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_a... | 6,485 |
def crusader_action(party_sorted_by_rank, hero, raid_info, enemy_formation):
"""[ Ideal skill load-out: smite, stunning blow, holy lance, inspiring cry ]"""
global UpdatedPartyOrder
party = party_sorted_by_rank
list_of_attacks = ['smite', 'holy_lance']
stall_count = raid_info['battle']['round_s... | 6,486 |
def predict(endpoint_id: str, instance: object) -> object:
"""Send a prediction request to a uCAIP model endpoint
Args:
endpoint_id (str): ID of the uCAIP endpoint
instance (object): The prediction instance, should match the input format that the endpoint expects
Returns:
object: Prediction re... | 6,487 |
def positionNoFlag(PosName, coords):
"""This function writes the postion with no flags, on the format P1=(X,Y,Z,A,B,C)"""
definePosition(PosName, coords, True, [0,0]) | 6,488 |
async def resolve_address(ipaddr, *args, **kwargs):
"""Use a resolver to run a reverse query for PTR records.
See ``dns.asyncresolver.Resolver.resolve_address`` for more
information on the parameters.
"""
return await get_default_resolver().resolve_address(ipaddr, *args, **kwargs) | 6,489 |
def _stringify(item):
"""
Private funtion which wraps all items in quotes to protect from paths
being broken up. It will also unpack lists into strings
:param item: Item to stringify.
:return: string
"""
if isinstance(item, (list, tuple)):
return '"' + '" "'.join(item) + '"'
i... | 6,490 |
def _get_tree_filter(attrs, vecvars):
"""
Pull attributes and input/output vector variables out of a tree System.
Parameters
----------
attrs : list of str
Names of attributes (may contain dots).
vecvars : list of str
Names of variables contained in the input or output vectors.
... | 6,491 |
def db(sql, action):
"""Create or Drop tables from a database"""
db = SQL(sql)
settings.SQL = sql
# auth_mod = importlib.import_module("labfunctions.auth.models")
wf_mod = importlib.import_module("labfunctions.models")
if action == "create":
db.create_all()
click.echo("Created..... | 6,492 |
def gradient2(Y,x,sum_p):
"""
Description
-----------
Used to calculate the gradients of the beta values (excluding the first).
Parameters
----------
Y: label (0 or 1)
x: flux value
sum_p: sum of all beta values (see 'param_sum' function)
Returns
-------
num/denom: gradient value
"""
if Y... | 6,493 |
def test_dramatiq_collector_returns_queues_sizes(dramatiq_queue):
"""
DramatiqCollector returns a correct list of queues sizes.
GIVEN: There is a Dramatiq queue in Redis.
WHEN: _get_queues_sizes method is called with a list of valid queues names.
THEN: A list of tuples with correct queues names and... | 6,494 |
def test_dataset(args, valid_loader):
"""
return the required model depending on the arguments:
"""
test_data = next(iter(valid_loader))
print("Input dimension:")
if args.model_type == "diagnosis":
print(test_data["img"][args.perspectives[0]].shape)
print(torch.min(test_data["im... | 6,495 |
def takeBlock2(aList, row_list, col_list):
"""
Take sublist given from rows specified by row_list and column specified by col_list from
a doublely iterated list.
The convention for the index of the rows and columns are the same as in slicing.
"""
result = []
for row in row_list:
result.append(map(lambda col... | 6,496 |
def err_callback(signum: signal.Signals, frame: Any) -> None:
"""Callback that raises Timeout.ContextTimeout"""
raise ContextTimeout() | 6,497 |
def param(key, desired_type=None):
"""Return a decorator to parse a JSON request value."""
def decorator(view_func):
"""The actual decorator"""
@wraps(view_func)
def inner(*args, **kwargs):
data = request.get_json() # May raise a 400
try:
value = ... | 6,498 |
def make_client(instance):
"""Returns a client to the ClientManager."""
tacker_client = utils.get_client_class(
API_NAME,
instance._api_version[API_NAME],
API_VERSIONS)
LOG.debug('Instantiating tacker client: %s', tacker_client)
kwargs = {'service_type': 'nfv-orchestration',
... | 6,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.