content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def r_to_oxd(
r: Union[np.ndarray, xr.DataArray, float],
r_min: float = 0.852,
r_max: float = 6.65,
instrument_factor: float = 0.171,
):
"""
Convert ratios to OxD
Parameters
----------
r
r_min
r_max
instrument_factor
Returns
-------
"""
return (r - r_mi... | 58,300 |
def box_utils_expand_boxes(boxes, scale):
"""Expand an array of boxes by a given scale."""
w_half = (boxes[:, 2] - boxes[:, 0]) * .5
h_half = (boxes[:, 3] - boxes[:, 1]) * .5
x_c = (boxes[:, 2] + boxes[:, 0]) * .5
y_c = (boxes[:, 3] + boxes[:, 1]) * .5
w_half *= scale
h_half *= scale
b... | 58,301 |
def merge_mmio_overhead_elimination_maps(elim_maps):
""" Merge different MMIO overhead elimination maps.
This adds values together and re-calculates percentages.
"""
if not elim_maps:
return {}
result = {}
# 1. Totals
total_bytes_raw = sum(m['overall']['bytes_raw'] for m in elim_ma... | 58,302 |
def get_most_common_submitters(df):
"""Prints the 20 most frequent submitters.
Parameters
----------
df : pandas.DataFrame
The submissions DataFrame.
"""
# Optional: Remove the [deleted] user.
df.drop(df[df["author"] == "[deleted]"].index, inplace=True)
df = df["author"].valu... | 58,303 |
def union_by_category(category, filter_ids, user=None):
"""TODO (ASUC) Write docstring."""
playlists = Playlist.objects.filter(id__in=filter_ids, category=category)
if category == "custom":
playlists = playlists.filter(user=user)
intersected = [playlist.courses.all() for playlist in playlists]
... | 58,304 |
def get_regions():
"""Get list of all AWS regions"""
client = boto3.client("ec2")
response = client.describe_regions()
regions = [region["RegionName"] for region in response["Regions"]]
return regions | 58,305 |
def remove_ignorable_whitespace(node):
"""Remove insignificant whitespace from XML nodes
It should only remove whitespace in between elements and sub elements.
This should be safe for Jenkins due to how it's XML serialization works
but may not be valid for other XML documents. So use this method with
... | 58,306 |
def GetBuildDir():
"""Returns the absolute path of the directory where the test binaries are."""
return os.path.abspath(GetFlag('build_dir')) | 58,307 |
def prepare_labels(cells: list, root_labels: str, root_images: str) -> np.ndarray:
"""
Convinience for label load. Takes a list of cells (the naming is used to
refer to the fact that we often use minipics of cells from tables - they
need not be cells. Just any list of strings such that the strings are
... | 58,308 |
def which(exe):
"""
Decorator wrapper for salt.utils.path.which
"""
def wrapper(function):
@functools.wraps(function)
def wrapped(*args, **kwargs):
if salt.utils.path.which(exe) is None:
raise CommandNotFoundError(
"The '{}' binary was not... | 58,309 |
def st_grep_on_off(what, to_find_on=None, to_find_off=None, n=1, rev=False, verbose=False):
"""
filter a list of strings for groups delimited by "on" /"off"
input: list of strings
output: list of strings
use n to select how many groups to return
warning: does not accept word_only yet!
"""
line... | 58,310 |
def test_multiple_modules_in_batch(salt_cli, salt_minion, salt_sub_minion, run_timeout):
"""
Ensure that running multiple modules at the same time works in batch.
See issue #60361
"""
cmd = salt_cli.run(
"test.ping,test.retcode",
",23",
"-b 1",
minion_tgt="*minion*",... | 58,311 |
def print_cards_from_board(board_id, client):
"""
Access board with ID board_id in the client instance
and print all non-archived lists with their non-archived cards
"""
all_boards = client.list_boards()
my_board = all_boards[board_id]
all_lists_on_board = my_board.list_lists(... | 58,312 |
def _log_summary(manifest_is_valid, manifest_path, lines_validated):
"""
Logs a short summary of validation that potentially includes number of
lines validated and whether errors were found.
Args:
manifest_is_valid(bool): whether manifest is valid
manifest_path(str): the path to the man... | 58,313 |
def tests():
""" Make these Unittests for each function. """
tests_list = [
'assertNotEqual',
'assertEqual'
]
return tests_list | 58,314 |
def view(request):
"""
A minimal view for use in testing.
"""
return HttpResponse("Content.") | 58,315 |
def prodtab_321():
"""
produces angular distance from [3,2,2] plane with other planes up to (321) type
"""
listangles_321 = [anglebetween([3, 2, 1], elemref) for elemref in LISTNEIGHBORS_321]
return np.array(listangles_321) | 58,316 |
def gradient_step(v: Vector, gradient: Vector, step_size: float) -> Vector:
"""Moves `step_size` in the `gradient` direction from `v`"""
assert len(v) == len(gradient)
step = scalar_multiply(step_size, gradient)
return add(v, step) | 58,317 |
def test_list_name_max_length_1_nistxml_sv_iv_list_name_max_length_2_1(mode, save_output, output_format):
"""
Type list/Name is restricted by facet maxLength with value 6.
"""
assert_bindings(
schema="nistData/list/Name/Schema+Instance/NISTSchema-SV-IV-list-Name-maxLength-2.xsd",
instanc... | 58,318 |
def _inactiveplayers():
"""
Scrape DB to find players who are not on active rosters.
"""
rosters = _activerosters()
dbrosters = _eidset() # players not in rosters scrape but in db.
notactive = dbrosters.difference(rosters)
return notactive | 58,319 |
def extract(video, landmark_model, embedding_model, tracking, landmark_output, embedding_output):
"""Facial features detection"""
faces_folder = "./Video2Faces/"
# face generator
frame_width, frame_height = video.frame_size
faceGenerator = getFaceGenerator(tracking,
... | 58,320 |
def logoutHttpMethods(request,*args,**kwargs):
"""
注销
:param request:
:param args:
:param kwargs:
:return:
"""
logout(request)
return response_success() | 58,321 |
def isPostCSP(t, switch=961986575.):
"""
Given a GALEX time stamp, return TRUE if it corresponds to a "post-CSP"
eclipse. The actual CSP was on eclipse 37423, but the clock change
(which matters more for calibration purposes) occured on 38268
(t~=961986575.)
:param t: The time stamp... | 58,322 |
def build_wheels(dist_dir, pip_wheel_args):
"""build wheels using pip wheel command line tool"""
args = ["pip", "wheel", "--wheel-dir", dist_dir] + pip_wheel_args
spawn(args)
return dist_dir | 58,323 |
def taoyuan_water_supply_network_1():
"""
Real Name: TaoYuan Water Supply Network 1
Original Eqn: 0
Units: m3
Limits: (None, None)
Type: constant
primary design assumes zero in this model, which means does not consider
the impact of this pipeline.
"""
return 0 | 58,324 |
def convert_trsp_index(geneDictNonCoding, df, TR_index_dict):
"""
take input geneDict and output a single transcript for each gene
use transcript slices defined in TR_index_dict
for noncoding genes, take the longest transcripts
There are ~7 snoRNAs that have multiple noncoding transcripts, but the longest of t... | 58,325 |
def menunode_fieldfill(caller, raw_string, **kwargs):
"""
This is an EvMenu node, which calls itself over and over in order to
allow a player to enter values into a fillable form. When the form is
submitted, the form data is passed to a callback as a dictionary.
"""
# Retrieve menu info - taken... | 58,326 |
def scaleBenchmarks(runLength, benchmark='design'):
"""
Set the design and stretch values of the number of visits, area of the footprint,
seeing values, FWHMeff values, skybrightness, and single visit depth (based on SRD values).
Scales number of visits for the length of the run, relative to 10 years.
... | 58,327 |
def serialize_for_api(data):
"""Transform complex types that we use into simple ones recursively.
Note: recursion isn't followed when we know that transformed types aren't
supposed to contain any more complex types.
TODO: this is rather ugly, would look better if views/models defined
transformation... | 58,328 |
def patch_validate_gpg_sig(return_value):
"""
Mocks the InsightsUploadConf.validate_gpg_sig method so it returns the given validation result.
"""
def decorator(old_function):
patcher = patch("insights.client.collection_rules.InsightsUploadConf.validate_gpg_sig",
return_va... | 58,329 |
def _ncac_to_stubs(ncac):
"""
Vector const & center,
Vector const & a,
Vector const & b,
Vector const & c
)
{
Vector e1( a - b);
e1.normalize();
Vector e3( cross( e1, c - b ) );
e3.normalize();
Vector e2( cross( e3,e1) );
M.col... | 58,330 |
def constructBayesNet(gameState):
"""
Question 1: Bayes net structure
Construct an empty Bayes net according to the structure given in the project
description.
There are 5 kinds of variables in this Bayes net:
- a single "x position" variable (controlling the x pos of the houses)
- a singl... | 58,331 |
def motioncheck(ref_file, end_file, out_path=None, thres=5.0):
"""
Checks motion between structural scans of the same modality.
Ideally obtained at the beginning and end of a scanning session.
Parameters
----------
ref_file: nifti file
Nifti file of first localizer acquired at the beg... | 58,332 |
def write_atmostone_constraints(m, n, fh, format='minisat+'):
"""
Write the constraints to ensure that each SSE is matched with at most
one SSE in the other tableau i.e.
\sum {i=1}_m y_{ij} <= 1
here the y_{ij} are for MiniSat+ new variables so we start them at y_r
Parameters:
m - order... | 58,333 |
def sync_case_body_cache_for_all_vols():
"""
Call sync_case_body_cache_for_vol celery task for each volume
"""
for volume_id in VolumeMetadata.objects.exclude(xml_metadata=None).values_list('pk', flat=True):
sync_case_body_cache_for_vol.delay(volume_id) | 58,334 |
def __cocoseg_to_binary(seg, height, width):
"""
COCO style segmentation to binary mask
:param seg: coco-style segmentation
:param height: image height
:param width: image width
:return: binary mask
"""
if type(seg) == list:
rle = cocomask.frPyObjects(seg, height, width)
... | 58,335 |
def get_a_uuid() -> str:
"""Gets a base 64 uuid
Returns:
The id that was generated
"""
r_uuid = str(uuid.uuid4())
return r_uuid | 58,336 |
def cookiecutter_cache_path(template):
"""
Determine the cookiecutter template cache directory given a template URL.
This will return a valid path, regardless of whether `template`
:param template: The template to use. This can be a filesystem path or
a URL.
:returns: The path that cookiec... | 58,337 |
def libtree(lib):
"""Generates a filesystem-like directory tree for the files
contained in `lib`. Filesystem nodes are (files, dirs) named
tuples in which both components are dictionaries. The first
maps filenames to Item ids. The second maps directory names to
child node tuples.
"""
root = ... | 58,338 |
def generate_comic_html(comic={}):
"""Generates part HTML for the qotd supplied"""
return """
<h3>Dilbert by Scott Adams -</h3>
<a href="{0}"><img alt="{1} - Dilbert by Scott Adams" src="{2}"></a>
""".format(comic['url'], comic['title'], comic['image']) | 58,339 |
def get_cloudify_endpoint(_ctx):
"""
ctx.endpoint collapses the functionality for local and manager
rest clients.
:param _ctx: the NodeInstanceContext
:return: endpoint object
"""
if hasattr(_ctx._endpoint, 'storage'):
return _ctx._endpoint.storage
return _ctx._endpoint | 58,340 |
def some_invoice(full_invoice_data: Dict[str, Any]) -> Invoice:
"""Returns some `Invoice`."""
return Invoice(**full_invoice_data) | 58,341 |
def order_by(field, desc=False):
"""
Allows ordering of results. You may only ever order a collection's results
once in a given request. For example::
# sort results by Instances group
client.linode.instances(order_by(Instance.group))
:param field: The field to order results by. Must ... | 58,342 |
def new_post():
"""NEW-POST page which allows users to create new blog posts."""
form = PostForm()
if form.validate_on_submit():
post = Post(
user=current_user, title=form.data.get("title"), body=form.data.get("body")
)
db.session.add(post)
db.session.commit()
... | 58,343 |
def qsin(dataset, ssb=1, **kwargs):
"""
Equivalent to :meth:`sp`, with pow = 2 (squared sine bell apodization window).
See Also
--------
em, gm, sp, sine, sinm, hamming, triang, bartlett, blackmanharris
"""
return sp(dataset, ssb=ssb, pow=2, **kwargs) | 58,344 |
def standardize_smiles(smiles):
"""Return a standardized canonical SMILES string given a SMILES string.
Note: This is a convenience function for quickly standardizing a single SMILES string. It is more efficient to use
the :class:`~molvs.standardize.Standardizer` class directly when working with many molec... | 58,345 |
def test_double_bond_stereo_branch():
"""Check that a double bond stereochemisty is well defined over
explicit hydrogens"""
parser.parse(smiles=r'C/C([H])=C([H])/C')
builder.build(atoms=parser.atoms, bonds=parser.bonds)
# Carbon dihedral should be ~π for this trans double bond, as hydrogens
# ... | 58,346 |
def geraPalavraAleatória():
"""
Função que retorna uma string a partir da
lista de palavras global
"""
global palavras
return random.choice(palavras) | 58,347 |
def test_oauth_client_request_auth(client):
"""
Ensure that OAuth client returns the appropriate auth instance for use in
requests.
"""
auth = client.request_auth
assert isinstance(auth, oauth.AccessTokenAuth)
assert client.request_auth.access_token == client.access_token | 58,348 |
def get_iphot_line(iphot, linenum, lcobject, iphotlinechars=338):
"""
This gets a random iphot line out of the file iphot.
"""
iphotf = open(iphot, 'rb')
filelinenum = iphotlinechars*linenum
if filelinenum > 0:
iphotf.seek(filelinenum - 100)
else:
iphotf.seek(filelinenum)
... | 58,349 |
def addFmt( lang, isMnthOfYear, patterns ):
"""Add 12 month formats for a specific type ('January','Feb..), for a given language.
The function must accept one parameter for the ->int or ->string conversions, just like
everywhere else in the formats map.
The patterns parameter is a list of 12 elements to... | 58,350 |
def get_sys_cards():
"""This function retrieves the system cards using nvsmi for linux and windows;
macOS support is in the works.
:return: returns a tuple containing the in `gpu_ratios_min` and actual `gpu_ratios`; the
difference being that the latter is sorted in ascending order while the other one i... | 58,351 |
def adjust_learning_rate(optimizer, epoch, args):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
epochs = 10.
lr_warmup = [i / epochs * args.lr for i in range(1, int(epochs +1))]
if epoch < epochs:
for param_group in optimizer.param_groups:
param_group[... | 58,352 |
def test_eq_placeholder():
"""_eq should assign placeholders."""
a = TCommand()
a.foo = 42
a.bar = tutils.Placeholder()
b = TCommand()
b.foo = tutils.Placeholder()
b.bar = 43
assert tutils._eq(a, b)
assert a.foo == b.foo() == 42
assert a.bar() == b.bar == 43
b.foo._obj = 44
... | 58,353 |
def get_initial_density(xgrid, ygrid):
"""
Initialize a "relatively" random density profile. Please see notebook for visualization
:param xgrid:
:param ygrid:
:return:
"""
xm, ym = np.meshgrid(xgrid, ygrid, indexing="ij")
x0 = np.random.uniform(0.5 * xgrid.min(), 0.0)
y0 = np.random... | 58,354 |
def get_vendors(ven):
"""
Input arguments for function = tuple
Coverts tuple into a list. I know, it is silly.
Input example:
get_vendors(("Neste", "Circle K"))
Output example:
['Neste', 'Circle K']
"""
vendors_list = list(ven)
return vendors_list | 58,355 |
def delete_all_closed(bot, update, session, user):
"""Delete all closed polls of the user."""
for poll in user.polls:
if poll.closed:
session.delete(poll)
return i18n.t('deleted.closed_polls', locale=user.locale) | 58,356 |
def BS_call(S, K, r, sigma, T):
"""Define a function of Black_Scholes for call option(without dividend)
"""
d1 = (np.log(S / K) + (r + 0.5 * np.power(sigma, 2))* T) / sigma / np.sqrt(T)
d2 = d1 - sigma*np.sqrt(T)
C = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
return C | 58,357 |
def printTwoPointHDU(name, ind=1):
"""
Print the content of a given HDU of a twopoint file
"""
hdr = fits.getheader(name, ind)
data = fits.getdata(name, ind)
print()
print(hdr.tostring(sep='\n'))
print(data)
return | 58,358 |
def publish_checklist(request, checklist_id):
# for "messages", refer https://stackoverflow.com/a/61603003/6543250
"""if user cannot retract upvote, then this code be uncommented
if Upvote.objects.filter(user=User.objects.filter(username=username).first(), checklist=Checklist.objects.get(id=checklist_id)):... | 58,359 |
def get_menu_items(soup):
"""Return a dictionary of key menu-items and value prices"""
items = clean(soup.find_all(class_="menu-item__name")) # has tags
prices = clean(soup.find_all(class_="menu-item__price")) # has tags
menu_items = dict(zip(items, prices)) # zip into dict with item:price
... | 58,360 |
def only_max(sim, rtrv, y, y_hat, y_lrn, y_ex, ex_counts, n_ex, n_y, sim_pars):
"""
Only the most similar exemplar has a non-zero learning rate, which is constant.
Notes
-----
This is the form of learning assumed by Ghirlanda (2015) when showing the equivalence
between exemplar and RW famil... | 58,361 |
def analyse_book(gutenberg_file):
"""Takes a text file from the Gutenberg Project, returns a list of words
in book that are not in word_list"""
result = []
word_usage.clear()
fin = open(gutenberg_file)
remove_header(fin)
for line in fin:
if '*** END OF' in line:
break
... | 58,362 |
def is_format(fid):
"""
Check the raw file for frequency base
"""
first = fid.readline()
first = first.strip().split('/')
first = first[0].split(',')
if float(first[5]) == 50.0 or float(first[5]) == 60.0:
return True
else:
return False | 58,363 |
def get_success_rate(episodes_infos, task_names, per_task=False):
"""
:param episodes_infos: nested lists (n_tasks, n_episodes, n_timestemps) of dicts
i.e. (meta_batch_size, fast_batch_size, n_timestemps)
"""
# info keys: reachDist, pickRew, epRew, goalDist, success, goal, ta... | 58,364 |
def load_raw_ens_data(data_dir):
"""
Loads raw ensemble [time, ens, station]
"""
rg = Dataset(data_dir + 'data_interpolated_00UTC.nc')
ens = rg.variables['t2m_fc'][:]
return ens | 58,365 |
def stringify_mongovalues(v: Any):
"""
Mostly the values are fine, but at least datetime needs handled.
Also need to handle datetimes embedded in dicts, so use recursion to get them.
"""
if type(v) == datetime:
return v.isoformat()
elif type(v) == dict:
return {key: stringify_mon... | 58,366 |
def pvrpm_sim(
case: SamCase,
save_results: bool = False,
save_graphs: bool = False,
progress_bar: bool = False,
debug: int = 0,
threads: int = 1,
) -> List[Components]:
"""
Run the PVRPM simulation on a specific case. Results will be saved to the folder specified in the configuration.
... | 58,367 |
def ftp_quit():
""" Quit session """
f_quit = FTP.quit()
return f_quit | 58,368 |
def test_atomic_integer_max_exclusive_4_nistxml_sv_iv_atomic_integer_max_exclusive_5_3(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet maxExclusive with value
999999999999999999.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchema... | 58,369 |
def multi_pred(exe, gw, gf, program, y_pred, seq, batch_size, \
n_his, n_pred, step_idx, dynamic_batch=True):
"""multi step prediction"""
pred_list = []
for i in gen_batch(
seq, min(batch_size, len(seq)), dynamic_batch=dynamic_batch):
# Note: use np.copy() to avoid the modificat... | 58,370 |
def max_gram_basis(op_labels, dataset, max_length=0):
"""
Compute a maximal set of basis circuits for a Gram matrix.
That is, a maximal set of strings {S_i} such that the gate
strings { S_i S_j } are all present in dataset. If max_length > 0, then
restrict len(S_i) <= max_length.
Parameters
... | 58,371 |
def routetraffic(model, model_split_tag_and_weight_dict, model_shadow_tag_list, account_id):
"""Route traffic between different versions"""
url = API_URL_BASE + '/predict-route'
headers = get_header_basic_auth()
#print(model_split_tag_and_weight_dict)
body = {
'model_split_tag_and_weight_dict': m... | 58,372 |
def create_cli() -> click.Command:
"""Build and return an instance of `queso`.
# Returns
cli (click.Command): contains both built-in and custom commands.
"""
@click.group(name="queso", cls=CustomCommandsGroup)
@version_option("-v", "-V", "--version")
def cli():
pass
for value ... | 58,373 |
def no_warnings(recwarn):
"""Fail on warning."""
yield
warnings = []
for warning in recwarn: # pragma: no cover
message = str(warning.message)
if "unclosed" in message:
# It may be worth fixing tests leaking sockets and file descriptors
continue
warn = f"... | 58,374 |
def nodeSetAdd(nset, newNSet, op):
"""
Adds newNSet to the nset using operation op.
nset : the currrent nodes set (or None).
newNSet : the new nodes set.
op : the operation type.
Returns : the combined nodes set or None if an error occurs.
"""
return xmlsecmod.nodeSetAdd(nset, ne... | 58,375 |
def to_web_mercator(x_lon, y_lat):
""" Converts lat, long into web mercator. Needed for tiletanic. """
if abs(x_lon) >= 180 and abs(y_lat) > 90:
print 'Invalid coordinate values for conversion'
return None
num = x_lon * 0.017453292519943295
x = 6378137.0 * num
a = y_lat * 0.01745329... | 58,376 |
def send_message(sender, to, subject, message_HTML, message_plain):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
... | 58,377 |
def down_sample(df, target):
"""
Fixes imbalanced dataset by down-sampling
Parameters
----------
df : pandas.DataFrame
target : name of the target column in df
Returns
-------
downsampled_df : pandas.DataFrame
"""
dfs = []
target_value_counts = df[target].value_counts()... | 58,378 |
def load_data(data_path=config.DATA_PATH, vector_length=187):
"""A function to load gender recognition dataset from `dataset` folder
After the second run, this will load from results/features.npy and results/labels.npy files
as it is much faster!"""
# make sure results folder exists
if not os.path.i... | 58,379 |
def _add_nastran_lines_to_grid(alt_grid: vtk.vtkUnstructuredGrid,
nid_map: Dict[int, int],
name: str, lines, model: BDF, nid_to_pid_map=None):
"""used to create MPC lines"""
nlines = lines.shape[0]
#nids = np.unique(lines)
#nnodes = len(nids)... | 58,380 |
def start_recording_scenario(site_name, scenario_name, pretty_print=False):
"""Flush old recording for the scenario. Start a new recording session."""
arc = ApiRecorderController(site_name, scenario_name, pretty_print)
arc.acr.flushdb()
arc.start_recording() | 58,381 |
def mean1(m):
"""mean(m) returns the mean along the first dimension of m. Note: if m is
an integer array, integer division will occur.
"""
return add.reduce(m)/len(m) | 58,382 |
def H_cond(X, Y, bins):
"""
Calculates the conditional entropy of X depending on Y.
If X and Y are already discretised, set \ref bins to the amount of bins, aka states of X and Y.
If X and Y are not discretised, \ref bins will be used, to diskretise X and Y into \ref bins states
@param X np vector ... | 58,383 |
def drop_semantic_duplicates(
student_comments: pd.Series
) -> pd.Series:
"""Remove the duplicate comments based on the comment's semantics, e.g.
"I was waiting for 1 hour." and "I waited for 1 hour." are orthographically
different, but the semantically the same, so one will be removed
... | 58,384 |
def create_summary_writer(log_dir):
"""Create a tensorboard summary writer.
Args:
log_dir: log directory.
Returns:
(SummaryWriter): a summary writer.
Example
>>> writer = create_summary_writer(os.path.join(self.basedir, 'logs'))
>>> write_meters_loss(writer, 'train', a... | 58,385 |
def test_vars_and_params_import(tmp_dir, dvc):
"""
Test that vars and params are both merged together for interpolation,
whilst tracking the "used" variables from params.
"""
d = {
"vars": [DEFAULT_PARAMS_FILE, {"dict": {"foo": "foobar"}}],
"stages": {"stage1": {"cmd": "echo ${dict.f... | 58,386 |
def _clip_bounds(bbox, filename):
"""Clip input fiona-compatible vector file to input bounding box.
:param bbox:
Tuple of (xmin,ymin,xmax,ymax) desired clipping bounds.
:param filename:
Input name of file containing vector data in a format compatible
with fiona.
:returns:
Shapel... | 58,387 |
def CheckChange(input_api, message_constructor):
"""Checks for files with a modified contents.
Some checking of validator happens on builbots, but comprehensive enumeration
tests must be run locally.
There are two dangers:
1. Source code for autogenerated files can be modified without regeneration
... | 58,388 |
def register(request):
"""
AJAX user registration
"""
from registration_backend.backend import JotleafBackend
backend = JotleafBackend()
if request.method == 'GET':
return _new_api_403()
data = request.POST.copy()
if not backend.registration_allowed(request):
return {
... | 58,389 |
def create_mapper(df: pd.DataFrame, field_name: str) -> Dict:
"""指定した DataFrame の field_name を利用したカラー用マッパーを返す
Args:
df (pd.DataFrame): 対象とするデータフレーム
field_name (str): カラーを調整するデータ列名
Returns:
Dict: 調整したマッパー
"""
mapper = linear_cmap(
field_name=field_name,
palet... | 58,390 |
def dedup_QC_alignments(Configuration):
"""
retrieves the aligned file and runs MarkDuplicates and CollectAlignmentSummaryMetrics
"""
align_output_dir = os.path.join(Configuration.aligned_dir, Configuration.file_to_process)
alignment_file = align_output_dir + f"/{Configuration.file_to_process}_... | 58,391 |
def _ssim_torch(raw_tensor: torch.Tensor,
dst_tensor: torch.Tensor,
window_size: int,
gaussian_kernel_window: np.ndarray) -> float:
"""PyTorch implements the SSIM (Structural Similarity) function, which only calculates single-channel data
Args:
raw_tensor... | 58,392 |
def create_joint_on_center():
"""
Creates a new joint on center of the selected objects or components
"""
selection = maya.cmds.ls(sl=True)
if not selection:
return maya.cmds.joint(n='joint#')
# if maya.cmds.objectType(selection[0]) != 'mesh':
# raise NotImplementedError('Cente... | 58,393 |
def check_drive(possible_drives, drive_mountpoint, drive_name, log_filename):
"""
Full check: drive existence/name, log file existence/name, ability to write,
so on
returns:
result,drive
"""
mount_tries_cnt = mount_tries
while True:
if mount_tries_cnt == 0:
retu... | 58,394 |
def role(args):
"""
%prog role src_acct src_username dst_acct dst_role
Change aws role. For example:
%prog role 205134639408 htang 114692162163 mvrad-datasci-role
"""
p = OptionParser(role.__doc__)
opts, args = p.parse_args(args)
if len(args) == 1 and args[0] == "htang":
args =... | 58,395 |
def _get_credentials():
"""Finds the credentials for a specific test and options.
Returns:
Credentials: set of credentials
Raises:
Exception: when the credential could not be set and they are needed
for that set of options
"""
if os.getenv('USE_ALTERNATE_ENV_CREDENTIALS... | 58,396 |
def filter_instances(project):
"""Filter EC2 instances based on Project tag"""
if project:
filters = [{'Name': 'tag:Project', 'Values': [project]}]
ec2_instances = ec2.instances.filter(Filters=filters)
else:
ec2_instances = ec2.instances.all()
return ec2_instances | 58,397 |
def test_get_fetch_start_time(mocker):
"""Unit test
Given
-
When
- the get_fetch_start_time is activated.
Then
- Validate the result are correct (the same as of the getLastRun obj).
"""
expected_start_detected_time = "2018-10-24T14:13:20Z"
... | 58,398 |
def plugin_poll(handle):
""" Poll readings from the modbus device and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a reading in a JSON document, as a Python dict, i... | 58,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.