content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def image_actions_group():
"""
image actions command group
"""
pass | 5,301,200 |
def lock_change_receiver():
"""
A decorator for connecting receivers to signals that a lock has change.
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
"""
def _decorator(func):
LockCache.lock_change_receivers.append(func)
re... | 5,301,201 |
def find_cached_kernel(R, x0, N=32, M=64, max_dx0=1/16):
""" Returns the key for a cached gridder with th given parameters
:param R: Half support in pixels
:param x0: Image plane coordinates up to which coordinates are optimised
:param N: Number of points to evaluate in image space
:param M: Numbe... | 5,301,202 |
def create_kmer_loc_fn(size):
""" Hash location of kmer for specific size.
NOTE: This is pretty much similar to encode. May refactor later.
"""
offset = kmer_location("A" * size)
def wrapped(seq):
return kmer_location(seq) - offset
return wrapped | 5,301,203 |
async def suggest_best_practice_by_QA_model(response: Response, data: suggest_best_practice_by_QA_model_body):
"""Example Questions:\n"What is the Item to be sell?",\n"Who is the buyer?",\n"Who is the seller?","What is the due date?"\n\n# Example Context: \n"Dan (the seller) Will be deemed to have completed its del... | 5,301,204 |
def get_topics(tagger_es, chunker_es, news_db, window_size=10, num_topics=35):
"""Main function"""
ini = time.time()
couch = couchdb.Server()
try:
topic_db = couch.create('meneame_topic_db')
except Exception:
topic_db = couch['meneame_topic_db']
logging.info('Loading Spanish Se... | 5,301,205 |
def kind_div(x, y) -> Union[int, float]:
"""Tries integer division of x/y before resorting to float. If integer
division gives no remainder, returns this result otherwise it returns the
float result. From https://stackoverflow.com/a/36637240."""
# Integer division is tried first because it is lossless.... | 5,301,206 |
def check_tps(row, method, correct_tps):
"""
Check if the trapping clips questions are answered correctly
:param row:
:param method: acr, dcr, or ccr
:return:
"""
# correct_tps = 0
try:
tp_itemcode = row['answer.tp_item_code']
print(tp_itemcode)
suffix =... | 5,301,207 |
def to_device(model):
"""
push model to gpu(s) if available
"""
# Send the model to GPU
if torch.cuda.device_count() > 1:
print("Using", torch.cuda.device_count(), "GPUs!")
model = nn.DataParallel(model)
model = model.to(config.DEVICE)
return model | 5,301,208 |
def collect_predicates(subject, row, structure_row, files, stc, prefixes):
"""
Function to collect predicates for a given subject
Parameters
----------
subject : string
Turtle object
row : Series
row from structure_to_keep
pandas series from generator
ie, row[1]... | 5,301,209 |
def path_to_file_uri(path):
"""Convert local filesystem path to legal File URIs as described in:
http://en.wikipedia.org/wiki/File_URI_scheme
"""
x = urllib.pathname2url(os.path.abspath(path))
if os.name == 'nt':
x = x.replace('|', ':') # http://bugs.python.org/issue5861
return 'file:///... | 5,301,210 |
def build_amqp_url(
user: str = None,
password: str = None,
host: str = None,
port: int = None,
virtual_host: str = None,
connection_attempts: int = None,
heartbeat_interval: int = None,
ssl_options: dict = None,
) -> str:
"""
Create a AMQP connection URL from parameters.
If... | 5,301,211 |
def parse_fun(serialized_example):
""" Data parsing function.
"""
features = tf.io.parse_single_example(serialized_example,
features={'image': tf.io.FixedLenFeature([], tf.string),
'label': tf.io.FixedLenFeature([], tf.i... | 5,301,212 |
def load_train_val_public_set(split=SPLIT, is_one_hot=False,
is_plot_data=False, is_drop_col=False, pca_transform=0):
"""
Load and transform public dataset by config mode
Return:
X, Y or X, Y divide into train/val set
"""
X = load_csv(os.path.join(os.g... | 5,301,213 |
def qrIsCharacter(character):
"""
This method checks whether the character was created using the Quick Rig
tool and therefore can be edited by the tool.
"""
pass | 5,301,214 |
def plot_frame(
fig0, n_obs, train_loss, val_loss, test_loss, r2, proxy_true, proxy_inferred,
color_array, train_time):
"""Plot frame."""
# Settings.
s = 10
gs = fig0.add_gridspec(2, 2)
f0_ax0 = fig0.add_subplot(gs[0, 0])
plot_loss(f0_ax0, n_obs, train_loss, val_loss, test_loss... | 5,301,215 |
def test_flat_bad_acq_skip():
"""Test that acquisition skips are handled properly."""
# -- file with a couple of skip and flat channels --
raw = read_raw_fif(skip_fname, preload=True)
annots, bads = annotate_amplitude(raw, flat=0)
assert len(annots) == 0
assert bads == [ # MaxFilter finds the s... | 5,301,216 |
def reset ():
""" Clear the module state. This is mainly for testing purposes.
"""
global __generators, __type_to_generators, __generators_for_toolset, __construct_stack
global __overrides, __active_generators
global __viable_generators_cache, __viable_source_types_cache
global __vstg_cached_gen... | 5,301,217 |
def parse_feedstock_file(feedstock_fpath):
"""
Takes a file with space-separated feedstocks on each line and comments
after hashmarks, and returns a list of feedstocks
:param str feedstock_fpath:
:return: `list` -- list of feedstocks
"""
from itertools import chain
if not (isinstance(fe... | 5,301,218 |
def get_processes(options):
"""Interprets provided options and returns a list of processes"""
nf_core_mapping = {}
multiprocesses = {}
inputs = []
outputs = []
errouts = []
pargs = []
workloads = options.cmd.split(';')
print(workloads)
if options.input != "":
inputs = ... | 5,301,219 |
def assert_array_equal(x: numpy.ndarray, y: numpy.memmap):
"""
usage.scipy: 7
usage.sklearn: 2
"""
... | 5,301,220 |
def softmax(Z):
"""
Z: output out of the dense layer. shape: (vocab_size, m)
"""
softmax_out = np.divide(np.exp(Z), np.sum(np.exp(Z), axis=0, keepdims=True) + 0.001)
assert (softmax_out.shape == Z.shape)
return softmax_out | 5,301,221 |
def test_status_state3(mock_ssh):
"""
Test if job status is grabbed.
"""
job = {
"user": "test",
"jobid": "953631"
}
mock_ssh.return_value = (out, "", 0)
output = status(job)
assert output == "Queued" | 5,301,222 |
def log_settings(config):
"""Set custom log settings."""
LOGGER.propagate = False
formatter = ViseronLogFormat(config.logging)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.addFilter(DuplicateFilter())
LOGGER.addHandler(handler)
LOGGER.setLevel(LOG_LEVELS[con... | 5,301,223 |
def lin_2020_to_xyz(rgb: MutableVector) -> MutableVector:
"""
Convert an array of linear-light rec-2020 values to CIE XYZ using D65.
(no chromatic adaptation)
http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
"""
return cast(MutableVector, util.dot(RGB_TO_XYZ, rgb)) | 5,301,224 |
def match_matrix_transform(source, target):
"""
match the transform
:param source: <str> source object to snap to target.
:param target: <str>, <tuple> target object, or matrix array.
:return: <bool> True for success. <bool> False for failure.
"""
if isinstance(target, (tuple, list)) and len... | 5,301,225 |
def unit_state_cb (unit, state):
""" this callback is invoked on all unit state changes """
print "[Callback]: ComputeUnit '%s' state: %s." % (unit.uid, state) | 5,301,226 |
def gather_ss_evaluations(
evaluations: typing.Iterable[tuple],
) -> tk.evaluations.EvalsType:
"""evaluate_ss_singleの結果のリストから評価結果を作成して返す。
Args:
evaluations: evaluate_ss_singleの結果のリスト
Returns:
各種metrics
- "iou": クラスごとのIoU
- "miou": クラスごとのIoUのマクロ平均
- "iou_score":... | 5,301,227 |
def get_unrecognized_folders(snapshots, out_dir: Path=OUTPUT_DIR) -> Dict[str, Optional[Link]]:
"""dirs that don't contain recognizable archive data and aren't listed in the main index"""
unrecognized_folders: Dict[str, Optional[Link]] = {}
for entry in (Path(out_dir) / ARCHIVE_DIR_NAME).iterdir():
... | 5,301,228 |
def _bgconfig_build_hook(config_template, file_path, home_folder, config_name):
"""Trick to raise an error if the config file does not exits"""
raise ProfileError('Profile {} not found'.format(config_name)) | 5,301,229 |
def lookup_device(name):
"""Look up the device's address from the given name"""
global DEBUG, m_devices
devaddr = 0
if m_devices is None or name == '':
return devaddr
if DEBUG: print("DEBUG: Looking up device ID from database")
for dev in m_devices:
try:
devname = dev... | 5,301,230 |
def appendIfTruthy(lst, item):
"""Appends an item to a list only if that item exists or is considered truthy (not None, not '', etc)."""
if item:
lst.append(item) | 5,301,231 |
def _remove_empty_timesteps(sp_tensor):
"""Creates a 3D SparseTensor skipping empty time steps.
Args:
sp_tensor: A SparseTensor with at least 2 dimensions (subsequent ones will
be ignored and simply flattened into the 2nd dimension).
Returns:
A 3D SparseTensor with index 0 for dimension 3 and a se... | 5,301,232 |
def get_first_node_of_tree(root_node):
"""root_node's rhythm is #4"""
return root_node.sons[0].sons[0].sons[0].sons[0].sons[0] | 5,301,233 |
def secondary_feature(name, dependencies):
"""
Some explanation of how to use this decorator goes here.
"""
def _wrapper1(func):
def _wrapper2(*args, **kwargs):
# Verify all required parameters for the primary feature function.
params = [
... | 5,301,234 |
def rat_fun(x, poles):
"""
Computes the value of a rational function with poles in poles and roots in
-poles; see Definition 8.29 from the doctoral thesis "Model Order Reduction
for Fractional Diffusion Problems" for a precise definition.
Parameters
----------
x : float
The argument... | 5,301,235 |
def orffinder(sequence, output, min_prot_len=30, description="putative protein"):
"""
Find all open reading frames in a nucleotide sequence.
ORFs are translated to amino acid sequences and written to a protein
fasta. The unique identifier for each translated ORF contains information
about it's star... | 5,301,236 |
def createCode(videoNameList, fileUrlList, videoIdList, codeFile):
"""
参数:文件名称列表,文件链接列表,文件id列表,代码文件
功能:将已有数据批量写入代码并形成列表
返回值:代码列表
"""
codeList = []
for i in range(len(videoNameList)):
codeF = open(codeFile, "r", encoding = "utf-8")
code = codeF.read()
codeF.close()
... | 5,301,237 |
def snapshot_in_progress(client, repository=None, snapshot=None):
"""
Determine whether the provided snapshot in `repository` is ``IN_PROGRESS``.
If no value is provided for `snapshot`, then check all of them.
Return `snapshot` if it is found to be in progress, or `False`
:arg client: An :class:`el... | 5,301,238 |
def is_ssl_cert_master(votes=None):
"""Return True if this unit is ssl cert master."""
votes = votes or get_ssl_cert_master_votes()
set_votes = set(votes)
# Discard unknown votes
if 'unknown' in set_votes:
set_votes.remove('unknown')
# This is the elected ssl-cert-master leader
if ... | 5,301,239 |
def step_impl(context, word):
"""
:type context: behave.runner.Context
:type word: str
"""
print("when_i_enter_a_word_as ", word, "\n")
context.encoded = context.soundex.encode(word) | 5,301,240 |
def get_crop_cycle_length(crop):
"""Get crop cycle length for named crop"""
path = _find_crop_file(crop)
return _get_crop_cycle_length(path) | 5,301,241 |
def node_to_get_shape_value_of_indices(shape_node: Node, indices: list) -> Node:
"""
The function returns a node that produces values of the specified indices of the input node 'shape_node'
:param shape_node: the node of 1D output shape to get elements from
:param indices: the list of element indices t... | 5,301,242 |
def handle_sample(sample, module_name, field_name):
"""Check if a sample has already been processed and if not process it."""
if sample.analysis_result(UPLOAD_MODULE_NAME).exists():
click.echo(f'Sample {sample.name} has already been processed')
else:
click.echo(f'Sample {sample.name} has not... | 5,301,243 |
def get_TIS_highest_interface_update_mask(
TIS_origins, highest_interface, update_factor):
"""Make a mask with the update_factor at all positions of the
highest interface and 0 everywhere else.
"""
return get_TIS_highest_interface_true_mask(
TIS_origins, highest_interface) * update_facto... | 5,301,244 |
def import_mission_reports(vehicles_file, missions_file, no_confirm):
""" Imports the existing mission reports. """
if not no_confirm:
click.confirm(
'This will delete all existing missions and vehicles, continue?',
abort=True
)
with open(vehicles_file, 'rb') as f:
... | 5,301,245 |
def _removeLine(label, ax):
"""Remove a line from the ax when a label is specified"""
for line in reversed(ax.lines):
if line.get_label() == label:
line.remove()
del line | 5,301,246 |
def _optargs_to_kwargs(args):
"""Convert --bar-baz=quux --xyzzy --no-squiz to kwargs-compatible pairs.
E.g., [('bar_baz', 'quux'), ('xyzzy', True), ('squiz', False)]
"""
kwargs = []
for arg in args:
if not arg.startswith('--'):
raise RuntimeError("Unknown option %r" % arg)
... | 5,301,247 |
def test_comparisons():
"""make sure comparison operators work"""
str1 = _FakeString("this is a fake string")
str2 = _FakeString("this is a fake string")
str3 = _FakeString("fake string, this is")
str4 = "this is a fake string"
str5 = "fake string, this is"
assert str1 <= str2
assert st... | 5,301,248 |
def vgg19_bn():
"""VGG19_BN Model pre-trained on ImageNet"""
model = torchvision.models.vgg19_bn(pretrained=True)
obj = ImageClassificationModule(model, "VGG19_BN", model_example="default")
return obj | 5,301,249 |
def barrier(
store, rank: int, world_size: int, key_prefix: str, barrier_timeout: float = 300
) -> None:
"""
A global lock between agents.
Note: Since the data is not removed from the store, the barrier can be used
once per unique ``key_prefix``.
"""
data = f"{rank}".encode(encoding="UT... | 5,301,250 |
def _test(verbose=True):
"""run doctests"""
if not os.path.isdir("tests/data"):
sys.exit("Error: Running doctests requires 'tests/data' dir to be present")
import doctest
doctest.testmod(verbose=verbose) | 5,301,251 |
def test_el_sbd(el_default_fixture, text, expected_sents):
"""Greek language SBD tests"""
segments = el_default_fixture.segment(text)
segments = [s.strip() for s in segments]
assert segments == expected_sents | 5,301,252 |
def make_map(seed=None):
"""
Generate a two-color map with multiple patterns for each team.
"""
rows = ROWS
cols = COLS
# set rng seed (optional)
if seed is not None:
random.seed(seed)
# Place two wickstretchers at edge of map, facing each other
# Small amount of vertical ji... | 5,301,253 |
def spatial_aggregation(target_dataset, lon_min, lon_max, lat_min, lat_max):
""" Spatially subset a dataset within the given longitude and latitude boundaryd_lon-grid_space, grid_lon+grid_space
:param target_dataset: Dataset object that needs spatial subsetting
:type target_dataset: Open Climate Workbench D... | 5,301,254 |
def mark_overlaps_high_res(low_list,high_list):
"""mark overlapping loops between low resolution loops
and high resolution loops,
return lists of loops in which low resolution overlaping loops marked by 1"""
marker=np.zeros(len(low_list))
for index, row in low_list.iterrows():
c1=row[0... | 5,301,255 |
def crosschannelnormalization(alpha = 1e-4, k=2, beta=0.75, n=5,**kwargs):
"""
This is the function used for cross channel normalization in the original Alexnet
combing the conventkeras and pylearn functions.
erralves
"""
def f(X):
ch, r, c, b = X.shape
half = n // 2
sq ... | 5,301,256 |
def fetSpIdx(spikes_data):
"""Spike sequential index (0,1,2, ...)
"""
spikes = _get_data(spikes_data, [0])
n_datapts = spikes.shape[1]
return {'data':np.arange(n_datapts)[:, np.newaxis],'names':["SpIdx"]} | 5,301,257 |
def onfiledeletion(archiveselection_name, p5_connection=None, command=None):
"""
Syntax: ArchiveSelection <name> onfiledeletion <command>
Description: Registers the <command> to be executed immediately after the
files are deleted through a job created by the submit method. See
onjobactivation for fu... | 5,301,258 |
def slem(driver, url):
"""
Selenium calling function.
:param driver:
:param url:
:return:
"""
global new_uri
new_uri = url
try:
driver.get(url, )
except Exception as e:
print "Error Got !!!"
return | 5,301,259 |
def scopes_size(scopes: Scopes) -> Counter:
"""
scopes_size(scopes: Scopes) -> Counter:
Calculate the different scope lengths.
Parameters
----------
scopes
Dictionary of cells (keys) and their scopes
Returns
-------
Counter of scopes lengths (key) and their freq... | 5,301,260 |
def make_npz(input_file, npz_file, k=0):
"""Convert input data (SVMLight or .npz) into .npz format"""
if input_file.endswith('.npz'):
x, y, qid, docno = core.io.load_npz(input_file)
else:
x, y, qid, docno = core.io.load_svmlight_file(input_file)
# eliminate explicit zeros
x.eliminat... | 5,301,261 |
def compile(model: torch.nn.Module,
example_args: List[torch.Tensor],
output_type: OutputType = OutputType.TORCH,
use_tracing=False):
"""Convert a PyTorch model to MLIR.
Args:
model: The PyTorch model to convert.
example_args: A list of example arguments to u... | 5,301,262 |
def _get_reader(file):
"""Get CSV reader and skip header rows."""
reader = csv.reader(file)
# Skip first 3 rows because they're all headers.
for _ in range(3):
next(reader)
return reader | 5,301,263 |
def test_atx_headings_extra_30():
"""
Test case extra 30: ATX headings string ending with a link.
"""
# Arrange
source_markdown = """## a link looks like [Foo](/uri)"""
expected_tokens = [
"[atx(1,1):2:0:]",
"[text(1,4):a link looks like : ]",
"[link(1,22):inline:/uri::... | 5,301,264 |
def hx(x):
""" compute measurement for slant range that
would correspond to state x.
"""
global X1,Y1,X2,Y2,X3,Y3,A1,A2,A3,n1,n2,n3
h1 = -(A1+5*n1*log10(pow((x[0]-X1),2)+pow((x[1]-Y1),2)))
h2 = -(A2+5*n2*log10(pow((x[0]-X2),2)+pow((x[1]-Y2),2)))
h3 = -(A3+5*n3*log10(pow((x[0]-X3),2)+pow((x[1... | 5,301,265 |
def add_intersection_delay(G, intersection_delay=7, time_col = 'time', highway_col='highway', filter=['projected_footway','motorway']):
"""
Find node intersections. For all intersection nodes, if directed edge is going into the intersection then add delay to the edge.
If the highest rank road at an intersec... | 5,301,266 |
def copy_template_file(src, dest, replace=None):
"""
Copy a source file to a new destination file.
To replace boilerplate strings in the source data, pass a dictionary to the
``replace`` argument where each key is the boilerplate string and the
corresponding value is the string which should rep... | 5,301,267 |
def left_justify_string(keyword, value):
"""Returns a string with dotted separation.
"""
return '%s' % keyword .ljust(40, ".") + ": " + '%s\n' % value | 5,301,268 |
async def get_obs_loc(place='', *, exclude=''):
"""
Accepts place and JSON arguments for One Call data to ignore.
Returns tuple with PyOWM OneCall and geopy Location.
Default place is Toronto, ON.
Observation taken using OWM One Call API.
https://openweathermap.org/api/one-call-api
Ge... | 5,301,269 |
def test_check_data():
"""Data Type Check of all the elements"""
assert isinstance(URDU_ALL_CHARACTERS, frozenset)
assert isinstance(URDU_ALL_CHARACTERS_UNICODE, dict)
assert len(URDU_ALL_CHARACTERS) == 90
assert len(URDU_ALL_CHARACTERS_UNICODE) == len(URDU_ALL_CHARACTERS) | 5,301,270 |
def svn_inheritance_from_word(*args):
"""svn_inheritance_from_word(char word) -> svn_mergeinfo_inheritance_t"""
return apply(_core.svn_inheritance_from_word, args) | 5,301,271 |
def APO(ds, count, fastperiod=-2**31, slowperiod=-2**31, matype=0):
"""Absolute Price Oscillator"""
return call_talib_with_ds(ds, count, talib.APO, fastperiod, slowperiod, matype) | 5,301,272 |
def download_ftp_file(
path, outdir
):
"""Given a link starting with ftp://, use wget to download file."""
import os
run_cmd = 'wget -P ' + outdir + ' ' + path
os.system(run_cmd) | 5,301,273 |
def write_text(path: str, data: str, encoding=None, append=False):
"""write text `data` to path `path` with encoding
e.g
j.sals.fs.write_text(path="/home/rafy/testing_text.txt",data="hello world") -> 11
Args:
path (str): path to write to
data (str): ascii content
encoding (... | 5,301,274 |
def api_url_env_var_trailing_slash():
"""Sets an api_url via environment variable. The url has trailing slash"""
os.environ["RUBRIX_API_URL"] = "http://fakeurl.com/" | 5,301,275 |
def request_json(url: str, data=None, headers=None, method=None) -> dict:
"""
requests a url and convert return into json
:raises EzeNetworkingError: on networking error or json decoding error"""
log_debug(f"calling url '{url}'")
if not headers:
headers = {}
contents = request(url, data... | 5,301,276 |
def main(filenames=[], debug=False):
"""
start the editor, with a new empty document
or load all *filenames* as tabs
returns the tab object
"""
odmlui.DEBUG = debug
Editor.register_stock_icons()
editor = Editor.EditorWindow()
# Convert relative path to absolute path, if any
for... | 5,301,277 |
def z_cmp(calculated_z_score_proportion, criticalz_percentage_proportion):
"""
calculated_z_score_proportion: the z score calculated from mu and xbar in proportion
criticalz_percentage_proportion: Given Critical Value proportion for acceptance criteria
if calculated_z_score_proportion > criticalz_percen... | 5,301,278 |
def get_first_index_greater_than_benchmark(arr, benchmark, reverse=False):
"""
获取在数组 arr 中第一个大于基准值的索引。reverse 控制反向查找或正向查找
Args:
arr(list):
benchmark():
reverse(bool):
Returns:
"""
if reverse:
start = len(arr) - 1
stop = -1
step = -1
else:
start = 0
stop = len(arr)
ste... | 5,301,279 |
async def test_arm_home_with_pending(opp, mqtt_mock):
"""Test arm home method."""
assert await async_setup_component(
opp,
alarm_control_panel.DOMAIN,
{
"alarm_control_panel": {
"platform": "manual_mqtt",
"name": "test",
"code":... | 5,301,280 |
def load_from_dump(inLoc):
"""
Loads data from dumped state (generated by dumped_params), and creates a
new DBN.
"""
dump = cPickle.load(open(inLoc, 'rb'))
# Get the number of layers.
max_layer = 0
for layer, _ in dump:
if layer > max_layer:
max_layer = layer
max_... | 5,301,281 |
def make_roc_curve_plot(
train_inputs: Tuple[np.ndarray],
test_inputs: Tuple[np.ndarray],
job_config: ht.config,
save_dir: ht.pathlike,
):
"""Plots ROC curve."""
logger.info("Plotting train/test ROC curve.")
tc = job_config.train.clone()
ac = job_config.apply.clone()
# prepare
ou... | 5,301,282 |
def _assemble_tn_as_iterator_content_by_verse(
usfm_resource: Optional[USFMResource],
tn_resource: Optional[TNResource],
tq_resource: Optional[TQResource],
tw_resource: Optional[TWResource],
ta_resource: Optional[TAResource],
usfm_resource2: Optional[USFMResource],
assembly_substrategy_kind:... | 5,301,283 |
def _labels_cost(Xnum, Xcat, centroids, num_dissim, cat_dissim, gamma, membship=None):
"""Calculate labels and cost function given a matrix of points and
a list of centroids for the k-prototypes algorithm.
"""
n_points = Xnum.shape[0]
Xnum = check_array(Xnum)
cost = 0.
labels = np.empty(n_... | 5,301,284 |
def cookie_app(environ, start_response):
"""A WSGI application which sets a cookie, and returns as a response any
cookie which exists.
"""
response = Response(environ.get('HTTP_COOKIE', 'No Cookie'),
mimetype='text/plain')
response.set_cookie('test', 'test')
return respon... | 5,301,285 |
def local_args():
""" Create an argparse namespace to create a local dask cluster.
"""
args = argparse.Namespace()
args.num_procs = 1
args.num_threads_per_proc = 1
args.cluster_location = "LOCAL"
args.client_restart = False
return args | 5,301,286 |
def weighted_bipartite_matching(A, perm_type='row'):
"""
Returns an array of row permutations that attempts to maximize the product
of the ABS values of the diagonal elements in a nonsingular square CSC
sparse matrix. Such a permutation is always possible provided that the
matrix is nonsingular.
... | 5,301,287 |
def _assert_shape_eq(inp, tgt_shape, dim=None):
"""Asserts that the shape of tensor `inp` is equal to the tuple `tgt_shape`
along dimension `dim`.
If `dim` is None, shapes along all dimensions must be equal.
"""
if dim is None:
if inp.shape != tgt_shape:
raise ValueError(
... | 5,301,288 |
def filename_timestamp():
"""Returns a timestamp appropriate for inclusion as part of a filename.
The timestamp includes microseconds, and so subsequent calls to this
function are guaranteed to return different filenames.
"""
# FILENAME_TIMESTAMP_FORMAT is hidden inside this function because it
... | 5,301,289 |
def print_sequences(char_list, n, ret=[]):
"""
Print all sequences of char list with n length
:param char_list:list
:param n:number
:param ret:list
"""
if (len(ret) == n):
print("".join(ret))
else:
for item in char_list:
new_list = ret[:]
new_list.... | 5,301,290 |
def set_file_logger(filename, name='funcx', level=logging.DEBUG, format_string=None):
"""Add a stream log handler.
Args:
- filename (string): Name of the file to write logs to
- name (string): Logger name
- level (logging.LEVEL): Set the logging level.
- format_string (string): ... | 5,301,291 |
def generate_files(app_config):
"""Generate a Dockerfile and helper files for an application.
Args:
app_config (AppConfig): Validated configuration
Returns:
dict: Map of filename to desired file contents
"""
if app_config.has_requirements_txt:
optional_requirements_txt = ge... | 5,301,292 |
def fixture_packages_with_trailing_spaces():
"""
A packages dictionary with trailing spaces on some items
"""
packages = {
"basic": ["package-one ", "package-two"],
"complex": ["package-three", "package-four", "package-five"],
}
return packages | 5,301,293 |
def solve_pdd(cell: PVCell, v: f64, pot_ini: Potentials):
"""Solve PDD system at a specified voltage, with IFT for gradient
Args:
cell (PVCell): An initialized cell
v (f64): Voltage to solve at, in dimensionless form
pot_ini (Potentials): Initial guess of solution
Returns:
... | 5,301,294 |
def Backbone(backbone_type='ResNet50', use_pretrain=True, post_name='_extractor'):
"""Backbone Model"""
weights = None
if use_pretrain:
weights = 'imagenet'
def backbone(x):
if backbone_type.lower() == 'MLSD'.lower():
extractor = MobileNetV2(
input_shape=... | 5,301,295 |
def run_dmenu(words=[]):
"""
Runs dmenu
"""
if not words:
command = ["echo", "Search wikipedia"]
else:
command = ["echo", '\n'.join(words)]
ps = subprocess.Popen(command, stdout=subprocess.PIPE)
result = subprocess.check_output([
_get_exec(), "-p", "WikiP | Word:"], s... | 5,301,296 |
def convert_numeric(dataframe: pd.DataFrame) -> pd.DataFrame:
"""Convert objects or numerics to downcasted nullable boolean, nullable integer, or nullable float data type if possible.
Parameters
----------
dataframe (pandas.DataFrame) : contains unconverted and non-downcasted columns
Returns
-... | 5,301,297 |
def conn_portal(webgis_config):
"""Creates a connection to an ArcGIS Portal."""
w_gis = None
try:
if cfg_webgis['profile']:
w_gis = GIS(profile=webgis_config['profile'])
else:
w_gis = GIS(webgis_config['portal_url'], webgis_config['username'], webgis_config['password'... | 5,301,298 |
def about():
"""
The about me page.
"""
about_page = Page.query.filter(name='about')
return render_template('blog/about.html', about=about_page, page='about') | 5,301,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.