content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _all_steps_multiples_of_min_step(rows: np.ndarray) -> bool:
"""
Are all steps integer multiples of the smallest step?
This is used in determining whether the setpoints correspond
to a regular grid
Args:
rows: the output of _rows_from_datapoints
Returns:
The answer to the qu... | 5,328,300 |
def black_config(
config: c2cciutils.configuration.ChecksBlackConfigurationConfig,
full_config: c2cciutils.configuration.Configuration,
args: Namespace,
) -> bool:
"""
Check the black configuration.
config is like:
properties: # dictionary of properties to check
Arguments:
... | 5,328,301 |
def consumer(id, num_thread=1):
"""
Main loop to consume messages from the Rucio Cache producer.
"""
logging.info('Rucio Cache consumer starting')
brokers_alias = []
brokers_resolved = []
try:
brokers_alias = [b.strip() for b in config_get('messaging-cache', 'brokers').split(',')]
... | 5,328,302 |
def get_full_test_names(testargs, machine, compiler):
###############################################################################
"""
Return full test names in the form:
TESTCASE.GRID.COMPSET.MACHINE_COMPILER.TESTMODS
Testmods are optional
Testargs can be categories or test names and support th... | 5,328,303 |
def prod_time_series(qa_prod, qatype, metric, xlim=None, outfile=None, close=True, pp=None,
bright_dark=0):
""" Generate a time series plot for a production
Args:
qa_prod:
qatype:
metric:
xlim:
outfile:
close:
pp:
bright_dark: ... | 5,328,304 |
def record_or_not(record_mode, line, start_block, end_block):
""" """
if not record_mode:
if start_block in line:
record_mode = True
elif end_block in line:
record_mode = False
return record_mode | 5,328,305 |
def protocol_increasing_persistence_change_pas():
"""
Change leak conductance (input resistance) of persistent synapse model
"""
config_functions = {config_persistent_synapses: change_persist_numbers}
run_protocol(compare_pas, root="persistent_pas", timestamp=False, filenames=["distal", "distal_KCC2... | 5,328,306 |
def compute_angle_stats(vec_mat, unit='deg'):
""" Get mean of angles the successif vectors used in the reconstruction.
return mean an variance of the angles.
"""
angles = []
for i in range(vec_mat.shape[1] - 1):
aux = 0
dot_prod = np.dot(vec_mat[i] / np.linalg.norm(vec_mat[i]... | 5,328,307 |
def id_test_data(value):
"""generate id"""
return f"action={value.action_name} return={value.return_code}" | 5,328,308 |
def AppcommandsUsage(shorthelp=0, writeto_stdout=0, detailed_error=None,
exitcode=None, show_cmd=None, show_global_flags=False):
"""Output usage or help information.
Extracts the __doc__ string from the __main__ module and writes it to
stderr. If that string contains a '%s' then that is repl... | 5,328,309 |
def kneeJointCenter(frame, hip_JC, delta, vsk=None):
"""Calculate the knee joint center and axis.
Takes in a dictionary of marker names to x, y, z positions, the hip axis
and pelvis axis. Calculates the knee joint axis and returns the knee origin
and axis.
Markers used: RTHI, LTHI, RKNE, LKNE, hip... | 5,328,310 |
def uniform(low: float = 0.0,
high: float = 1.0,
size: tp.Optional[SIZE_TYPE] = None):
"""
Draw samples from a uniform distribution.
"""
if high < low:
raise ValueError("high must not be less than low")
u = _draw_and_reshape(size, rand)
return u * (high - low) +... | 5,328,311 |
def toInt():
"""This built-in function casts the current value to Int and returns the result.
"""
def transform_function(current_value: object, record: dict, complete_transform_schema: dict,
custom_variables: dict):
value_to_return = None
if current_value is not ... | 5,328,312 |
def public_upload(request):
"""Public form to upload missing images
:param request: current user request
:type request: django.http.request
:return: rendered response
:rtype: HttpResponse
"""
upload_success = False
if request.method == "POST":
document = Document.objects.get(id=... | 5,328,313 |
def setup_image_service():
"""Provisions image services in openstack nodes"""
if env.roledefs['openstack']:
execute("setup_image_service_node", env.host_string) | 5,328,314 |
def load_classes(fstem):
"""Load all classes from a python file."""
all_classes = []
header = []
forward_refs = []
class_text = None
done_header = False
fname = pathlib.Path('trestle/oscal/tmp') / (fstem + '.py')
with open(fname, 'r', encoding='utf8') as infile:
for r in infil... | 5,328,315 |
def findAllSubstrings(string, substring):
""" Returns a list of all substring starting positions in string or an empty
list if substring is not present in string.
:param string: a template string
:param substring: a string, which is looked for in the ``string`` parameter.
:returns: a list of subst... | 5,328,316 |
def create_repo(path: str):
"""Creates a new repository at path"""
repo = Repository(path, True)
assert(repo_dir(repo, "branches", mkdir=True))
assert(repo_dir(repo, "objects", mkdir=True))
assert(repo_dir(repo, "refs/heads", mkdir=True))
assert(repo_dir(repo, "refs/tags", mkdir=True))
fpa... | 5,328,317 |
def build_optimizer(name, lr=0.001, **kwargs):
"""Get an optimizer for TensorFlow high-level API Estimator.
Args:
name (str): Optimizer name. Note, to use 'Momentum', should specify
lr (float): Learning rate.
kwargs (dictionary): Optimizer arguments.
Returns:
tf.train.Optim... | 5,328,318 |
def generate_pruning_config(model_name,
sparsity,
begin_step=0,
end_step=-1,
schedule='ConstantSparsity',
granularity='BlockSparsity',
respect_submatrix... | 5,328,319 |
def collect_FR_dev(stim_array,stim_dt,sim_dt,spikemon,n,return_spikes=False):
"""
get all firing rates for a given spikemon
stim_array: array of stimulation time/strengths, e.g., [0,0,0,0,1,0,0,0,1,0,0]
stim_dt: time interval of stimulation
sim_dt: time interval of simulation
spikemon_t: ti... | 5,328,320 |
def assertDict(s):
""" Assert that the input is a dictionary. """
if isinstance(s,str):
try:
s = json.loads(s)
except:
raise AssertionError('String "{}" cannot be json-decoded.'.format(s))
if not isinstance(s,dict): raise AssertionError('Variable "{}" is not a dictionary.'.format(s))
return... | 5,328,321 |
def _consolidate_subdivide_geometry(geometry, max_query_area_size):
"""
Consolidate and subdivide some geometry.
Consolidate a geometry into a convex hull, then subdivide it into smaller
sub-polygons if its area exceeds max size (in geometry's units).
Parameters
----------
geometry : shape... | 5,328,322 |
def deleteAllPatientes():
"""Delete all patient record
Raises:
HTTPException: raises if there is any error in underlying CRUD
operation.
Returns:
null: success response if all the records are successfully deleted
"""
logging.debug("Router: /patient/all")
logging.debug(f... | 5,328,323 |
def get_function_args(node: ast.FunctionDef) -> Tuple[List[Any], List[Any]]:
"""
This functon will process function definition and will extract all
arguments used by a given function and return all optional and non-optional
args used by the function.
Args:
node: Function node containing fun... | 5,328,324 |
def test_view_change_after_some_txns(txnPoolNodesLooper, txnPoolNodeSet,
some_txns_done, testNodeClass, viewNo, # noqa
sdk_pool_handle, sdk_wallet_client,
node_config_helper_class, tconf, tdir,
... | 5,328,325 |
def svn_client_copy3(*args):
"""
svn_client_copy3(svn_commit_info_t commit_info_p, char src_path, svn_opt_revision_t src_revision,
char dst_path,
svn_client_ctx_t ctx, apr_pool_t pool) -> svn_error_t
"""
return apply(_client.svn_client_copy3, args) | 5,328,326 |
def delete(server = None, keys = None):
"""
Marks an entity or entities as deleted on the server. Until an entity
is permanently deleted (an administrative operation, not available
through the RESTful API), it can still be accessed, but will not turn
up in search results.
:param server: a :cl... | 5,328,327 |
def ParseMemCsv(f):
"""Compute summary stats for memory.
vm5_peak_kib -> max(vm_peak_kib) # over 5 second intervals. Since it uses
the kernel, it's accurate except for takes that spike in their last 4
seconds.
vm5_mean_kib -> mean(vm_size_kib) # over 5 second intervals
"""
peak_by_pid = collections.d... | 5,328,328 |
def display(training_data, vis_data, interp):
"""Display training samples, true PSF, model PSF, and residual over field-of-view.
"""
import matplotlib.pyplot as plt
interpstars = params_to_stars(vis_data, noise=0.0)
interpstars = interp.interpolateList(interpstars)
fig, axarr = plt.subplots(5,... | 5,328,329 |
def index_containing_substring(list_str, substring):
"""For a given list of strings finds the index of the element that contains the
substring.
Parameters
----------
list_str: list of strings
substring: substring
Returns
-------
index: containing the substring or -1
"""
... | 5,328,330 |
def _localized_country_list_inner(locale):
"""
Inner function supporting :func:`localized_country_list`.
"""
if locale == 'en':
countries = [(country.name, country.alpha_2) for country in pycountry.countries]
else:
pycountry_locale = gettext.translation('iso3166-1', pycountry.LOCALES... | 5,328,331 |
def ingest_questions(questions: dict, assignment: Assignment):
"""
questions: [
{
sequence: int
questions: [
{
q: str // what is 2*2
a: str // 4
},
]
},
...
]
response = {
rejected: [ ... ]
ignored: [ ... ... | 5,328,332 |
def render_book_template(book_id):
"""
Find a specific book in the database.
Locate the associated reviews (sorted by score and date).
Create the purchase url.
Check whether the user has saved the book to their wishlist.
"""
# Find the book document in the database
this_book = mongo.db.b... | 5,328,333 |
async def replace_dispatcher(client: ClientAsync, replacement: Dispatcher):
"""
replace a dispatcher
"""
response = await client.replace_dispatcher(replacement)
assert (
response.status_code == 200
), f"failed to replace the dispatcher ({response.json()}" | 5,328,334 |
def iatan2(y,x):
"""One coordinate must be zero"""
if x == 0:
return 90 if y > 0 else -90
else:
return 0 if x > 0 else 180 | 5,328,335 |
def fuse_bn_sequential(model):
"""
This function takes a sequential block and fuses the batch normalization with convolution
:param model: nn.Sequential. Source resnet model
:return: nn.Sequential. Converted block
"""
if not isinstance(model, torch.nn.Sequential):
return model
stack ... | 5,328,336 |
def get_baseconf_settings( baseconf_settings_filename = None ):
"""
Returns the basic configuration settings as a parameter structure.
:param baseconf_settings_filename: loads the settings from the specified filename, otherwise from the default filename or in the absence of such a file creates default sett... | 5,328,337 |
def get_variants(df, space_order, point_type, axis, stencils, weights):
"""
Get the all the stencil variants associated with the points, evaluate them,
and fill the respective positions in the weight function.
Parameters
----------
df : pandas DataFrame
The dataframe of boundary-adjacen... | 5,328,338 |
def create_app(test_config=None):
"""Create and configure an instance of the Flask application."""
app = Flask(__name__, instance_relative_config=True)
app.logger.debug('app.instance_path = %s', app.instance_path)
app.config.from_mapping(
SECRET_KEY="$%px0vz%84j2y9ztqg^8k8_!8*-372g85z73(art... | 5,328,339 |
def subtract_background(image, background_image):
"""Subtracts background image from a specified image.
Returns
-------
bs_image : np.ndarray of type np.int | shape = [image.shape]
Background-subtracted image.
"""
image = image.copy().astype(np.int)
background = background_... | 5,328,340 |
def preprocess_testing():
"""
"""
FLAGS = tf.app.flags.FLAGS
description = {
'source_path': FLAGS.source_csv_path,
'image_size': FLAGS.image_size,
'perturb': FLAGS.perturb,
}
examples = preprocess(description)
# NOTE: write gzip
options = tf.python_io.TFRecordO... | 5,328,341 |
def batch_genomes(genomes, num_batches, order):
"""
Populates 2D numpy array with len(rows)==num_batches in {order} major order.
Using col is for when you know you are using X number of nodes, and want-
to evenly distribute genomes across each node
Use row when you want to fill each node, i.e. you g... | 5,328,342 |
def single_gate_params(gate, params=None):
"""Apply a single qubit gate to the qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
a tuple of U gate parameters (theta, phi, lam)
"""
if gate == 'U' or gate == 'u3':
... | 5,328,343 |
def main():
"""
:return: Place and magnitude, where magnitude is greater than 1.0.
"""
start = time.time()
data = os.path.join(root, path)
df = sqlContext.read.json(data)
df.createOrReplaceTempView('earthquakes')
earthquakes_df = sqlContext.sql("SELECT properties.mag, properties.place "... | 5,328,344 |
def pickleAllFeatureFilesFromDir(in_path, out_path, is_malware=False):
"""
Creates pickle files with ML features for all the mmt-probe .csv reports in the given folder
:param in_path: folder with .csv reports
:param out_path: folder where pickle files are to be written
:param is_malware: label (nor... | 5,328,345 |
def check_copr_build(build_id: int) -> bool:
"""
Check the copr_build with given id and refresh the status if needed.
Used in the babysit task.
:param build_id: id of the copr_build (CoprBuildModel.build.id)
:return: True if in case of successful run, False when we need to retry
"""
logger... | 5,328,346 |
def net_to_graph(net):
"""
Convert Net object from parse_net_file to graph represented
(as per dijkstra.py) as dict of dicts where G[v][w] for any v,w
is cost of edge from v to w. Here v and w are just integers (node numbers).
Parameters:
net (in/OUT) - Net object as returned by parse_net_fi... | 5,328,347 |
def runTests(data, targets, pipeline, parameters):
""" Perform grid search with specified pipeline and parameters
on data training set with targets as labels
Evaluate performance based on precision and print parameters
for best estimator
grid search object is retur... | 5,328,348 |
def isMultipleTagsInput(item):
"""
Returns True if the argument datatype is not a column or a table, and if it allows lists and if it has no permitted value.
This function is used to check whether the argument values have to be delimited by the null character (returns True) or not.
:param item: Tab... | 5,328,349 |
def _setup_default_prefixer():
"""`reverse` depends on a prefixer being set for an app and/or locale in the url,
and for non-requests (i.e. cron) this isn't set up."""
request = HttpRequest()
request.META['SCRIPT_NAME'] = ''
prefixer = amo.urlresolvers.Prefixer(request)
prefixer.app = settings.D... | 5,328,350 |
def _send():
"""Polls the mg9_send_q queue, sending requests to margo. If the margo
process is not running _send() starts it and sets the PROC_ATTR_NAME attr.
"""
# TODO: REFACTOR.
while True:
try:
try:
method, arg, cb = gs.mg9_send_q.get()
# CEV... | 5,328,351 |
def imagenet_vgg_compression(compression_config, var_config, overall_model, muVes, strategy, optimizer, verbose=True):
"""
:param compression_config:
:param var_config:
:param overall_model:
:param muVes:
:param strategy:
:param optimizer:
:param verbose:
:return:
"""
cc = c... | 5,328,352 |
def remove_url(url: str = Form(...)):
"""
Remove url from the url json file
:param url: api url in the format: http://ip:port/
:return: ApiResponse
"""
try:
payload = helpers.parse_json(url_config_path)
except Exception as e:
return ApiResponse(success=False, ... | 5,328,353 |
def test_check_size() -> None:
"""
Test `check_size_matches` function.
"""
a1 = np.zeros((2, 3, 4))
a2 = np.zeros((5, 2, 3, 4))
check_size_matches(a1, a1)
check_size_matches(a1, a2, matching_dimensions=[-3, -2, -1])
check_size_matches(a1, a2, dim1=3, dim2=4, matching_dimensions=[-3, -2, ... | 5,328,354 |
def load_CSVdata(messages_filepath, categories_filepath):
"""
Load and merge datasets messages and categories
Inputs:
Path to the CSV file containing messages
Path to the CSV file containing categories
Output:
dataframe with merged data containing messages and categories
... | 5,328,355 |
def run(report_name):
"""Run a report and output to a text file."""
now = datetime.datetime.now().strftime('%Y-%m-%d')
filename = '{} {}.txt'.format(now, report_name)
outputs = [settings for (rep, settings) in reports.items() if report_name in ('all', rep)]
if not outputs:
click.echo('No re... | 5,328,356 |
def test_normalize_resource():
"""
Test that the normalize_resource method is properly called on
resources returned from get_resource.
"""
class Normalize(MockPool):
def normalize_resource(self, resource):
setattr(resource, 'one', 1)
pool = Normalize(mockresource.factory, c... | 5,328,357 |
def cli(ctx, proxy, login):
"""
NokDoc CLI Tool is exposing a set of commands to interact with
Nokia documentation portal.
It offers CLI experience for tasks like
- getting links to the docs aggregated into HTML file
- downloading docs collections automatically
It works for authorized users... | 5,328,358 |
def test_post_415(
api_client: TestClient,
access_token,
) -> None:
"""Test a post request with invalid media type."""
response = api_client.post(
URL,
files={
"file": (Path(__file__).name, open(__file__).read(), "image/png"),
},
headers=access_token,
)
... | 5,328,359 |
def accept_invite(payload, user):
"""
Accepts an invite
args: payload, user
ret: response
"""
try:
invite = Invites.get(payload['invite'])[0]
except:
return Message(
Codes.NOT_FOUND,
{ 'message': 'There isn\'t any active invite with the given id.' }
... | 5,328,360 |
def clean_status_output(
input: str,
) -> Tuple[bool, Dict[str, str], List[Dict[str, str]]]:
# example input
"""
# Health check:
# - dns: rename /etc/resolv.conf /etc/resolv.pre-tailscale-backup.conf: device or resource busy
100.64.0.1 test_domain_1 omnet linux -
10... | 5,328,361 |
def test_tensor_method_mul():
"""test_tensor_method_mul"""
class Net(Cell):
def __init__(self):
super(Net, self).__init__()
self.sub = P.Sub()
def construct(self, x, y):
out = x * (-y)
return out.transpose()
net = Net()
x = ms.Tensor(np... | 5,328,362 |
def verify_target_catalog(df, metadf):
"""
Check that each entry in the (pre magnitude cut) target catalog has
a source_id that matches the original catalog. (i.e., ensure that no
int/int64/str lossy conversion bugs have happened).
"""
print(79*'-')
print('Beginning verification...')
pr... | 5,328,363 |
def _get_top_artists(session: Session, limit=100):
"""Gets the top artists by follows of all of Audius"""
top_artists = (
session.query(User)
.select_from(AggregateUser)
.join(User, User.user_id == AggregateUser.user_id)
.filter(AggregateUser.track_count > 0, User.is_current)
... | 5,328,364 |
def run_test_spin_to_track_beacon(robot):
"""
Tests the spin_until_beacon_seen and spin_to_track_beacon methods of the class.
:type robot: rosebot.RoseBot
"""
print('--------------------------------------------------')
print('Testing the spin_to_track_beacon method of the BeaconSeeker'... | 5,328,365 |
def test_interpolation_option_contract():
""" Tests for InterpolationOption pseudo-type """
obj = putil.ptypes.interpolation_option
check_contract(obj, 'interpolation_option', 5)
exmsg = (
"[START CONTRACT MSG: interpolation_option]Argument "
"`*[argument_name]*` is not one of ['STRAIGHT... | 5,328,366 |
def get_imagenet_lmdb(train_transform, val_transform, test_transform, CONFIG):
"""
Load lmdb imagenet dataset
https://github.com/Fangyh09/Image2LMDB
"""
train_path = os.path.join(CONFIG.dataset_dir, "train_lmdb", "train.lmdb")
val_path = os.path.join(CONFIG.dataset_dir, "val_lmdb", "val.lmdb")
... | 5,328,367 |
def _get_other_locations():
"""Returns all locations except convention venues."""
if 'all' not in location_cache.keys():
conv_venue = LocationType.objects.get(name='Convention venue')
location_cache['all'] = Location.objects.exclude(loc_type=conv_venue)
return location_cache['all'] | 5,328,368 |
def _check_cuda_version():
"""
Make sure that CUDA versions match between the pytorch install and torchvision install
"""
if not _HAS_OPS:
return -1
import torch
_version = torch.ops.torchvision._cuda_version()
if _version != -1 and torch.version.cuda is not None:
tv... | 5,328,369 |
def test_dcgain_consistency():
"""Test to make sure that DC gain is consistently evaluated"""
# Set up transfer function with pole at the origin
sys_tf = ctrl.tf([1], [1, 0])
assert 0 in sys_tf.pole()
# Set up state space system with pole at the origin
sys_ss = ctrl.tf2ss(sys_tf)
assert 0 i... | 5,328,370 |
def test_exists(value: t.Any, exp: bool) -> None:
"""It exists if it's not None."""
assert exists(value) is exp | 5,328,371 |
def largest(layer,field):
"""largest(layer,field)
Returns the largest area significant class in the study area.
"""
theitems = []
rows = arcpy.SearchCursor(layer)
for row in rows:
theitems.append(row.getValue(field))
del rows
theitems.sort()
max1= theitems[-1]
... | 5,328,372 |
async def double_up(ctx):
"""
「ダブルアップチャンス!」を開始します。
"""
depth = 1 # 現在の階層
HOLE = "\N{HOLE}\N{VARIATION SELECTOR-16}"
LEFT_ARROW = "\N{LEFTWARDS BLACK ARROW}\N{VARIATION SELECTOR-16}"
RIGHT_ARROW = "\N{BLACK RIGHTWARDS ARROW}\N{VARIATION SELECTOR-16}"
TOP_ARROW = "\N{UPWARDS BLACK ARROW}\... | 5,328,373 |
def read_version(file_contents):
"""Read the project setting from pyproject.toml."""
data = tomlkit.loads(file_contents)
details = data["tool"]["poetry"]
return details["version"] | 5,328,374 |
def schedule_time(check_start_time, check_end_time, time_duaration=7) -> dict:
""" Returns dictionary of earliest available time within the next week """
all_busy_events = get_busy_events()
for d in range(1,time_duaration):
# Increment by one day throughout the week
check_day = datetime.toda... | 5,328,375 |
def _to_array(value):
"""When `value` is a plain Python sequence, return it as a NumPy array."""
if not hasattr(value, 'shape') and hasattr(value, '__len__'):
return array(value)
else:
return value | 5,328,376 |
def dict_pix_to_deg(input_dict, changeN):
"""Convert pix to deg for a given dictionary format,
changeN is 1 or 2, to let the function works for the first
or both elements of the tuple"""
dict_deg = {}
for key, values in input_dict.items():
new_display = []
for display in values:
... | 5,328,377 |
def remove_container_name_from_blob_path(blob_path, container_name):
"""
Get the bit of the filepath after the container name.
"""
# container name will often be part of filepath - we want
# the blob name to be the bit after that
if not container_name in blob_path:
return blob_path
b... | 5,328,378 |
def _complex_ar_from_dict(dic: Dict[str, List]) -> np.ndarray:
"""Construct complex array from dictionary of real and imaginary parts"""
out = np.array(dic["real"], dtype=complex)
out.imag = np.array(dic["imag"], dtype=float)
return out | 5,328,379 |
def endpoint(url_pattern, method="GET"):
"""
:param url_pattern:
:param method:
:param item:
:return:
"""
def wrapped_func(f):
@wraps(f)
def inner_func(self, *args, **kwargs):
"""
:param self:
:param args:
:param kwargs:
... | 5,328,380 |
def test_benchmarks_bad_user(client, mocker):
"""Tests the benchmarks route with an invalid user."""
mocked_user = mocker.patch('app.routes.AppUser')
mocked_user.query.filter_by.return_value.first.return_value = None
response = client.get('/benchmarks/foo')
assert response.status_code == 403 | 5,328,381 |
def elastic_transform(
image,
alpha,
sigma,
alpha_affine,
interpolation=cv2.INTER_LINEAR,
border_mode=cv2.BORDER_REFLECT_101,
random_state=None,
approximate=False,
):
"""Elastic deformation of images as described in [Simard2003]_ (with modifications).
Based on https://gist.github... | 5,328,382 |
def crystal_atnum(list_AtomicName, unique_AtomicName, unique_Zatom,list_fraction, f0coeffs):
"""
To get the atom and fractional factor in diffierent sites
list_AtomicName: list of all atoms in the crystal
unique_AtomicName: list of unique atomicname in the list
unique_Zatom: list of unique atom... | 5,328,383 |
def graph_fft_signals(x: np.ndarray, y1: np.ndarray, y2: np.ndarray,
y3: np.ndarray, frequencies: np.ndarray,
fft: np.ndarray) -> None:
"""Displays 4 graphs: two containing signals, one containing the sum of
the previous signals, and another containing the fft of the ... | 5,328,384 |
def integrate(name, var):
""" given filename and var, generate profile """
d = vtk.vtkExodusIIReader()
d.SetFileName(name)
d.UpdateInformation()
d.SetPointResultArrayStatus(var,1)
d.Update()
blocks = d.GetOutput().GetNumberOfBlocks()
data = d.GetOutput()
# range... | 5,328,385 |
def rename_files_in_dir(path, config, only_print=False):
"""
please run in python3 if your os is windows, cause os.walk has a encoding bug
:param only_print:
:type path: str
:type config: dict
:param path:
:param config:
:return:
"""
refuse_suffix = config.get('refuse_suffix', [... | 5,328,386 |
def mediate(timer: TimerBase, decimals: int | None) -> int:
"""If the start function doesn't have decimals defined, then use the decimals value defined when the Timer() was initiated."""
return timer.decimals if decimals is None else validate_and_normalise(decimals) | 5,328,387 |
def calculate_n_inputs(inputs, config_dict):
"""
Calculate the number of inputs for a particular model.
"""
input_size = 0
for input_name in inputs:
if input_name == 'action':
input_size += config_dict['prior_args']['n_variables']
elif input_name == 'state':
i... | 5,328,388 |
async def test_connection_pool_with_no_keepalive_connections_allowed():
"""
When 'max_keepalive_connections=0' is used, IDLE connections should not
be returned to the pool.
"""
with pytest.raises(ValueError):
AsyncConnectionPoolMixin(max_keepalive_connections=0.0) | 5,328,389 |
def clustering(
adata: ad.AnnData,
resolutions: Sequence[float],
clustering_method: str = "leiden",
cell_type_col: str = "cell_types",
batch_col: str = "batch_indices"
) -> Tuple[str, float, float]:
"""Clusters the data and calculate agreement with cell type and batch
variable.
This met... | 5,328,390 |
async def login_swagger(form_data: OAuth2PasswordRequestForm, db: AsyncIOMotorClient) -> LoginUserReplyModel:
"""
Login route, returns Bearer Token.
SWAGGER FRIENDLY.
Due to the swagger Api not letting me add otp as a required parameter
the otp needs to be added to the the end of the... | 5,328,391 |
def coords(lat: float, lon: float, alt: float = None ) -> str:
"""Turn longitude, latitude into a printable string."""
txt = "%2.4f%s" % (abs(lat), "N" if lat>0 else "S")
txt += " %2.4f%s" % (abs(lon), "E" if lon>0 else "W")
if alt:
txt += " %2.0fm" % alt
return txt | 5,328,392 |
def chromosome_to_smiles():
"""Wrapper function for simplicity."""
def sc2smi(chromosome):
"""Generate a SMILES string from a list of SMILES characters. To be customized."""
silyl = "([Si]([C])([C])([C]))"
core = chromosome[0]
phosphine_1 = (
"(P(" + chromosome[1] + ... | 5,328,393 |
def softmax_edges(graph, feat):
"""Apply batch-wise graph-level softmax over all the values of edge field
:attr:`feat` in :attr:`graph`.
Parameters
----------
graph : DGLGraph
The graph.
feat : str
The feature field.
Returns
-------
tensor
The tensor obtaine... | 5,328,394 |
def command_result_processor_parameter_required(command_line_parameter):
"""
Command result message processor if a parameter stays unsatisfied.
Parameters
----------
command_line_parameter : ``CommandLineParameter``
Respective command parameter.
Returns
-------
message ... | 5,328,395 |
def r_importer(modules, install_only=[], log=False):
"""
Import and install R packages. If the desired packages are not installed it will
automatically install them. Note that this function will act as a one time
delay in running time, if modules need to be installed. Import R packages
manually as e.g. <starg... | 5,328,396 |
def randdirichlet(a):
""" Python implementation of randdirichlet.m using randomgamma fucnction
:param a: vector of weights (shape parameters to the gamma distribution)
"""
try:
x = rand.randomgamma(a)
except ValueError:
a[a == 0] += 1e-16
x = rand.randomgamma(a)
x /= x... | 5,328,397 |
def ensure_lockfile(keep_outdated=False, pypi_mirror=None):
"""Ensures that the lockfile is up-to-date."""
if not keep_outdated:
keep_outdated = project.settings.get("keep_outdated")
# Write out the lockfile if it doesn't exist, but not if the Pipfile is being ignored
if project.lockfile_exists:... | 5,328,398 |
def home(request):
"""
This is the home page request
"""
return render(request, 'generator/home.html') | 5,328,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.