content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _write_relabeling_rules(relabeling_rules):
"""Write to a file the relabeling rules when the clean train dataset is used.
Args:
relabeling_rules: dictionary of relabeling rules applied when the clean
train dataset is used (key = old_label, value = new_label).
"""
relabelin... | 41,900 |
def css(minify=False, verbose=False, force=False):
"""generate the css from less files"""
# minify implies force because it's not the default behavior
if not force and not minify and not _need_css_update():
print("css up-to-date")
return
for name in ('style', 'ipython'):
sou... | 41,901 |
def get_ecs_secret_access_key(config_fpath, bucket_name):
"""Return the ECS secret access key.
:param config_fpath: path to the dtool config file
:param bucket_name: name of the bucket in a ECS namespace
:returns: the ECS secret access key or an empty string
"""
key = ECS_SECRET_ACCESS_KEY_KEY_... | 41,902 |
def unmount(path):
"""Unmount the given mount point.
This function shells out to the 'fusermount' program to unmount a
FUSE filesystem. It works, but it would probably be better to use the
'unmount' method on the MountProcess class if you have it.
"""
for num_tries in xrange(3):
proces... | 41,903 |
def solve_naked_quads(sudoku, verbose):
"""Exclude the candidates of seen quad-value cell quads from unsolved cells
in their unit."""
return solve_naked_n_tuples(sudoku, 4, verbose) | 41,904 |
def prototypical_spectra_plot(
dataset,
results_df,
plot_type="imshow",
fig=None,
fig_kws={},
plot_kws={},
cbar_kws={},
**kwargs
):
"""Plot the prototypical spectra from the calibration samples.
Args:
dataset (pyeem.datasets.Dataset): [description]
results_df (pa... | 41,905 |
def parse(name, **kwargs):
""" Parse a C/C++ file
"""
idx = clang.cindex.Index.create()
assert os.path.exists(name)
tu = idx.parse(name, **kwargs)
return _ensure_parse_valid(tu) | 41,906 |
def generate_gate_piover8(
c_sys: CompositeSystem, is_physicality_required: bool = True
) -> "Gate":
"""Return the Gate class for the pi/8 (T) gate on the composite system.
Parameters
----------
c_sys: CompositeSystem
is_physicality_required: bool = True
whether the generated object is... | 41,907 |
def get_ftext_trials_fast(review_id):
"""
retrieve all ftext trials related to a review
@param review_id: pmid of review
@return: all registered trials and their linked publications
"""
conn = dblib.create_con(VERBOSE=True)
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur... | 41,908 |
def find_edges(names: List[str]) -> List[Tuple[str, str]]:
"""
Given a set of short lineages, return a list of pairs of parent-child
relationships among lineages.
"""
longnames = [decompress(name) for name in names]
edges = []
for x in longnames:
if x == "A":
continue # ... | 41,909 |
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Apples and bananas',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text',
metavar='text',
help='Input text or file'... | 41,910 |
def get_plot_spec_binstat_abs(energy, bins = 50, range = (0, 5)):
"""
Create `PlotSpec` for plot of some stat of abs energy resolution vs TrueE.
"""
# pylint: disable=redefined-builtin
return PlotSpec(
title = None,
label_x = 'True %s Energy [GeV]' % (energy),
label_y = '(R... | 41,911 |
def generate_token(data):
"""Generate a token for given data object"""
serializer = URLSafeTimedSerializer(current_app.config['SECRET_KEY'])
return serializer.dumps(data, salt=current_app.config['SECURITY_PASSWORD_SALT']) | 41,912 |
def monitor_gcp(vm_name: str, job_arguments: dict):
"""Monitor status of job based on vm_name. Requires stable connection."""
# Check VM status from command line
while True:
try:
check_cmd = (
[
"gcloud",
"alpha",
... | 41,913 |
def test_list_no_files():
"""Test if listing files of an S3 bucket works."""
# We need to create the bucket since this is all in Moto's 'virtual'
# AWS account
conn = boto3.resource("s3", region_name="us-east-1")
conn.create_bucket(Bucket="mybucket")
assert mpu.aws.list_files("mybucket") == []
... | 41,914 |
def CleanError(ErrorMessage,subproc=False):
"""Clean Errors from Log File when using import statement"""
try:
error = ErrorMessage[-2]#.split(':')
except:
sys.stdout.write("\n%s%s%s%s%s" % (bcolors.red,bcolors.underline,bcolors.bold,"Something Went Wrong - Seems You might have Imported Debuggy in the ... | 41,915 |
def five_top_workers(month, year):
"""
Top 5 presence users with information about them.
"""
dict_months = []
monthly_grouped = group_by_month(get_data(), year)
for user in monthly_grouped:
try:
dict_months.append((user.items()[0][0], user.items()[0][1][month]))
excep... | 41,916 |
def main(
content_dir=os.getenv("CONTENT_PATH", "content"),
model_dir=os.getenv("MODEL_PATH", "model"),
style="mosaic",
output_dir=os.getenv("OUTPUT_PATH", "output"),
cuda=True,
):
"""
:param content_dir:
:param model_dir:
:param style: one of candy, mosaic, rain_princess, udnie
... | 41,917 |
def get_assignment_map_from_checkpoint(tvars, init_checkpoint, prefix=""):
"""Compute the union of the current variables and checkpoint variables."""
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:
name = m.group(1)
name_to... | 41,918 |
def u_rce_hh80(lats, thermal_ro, rot_rate=ROT_RATE_EARTH, radius=RAD_EARTH):
"""Zonal wind in gradient balance with equilibrium temperatures."""
return rot_rate*radius*cosdeg(lats)*((1 + 2*thermal_ro)**0.5 - 1) | 41,919 |
def CreatePiecewiseFunction(**params):
"""Create and return a piecewise function. Optionally, parameters can be
given to assign to the piecewise function.
"""
pfunc = servermanager.piecewise_functions.PiecewiseFunction()
controller = servermanager.ParaViewPipelineController()
controller.Initial... | 41,920 |
def sec2_parse():
"""Parse Section Two from 6.03 and greater files.
Section two contains all download history data
"""
csv_body = ''
data.seek(128)
if data.tell() >= filesize:
print '[!] Error! Truncated file. Section 2 is missing.'
return
len_URL = struct.unpack('>l', data... | 41,921 |
def cancelCardTransactionPayload(cancel_time):
"""
Function for constructing payload for cancelCardTransaction API call.
Note: All parameters are of type String unless otherwise stated below.
:param cancel_time: Date and time of the request. Format - YYYY-MM-DD HH:mm:ss
:return: JSON Payload for AP... | 41,922 |
def remove_elongation(word):
"""
:param word: the input word to remove elongation
:return: delongated word
"""
regex_tatweel = r'(\w)\1{2,}'
# loop over the number of times the regex matched the word
for index_ in range(len(re.findall(regex_tatweel, word))):
if re.search(regex_tatweel, word):... | 41,923 |
def coevolve_alignment(method,alignment,**kwargs):
""" Apply coevolution method to alignment (for intramolecular coevolution)
method: f(alignment,**kwargs) -> 2D array of coevolution scores
alignment: alignment object for which coevolve scores should be
calculated
**kwargs: para... | 41,924 |
def compute_known_facts(known_facts, known_facts_keys):
"""Compute the various forms of knowledge compilation used by the
assumptions system.
This function is typically applied to the results of the ``get_known_facts``
and ``get_known_facts_keys`` functions defined at the bottom of
this file.
"... | 41,925 |
def mro(*bases):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
... | 41,926 |
def getPeaksAt(peaks, bigwigs, folder='', bigwignames=[], peaknames=[], window=1000, title='', numpeaks=4000, numthreads=8,
width=5, length=10,torecompute=False, name='temp/peaksat.pdf', refpoint="TSS", scale=None,
sort=False, withDeeptools=True, onlyProfile=False, cluster=1, vmax=None, vmin=None, overlap... | 41,927 |
def CalculatepHfromTA(param, TA, val, TP, TSi):
""" SUB CalculatepHfromTATC, version 04.01, 10-13-96, written by Ernie Lewis.
Inputs: TA, TC, TP, TSi
Output: pH
This calculates pH from TA and TC using K1 and K2 by Newton's method.
It tries to solve for the pH at which Residual = 0.
The starting ... | 41,928 |
def transform_image(image, shiftx, shifty, angle, order=1):
"""
Apply shift and rotation to the image.
The translation is applied first, then the rotation. If no rotation is
requested (``angle=0``), then ``scipy.ndimage.shift()`` is called to
perform a translation. Otherwise, ``scipy.ndimage.affine... | 41,929 |
def set_session_next_url(remote_app, url):
"""Store redirect url in session for security reasons.
:param remote_app: The remote application.
:param url: the redirect URL.
"""
session['%s_%s' % (token_session_key(remote_app), 'next_url')] = \
url | 41,930 |
def instate():
"""
Same as calculate() but the results are not saved to the database
Use this to update the state of the server to further analyse the model
:return: id of the simulation and result of the calculation
"""
# get the name of the calculation setup
name = request.args.get('name'... | 41,931 |
def pickler(obj=None, filename: str= None, mode: str = 'pickle'):
"""
pickles the file to filename, or
unpickles and returns the file
(to save the result of long running calculations)
Parameters
----------
obj :
the object to pickle
filename : str
file to pickle to
mode:
one of 'pickle... | 41,932 |
def list_books():
"""
Принтира таблица от книги
"""
pass | 41,933 |
def csrgeam(m, n, descrA, csrValA, csrRowPtrA, csrColIndA, descrB, csrValB,
csrRowPtrB, csrColIndB, handle=None, alpha=1.0, beta=0.0,
nnzA=None, nnzB=None, check_inputs=True):
""" add two sparse matrices: C = alpha*A + beta*B.
higher level wrapper to cusparse<t>csrgemm routines.
""... | 41,934 |
def is_json_request_accept(req):
"""Test if http request 'accept' header configured for JSON response.
:param req: HTTP request
:return: True if need to return JSON response.
"""
return (
type(req.accept) is accept.NoHeaderType or
type(req.accept) is accept.ValidHeaderType and (
... | 41,935 |
def make_hierarchy(parent_ps, relative_size, make_subsys, *args, **kwargs):
"""
"""
parent_size = parent_ps.radial_size
ps = ParticleSystem()
for p in parent_ps:
subsys = make_subsys(*args, **kwargs)
subsys.dynrescale_total_mass(p.mass)
subsys_size = relative_size * parent_... | 41,936 |
def device_exists(device):
"""Check if ethernet device exists."""
return os.path.exists('/sys/class/net/%s' % device) | 41,937 |
def get_site_stats(array, player_names):
"""
Return the summarized statistics for a given array corresponding
to the values sampled for a latent or response site.
"""
if len(array.shape) == 1:
df = pd.DataFrame(array).transpose()
else:
df = pd.DataFrame(array, columns=player_name... | 41,938 |
async def send_embed_message(bot, embed,plain_text=None, ctx=None, message=None, channel=None):
"""
成功メッセージを送信する。
params
----
```
bot:discord.ext.commands.Bot # このプログラムの場合は大体self.bot
embed:discord.Embed # タイトル、本文、色を設定したembed
# ex
embed = discord.Embed(
title="✅ 登録完了",
... | 41,939 |
def test_single_activity_fail_with_repeat_flow():
"""Tests that a single activity will be repeated on failure"""
class FooActivity(flow.Activity):
def execute(self, **payload):
raise Exception('fail!')
workflow = flow.ActivityFlow([
('foo', flow.ActivityConfig(kind=FooActivity, ... | 41,940 |
def new(data=None, custom=None):
"""Return a fresh instance of a KangarooTwelve object.
Args:
data (bytes/bytearray/memoryview):
Optional.
The very first chunk of the message to hash.
It is equivalent to an early call to :meth:`update`.
custom (bytes):
Opt... | 41,941 |
def document_edit(document_id: int):
"""Edits document entry.
Args:
document_id: ID of the document to be edited
"""
document = Upload.get_by_id(document_id)
if not document:
return abort(404)
form = DocumentEditForm()
if request.method == 'GET':
form.name.data = do... | 41,942 |
def get_output_tensors(graph: Union[tf.Graph, GraphDef]) -> List[str]:
"""
Return the names of the graph's output tensors.
Args:
graph: Graph or GraphDef object
Returns:
List of tensor names
"""
return [node.tensor for node in get_output_nodes(graph)] | 41,943 |
def create_build_list(select_repo, all_repos_opt):
"""Create a list of repos to build depending on a menu that the user picks from."""
if all_repos_opt is True:
build_list = repo_info.REPO_LIST
print "Building repos: " + str(build_list)
print "\n"
return build_list
# If the ... | 41,944 |
def test_time(value, fails, allow_empty, minimum, maximum, coerce_value):
"""Test the datetime validator."""
if not fails:
validated = validators.time(value,
allow_empty = allow_empty,
minimum = minimum,
... | 41,945 |
def test_project_private_query_filter(request_helper, default_data, session):
"""
Test that private projects are not filtered for admin users.
Private projects should only be visible to the user who created
the project, or to users with right permission.
"""
# Get the number of visible project... | 41,946 |
def homeFolder():
""" home folder for current user """
import os
f = os.path.abspath(os.curdir)
toks = f.split(os.sep)
if (sys.platform == 'win32'):
t = toks[0:2]
else:
t = toks[0:3]
return os.sep.join(t) | 41,947 |
def hinton(matrix, significant=None, max_weight=None, ax=None):
"""Draw Hinton diagram for visualizing a weight matrix."""
ax = ax if ax is not None else plt.gca()
if not max_weight:
max_weight = [2 ** np.ceil(np.log(np.abs(matrix[i]).max()) / np.log(2)) for i in range(matrix.shape[0])]
ax.pat... | 41,948 |
def RequireListOrTupleOfStrings(arg,name=None,allowNone=False):
"""Complain if input is not a list/tuple of strings.
INPUTS:
-- arg: Argument to check.
-- name=None: String name of variable we are checking. Only used to
create exception messages.
... | 41,949 |
def to_bin(s):
"""
:param s: string to represent as binary
"""
r = []
for c in s:
if not c:
continue
t = "{:08b}".format(ord(c))
r.append(t)
return '\n'.join(r) | 41,950 |
def get_bppair(bamfile, bp_cand_df, \
seq_len = 50, seed_len = 5, min_nt = 5,
match_method = 'fuzzy_match'):
"""
get the bppairs from bp_cand_stats (a list of bps)
parameters:
seq_len - # bases within breakend
seed_len - # of bases up and down stream of the breakend
in assembled b s... | 41,951 |
def test_general_inverse_transform_fail_not_all_test(transform, df_nans):
"""Test that differencing transform fails to make inverse_transform only on part of train."""
transformed_df = transform.fit_transform(df_nans)
with pytest.raises(ValueError, match="Inverse transform can be applied only to full train... | 41,952 |
def p_query(p):
""" query : SELECT non_mselect_clause FROM non_mrelation_list opwhere_clause """
p[0] = QueryNode(p[2], p[4], p[5]) | 41,953 |
def train_fn(
save_dir: Path,
venv: Optional[ProcgenGym3Env] = None,
env_name="coinrun",
distribution_mode="hard",
model_path: Optional[Path] = None,
start_time: int = 0,
arch: ppg.Architecture = "dual",
interacts_total=100_000_000,
num_envs=64,
n_epoch_pi=1,
n_epoch_vf=1,
... | 41,954 |
def ExecutePythonTool(tool_dir, exec_name, *args):
"""Execute the given python script with the given args and command line.
Args:
tool_dir: the directory the tool is located in
exec_name: additional path to the executable under the tool_dir
*args: args for the command
"""
_ExecuteTool(
execut... | 41,955 |
def get_dropdown_items(df: pd.DataFrame, attribute: str) -> list:
"""
Returns a list of dropdown elements for a given attribute name.
:param df: Pandas DataFrame object which contains the attribute
:param attribute: str, can be either port, vessel_type, year, or month
:return: list of unique attrib... | 41,956 |
def test_cache_remove_too_many_args(script):
"""Passing `pip cache remove` too many arguments should cause an error."""
script.pip('cache', 'remove', 'aaa', 'bbb',
expect_error=True) | 41,957 |
def RunFromFile():
"""Take robot commands as input"""
lm = ev3.LargeMotor("outC")
assert lm.connected # left motor
rm = ev3.LargeMotor("outA")
assert rm.connected # right motor
drive = ReadInDirection()
t0 = time.time()
a = True
while a:
a = drive.run()
t1 = time.time()... | 41,958 |
def print_delimeter() -> None:
"""
Prints delimeter line.
"""
print()
print('====================')
print() | 41,959 |
def veljavna(barva, di, dj, polje, i, j):
"""Če je poteza v smeri (di,dj) na polju (i,j) veljavna, vrne True, sicer vrne False"""
#parametra di in dj predstavljata spremembo koordinate i in koordinate j
#npr. če je di==1 in dj==1, se pomikamo po diagonali proti desnemu spodnjemu
#robu plošče in pre... | 41,960 |
def _do_filter(items, scores, filter_out, return_scores, n):
"""Filter items out of the recommendations.
Given a list of items to filter out, remove them from recommended items
and scores.
"""
# Zip items/scores up
best = zip(items, scores)
return _recommend_items_and_maybe_scores(
... | 41,961 |
def userlogout(request):
"""
Log out a client from the application.
This funtion uses django's authentication system to clear the session,
etc. The view will redirect the user to the index page after logging
out.
Parameters:
request -- An HttpRequest
Returns:
An HttpRespon... | 41,962 |
def shard_filename(path, prefix, lang_pair, tag, shard_num, total_shards):
"""Create filename for data shard."""
return os.path.join(
path, "%s-%s-%s-%.5d-of-%.5d" % (prefix, lang_pair, tag, shard_num, total_shards)) | 41,963 |
def histogram(values, inclusionVector=None, quantiles=None, title='', xlabel='', histBins=100, color=None, logy=False, logx=False, xlim=None, savePath=None, figureFormat='png', dpi=72, figureSize=(11,7)):
"""
histogram(values, inclusionVector=None, quantiles=None, histBins=100, color=None, logy=False, logx=False, **k... | 41,964 |
def get_builder_plugin():
"""
Get the builder plugin name default.
If not provided by CLI opt, start with
user pref in gitconfig,
Look for hint in cirrus conf or just resort
to a guess based on what python cirrus is using
"""
# TODO look up in git config
config = load_configuration... | 41,965 |
def regularize(dn, a0, method):
"""Regularization (amplitude limitation) of radial filters.
Amplitude limitation of radial filter coefficients, methods according
to (cf. Rettberg, Spors : DAGA 2014)
Parameters
----------
dn : numpy.ndarray
Values to be regularized
a0 : float
... | 41,966 |
def get_fields_by_queue(client: Client, queue: Optional[list]) -> list:
"""
Creating a list of all queue ids that are in the system.
Args:
client: Client for the api.
Returns:
list of queue ids.
"""
if queue:
queues_id = queue
else:
queues_id = get_queue_ids(c... | 41,967 |
def emitter_20():
"""Interval, emit from center, velocity fixed speed around 360 degrees"""
e = arcade.Emitter(
center_xy=CENTER_POS,
emit_controller=arcade.EmitterIntervalWithTime(DEFAULT_EMIT_INTERVAL, DEFAULT_EMIT_DURATION),
particle_factory=lambda emitter: arcade.LifetimeParticle(
... | 41,968 |
def add_mask_rncc_losses(model, blob_mask):
"""Add Mask R-CNN specific losses"""
loss_mask = model.net.SigmoidCrossEntropyLoss(
[blob_mask, 'masks_init32'],
'loss_mask',
scale=model.GetLossScale() * cfg.MRCNN.WEIGHT_LOSS_MASK
)
loss_gradients = blob_utils.get_loss_gradients(model... | 41,969 |
def test_update_high_value_domain_fails_ip4_ptr(shared_zone_test_context):
"""
Test that updating a high value domain fails for ip4 ptr
"""
client = shared_zone_test_context.ok_vinyldns_client
zone_ip4 = shared_zone_test_context.classless_base_zone
list_results_page_ip4 = client.list_recordsets_... | 41,970 |
def fixed_discount(order: Order):
"""
5k fixed amount discount
"""
return Decimal("5000") | 41,971 |
def pinMux(gpio_pin, mode, preserve_mode_on_exit=False):
""" Uses kernel omap_mux files to set pin modes. """
# There's no simple way to write the control module registers from a
# user-level process because it lacks the proper privileges, but it's
# easy enough to just use the built-in file-based system and ... | 41,972 |
def combine_details(source_details, target_details):
"""Add every value from source to target deduping common keys."""
for name, content_object in source_details.items():
new_name = name
disambiguator = itertools.count(1)
while new_name in target_details:
new_name = '%s-%d' %... | 41,973 |
def index():
"""
The index page.
Just welcomes the user and asks them to start a quiz.
"""
return render_template('index.html') | 41,974 |
def parse_element(stream: BinaryIO):
"""Parse the content of the UPF file to determine the element.
:param stream: a filelike object with the binary content of the file.
:return: the symbol of the element following the IUPAC naming standard.
"""
lines = stream.read().decode('utf-8')
match = REG... | 41,975 |
def mention_subclass(
class_name: str,
cardinality: Optional[int] = None,
values: Optional[List[Any]] = None,
table_name: Optional[str] = None,
) -> Type[Mention]:
"""Create new mention.
Creates and returns a Mention subclass with provided argument names,
which are Context type. Creates the... | 41,976 |
def _check_python_bin(repository_ctx, python_bin):
"""Checks the python bin path."""
cmd = '[[ -x "%s" ]] && [[ ! -d "%s" ]]' % (python_bin, python_bin)
result = raw_exec(repository_ctx, [get_bash_bin(repository_ctx), "-c", cmd])
if result.return_code == 1:
auto_config_fail("--define %s='%s' is ... | 41,977 |
def undupe_column_names(df, template="{} ({})"):
"""
rename df column names so there are no duplicates (in place)
e.g. if there are two columns named "dog", the second column will be reformatted to "dog (2)"
Parameters
----------
df : pandas.DataFrame
dataframe whose column names shoul... | 41,978 |
def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
"""
An extension to the matplotlib.pyplot.plot function that allows for
the nice plotting of :class:`ooipy.hydrophone.basic.Spectrogram`
and :class:`ooipy.hydrophone.basic.Psd` objects. For a description
of the input parameters, please ... | 41,979 |
def p(*args):
"""
Convenience function to join the temporary directory path
with the provided arguments.
"""
return os.path.join(temp_dir, *args) | 41,980 |
def get_example_data(dataset_name):
"""
This is a smart package loader that locates text files inside our package
:param dataset_name:
:return:
"""
provider = get_provider('ebu_tt_live')
manager = ResourceManager()
source = provider.get_resource_string(manager, 'examples/'+dataset_name)... | 41,981 |
def format_file(file): # type: (Path) -> None
"""
use black or autopep8 to format python file
"""
try:
# noinspection PyPackageRequirements
import black
with Popen(
[sys.executable, "-m", "black", str(file)], stdout=PIPE, stderr=PIPE
) as p:
p.co... | 41,982 |
def read_cli(data_dir, mode, epoch, data_split, continue_train, checkpoint, batch_size, model_dir, lr, log_dir, use_gpu, save_frequency):
"""
:param data_dir:
:param mode:
:param epoch:
:param data_split:
:param continue_train:
:param checkpoint:
:param batch_size:
:param model_dir:... | 41,983 |
def js(data):
""" JSをミニファイ """
# 今のところは何もしない
return data | 41,984 |
def _tag_instance_by_submission(config, instance_id, submission_name):
"""
Add tags to an instance with infos from the submission to know which
submission is being trained on the instance.
"""
# _add_or_update_tag(
# config, instance_id, 'submission_id', str(submission.id))
# _add_or_upd... | 41,985 |
def _has_endpoint_name_flag(flags):
"""
Detect if the given flags contain any that use ``{endpoint_name}``.
"""
return '{endpoint_name}' in ''.join(flags) | 41,986 |
def convert_example(example,
tokenizer,
max_seq_len=512,
max_response_len=128,
max_knowledge_len=256,
mode='train'):
"""Convert all examples into necessary features."""
goal = example['goal']
knowledge = exam... | 41,987 |
def test_rest_validation_invalid():
"""Test validation of an Annotation record with an invalid value."""
data, errors = AnnoSchema().load({u'bounded': u'uncertain',
u'invalid': u'false',
u'extended': u'true',
... | 41,988 |
def mag2Jy(info_dict, Mag):
"""Converts a magnitude into flux density in Jy
Parameters
-----------
info_dict: dictionary
Mag: array or float
AB or vega magnitude
Returns
-------
fluxJy: array or float
flux density in Jy
"""
fluxJy=info_dict['Fl... | 41,989 |
def load_array(data_arrays, batch_size, is_train=True):
"""Construct a PyTorch data iterator.
Defined in :numref:`sec_utils`"""
dataset = ArrayData(data_arrays)
data_column_size = len(data_arrays)
dataset = ds.GeneratorDataset(source=dataset, column_names=[str(i) for i in range(data_column_size)], s... | 41,990 |
def do_get_batched_targets(parser, token):
"""
Retrieves the list of broadcasters for an action and stores them in a context variable which has
``broadcasters`` property.
Example usage::
{% get_batched_targets action_id_list parent_action_id as batched_targets %}
"""
bits = token.conte... | 41,991 |
def task_success_slack_alert(context):
"""
Callback task that can be used in DAG to alert of successful task completion
Args:
context (dict): Context variable passed in from Airflow
Returns:
None: Calls the SlackWebhookOperator execute method internally
"""
slack_webhook_token... | 41,992 |
def return_img_stream(img_local_path):
"""
工具函数:
获取本地图片流
:param img_local_path:文件单张图片的本地绝对路径
:return: 图片流
"""
import base64
img_stream = ''
with open(img_local_path, 'rb') as img_f:
img_stream = img_f.read()
img_stream = base64.b64encode(img_stream)
return img_str... | 41,993 |
def filter_log_on_max_no_activities(log: EventLog, max_no_activities : int = 25, parameters: Optional[Dict[Union[str, Parameters], Any]] = None) -> EventLog:
"""
Filter a log on a maximum number of activities
Parameters
-------------
log
Log
max_no_activities
Maximum number of a... | 41,994 |
def GSSO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2.0.5", **kwargs
) -> Graph:
"""Return ... | 41,995 |
def tb(
data: pd.DataFrame,
columns: Optional[Union[Sequence[str], pd.Index]] = None,
subscales: Optional[Dict[str, Sequence[int]]] = None,
) -> pd.DataFrame:
"""Compute the **Technology Commitment Questionnaire (TB – Technologiebereitschaft)**.
It consists of the subscales with the item indices (c... | 41,996 |
def format_date(date: str):
"""
This function formats dates that are in MM-DD-YYYY format,
and will convert to YYYY-MM-DD, which is required sqlite.
:param date: The date to modify.
:return: The modified string.
"""
tmp = date.split("/")
return "{}-{}-{}".format(tmp[2], tmp[0], tmp[1]) | 41,997 |
def _doUpgradeApply(sUpgradeDir, asMembers):
"""
# Apply the directories and files from the upgrade.
returns True/False/Exception.
"""
#
# Create directories first since that's least intrusive.
#
for sMember in asMembers:
if sMember[-1] == '/':
sMember = sMember[len(... | 41,998 |
def _parse_atat_lattice(lattice_in):
"""Parse an ATAT-style `lat.in` string.
The parsed string will be in three groups: (Coordinate system) (lattice) (atoms)
where the atom group is split up into subgroups, each describing the position and atom name
"""
float_number = Regex(r'[-+]?[0-9]*\.?[0... | 41,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.