content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def genmove(proc, colour, pluck_random=True):
""" Send either a `genmove` command to the client, or generate a random
move until it is accepted by the client """
if pluck_random and random() < 0.05:
for _count in range(100):
proc.stdin.write('1000 play %s %s\n' % (colour, random_vertex()... | 5,346,600 |
def geojson_to_meta_str(txt):
""" txt is assumed to be small
"""
vlayer = QgsVectorLayer(txt, "tmp", "ogr")
crs_str = vlayer.sourceCrs().toWkt()
wkb_type = vlayer.wkbType()
geom_str = QgsWkbTypes.displayString(wkb_type)
feat_cnt = vlayer.featureCount()
return geom_str, crs_str, feat_cnt | 5,346,601 |
def tdf_UppestID(*args):
"""
* Returns ID 'ffffffff-ffff-ffff-ffff-ffffffffffff'.
:rtype: Standard_GUID
"""
return _TDF.tdf_UppestID(*args) | 5,346,602 |
def blend_multiply(cb: float, cs: float) -> float:
"""Blend mode 'multiply'."""
return cb * cs | 5,346,603 |
def print_data_distribution(y_classes, class_names):
"""
:param y_classes: class of each instance, for example, if there are 3 classes, and y[i] is [1,0,0], then instance[i] belongs to class[0]
:param class_names: name of each class
:return: None
"""
count = np.zeros(len(class_names))
pro = ... | 5,346,604 |
def reorder_conj_pols(pols):
"""
Reorders a list of pols, swapping pols that are conjugates of one another.
For example ('xx', 'xy', 'yx', 'yy') -> ('xx', 'yx', 'xy', 'yy')
This is useful for the _key2inds function in the case where an antenna
pair is specified but the conjugate pair exists in the d... | 5,346,605 |
def dx_login(project_name):
"""
Check if user has logged into the system using dx toolkit
:return: boolean True is user has logged in else false
"""
cmd = ["dx", "whoami"]
try:
cmd_out = subprocess.check_output(cmd)
except subprocess.CalledProcessError as cp:
raise AssetBuil... | 5,346,606 |
def get_machine_from_uuid(uuid):
"""Helper function that returns a Machine instance of this uuid."""
machine = Machine()
machine.get_from_uuid(uuid)
return machine | 5,346,607 |
def select_loop_directional(edge, directional = True, direction = 0):
"""
*Bugs: Improve selection of edges that dont have two faces
Selects more than intended
FEATURES:
*Select border if the selection is in a border
"""
counter = 0
iterations = 0
selection = [edge]
selected = selection
new_selection ... | 5,346,608 |
def convert_numbers(text):
"""Convert numbers to number words"""
tokens = []
for token in text.split(" "):
try:
word = w2n.num_to_word(token)
tokens.append(word)
except:
tokens.append(token)
return " ".join(tokens) | 5,346,609 |
def init_emulator(rom: bytes):
""" For use in interactive mode """
emulator = NitroEmulator()
emulator.load_nds_rom(rom, True)
return emulator | 5,346,610 |
def sub_module_name_of_named_params(named_params: kParamDictType, module_name_sub_dict: Dict[str, str]) \
-> Union[Dict[str, nn.Parameter], Dict[str, torch.Tensor]]:
"""Sub named_parameters key's module name part with module_name_sub_dict.
Args:
named_params: Key-value pair of param name and param ... | 5,346,611 |
def add_mongodb_document(
m_client_db=get_mongodb_database(),
collection=None,
index_name=None,
doc_type=None,
doc_uuid=None,
doc_body=None
):
"""
Funtion to add a MongoDB document by providing index_name,
document type, document contents as doc and document id.
"""
status = { 'status_code' : 2... | 5,346,612 |
def my_func_1(x, y):
"""
Возвращает возведение числа x в степень y.
Именованные параметры:
x -- число
y -- степень
(number, number) -> number
>>> my_func_1(2, 2)
4
"""
return x ** y | 5,346,613 |
def test_run_model(fake_regression_data) -> alt.Chart:
"""Smoke test.
"""
res = run_model.run(fake_regression_data,
y='y',
X=['x1', 'x2', 'x3', 'x4'])
assert isinstance(res, RegressionResultsWrapper) | 5,346,614 |
def indexer_testapp(es_app):
""" Indexer testapp, meant for manually triggering indexing runs by posting to /index.
Always uses the ES app (obviously, but not so obvious previously) """
environ = {
'HTTP_ACCEPT': 'application/json',
'REMOTE_USER': 'INDEXER',
}
return webtest.Test... | 5,346,615 |
def BNN_like(NN,cls=tfp.layers.DenseReparameterization,copy_weight=False,**kwargs):
"""
Create Bayesian Neural Network like input Neural Network shape
Parameters
----------
NN : tf.keras.Model
Neural Network for imitating shape
cls : tfp.layers
Bayes layers class
copy_weight... | 5,346,616 |
def CreateRepository(repoDir):
""" Creates a Subversion repository """
try:
TimestampDir(repoDir) # renames previous repository if it already exists
Execute(r'%s create %s --fs-type fsfs' % (SVN_ADMIN_EXE, repoDir))
print 'Finished -- CreateRepository'
except Exception, e:
p... | 5,346,617 |
def flattenImageALFOSC(fn,outfn):
""" Flatten all ALFOSC image extentions """
import numpy
import pyfits
f = pyfits.open(fn)
h1 = f[1].header
d1 = f[1].data
d2 = f[2].data
f.close()
d = numpy.hstack((d1,d2))
hdu = pyfits.PrimaryHDU(d)
n = pyfits.HDUList([hdu])
n[0].header.update('AMPLMODE',... | 5,346,618 |
def matrix_mult(a, b):
"""
Function that multiplies two matrices a and b
Parameters
----------
a,b : matrices
Returns
-------
new_array : matrix
The matrix product of the inputs
"""
new_array = []
for i in range(len(a)):
new_a... | 5,346,619 |
def build_type(tp) -> Tuple[str, List[Type]]:
"""
Build typescript type from python type.
"""
tokens = tokenize_python_type(tp)
dependencies = [
token
for token in tokens
if token not in TYPE_MAPPING_WITH_GENERIC_FALLBACK
and not type(token) in TRIVIAL_TYPE_MAPPING
... | 5,346,620 |
def laplacian_radial_kernel(distance, bandwidth=1.0):
"""Laplacian radial kernel.
Parameters
----------
distance : array-like
Array of non-negative real values.
bandwidth : float, optional (default=1.0)
Positive scale parameter of the kernel.
Returns
-------
weight : ar... | 5,346,621 |
def build_eslog_config_param(
group_id,
task_name,
rt_id,
tasks,
topic,
table_name,
hosts,
http_port,
transport,
es_cluster_name,
es_version,
enable_auth,
user,
password,
):
"""
es参数构建
:param group_id: 集群名
:param task_name: 任务名
:param rt_id: rt... | 5,346,622 |
def greet_user(username):
# Docstring - used for documentation of functions
"""Display a simple greeting."""
print("Hello, " + username.title() + "!") | 5,346,623 |
def test_crud__EditForm__2(address_book, browser):
"""Editing the addressbook can be canceled."""
address_book.title = u'ftest-ab'
browser.login('mgr')
browser.open(browser.ADDRESS_BOOK_DEFAULT_URL)
browser.getLink('Master data').click()
browser.getLink('Address book').click()
assert browser... | 5,346,624 |
def disclosure(input_df, cur_period):
"""
Reading in a csv, converting to a data frame and converting some cols to int.
:param input_df: The csv file that is converted into a data frame.
:param cur_period: The current period for the results process.
:return: None.
"""
input_df = pd.read_csv... | 5,346,625 |
def assert_c0_L0_mod(s: Section, attr: Any) -> None:
"""Assert after child0, leaf0 have a modification."""
assert s(attr) == [10, '2', '3']
assert s.children(attr) == [10, '2', '3']
assert s.leaves(attr) == [0, '1', '2', '3']
assert s[0](attr) == 10
assert s[0].leaves(attr) == [0, '1']
asser... | 5,346,626 |
def get_all_file_paths(directory):
"""
Gets all the files in the specified input directory
"""
file_paths = []
for root, _, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths | 5,346,627 |
def save_result(save_path, bbox_res, catid2name, threshold):
"""
save result as txt
"""
with open(save_path, 'w') as f:
for dt in bbox_res:
catid, bbox, score = dt['category_id'], dt['bbox'], dt['score']
if score < threshold:
continue
# each bb... | 5,346,628 |
def kitchen_sink():
"""Combines all of the test data."""
return word_frequencies.load(_KITCHEN_SINK_DATA) | 5,346,629 |
def sim_matrix(a, b, eps=1e-8):
"""
added eps for numerical stability
"""
a = normalize_embeddings(a, eps)
b = normalize_embeddings(b, eps)
sim_mt = torch.mm(a, b.transpose(0, 1))
return sim_mt | 5,346,630 |
def delete_model(name, force=False):
"""Permanently deletes the given model from local and remote storage.
CAUTION: this cannot be undone!
Args:
name: the name of the model, which can have "@<ver>" appended to refer
to a specific version of the model. If no version is specified, the
... | 5,346,631 |
def read_addon_xml(path):
"""Parse the addon.xml and return an info dictionary"""
info = dict(
path='./', # '/storage/.kodi/addons/plugin.video.vrt.nu',
profile='special://userdata', # 'special://profile/addon_data/plugin.video.vrt.nu/',
type='xbmc.python.pluginsource',
)
tree... | 5,346,632 |
def get_submission_list(start_timestamp, end_timestamp, args=None):
"""
Scrapes a subreddit for submissions between to given dates. Due to limitations
of the underlying service, it may not return all the possible submissions, so
it will be necessary to call this method again. The method requests the res... | 5,346,633 |
def test_invalid_hopping_matrix():
"""
Check that an error is raised when the passed size does not match the
shape of hopping matrices.
"""
with pytest.raises(ValueError):
tbmodels.Model(size=2, hop={(0, 0, 0): np.eye(4)}) | 5,346,634 |
def loadDataSet():
"""
load data from data set
Args:
Returns:
dataSet: train input of x
labelSet: train input of y
"""
# initialize x-trainInput,y-trainInput
dataSet = []
labelSet = []
# open file reader
fr = open('testSet.txt')
for line in fr.readlines():
# strip() -- get rid of the space on bot... | 5,346,635 |
def xds_read_xparm_new_style(xparm_file):
"""Parse the XPARM file to a dictionary."""
data = map(float, " ".join(open(xparm_file, "r").readlines()[1:]).split())
starting_frame = int(data[0])
phi_start, phi_width = data[1:3]
axis = data[3:6]
wavelength = data[6]
beam = data[7:10]
spac... | 5,346,636 |
def clear_bit(val, offs):
"""Clear bit at offset 'offs' in value."""
return val & ~(1 << offs) | 5,346,637 |
def get_org_details(orgs):
"""Get node and site details, store in Org object"""
org_details = []
for org in orgs:
org_id = org['id']
org_name = org['name']
org_longname = org['longname']
Org = namedtuple('Org', ['org_id', 'org_name', 'org_longname'])
org_details.exten... | 5,346,638 |
def decrypt(ctx, input_file, output_file):
"""Decrypt CSE configuration file."""
SERVER_CLI_LOGGER.debug(f"Executing command: {ctx.command_path}")
console_message_printer = utils.ConsoleMessagePrinter()
utils.check_python_version(console_message_printer)
try:
try:
password = os.... | 5,346,639 |
def flipFast(index, s, T, rand, neighs, bonds):
"""
Much more efficient version of _oneSweep MC
input:
index: spin to attempt flipping
s: spin configuration
T: temperature
rand: a uniform random float
neighs: list of neighboring sites to index
bonds: list of b... | 5,346,640 |
def slot_size_selection():
"""
Plots the latency and number of slots needed to encode repeater protocols for
a few different levels of fidelity for both cases when two nodes are connected
or separated by two hops
:return: None
"""
link_length = 5
topology = gen_line_topology(num_end_node... | 5,346,641 |
def flush_after(handler, delay):
"""Add 'handler' to the queue so that it is flushed after 'delay' seconds by the flush thread.
Return the scheduled event which may be used for later cancellation (see cancel()).
"""
if not isinstance(handler, logging.Handler):
raise TypeError("handler must be ... | 5,346,642 |
def _ExtractCLPath(output_of_where):
"""Gets the path to cl.exe based on the output of calling the environment
setup batch file, followed by the equivalent of `where`."""
# Take the first line, as that's the first found in the PATH.
for line in output_of_where.strip().splitlines():
if line.startswith('LOC:'... | 5,346,643 |
def test_graph_get_node(full_graph):
"""Passing get_node an invalid node raises a KeyError."""
assert full_graph.get_node('top1') == {'mid1': 78, 'mid2': 113}
assert full_graph.get_node('mid2') == {'third4': 78, 'third5': 91} | 5,346,644 |
def model_location(model):
"""
Set ODAHUFLOW_MODEL_LOCATION_ENV_VAR to `model` if `model` is not None
Add ODAHUFLOW_MODEL_LOCATION_ENV_VAR to sys.path
Clean state in context manager exit
:param model:
:return:
"""
model_location_for_use = original_model_location = os.environ.get(ODAHUFL... | 5,346,645 |
def getprotobyname(*args,**kw):
"""getprotobyname(name) -> integer
Return the protocol number for the named protocol. (Rarely used.)"""
pass | 5,346,646 |
async def test_bad_coin_name(get_auto_switching_and_profits_statistics_response):
"""Tests an API call with a non-existent coin name"""
session = aiohttp.ClientSession()
miningpoolhubapi = MiningPoolHubAPI(session=session)
assert miningpoolhubapi.api_key_set() is True
with aioresponses() as m:
... | 5,346,647 |
def logGamma(x):
"""The natural logarithm of the gamma function.
Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz<BR>
Applied Mathematics Division<BR>
Argonne National Laboratory<BR>
Argonne, IL 60439<BR>
<P>
References:
<OL>
<LI>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for ... | 5,346,648 |
def regional_validity(query_point, regional_inclusion, regional_exclusions):
""" regional_validity
Returns whether a coordinate point is inside a polygon and outside of excluded regions.
Input: A Point object, a Polygon Object of the inclusion region; a list of Polygon Objects of excluded regions.
Output: True if t... | 5,346,649 |
def get_word_vector_list(doc, w2v):
"""Get all the vectors for a text"""
vectors = []
for word in doc:
try:
vectors.append(w2v.wv[word])
except KeyError:
continue
return vectors | 5,346,650 |
def solve(lines, n):
"""Apply the rules specified in the input lines to the starting
pattern for n iterations.
The number of lit pixels in the final pattern is returned.
"""
rules = load_rulebook(lines)
pattern = START
for _ in range(n):
pattern = enhance(pattern, rules)
return s... | 5,346,651 |
def _to_plotly_color(scl, transparence=None):
"""
converts a rgb color in format (0-1,0-1,0-1) to a plotly color 'rgb(0-255,0-255,0-255)'
"""
plotly_col = [255 * _c for _c in mplc.to_rgba(scl)] if len(scl) == 3 else [255 * _c for _c in mplc.to_rgb(scl)]
if transparence is not None:
assert 0.... | 5,346,652 |
def dense_attention_block(seqs_repr, is_training, num_layers,
decay_variable, decay_constant,
units, dropout, query_dropout,
l2_scale, name=''):
"""
"""
for i in range(num_layers):
with tf.variable_scope('dense_attention{}'.format... | 5,346,653 |
def reset_get_unique_name():
"""Reset the heaps that store previously-assigned names."""
global name_heap, prefix_counts
name_heap = set([None])
prefix_counts = collections.Counter() | 5,346,654 |
def _pp(data, title=None, prefix=''):
"""
pretty printer
:param data: single enty or list of key-value tuples
:param title: optional title
:param quiet: if true print only the values
"""
ctx = click.get_current_context()
if title is not None:
print(title)
if not isinstance(da... | 5,346,655 |
def generate_schema_type(app_name: str, model: object) -> DjangoObjectType:
"""
Take a Django model and generate a Graphene Type class definition.
Args:
app_name (str): name of the application or plugin the Model is part of.
model (object): Django Model
Example:
For a model wit... | 5,346,656 |
def do_authorize():
"""
Send a token request to the OP.
"""
oauth2.client_do_authorize()
try:
redirect = flask.session.pop("redirect")
return flask.redirect(redirect)
except KeyError:
return flask.jsonify({"success": "connected with fence"}) | 5,346,657 |
def run(number, gens, neat_stats, hyperneat_stats, es_hyperneat_small_stats,
es_hyperneat_medium_stats, es_hyperneat_large_stats):
"""
Run the experiments.
"""
print(f"This is run #{str(number)}")
neat_stats.append(neat_xor.run(gens)[1])
hyperneat_stats.append(hyperneat_xor.run(gens)[1])... | 5,346,658 |
def get_windows():
"""
Return all windows found by WM with CPU, fullscreen, process name, and class information.
"""
# Basic window information
result = check_output('nice -n 19 wmctrl -l -p', shell=True)
lines = [a for a in result.decode('utf8').split('\n') if a != '']
windows = [re.split(r... | 5,346,659 |
def get_google_open_id_connect_token(service_account_credentials):
"""Get an OpenID Connect token issued by Google for the service account.
This function:
1. Generates a JWT signed with the service account's private key
containing a special "target_audience" claim.
2. Sends it to the OAUTH_TOKEN_U... | 5,346,660 |
def test_date_expression(
dask_client, # pylint: disable=redefined-outer-name,unused-argument
):
"""Test of expressions handling dates.."""
ds = make_dataset(5 * 24)
partitioning = Date(("dates", ), "D")
for partition, _ in partitioning.split_dataset(ds, "num_lines"):
variables = dict(... | 5,346,661 |
def main():
"""
Handles the execution of the code
"""
parser = argparse.ArgumentParser()
parser.add_argument("--snpEff_jar", default=None, required=False,
help="path of local snpEff jar")
parser.add_argument("--vcf", type=str, required=True,
help="... | 5,346,662 |
def term_to_atoms(terms):
"""Visitor to list atoms in term."""
if not isinstance(terms, list):
terms = [terms]
new_terms = []
for term in terms:
if isinstance(term, And):
new_terms += term_to_atoms(term.to_list())
elif isinstance(term, Or):
new_terms += te... | 5,346,663 |
def expr_max(argv):
"""
Max aggregator function for :class:`Expression` objects
Returns
-------
exp : :class:`Expression`
Max of given arguments
Examples
--------
>>> x = so.VariableGroup(10, name='x')
>>> y = so.expr_max(2*x[i] for i in range(10))
"""
return expr... | 5,346,664 |
def test_get_url(test_dict: FullTestDict, page_number: int):
"""
- GIVEN a list of words and a page number
- WHEN the url is generated
- THEN test it is returns the expected url
"""
word_list = convert_list_of_str_to_kaki(test_dict['input'])
expected_url = test_dict['ojad']['url'] % page_num... | 5,346,665 |
def handle_size(bytes_in=False, bytes_out=False):
"""
a function that converts bytes to human readable form. returns a
string like: 42.31 TB. example:
your_variable_name = make_readable(value_in_bytes)
"""
tib = 1024 ** 4
gib = 1024 ** 3
mib = 1024 ** 2
kib = 1024
if bytes_in:
... | 5,346,666 |
def return_elapsed(gs):
"""Returns a description of the elapsed time of recent operations.
Args:
gs: global state.
Returns:
A dictionary containing the count, minimum elapsed time,
maximum elapsed time, average elapsed time, and list of elapsed time
records.
"""
assert isinstance(gs, global_state.... | 5,346,667 |
def mirror():
"""Runs dump, sync_media, sync_dump and sqlimport."""
dump()
sync_dump()
local('python manage.py sqlimport')
sync_media() | 5,346,668 |
def calculate_per_class_lwlrap(truth, scores):
"""Calculate label-weighted label-ranking average precision.
Arguments:
truth: np.array of (num_samples, num_classes) giving boolean ground-truth
of presence of that class in that sample.
scores: np.array of (num_samples, num_classes) giving the classi... | 5,346,669 |
def test_uci_getLineParts():
"""
Test the UCI getLineParts utility function
"""
from paradrop.lib.utils import uci
line = "config interface wan"
result = uci.getLineParts(line)
assert result == line.split()
# It should eat the apostrophes and give same result.
line2 = "config 'inte... | 5,346,670 |
def chan_faces(n1: int, n2: int, xform,
dim1: Tuple[float, float, float, float],
dim2: Tuple[float, float, float, float]):
"""
^y
| 0--------7
| | |
| | 5-----6
| | |
+--|--|-------> z
| |
| 4-----3
| |
1--------... | 5,346,671 |
def generate_manifest(name, p, h=None):
""" generate_manifest(name, p, h) -> mapping
Generates a mapping used as the manifest file.
:param name: a dotted package name, as in setup.py
:param p: the zip file with package content.
:param h: optional hash function to use.
:ret... | 5,346,672 |
def benchrun(methods,
model,
case_args,
filename,
cpus=1,):
"""
Parameters
----------
methods : list of str
Voter systems to be assessed by the election model.
model : func
Election model running function as
... | 5,346,673 |
def retry( exceptions,times=3,sleep_second=0):
"""
Retry Decorator
Retries the wrapped function/method `times` times if the exceptions listed
in ``exceptions`` are thrown
:param times: The number of times to repeat the wrapped function/method
:type times: Int
:param Exceptions: Lists of exceptions... | 5,346,674 |
def positiveId(obj):
"""Return id(obj) as a non-negative integer."""
result = id(obj)
if result < 0:
result += _address_mask
assert result > 0
return result | 5,346,675 |
def get_vroitems_from_package(package):
"""Get all the items from the vRO Package.
Args:
package (str): Path to a package file.
Returns:
VROElementMetadata[]: a list of VROElementMetadata.
"""
vro_items_id, vro_items = [], []
with zipfile.ZipFile(package, 'r') as zip_ref:
... | 5,346,676 |
def compute_annualized_total_return_over_months(df, column_price, months):
"""
Computed the annualized total return over the specified number of months.
This is equivalent to Compound Annual Growth Rate (CAGR).
Note: If the period is less than one year, it is best not to use annualized total return as... | 5,346,677 |
def build_sparse_ts_from_distributions(start_date, end_date, seasonalities, time_interval, dist_dict, **kwargs):
"""constructs a time series with given distributions and seasonalities in a given frequency time_interval"""
ts_list = []
for (name, dist), seasonality in zip(dist_dict.items(), seasonalities):
... | 5,346,678 |
def preprocess_label(labels, scored_classes, equivalent_classes):
""" convert string labels to binary labels """
y = np.zeros((len(scored_classes)), np.float32)
for label in labels:
if label in equivalent_classes:
label = equivalent_classes[label]
if label in scored_classes:
... | 5,346,679 |
def compile_on_disk(source_file: str,
parser_name: str = '',
compiler_suite: str = "",
extension: str = ".xml") -> Iterable[Error]:
"""
Compiles the a source file with a given compiler and writes the
result to a file.
If no ``compiler_suite`` ... | 5,346,680 |
def load_settings(filename='settings.yaml'):
"""Read settings from a file.
Keyword arguments:
filename -- the source file (default settings.yaml)
"""
with open(filename, 'r') as settings_yaml:
logging.debug("Reading settings from file: %s", filename)
return yaml.load(settings_yaml) | 5,346,681 |
def enforce_types(data):
"""Convert lists to sets.
"""
# We properly set 'title', 'text', 'pretext' and 'alias' as unicode
for _, node in data.iter_all_nodes():
# This avoid warnings about mix of types in 'rank' later
if node.data['alias'] is not None:
node.data['alias'] = un... | 5,346,682 |
def pytest_configure(config):
"""
pytest hook, used here to register custom marks to get rid of spurious
warnings
"""
config.addinivalue_line(
"markers", "mock_device_proxy: the test requires tango.DeviceProxy to be mocked"
) | 5,346,683 |
def main():
""" Hook for command line interface """
npix = (1800, 900)
skydir_gc = coordinates.SkyCoord(0., 0., frame=coordinates.Galactic, unit="deg")
wcs_gc = create_wcs(skydir_gc, coordsys='GAL', projection="AIT",
cdelt=0.2, crpix=(900.5, 450.5))
t_all = table.Table.read... | 5,346,684 |
def extract_ocr_region(
datasets_root_path,
img_extracted_path,
labels_out_path
):
"""
Description:
To extract ocr regions from the raw imgs,
and record corresponding label.
params:
path_with_raw_imgs_and_labels,
path to save imgs extracted,
path to s... | 5,346,685 |
def vec_abs(field: SampledField):
""" See `phi.math.vec_abs()` """
if isinstance(field, StaggeredGrid):
field = field.at_centers()
return field.with_values(math.vec_abs(field.values)) | 5,346,686 |
def print_filters():
"""This method will print list of filters fields used by ``buildtest build --filter``. This method is invoked by
running ``buildtest build --helpfilter``.
"""
table = Table("[blue]Field", "[blue]Description", title="Buildtest Filters")
table.add_row("[green]tags", "[red]Filter ... | 5,346,687 |
def spoofRequest(app):
"""
Make REQUEST variable to be available on the Zope application server.
This allows acquisition to work properly
"""
_policy=PermissiveSecurityPolicy()
_oldpolicy=setSecurityPolicy(_policy)
newSecurityManager(None, OmnipotentUser().__of__(app.acl_users))
info = ... | 5,346,688 |
def plot_precision_recall(AP, precisions, recalls):
"""Draw the precision-recall curve.
AP: Average precision at IoU >= 0.5
precisions: list of precision values
recalls: list of recall values
"""
# Plot the Precision-Recall curve
_, ax = plt.subplots(1)
ax.set_title("Precision-Recall Cur... | 5,346,689 |
def data_to_percentage(data_list: pd.DataFrame) -> pd.DataFrame:
"""
Takes a dataframe with one or more columns filled with digits and returns a
dataframe with the percentages corresponding to the number of times the
numbers 1-9 appear in each column.
Args:
data_list: a dataframe of integer... | 5,346,690 |
def is_not_none_or_whitespace(param_name: str, value_to_check: str) -> None:
"""
Raises ValueError if the value is None or a whitespace/empty string
:param param_name: Name of the parameter to validate
:param value_to_check: Value to of the parameter being validated
"""
if value_to_check is None... | 5,346,691 |
def create_classifier_from_encoder(data:DataBunch, encoder_path:str=None, path=None,
dropout1=0.5, device: torch.device = torch.device('cuda', 0), **kwargs):
"""Factory function to create classifier from encoder to allow transfer learning."""
from .models.models import Encod... | 5,346,692 |
def gz_compression(filepath, delete_source=True):
"""
Compress the given file using gzip.
Delete the source file if asked.
:param filepath: path pointing to the source file
:param delete_source: boolean indicating if the source file should be deleted
"""
# compress the file using gzip
... | 5,346,693 |
def clone(job):
"""
Action that creates a clone of a machine.
"""
service = job.service
vdc = service.parent
if 'g8client' not in vdc.producers:
raise j.exceptions.RuntimeError("No producer g8client found. Cannot continue clone of %s" % service)
g8client = vdc.producers["g8client"]... | 5,346,694 |
def test_force_overwrite_two_pages(overwrite_pages, tmp_path, setup_page):
"""Checks for multiple pages force overwrite flag is set <=> page is updated if author is changed"""
pages_obj = {1: {}, 2: {}}
config_file, (
pages_obj[1]["page_id"],
pages_obj[1]["page_title"],
pages_obj[2][... | 5,346,695 |
def filter_string(
df: pd.DataFrame,
column_name: Hashable,
search_string: str,
complement: bool = False,
case: bool = True,
flags: int = 0,
na=None,
regex: bool = True,
) -> pd.DataFrame:
"""Filter a string-based column according to whether it contains a substring.
This is supe... | 5,346,696 |
def on_demand_feature_view(
features: List[Feature], inputs: Dict[str, Union[FeatureView, RequestDataSource]]
):
"""
Declare an on-demand feature view
:param features: Output schema with feature names
:param inputs: The inputs passed into the transform.
:return: An On Demand Feature View.
"... | 5,346,697 |
def get_error_string(ftdi):
"""
get_error_string(context ftdi) -> char *
Get string representation for last error code
Parameters:
-----------
ftdi: pointer to ftdi_context
Returns:
--------
Pointer: to error string
"""
errstr = ftdi_get_error_string(ftdi)
retur... | 5,346,698 |
def DenseNet52k12(growth_rate = 12,
reduction = 0.5):
"""
Parameters:
----------
Returns
-------
"""
return DenseNet(reduction = reduction,
growth_rate = growth_rate,
layers=52) | 5,346,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.