content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def jobsWorker(
jobQueue,
output,
model,
funcProgress,
controlQueue,
trayIconMessageSignal,
log=False,
):
"""
jobsWorker execute jobs on queue
Args:
jobQueue (JobQueue): Job queue has all related information for the job
funcProgress (func): function to call to re... | 5,323,400 |
def evaluate_surface(name, oname=None, mesh=False, topology=False, intersections=False, collisions=0, opts={}):
"""Evaluate properties of surface mesh"""
argv = ['evaluate-surface-mesh', name]
if oname:
argv.extend([oname, '-v'])
argv.extend(['-threads', str(threads)])
if mesh: argv.appe... | 5,323,401 |
def dumpDictToPath(path, obj):
"""
Dump a DotDict in to the specified path in (pretty indented) JSON format.
"""
f = open(path, 'w')
f.write(dumpDictToString(obj))
f.close() | 5,323,402 |
def uu_query_STK_STATUS_CHANGE():
"""
上市公司状态变动
获取上市公司已发行未上市、正常上市、实行ST、*ST、暂停上市、终止上市的变动情况等
:param :query(finance.STK_STATUS_CHANGE):表示从finance.STK_STATUS_CHANGE这张表中查询上市公司的状态变动信息,还可以指定所要查询的字段名,格式如下:query(库名.表名.字段名1,库名.表名.字段名2),多个字段用英文逗号进行分隔;query函数的更多用法详见:sqlalchemy.orm.query.Query对象
finance.... | 5,323,403 |
def add_custom_encoder_arguments(group):
"""Define arguments for Custom encoder."""
group.add_argument(
"--enc-block-arch",
type=eval,
action="append",
default=None,
help="Encoder architecture definition by blocks",
)
group.add_argument(
"--enc-block-repea... | 5,323,404 |
def expost_te(returns, bmk_returns, periods):
"""
Calculate the EX-POST Tracking Error. Returns a Dataframe of rolling Ex-Post Tracking Error Annualized
"""
temp = pd.concat([pd.DataFrame(returns) - pd.DataFrame(bmk_returns)], axis=1)
temp = temp.dropna()
temp.columns = ["returns", "bmk_re... | 5,323,405 |
def cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H'):
"""
Cruise control with PI controller and hill disturbance.
This function returns various system function configurations
for a the cruise control Case Study example found in
the supplementary article. The plant model is obtained by the
li... | 5,323,406 |
def load_feature_toggles(request, context):
"""Load feature toggles.
Load all feature toggle values from the database.
"""
LOGGER.info('Load feature toggles request')
feature_toggles = core.load()
response = {'feature_toggles': feature_toggles}
LOGGER.debug('Load feature toggles response: ... | 5,323,407 |
def place(args, env, cwd):
"""Command to place and route a SOC for a board."""
soc = get_soc_name(args.soc)
board = get_board_name(args.board)
board_data = open_board(args.board)
env['SOC'] = soc
env['BOARD'] = board
env['EFFORT'] = args.effort
env['STAGE'] = args.stage
if args.too... | 5,323,408 |
def svd(a, compute_uv=True, sort=True, copy=True, eps=1e-9):
""" Performs singular value decomposition of a ds-array via the one-sided
block Jacobi algorithm described in Arbenz and Slapnicar [1]_ and
Dongarra et al. [2]_.
Singular value decomposition is a factorization of the form A = USV',
where ... | 5,323,409 |
def renameID(idFrom, idTo, identifiedElements, referringNodes):
"""
Changes the ID name from idFrom to idTo, on the declaring element
as well as all nodes in referringNodes.
Updates identifiedElements.
Returns the number of bytes saved by this replacement.
"""
num = 0
definingNode = ... | 5,323,410 |
def rotate_hue(im, x):
"""
Adjust the hue of *im* by *x*, where *x* is a value between 0.0 to 1.0.
Full red to full green is 1/3, red to blue is 2/3.
"""
assert im.mode == 'RGB'
ima = np.asarray(im) / 255
ima_hsv = colors.rgb_to_hsv(ima)
ima_hsv[...,0] = (ima_hsv[...,0] + x) % 1
ima... | 5,323,411 |
def get_parser() -> argparse.ArgumentParser:
"""
Create a command line parser.
Returns:
argparse.ArgumentParser: Created parser
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-l",
"--list",
required=False,
action="store_true",
help="... | 5,323,412 |
def Pa_2_psig(value):
"""
converts pressure in abs Pa (Pascal) to gauged psig (pound-force per square inch)
:param value: pressure value in Pa
:return: pressure value in psi
"""
return value / const.psi - 14.7 | 5,323,413 |
def test_simple_node_id_generation():
"""
Test simple node automatic ID generation.
"""
cluster = Cluster((SimpleNode(),))
cluster[0] = 0
cluster['hello'] = 'world' | 5,323,414 |
def kwargs2attr_deep(obj, kwargs):
"""Deep copy attributes values based on keyword arguments. Assign only if the attribute already exists in obj."""
if kwargs is None:
return
if not isinstance(kwargs, dict):
raise TypeError("Attempted to set arguments not using a dictionary.")
attr = o... | 5,323,415 |
def get_vedges_details(customer, api_response_data, query_condition):
"""
Parses JSON response and builds CSV file with vEdge details
All other devices, such as vBond, vSmart are excluded
:param query_condition: filter
:param customer: string to build correct directory to store CSV files
:param... | 5,323,416 |
def print_unique_issues_summary(issues_directory, platform, arch, build_config):
"""Merge issues-summary-*-PartitionN.txt files from each partitions
and print a summary to markdown
Args:
issues_directory (string): Issues directory
Returns:
Number of issues found
"""
issues_by_a... | 5,323,417 |
def test_merge_security_groups(mock_properties, mock_details):
"""Make sure default Security Groups are added to the ingress rules."""
app_ingress = {
'test_app': [
{
'start_port': 30,
'end_port': 30,
},
],
}
mock_properties.return... | 5,323,418 |
def quota():
"""
This script is called every time nfs-provisioner projects file is changed.
According to the change in the projects file, adds into /deletes from xfs quota.
"""
xfs_dir = '/xfs'
nfs_dir = f'{xfs_dir}/nfs'
# projects file from xfs-nfs-provisioner
nfs_projects_path = f'{nf... | 5,323,419 |
def create_tables(host, user, password, database):
"""
create a table
"""
print("Creating tables in test database")
engine = create_engine(
"postgres://{user}:{pwd}@{host}/{db}".format(
user=user, host=host, pwd=password, db=database
)
)
create_all(engine)
ve... | 5,323,420 |
def correct_errors(page, labels, bboxes, model):
"""Error correction.
parameters:
page - 2d array, each row is a feature vector to be classified
labels - the output classification label for each feature vector
bboxes - 2d array, each row gives the 4 bounding box coords of the character
model -... | 5,323,421 |
def sign(x):
"""Returns sign of x"""
if x==0:
return 0
return x/abs(x) | 5,323,422 |
def get_sources(category):
"""
function that gets response from the api call
"""
sources_url = base_url.format(category,api_key)
with urllib.request.urlopen(sources_url) as url:
sources_data = url.read()
sources_response = json.loads(sources_data)
sources_results = None... | 5,323,423 |
def split(geometry, (dx_max, dy_max), (rx, ry), (bx0, by0, bx1, by1)):
""" Cut geometry to smaller blocks. """
#pylint: disable=invalid-name
def _get_sizes(v0, v1, dv_max, rv, bv0, bv1):
if rv > 0:
dv_max *= rv
if rv > 0:
vr0 = vr1 = 0.5*(rv*ceil((v1-v0)/rv) - (v1-v0... | 5,323,424 |
async def handleJoin(cls:"Client", payload:str) -> bool:
"""
handles all JOIN events
may calls the following events for custom code:
- onMemberJoin(Channel, User)
"""
JoinUser = User(payload)
# ignore self, but use it to update the clients channels
if JoinUser.name.lower() == cls.nickname.lower():
FreshCha... | 5,323,425 |
def execute_web_hook(hook_url: Optional[str], status_id: int) -> bool:
"""execute_web_hook
Discordに対してBOT用のデータを送る
Args:
hook_url (Optional[str]): webhook url
status_id (int): tweet id
Returns:
bool: hookに成功した場合はTrue失敗した場合はFalseを返す
"""
url = 'https://twitter.com/granb... | 5,323,426 |
def handler_callback(callback, user):
"""
A method for handling callbacks
:param user: user object
:param callback: callback from telebot.types.CallbackQuery
:return: datetime.date object if some date was picked else None
"""
if callback == "prev" and user.curr_date.replace(day=1) >= user.... | 5,323,427 |
def _check_region_shape(region, shape):
"""
Check shape lenght and if the region matches it
"""
if len(shape) not in (2, 3):
raise ValueError(
"Invalid shape '{}'. ".format(shape) + "Shape must have 2 or 3 elements."
)
if len(shape) != len(region) // 2:
raise Valu... | 5,323,428 |
def test_J7(i):
""" Test a property of J from result 1 of the paper """
d = SD([1 / i] * i)
assert J(d) < H(d) | 5,323,429 |
def get_weight(df):
"""This will give weights to encounter imbalanced class problem"""
# Getting number of data points for each class
weight_count = df["sentiment"].value_counts(sort=False)
# print(weight_count)
# Weight of class c is the size of largest class divided by the size of class c.
w... | 5,323,430 |
def test_UNTLElement_add_form_qualifier_only():
"""Test form is created with qualifier but not content passed."""
element = us.UNTLElement()
element.tag = 'creator'
element.add_form(qualifier='test_qualifier')
assert isinstance(element.form, FormElement)
assert element.form.untl_object == elemen... | 5,323,431 |
def main():
"""Perform steering wheel calibration.
Ask user to turn the steering wheel to the extremes and finds the max
"""
import argparse
if (sys.version_info < (3, 0)):
print("Please use python version 3")
return
parser = argparse.ArgumentParser(add_help=True,
... | 5,323,432 |
def bestellungen(request):
""" Übersicht der abgeschlossenen Bestellungen
Es werden die Käufe vom Nutzer gesucht und in einem dict nach
Kategorien geordnet ausgegeben, folgende Kategorien:
- kommende Veranstaltungen
- elektronische Medien
- unkategorisiert
(später noch bestellte Bücher)
... | 5,323,433 |
def test_that_bad_code_in_task_runner_is_caught():
"""
Test that an error in the actual TaskRunner code itself (not the execution of user code)
is caught
"""
class BadTaskRunner(TaskRunner):
def get_task_run_state(self, *args, **kwargs):
raise RuntimeError("I represent bad code ... | 5,323,434 |
def add_inflected_terms_to_db(inflections_path: str,
db: Connection,
limit: Optional[int] = None) -> None:
"""Add output from the morphological generator to `idx`."""
fieldnames = [
'rowid', 'formi', 'BT', 'title', 'stem', 'form', 'form_parts',... | 5,323,435 |
def comp_indexes_fcn(site, comp_name, n_inds):
"""
Returns an array of indexes to associate with new emissions
:param site: a GeneralClassesFunctions.simulation_classes.Site object
:param comp_name: name of a component contained in Site.comp_dict
:param n_inds: Integer of indexes to generate
:re... | 5,323,436 |
def update_cache_and_get_specs():
"""
Get all concrete specs for build caches available on configured mirrors.
Initialization of internal cache data structures is done as lazily as
possible, so this method will also attempt to initialize and update the
local index cache (essentially a no-op if it ha... | 5,323,437 |
def sodium_unpad(s, blocksize):
"""
Remove ISO/IEC 7816-4 padding from the input byte array ``s``
:param s: input bytes string
:type s: bytes
:param blocksize:
:type blocksize: int
:return: unpadded string
:rtype: bytes
"""
ensure(isinstance(s, bytes), raising=exc.TypeError)
... | 5,323,438 |
def find_lag(t,x,t_ref,x_ref):
"""
Report lag in time between x(t) and a reference x_ref(t_ref).
If times are already numeric, they are left as is and the lag is
reported in the same units.
If times are not numeric, they are converted to date nums via
utils.to_dnum. If they are np.datetime64,... | 5,323,439 |
def Main():
"""Entry point.
"""
dtEndpoints= ReadEndpoints("FindDirectory-endpoints.txt")
ReportEndpoints(dtEndpoints) | 5,323,440 |
def classname(obj: _rinterface_capi.SupportsSEXP) -> str:
"""Name of the R class."""
res = dollar(obj, 'classname')
if res is not rpy2.robjects.NULL:
assert len(res) == 1
res = res[0]
return res | 5,323,441 |
def get_ofp_cls(ofp_version, name):
"""get class for name of a given OF version"""
(_consts_mod, parser_mod) = get_ofp_module(ofp_version)
for i in inspect.getmembers(parser_mod, inspect.isclass):
if i[0] == name:
return i[1]
return None | 5,323,442 |
def split_file(rows_per_file: int, inpath: str, dir):
"""Split file from inpath into multiple named tempfiles with delete set to
false, each containing rows_per_file number of rows.
All split files are placed in dir. The intent is to use this function with dir
as a TemporaryDirectory.
Return p... | 5,323,443 |
def test_valid_method(test_endpoint):
"""Test that ValueError is raised when an invalid method is set"""
with pytest.raises(ValueError):
test_endpoint.method = False | 5,323,444 |
def update_torus(i, t, x, v, framestep, pos_points, neg_points):
""" Update particles positions on torus plot """
# Update positions on torus
pos_vel = x[i * framestep, v[i * framestep,] >= 0]
neg_vel = x[i * framestep, v[i * framestep,] < 0]
pos_points.set_data(np.sin(pos_vel), np.cos(pos_vel))
... | 5,323,445 |
def HHCF(r, sigma, xi , alpha):
"""
Model for height-height correlation function. This model is suitable for fitting when data is present for both above and below the correlation length.
Inputs:
r: Numpy array. This contains the distance data which would be used for the x coordinate on a HHCF plot.... | 5,323,446 |
def process_reaction_with_product_maps_atoms(
rxn, skip_if_not_in_precursors=False
):
"""
Remove atom-mapping, move reagents to reactants and canonicalize reaction.
If fragment group information is given, keep the groups together using
the character defined with fragment_bond.
Args:
rx... | 5,323,447 |
def echo_handler(completed_proc):
"""Immediately return ``completed_proc``."""
return completed_proc | 5,323,448 |
def bestNeverQFWin(matches, rankings,activeplayers):
"""finds players who never won a QF (+ streaks)"""
#matches = matches[matches['tourney_date'] > datetime.date(2012,12,29)]
qfmatches = matches[(matches['round']=='QF')]
qfmatches = qfmatches.sort_values(by='tourney_date')
qfgmatches = qfmatches.g... | 5,323,449 |
def render_path(
render_poses, hwf, K, chunk, render_kwargs, gt_imgs=None, savedir=None, render_factor=0,
fixed_viewdir=None):
"""
Render a batch of full images.
fixed_viewdir:
If a 4 x 4 matrix, use this view direction for all frames.
If `None`, use actual view direction (camera po... | 5,323,450 |
def _check_pr(pr, cfg):
"""make sure a PR is ok to automerge"""
if any(label.name == "automerge" for label in pr.get_labels()):
return True, None
# only allowed users
if pr.user.login not in ALLOWED_USERS:
return False, "user %s cannot automerge" % pr.user.login
# only if [bot-auto... | 5,323,451 |
def test_mixed_series(mixed_gdf, single_rectangle_gdf):
"""Test clipping a mixed GeoSeries"""
clipped = clip(mixed_gdf.geometry, single_rectangle_gdf)
assert (
clipped.geom_type[0] == "Point"
and clipped.geom_type[1] == "Polygon"
and clipped.geom_type[2] == "LineString"
) | 5,323,452 |
def iterate_tsv_rows(file_path):
"""
Iterate over every row in a TSV file and import each as a reaction document.
For each reaction, we create:
- A reaction
- A set of edges from the reaction to all constituent compounds
- A set of gene complexes based on the 'gpr' boolean expression of required... | 5,323,453 |
def create_test_data(length):
""" helper function to create an instance data set of the given length """
position = om.MVectorArray()
scale = om.MVectorArray()
rotation = om.MVectorArray()
instance_id = om.MIntArray()
visibility = om.MIntArray()
normal = om.MVectorArray()
tangent = om.M... | 5,323,454 |
def read_joblib(
bucket: str,
key: str,
) -> Any:
"""Read a joblib model from a given s3 bucket and key.
Parameters
----------
bucket : str
The S3 bucket to load from.
key : str
The object key within the s3 bucket.
Returns
-------
np.array
A joblib model... | 5,323,455 |
def cleandataseth5(*args, **kwargs) -> None:
"""
Read the the single file (with whole dataset), remove NaN and save 1 file per class.
"""
well_vars = [
"P-PDG",
"P-TPT",
"T-TPT",
"P-MON-CKP",
"T-JUS-CKP",
"P-JUS-CKGL",
"T-JUS-CKGL",
"QGL",
... | 5,323,456 |
def is_categorical_dtype(arr_or_dtype: pandas.core.dtypes.dtypes.DatetimeTZDtype):
"""
usage.dask: 2
"""
... | 5,323,457 |
def random_choice(choices):
"""returns a random choice
from a list of (choice, probability)"""
# sort by probability
choices = sorted(choices, key=lambda x:x[1])
roll = random.random()
acc_prob = 0
for choice, prob in choices:
acc_prob += prob
if roll <= acc_prob:
... | 5,323,458 |
def completion_add(toot):
"""Add usernames (original author, mentions, booster) co completion_list"""
if toot['reblog']:
username = '@' + toot['reblog']['account']['acct']
if username not in completion_list:
bisect.insort(completion_list, username)
username = '@' + toot['account'... | 5,323,459 |
def set_rdmol_positions_(mol, pos):
"""
Args:
rdkit_mol: An `rdkit.Chem.rdchem.Mol` object.
pos: (N_atoms, 3)
"""
assert mol.GetNumAtoms() == pos.shape[0]
conf = Chem.Conformer(mol.GetNumAtoms())
for i in range(pos.shape[0]):
conf.SetAtomPosition(i, pos[i].tolist())
... | 5,323,460 |
def _posprocess_padding(config: LayerConfig, conv_kwargs: Dict, ops: List[nn.Module]) -> None:
"""
Note:
conv_kwargs will be modified in-place. Make a copy before!
"""
padding_same = False
padding = conv_kwargs.get('padding')
if padding is not None and padding == 'same':
padding_... | 5,323,461 |
def test_transform_app_to_icrs_objs(astrometry_args):
"""
Test that we recover identical values when using Time/EarthLocation objects instead
of floats for time_array and telescope_loc, respectively for transform_app_to_icrs.
"""
telescope_loc = EarthLocation.from_geodetic(
astrometry_args["... | 5,323,462 |
def convert_label_to_color(label, color_map):
"""Convert integer label to RGB image.
"""
n, h, w = label.shape
rgb = torch.index_select(color_map, 0, label.view(-1)).view(n, h, w, 3)
rgb = rgb.permute(0, 3, 1, 2)
return rgb | 5,323,463 |
def is_collection(name):
"""compare with https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/user"""
return name in [
'assignedLicenses', 'assignedPlans', 'businessPhones', 'imAddresses',
'interests', 'provisionedPlans', 'proxyAddresses', 'responsibilities',
's... | 5,323,464 |
def unpack_list(string_: str):
"""
Recursively strip, split, translate and unpack provided string to the list.
:param string_: str -- string to be unpacked into the list
:return: list
"""
list_ = []
string2 = string_.replace("[", "", 1).strip("]")
elements = string2.split("], ") if "[" ... | 5,323,465 |
def login_access_token(
response: Response,
db: Session = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.user.authenticate(db, email=form_data.username, password=form... | 5,323,466 |
def bubble_sort_pro(lis):
"""
冒泡排序改进版
改进思路:
1) 有可能在进行到某一次的时候,整个列表已经排好序了,这个时候就不需要再进行后边的排序了
2) 另一个角度,假如索引为 0的值是整个列表中最大的值,那么它只需要交换 len(lis) - 1 就能交换到 索引最大的位置,
每一趟,其实都是各个值在向上交换几个位置,最多 len(lis) - 1 次就能交换完
"""
for i in range(len(lis) - 1): # 第 i ... | 5,323,467 |
def download_to_file(url, filename, chunk_size=10 * 1024):
"""Downloads a file via HTTP(S) directly to the filesystem."""
with closing(requests.get(url, stream=True, verify=True)) as req, \
open(filename, 'wb') as outfile:
for block in req.iter_content(chunk_size=chunk_size):
ou... | 5,323,468 |
def in_nested_list(my_list, item):
"""
Determines if an item is in my_list, even if nested in a lower-level list.
"""
if item in my_list:
return True
else:
return any(in_nested_list(sublist, item) for sublist in my_list if
isinstance(sublist, list)) | 5,323,469 |
def from_numpy_array(nparr, framerate):
"""
Returns an AudioSegment created from the given numpy array.
The numpy array must have shape = (num_samples, num_channels).
:param nparr: The numpy array to create an AudioSegment from.
:param framerate: The sample rate (Hz) of the segment to generate.
... | 5,323,470 |
def get_exc_info(exception):
"""Get an exc_info tuple based on an exception instance."""
try:
raise exception
except:
return sys.exc_info() | 5,323,471 |
def visits_stmt(node_cls):
"""Decorator that registers a function as a visitor for ``node_cls``.
:param node_cls: subclass of :class:`jinja2.nodes.Stmt`
"""
def decorator(func):
stmt_visitors[node_cls] = func
@functools.wraps(func)
def wrapped_func(node, macroses=None, config=de... | 5,323,472 |
def is_prebuffer() -> bool:
"""
Return whether audio is in pre-buffer (threadsafe).
Returns
-------
is_prebuffer : bool
Whether audio is in pre-buffer.
"""
is_prebuffer = bool(RPR.Audio_IsPreBuffer()) # type:ignore
return is_prebuffer | 5,323,473 |
def ad_reset_user_pwd_by_mail(user_mail_addr, new_password):
"""
通过mail重置某个用户的密码
:param user_mail_addr:
:return:
"""
conn = __ad_connect()
user_dn = ad_get_user_dn_by_mail(user_mail_addr)
result = conn.extend.microsoft.modify_password(user="%s" % user_dn, new_password="%s" % new_password... | 5,323,474 |
def main():
""" Test example of classifying k_nearest """
data = IrisDataset()
X, y = data.get_data()
classifier = KnearestClassifier(X=X, C=y, K=3)
unlabeled_data = data.synthetic_data(n_samples=5)
_, labels = classifier.run(unlabeled_data, 5)
print(f"Predicted labels: {labels} with k=5 nei... | 5,323,475 |
def get_data(name: str, override: bool=True) -> str:
"""
Obtiene el contenido del archivo SVG que coincida con el nombre.
Si override es False, se lanzará una excepción en caso de no encontrar el
archivo con el nombre indicado.
"""
if not ".svg" in name:
name += ".svg"
overri... | 5,323,476 |
def test_format():
"""
:description: Test that the format is valid
"""
FORMAT = 'b'
parameters.format = FORMAT
assert_equal("--format " + FORMAT, parameters.format)
return | 5,323,477 |
def array_read(array, i):
"""
This OP is used to read data at the specified position from the input array
:ref:`api_fluid_LoDTensorArray` . ``array`` is the input array and ``i``
is the specified read position. This OP is often used together with
:ref:`api_fluid_layers_array_write` OP.
Case 1... | 5,323,478 |
def main():
"""Main Function"""
args = getOptions()
pattern = re.compile(r'(?<=\').*(?=\')')
identifiers = [pattern.search(i).group() for i in args.collection_identifiers.split(",")]
filenames = [i.strip() for i in args.collection_filenames.split(",")]
input_dict = dict(zip(identifiers, filename... | 5,323,479 |
def get_user_posts (user_id, count, tags = None, expiry = None):
"""Get a user's Instagram posts.
Filter by tags and and max $count items.
Returns:
Response: the JSON items representing instagram posts.
"""
# create the cache key
cache_key = filecache.create_key('{user_id}{count}{tags... | 5,323,480 |
def session_folder():
"""
Generates and returns the file path for the session folder.
Args:
None
Returns:
The file path for the session folder.
"""
return os.path.join(constants.UPLOAD_FOLDER, session['id']) | 5,323,481 |
def list_active_containers():
"""Return python list of all containers in state table
list of tuples
"""
containers = []
state_info = ContainerState.query.all()
for state in state_info:
containers.append([state.c_id, state.name])
return containers | 5,323,482 |
def aeolus_prod_optimize_delete(prod_id, watch_log):
"""
generate an optimized (netCDF) file of the aeolus product
"""
# print("I'm in "+sys._getframe().f_code.co_name, prod_id)
# print("I'm in "+sys._getframe().f_code.co_name, prod_id, file=watch_log)
try:
execute_from_command_line... | 5,323,483 |
def resetVISA(line):
"""Reset VISA connection.
Close instruments before running this function"""
instruments.resetVISA() | 5,323,484 |
def slackmojify(image_path, save_path="new_image"):
"""
image_path: the path to the image that we want to compress
this function takes the image and compresses it to a size that
that is small enough to be uploaded as a custom emoji to Slack
"""
if os.path.isfile(image_path):
compressed =... | 5,323,485 |
def filter_imports(language: Language,
t: pydsdl.CompositeType,
sort: bool = True) -> typing.List[str]:
"""
Returns a list of all modules that must be imported to use a given type.
:param pydsdl.CompositeType t: The type to scan for dependencies.
:param bool sort: ... | 5,323,486 |
def test_create_fields_list(fields, result):
"""
Given
fields list parameter, expected result
When
User enters filter_field param
Then
Validate right result returned
"""
assert result == create_fields_list(fields) | 5,323,487 |
def compute_ramlak_filter(dwidth_padded, dtype=np.float32):
"""
Compute the Ramachandran-Lakshminarayanan (Ram-Lak) filter, used in
filtered backprojection.
:param dwidth_padded: width of the 2D sinogram after padding
:param dtype: data type
"""
L = dwidth_padded
h = np.zeros(L, dtype=d... | 5,323,488 |
def _interior_pixel_generator(X, tileDim, batchSize, mask=None):
"""An iterator over pixel indices that lie in the interior of an image.
Warning: this is fairly memory intensive (pre-computes the entire
list of indices).
Note: could potentially speed up the process of extracting subtiles by
creat... | 5,323,489 |
def t_seg(p1, p2, t, align=0):
""" trim segment
Args:
p1, p2: point(x, y)
t: scaling factor (1 - trimed segment / original segment)
align: 1: trim p2, 2: trim p1, 0: both side
Return:
trimmed segment(p1, p2)
"""
v = vector(p1, p2)
result = {
1: lambda a, b: (a, tr... | 5,323,490 |
def isomorphic(tt,ttt):
"""True if isomorphic."""
(a,b) = isomorphism(tt,ttt)
return (len(b) > 0) | 5,323,491 |
def test_review_submission_list_query_review_status(admin_drf_client, review_status):
"""
The review submission list view should return a list of submissions filtered by review status
"""
# Create a few submissions that should be filtered out due to submission status or application state
Application... | 5,323,492 |
async def test_wrong_pin_error(hass):
"""Test that incorrect pin throws an error."""
with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "user"}
)
assert result["type"] == data_entry_flo... | 5,323,493 |
def make_connector(name=None):
"""A connector between constraints"""
informant = None
constraints = []
def set_value(source, value):
nonlocal informant
val = connector["val"]
if val is None:
informant, connector["val"] = source, value
if name is not None:... | 5,323,494 |
def read_shp(path):
"""Generates a networkx.DiGraph from shapefiles. Point geometries are
translated into nodes, lines into edges. Coordinate tuples are used as
keys. Attributes are preserved, line geometries are simplified into start
and end coordinates. Accepts a single shapefile or directory of many
... | 5,323,495 |
def test_decks(fabdb):
""" Test decks function"""
deck = fabdb.decks(slug='eLxddlzb')
assert deck['name'] == 'Official Rhinar Hero Deck'
assert deck['format'] == 'constructed'
assert len(deck['cards']) > 0 | 5,323,496 |
def network_alignment(network_a, network_b):
"""combines two networks into a new network
| Arguments:
| :-
| network_a (networkx object): biosynthetic network from construct_network
| network_b (networkx object): biosynthetic network from construct_network\n
| Returns:
| :-
| Returns combined network as... | 5,323,497 |
def batch_render(voxel_dir, voxel_processor=None):
"""Render a bunch of voxel tensors stored as npy files in the voxel_dir.
Args:
voxel_dir: A directory containing voxel tensors stored in npy files.
voxel_processor: Function that processes the voxels before rendering
"""
npy_files = glo... | 5,323,498 |
def grab_cpu_scalar(v, nd):
"""
Get a scalar variable value from the tree at `v`.
This function will dig through transfers and dimshuffles to get
the constant value. If no such constant is found, it returns None.
Parameters
----------
v
Aesara variable to extract the constant value... | 5,323,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.