content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def bagnet9(**kwargs):
"""
BagNet-9 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
... | 5,297,000 |
def test_detail_view_return_Entry_instance_and_vals_of_correct_model_id(dummy_request):
"""Update view response has file content."""
from learning_journal.views.default import detail_view
first_entry = Entry(
title='Test',
creation_date='01/23/45',
body='Test should pass!'
)
... | 5,297,001 |
def create_df(dass_words, dfcp_words):
"""
this function creates a dictionary, that keeps track of each occurance of a word in a 'dass' context and 'dfcp' context
it returns this dictionary
"""
dass = {}
dfcp = {}
data = [dass, dfcp]
for listed_values in dass_words: # access single lis... | 5,297,002 |
def running_mean_axis2(cube, window, out):
"""Fast moving average for 3D array along last dimension.
Pass out = cube.copy() to keep original values at the ends (half window).
"""
assert window % 2 > 0, "Window must be odd!"
half = int(window / 2.0)
for i in range(cube.shape[0]):
for j... | 5,297,003 |
def t(message):
"""Replace $country and $language in message with dat from settings"""
tpl = string.Template(message)
return tpl.substitute(country=settings.COUNTRY_NAME, language=settings.LANGUAGE_NAME) | 5,297,004 |
def login_handler(fn):
"""
A decorator to redirect users to AWS Cognito login if they aren't already.
If already logged in user will redirect redirect uri.
Use this decorator on the login endpoint.
This handle will not return to handle the respose rather redirect to
redirect uri.
"""
@wr... | 5,297,005 |
def test_pytest_marker_with_kwargs_native_encoding(executed_docstring_source):
"""
>>> import pytest
>>> @pytest.mark.marker(stuff='я')
... def test_pytest_marker_with_kwargs_native_encoding_example():
... pass
"""
assert_that(executed_docstring_source.allure_report,
ha... | 5,297,006 |
def launch(tenant, addrs=DEFAULT_ADDRESS, period=DEFAULT_PERIOD):
""" Initialize the module. """
return RSSITracker(tenant, addrs=addrs, every=period) | 5,297,007 |
def open_webpage(browser, url, case, version, package):
"""
Opens the URL in desired browsers.
:param browser: Browser
:param url: Case URL
:param case: Case to be collected
:param version: Browser version
:param package: Browser package name
:return: None
"""
browser_obj = Brows... | 5,297,008 |
def test_score_with_sample_weight():
"""Assert that the score method works when sample weights are provided."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
atom.run("Tree")
score = atom.tree.score(X_bin, y_bin, sample_weight=list(range(len(y_bin))))
assert isinstance(score, np.float64) | 5,297,009 |
def train_transformer(net, data_iter, lr, num_epochs, tgt_vocab):
"""训练序列到序列模型"""
optimizer = nn.Adam(net.trainable_params(), lr)
loss = MaskedSoftmaxCELoss()
net_with_loss = NetWithLossCh8_Seq2seq(net, loss)
train = TrainCh8(net_with_loss, optimizer, 1)
animator = Animator(xlabel='epoch', ylab... | 5,297,010 |
def test_should_throw_error(name, constructor):
""""Check whether ValueError is thrown when name length is invalid"""
with pytest.raises(ValueError, match='Name must be 1 to 255 chars long'):
constructor(name=name, category_id=1) | 5,297,011 |
def register(cls_obj=None, encode=None, decode=None):
"""Register a serializer class.
By default the serializer will use the class type "__getstate__" and "__setstate__" methods if an encode and decode
method is not given.
Args:
cls_obj (class/type): Class/Type/object to register the serialize... | 5,297,012 |
def test_validate_empty_roles_claim_value(make_lti13_resource_link_request):
"""
Is the JWT valid with an empty roles claim value?
"""
validator = LTI13LaunchValidator()
jws = make_lti13_resource_link_request
jws["https://purl.imsglobal.org/spec/lti/claim/roles"] = ""
assert validator.valid... | 5,297,013 |
def runParentProcess():
"""父进程运行函数"""
# 创建日志引擎
print(u'启动行情记录守护父进程')
p = None # 子进程句柄
while True:
# 记录时间则需要启动子进程
if p is None:
print(u'启动子进程')
p = multiprocessing.Process(target=runChildProcess)
p.daemon = True
p.start(... | 5,297,014 |
def random_resize(image, min_image_size, max_image_size, max_out_prob=0.,
resize_method=tf.image.ResizeMethod.BILINEAR):
"""Randomly resize the image while preserving aspect ratio.
Args:
image: 3D image tensor.
min_image_size: minimum size for the longer side of the image.
max_image_s... | 5,297,015 |
def broyden_class_update(y, s, mat, phi=0.0):
"""
Scale free implementation of the broyden class update scheme.
:param y:
difference in gradient
:param s:
search direction in previous step
:param mat:
current hessian approximation
:param phi:
convex combination p... | 5,297,016 |
def main():
"""用来完成整体的控制"""
# 1. 创建套接字
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#为了确保端口复用
tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 2. 绑定
tcp_server_socket.bind(("", 7890))
# 3. 变为监听套接字
tcp_server_socket.listen(128)
... | 5,297,017 |
def resolve_jobs(job_counts, start, length):
"""
:param job_counts: list of blocks(queue, registry, job_count)
:param start: job start index for datatables
:param length: number of jobs to be returned for datatables
:return: list of jobs of len <= "length"
It may happen during processing some j... | 5,297,018 |
def star(x, y, points=20, outer=100, inner=50, **kwargs):
""" Draws a star with the given points, outer radius and inner radius.
The current stroke, strokewidth and fill color are applied.
This is about 20x slower than fast_star; use it only if you need the path returned.
"""
p = BezierPath(... | 5,297,019 |
def writeBatch(batchfile, fastfiles, fastExe=None):
""" Write batch file, everything is written relative to the batch file"""
if fastExe is None:
fastExe=FAST_EXE
fastExe_abs = os.path.abspath(fastExe)
batchfile_abs = os.path.abspath(batchfile)
batchdir = os.path.dirname(batchfile_abs... | 5,297,020 |
def hinton(matrix, 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).max()) / np.log(2))
ax.patch.set_facecolor('gray')
ax.set_aspect('equal', 'bo... | 5,297,021 |
def usage(code, msg=""):
"""Display help."""
print("\n".join(__doc__.split("\n")[:-2]), file=sys.stderr)
if msg:
print("** Error: " + str(msg) + " **", file=sys.stderr)
sys.exit(code) | 5,297,022 |
def q_in_valid_range(q):
"""
Asserts that q is either 1, 2 or 3.
For other values, the formulas have not been implemented.
"""
assert 1 <= q <= 3, "Please enter q in {1,2,3}"
return True | 5,297,023 |
def sha512_first_half(message: bytes) -> bytes:
"""
Returns the first 32 bytes of SHA-512 hash of message.
Args:
message: Bytes input to hash.
Returns:
The first 32 bytes of SHA-512 hash of message.
"""
return hashlib.sha512(message).digest()[:32] | 5,297,024 |
def find_svc_icon(id):
"""
Locate the absolute path of an ICON for a AWS service.
:type id: str
:param id: service id, for main service it is ``ec2``, for sub service it is
``ec2-instances``
:rtype: str
"""
if id in svc_icon_mapper:
return Icons.abspath(svc_icon_mapper[id])... | 5,297,025 |
def order_parquet_files_into_batches(parquet_files):
"""
Order the parquet files by searching for a digit within their name.
Returns the parquet files without their numbering or extension.
Parameters
----------
parquet_files : List
List of parquet files to be ordered.
"""
ordere... | 5,297,026 |
def acall(method, arg, cb):
"""Asynchronous send to margo.
"""
gs.mg9_send_q.put((method, arg, cb)) | 5,297,027 |
def get_xml_temperature (root):
"""
Get the temperature from the unit diagnostics XML.
Parameters:
root -- An XML element to the root of the unit diagnostics.
Return:
The system temperature or -1 if the temperature redaing isn't valid.
"""
if (get_xml_string_va... | 5,297,028 |
def median(arr: list):
"""
Returns the median and its index in the array.
"""
indices = []
list_size = len(arr)
median = 0
if list_size % 2 == 0:
indices.append(int(list_size / 2) - 1) # -1 because index starts from 0
indices.append(int(list_size / 2))
median = (arr... | 5,297,029 |
def _sample_many(
logp_dlogp_func: Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]],
model_ndim: int,
draws: int,
tune: int,
chain: int,
chains: int,
start: list,
random_seed: list,
step,
discard_tuned_samples=True,
callback=None,
**kwargs,
):
"""
Sample all ... | 5,297,030 |
def test_store_user_othererror(mocker):
"""Tests the store user function Database commit raises a differerent error."""
mocker.patch('app.dbops.AppUser')
mocked_db = mocker.patch('app.dbops.db')
mocked_db.session.commit.side_effect = Exception()
with pytest.raises(Exception):
store_user('foo... | 5,297,031 |
def init():
"""
Initialize all Endpoint(s) found
It shall be called with a Flask Application Context,
otherwise, it will fail
Raises:
RuntimeError: If called outside of an Application Context
"""
for endpoint in _endpoints.values():
endpoint() | 5,297,032 |
def plot_confusion_matrix(cm, classes, title="Матрица ошибок", cmap=plt.cm.winter):
"""
Визуализация матрицы ошибок с помощью Matplotlib
cm - матрица ошибок
cmap - стиль оформления
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title, fontsize=30)
plt.colorbar()
tic... | 5,297,033 |
def test_save_watchlist(browser):
"""
A saved watchlist should show the same results on the dashboard
"""
browser.visit(f"{settings.BASE_URL}search")
checkbox = browser.find_by_css("input[name=priority][value='UNKNOWN']")
checkbox.find_by_xpath("./following-sibling::label").click()
checkbo... | 5,297,034 |
def add_nonce_func(
string_array: Union[str, int, float, np.array]
) -> Union[str, int, float, np.array]:
"""
Add random prefix and suffix to an array of strings ``string_array``
This function takes an array of strings passed as ``string_array`` and
attaches nonces (random prefix and suffix) to eac... | 5,297,035 |
def rename_block_mesh(block_mesh_template_path, foam_files_templates):
"""rename the template to blockMeshDict, and leave in the templates folder for now.
Args:
block_mesh_template_path (str): full path of edited blockmesh template.
Returns:
blockMeshDict_for_run (str): renamed edited... | 5,297,036 |
def kmeanspp(matrix, k, *, msr=2, prior=0., seed=0, ntimes=1, lspp=0, expskips=0, n_local_trials=1, weights=None):
"""
Compute kmeans++ over the input matrix for given parameters.
Inputs:
Input matrix: sp.csr_matrix, minicore.CSparseMatrix, or numpy.ndarray
Second argument (k=) can... | 5,297,037 |
def find_constant_lengths(feature, tol=1e-6):
"""
Find lengths of all constant periods in feature data.
Parameters
----------
feature: Numpy array (shape: N)
Vector with feature data for all time
tol: Float (default=1e-2)
What scale factor is applied to variance to determine va... | 5,297,038 |
def endpoint_from_flag(flag):
"""The object used for interacting with relations tied to a flag, or None.
"""
relation_name = None
value = _get_flag_value(flag)
if isinstance(value, dict) and 'relation' in value:
# old-style RelationBase
relation_name = value['relation']
elif flag... | 5,297,039 |
def eliminate_stim_artifact(raw, events, event_id, tmin=-0.005,
tmax=0.01, mode='linear'):
"""Eliminates stimulations artifacts from raw data
The raw object will be modified in place (no copy)
Parameters
----------
raw : Raw object
raw data object.
events : ... | 5,297,040 |
def fast_nms(multi_bboxes,
multi_scores,
multi_coeffs,
score_thr,
iou_thr,
top_k,
max_num=-1):
"""Fast NMS in `YOLACT <https://arxiv.org/abs/1904.02689>`_.
Fast NMS allows already-removed detections to suppress other detections so
... | 5,297,041 |
def get_abs_path(in_path):
"""
Given a relative or absolute path, return the absolute path.
:param in_path:
:return:
"""
if os.path.isabs(in_path):
return in_path
else:
return os.path.abspath(in_path) | 5,297,042 |
def is_(a: object, b: object) -> bool:
"""
Return `a is b`, for _a_ and _b_.
Example:
>>> is_(object())(object())
False
Args:
a: left element of is expression
b: right element of is expression
Return:
`True` if `a is b`, `False` otherwise
"""
return... | 5,297,043 |
def WriteReactionsToMetabolitesNetwork(model, filename, ExtReacs=[], ExtMets=[]):
""" ExtReacs = []; ExtMets = [reac_id] """
rm = pandas.DataFrame(columns=['reaction','metabolite','stoichiometry'])
for reac in model.reactions:
if reac.id not in ExtReacs:
mets = reac.metabolites
... | 5,297,044 |
def recurse_sigfig(per_offset_data, num_digits):
"""
Recurse through a dictionary of offset data. Any impacts to ecosystem
services will be rounded to `num_digits` significant figures.
Parameters:
per_offset_data(dict): A dictionary of values, mapping string parcel
IDs to dictionar... | 5,297,045 |
def generate_vpt_title(radar, field):
"""
Generate a title for a VPT plot.
Parameters
----------
radar : Radar
Radar structure.
field : str
Field plotted.
Returns
-------
title : str
Plot title.
"""
time_str = generate_radar_time_begin(radar).isofor... | 5,297,046 |
def test_is_digit():
"""Check is_digit"""
if is_digit("1") is False:
print(is_digit("1"))
raise AssertionError
if is_digit("a") is True:
print(is_digit("a"))
raise AssertionError
if is_digit('"') is True:
print(is_digit('"'))
raise AssertionError | 5,297,047 |
def update_stats_count(today: str) -> None:
"""Counts the # of all house numbers as of today."""
statedir = config.get_abspath("workdir/stats")
csv_path = os.path.join(statedir, "%s.csv" % today)
count_path = os.path.join(statedir, "%s.count" % today)
city_count_path = os.path.join(statedir, "%s.cit... | 5,297,048 |
def get_event_bus_policy(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEventBusPolicyResult:
"""
Resource Type definition for AWS::Events::EventBusPolicy
"""
__args__ = dict()
__args__['id'] = id
if opts is None:
opts = pul... | 5,297,049 |
def get_logger(name, path, fname):
"""create a logger and return
"""
logger = logging.getLogger(name)
file_log_handler = logging.FileHandler(os.path.join(path, fname))
stderr_log_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(file_log_handler)
logger.addHandler(stderr_log_han... | 5,297,050 |
def scan_list(request):
"""
The function listing all ZAP Web scans.
:param request:
:return:
"""
all_scans = zap_scans_db.objects.filter(rescan='No')
rescan_all_scans = zap_scans_db.objects.filter(rescan='Yes')
return render(request,
'scan_list.html',
... | 5,297,051 |
def gen_resource_organization(elasticsearch_resource_dir, force=False):
"""Generate resource files for the organization analyzer."""
file_path_keep = os.path.join(elasticsearch_resource_dir, 'es_organization_keep.txt')
file_path_syn = os.path.join(elasticsearch_resource_dir, 'es_organization_synonyms.txt'... | 5,297,052 |
def _set_default_contact_rating(contact_rating_id: int, type_id: int) -> int:
"""Set the default contact rating for mechanical relays.
:param contact_form_id: the current contact rating ID.
:param type_id: the type ID of the relay with missing defaults.
:return: _contact_rating_id
:rtype: int
"... | 5,297,053 |
def calcMaxP():
"""maxP[i] has the value of p <= i that generates the most right triangles"""
mTris = 0
mP = 0
for p in range(5000001):
if(maxTris < numTriangles[p]): #found new max
maxP[p] = p
mP = p
mTris = numTriangles[p]
else:
maxP[p] =... | 5,297,054 |
def get_vector_info(vector_path, layer_id=0):
"""Get information about an GDAL vector.
Args:
vector_path (str): a path to a GDAL vector.
layer_id (str/int): name or index of underlying layer to analyze.
Defaults to 0.
Raises:
ValueError if ``vector_path`` does not exist... | 5,297,055 |
def create_report(user_options: UserOptions) -> Report:
"""
Analyse whether a Python package follows a set of contracts, returning a report on the results.
Raises:
InvalidUserOptions: if the report could not be run due to invalid user configuration,
such as a module that... | 5,297,056 |
def calc_rms(data, channel, num_channels, num_samples_per_channel):
""" Calculate RMS value from a block of samples. """
value = 0.0
index = channel
for _i in range(num_samples_per_channel):
value += (data[index] * data[index]) / num_samples_per_channel
index += num_channels
return ... | 5,297,057 |
def smiles_mol_generator(file_object, delimiter=None, header=True, mol_id=True):
""" A molecule generator for smi and txt files.
Parameters
----------
file_object : file
A file object
delimiter : str, default=None
The delimiter of the files. For smi ... | 5,297,058 |
def test_init_with_template_index(isolated_runner, project_init):
"""Test initialization with --template-index is deprecated."""
_, commands = project_init
# verify providing both index and id fails
result = isolated_runner.invoke(cli, commands["init_alt"] + commands["index"] + commands["force"])
... | 5,297,059 |
def _read_color_map(path, object_hook=None):
"""
Read a color map as json.
:param path (str): The path to read the map from.
:param object_hook (func): A Function to manipulate the json.
:return: A dictionary of color map.
"""
with open(path) as f:
return json.load(f, object_hook=obj... | 5,297,060 |
def train_forward_parameters(args, net, predictions, targets, loss_function,
forward_optimizer):
""" Train the forward parameters on the current mini-batch."""
if predictions.requires_grad == False:
# we need the gradient of the loss with respect to the network
# out... | 5,297,061 |
async def test_no_discovery_info_binary_sensor(hass, caplog):
"""Test setup without discovery info."""
assert SENSOR_DOMAIN not in hass.config.components
assert await async_setup_component(
hass,
SENSOR_DOMAIN,
{SENSOR_DOMAIN: {"platform": MODBUS_DOMAIN}},
)
await hass.async_... | 5,297,062 |
def device_of_devicendarray(devicendarray):
"""
Returns the device that backs memory allocated on the given
deviceNDArray
:param devicendarray: devicendarray array to check
:return: int device id
"""
dev = device_of_gpu_matrix(devicendarray)
return get_visible_devices()[dev] | 5,297,063 |
def create_warehouse() -> Warehouse:
"""Create a ware house."""
warehouse_yml = create_warehouse_yml()
warehouse = Warehouse(warehouse_yml)
return warehouse | 5,297,064 |
def transformer(model: str = 'xlnet', **kwargs):
"""
Load Transformer emotion model.
Parameters
----------
model : str, optional (default='bert')
Model architecture supported. Allowed values:
* ``'bert'`` - BERT architecture from google.
* ``'tiny-bert'`` - BERT architectur... | 5,297,065 |
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
await asyncio.gather(
*[
hass.async_add_executor_job(gateway.websocket_disconnect)
for gatew... | 5,297,066 |
def write_to_path(df: DataFrame, path_to_write: str = None) -> None:
"""
Write the dataframe to a local location.
Args:
df (DataFrame): dataframe to be written
path_to_write (str): path for csv file to write the file at
"""
if path_to_write is None:
path_to_write = f"file:/... | 5,297,067 |
def convertd2b(amount, x_pow, y_pow):
"""Apply the equation to get the result. Decimal to binary."""
res = amount * (10 ** x_pow / 2 ** y_pow)
return res | 5,297,068 |
def revtranslate(aa, dna, check=False):
"""Reverse translates aminoacids (with gaps) into DNA
Must supply original ungapped DNA.
"""
# trim stop codon
#if aa[-1] in "*X" and CODON_TABLE.get(dna[-3:], "") == "*":
# aa = aa[:-3]
# dna = dna[:-3]
a = len(aa.replace("-", "")) * 3... | 5,297,069 |
def plot_season_avg(
poll_df,
pollutant,
ax,
plot_error=True,
roll=True,
agg='max',
color='blue',
linestyle='solid',
linewidth=2, label=None, offset=182, draw=True, ci=95):
"""Plot the average by date of year. Good for looking seasonal pattern.... | 5,297,070 |
def task_3_list_customers_in_germany(cur) -> list:
"""
List the customers in Germany
Args:
cur: psycopg cursor
Returns: 11 records
"""
cur.execute("""SELECT * FROM Customers WHERE country='Germany'""")
return cur.fetchall() | 5,297,071 |
def recursive_replace(obj, key, val) -> None:
"""Find and replace a vector in a nested (mutable) structure.
Args:
obj: object to replace within
key: key to replace
val: value to replace with
"""
if isinstance(obj, dict):
if key in obj:
obj[key] = val
... | 5,297,072 |
def split_numpy_array(array, portion=None, size=None, shuffle=True):
"""Split NumPy array into two halves, by portion or by size.
Parameters
----------
array : np.ndarray
A NumPy array to be splitted.
portion : float
Portion of the second half. Ignored if `size` is specified.
... | 5,297,073 |
def testGetCaseDataByYearInParam():
"""[POSITIVE] Test Route /vaccination/yearly/2021 [get yearly cases by year]"""
testApp = createFlaskTestApp()
response = testApp.get('/vaccination/yearly/2021')
print(response.data)
decodedJson = json.loads(response.data)
assert response.status_code == 200
... | 5,297,074 |
def two_agents_three_actions() -> MACID:
"""This macim is a representation of a
game where two players must decide between
threee different actions simultaneously
- the row player is agent 1 and the
column player is agent 2 - the normal form
representation of the payoffs is as follows:
+... | 5,297,075 |
def add_spans():
"""Calls the opentracing API, doesn't use any LightStep-specific code.
"""
with opentracing.tracer.start_active_span('trivial/initial_request') as parent_scope:
parent_scope.span.set_tag('url', 'localhost')
sleep_dot()
parent_scope.span.log_event('All good here!', pa... | 5,297,076 |
def volume_unit_to_litres(symbol):
"""Convenience function that returns the factor one must multiply to convert a physical quantity with the specified
unit of volume into litres."""
return volume_units.get_scale_factor(symbol) | 5,297,077 |
def state_task_result_update(task_result, task_result_reason, task_work_result,
task_work_result_reason):
"""
Update State Task Result given a state task work result
"""
if STATE_TASK_WORK_RESULT.WAIT == task_result:
# Nothing to update
return task_result, ta... | 5,297,078 |
def createDBTable():
""" Used on install to create the necessary database table """
alchemyBase.metadata.create_all(alchemyEngine) | 5,297,079 |
def im_detect(net, im, _t, idx):
"""Detect object classes in an image given object proposals.
Arguments:
net (caffe.Net): Fast R-CNN network to use
im (ndarray): color image to test (in BGR order)
boxes (ndarray): R x 4 array of object proposals or None (for RPN)
Returns:
s... | 5,297,080 |
def find_page(pages, limit, value):
"""
Function to calculate and return the current page of a paginated result.
:param pages:
:param limit:
:param value:
:return:
"""
page_range = [limit * page for page in range(1, pages + 1)]
for index, my_range in enumerate(page_range):
if... | 5,297,081 |
def find_tuplets(part):
"""Identify tuplets in `part` and set their symbolic durations
explicitly.
This function adds `actual_notes` and `normal_notes` keys to
the symbolic duration of tuplet notes.
This function modifies the part in place.
Parameters
----------
part : :class:`Part`
... | 5,297,082 |
def kill(bot, trigger):
"""kill <user> -- Makes the bot kill <user>."""
target = trigger.group(2)
if " " in target:
notice("Invalid username!")
return
# if the user is trying to make the bot kill itself, kill them
if trigger.group(2) == bot.nick or trigger.group(2) == "itself":
... | 5,297,083 |
def get_gcloud_config_value(monkeypatch):
"""Returns predictable gcloud config values for testing.
Args:
monkeypatch: Fixture helper.
"""
def get_gcloud_config_value_for_tests(key, default=None):
"""Returns predictable gcloud config values for testing.
Args:
key: Config key to retrieve, e.g.... | 5,297,084 |
def dict_to_str(d):
"""Represent dictionary as string.
Represents a dictionary as a string. This is useful when
a representation for a filename is desired. The function
will unroll all keys and join their parameters with '_',
yielding a single string for the dictionary.
Parameters
--------... | 5,297,085 |
def compare(guess, answer):
"""
Compare guess and answer
Arguments:
guess -- a 4-digital number string of the guess.
answer -- a 4-digital number string of right answer.
Returns:
cow -- a number of the user guessed correctly in the correct place.
bull -- a number of the user gu... | 5,297,086 |
def discordance(CRITERIA, ACTIONS, PERFORMANCES, THRESHOLDS, CATEGORIES):
"""
Calculates the discordance matrix for a given reference profile.
:param CRITERIA: List containing the names of the criteria as strings.
:param ACTIONS: List containing the names of the actions as strings.
:param PERFORM... | 5,297,087 |
def mkid():
"""Generates a uuid4 (Example: 'f50ec0b7-f960-400d-91f0-c42a6d44e3d0') using the Python
uuid module
Returns:
string: a unique universal ID of type 4. (Example: 'f50ec0b7-f960-400d-91f0-c42a6d44e3d0')
"""
return str(uuid4()) | 5,297,088 |
def test_hasvalue_with_rule_each_doesnt_reload():
"""hasvalue with rule each doesnt reload.""" | 5,297,089 |
async def _process_recorder_platform(hass, domain, platform):
"""Process a recorder platform."""
hass.data[DOMAIN][domain] = platform | 5,297,090 |
def setup():
"""Function to setup the test."""
global profile
profile = Profile(prober=conv.prober_path)
profile.update(new_quality='MP4 Fullscreen (4:3)') | 5,297,091 |
def floorf(f):
"""
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_floorf.html
:param f: Argument.
:type f: float32
:rtype: float32
""" | 5,297,092 |
def colinterp(a, x):
"""Interpolates colors"""
l = len(a) - 1
i = min(l, max(0, int(x * l)))
(u, v) = a[i:i + 2, :]
return u - (u - v) * ((x * l) % 1.0) | 5,297,093 |
def pipeline_validates_with_error(context: object):
"""
The validation raised errors.
:param obj context: context object being passed through functions.
"""
with pytest.raises(ValueError):
context.validator.validate() | 5,297,094 |
def neural_network_2_layers(X, Y, n_1, num_iterations=10, learning_rate=0.01,
early_stop_cost=0., msg_interval=1, print_interval=100):
"""
X: [n_x, m] train data set
Y: [n_y, m] n_y=1 in this case
n_1: first hidden layer dimension
num_iterations: nu... | 5,297,095 |
def test_add_facility():
"""test_add_facility."""
workplace = BaseWorkplace("workplace")
facility = BaseFacility("facility")
workplace.add_facility(facility)
assert len(workplace.facility_list) == 1
assert facility.workplace_id == workplace.ID | 5,297,096 |
def _get_parent_node_by_pred(node, pred, search_current=False):
"""Find the first parent node that satisfies a predicate function."""
if not search_current:
node = node.parent
while node is not None:
if pred(node):
return node
node = node.parent
return None | 5,297,097 |
def hdf5_read(f,h,p):
"""Main driver for reading HDF5 files"""
if h.reading == 'metallicity':
arr = hdf5_readmetals(f,h,p)
elif h.reading == 'metalarray':
arr = hdf5_readmetals(f,h,p,single=0)
elif h.reading == 'mass':
arr = hdf5_readmass(f,h,p)
else:
arr = hdf5_gener... | 5,297,098 |
def scale_0to1(image_in,
exclude_outliers_below=False,
exclude_outliers_above=False
, multiply_factor=1.0):
"""Scale the two images to [0, 1] based on min/max."""
# making a copy to ensure no side-effects
out_image = image_in.copy()
min_value = np.percentil... | 5,297,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.