content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def almost_equal_ignore_nan(a, b, rtol=None, atol=None):
"""Test that two NumPy arrays are almost equal (ignoring NaN in either array).
Combines a relative and absolute measure of approximate eqality.
If either the relative or absolute check passes, the arrays are considered equal.
Including an absolute... | 5,334,500 |
def make_commands(manager):
"""Prototype"""
# pylint: disable=no-member
return (cmd_t(manager) for cmd_t in
AbstractTwitterFollowersCommand.__subclasses__()) | 5,334,501 |
def copy_rds_snapshot(
target_snapshot_identifier: str,
source_snapshot_identifier: str,
target_kms: str,
wait: bool,
rds,
):
"""Copy snapshot from source_snapshot_identifier to target_snapshot_identifier and encrypt using target_kms"""
logger = logging.getLogger("copy_rds_snapshot")
xs ... | 5,334,502 |
def test_load_yaml_without_yaml_support():
"""
Test that YAML files are not loaded if YAML is not installed.
"""
@ddt
class NoYAMLInstalledTest(object):
@file_data('test_data_dict.yaml')
def test_file_data_yaml_dict(self, value):
assert_true(has_three_elements(value))
... | 5,334,503 |
def get_other_menuitems():
"""
returns other menu items
each menu pk will be dict key
{0: QuerySet, 1: QuerySet, ..}
"""
menuitems = {}
all_objects = Menu.objects.all()
for obj in all_objects:
menuitems[obj.pk] = obj.menuitem_set.all()
return menuitems | 5,334,504 |
def buildlxc(host):
""" Creates lxc in proxmox using given hostresource configuration """
if not exists(host):
raise ValueError("Host template is missing. Please create host template")
container = Container.getContainer(HOST_CONTAINER)
hostresource = container.loadResource(host)
... | 5,334,505 |
def event_loop(handle_key, delay=10):
""""Processes events and updates callbacks."""
while True:
pygame.event.pump()
event = pygame.event.poll()
if event.type == KEYDOWN:
handle_key(event.key)
pygame.time.delay(delay) | 5,334,506 |
def gather_simulation_file_paths(in_folder: str, filePrefix: str = "",
fileSuffixes: Union[str, List[str]] = [".tre", ".tre.tar.gz"],
files_per_folder: int = 1,
verbose: bool = False) -> List[str]:
"""gather_simulatio... | 5,334,507 |
def create_deck(shuffle=False):
"""Create a new deck of 52 cards"""
deck = [(s, r) for r in RANKS for s in SUITS]
if shuffle:
random.shuffle(deck)
return deck | 5,334,508 |
def mock_gate_util_provider_oldest_namespace_feed_sync(
monkeypatch, mock_distromapping_query
):
"""
Mocks for anchore_engine.services.policy_engine.engine.policy.gate_util_provider.GateUtilProvider.oldest_namespace_feed_sync
"""
# required for FeedOutOfDateTrigger.evaluate
# setup for anchore_e... | 5,334,509 |
def ESMP_LocStreamGetBounds(locstream, localDe=0):
"""
Preconditions: An ESMP_LocStream has been created.\n
Postconditions: .\n
Arguments:\n
:RETURN: Numpy.array :: \n
:RETURN: Numpy.array :: \n
ESMP_LocStream :: locstream\n
"""
llde = ct.c_int(localDe)
# lo... | 5,334,510 |
def PlotEStarRStarBasins(DataDirectory, FilenamePrefix, PlotDirectory, Sc = 0.8):
"""
Function to make an E*R* plot for a series of drainage basins.
Changing so that we calculate E* and R* in the python script following
Martin's example, so that we can test sensitivity to Sc.
Args:
DataDire... | 5,334,511 |
def reverse(collection):
"""
Reverses a collection.
Args:
collection: `dict|list|depset` - The collection to reverse
Returns:
`dict|list|depset` - A new collection of the same type, with items in the reverse order
of the input collec... | 5,334,512 |
def A_fast_full5(S, phase_factors, r, r_min, MY, MX):
""" Fastest version, takes precomputed phase factors, assumes S-matrix with beam tilt included
:param S: B x NY x NX
:param phase_factors: K x B
:param r: K x 2
:param out: K x MY x MX
:return: exit ... | 5,334,513 |
def get_metadata_for_druid(druid, redownload_mods):
"""Obtains a .mods metadata file for the roll specified by DRUID either
from the local mods/ folder or the Stanford Digital Repository, then
parses the XML to build the metadata dictionary for the roll.
"""
def get_value_by_xpath(xpath):
t... | 5,334,514 |
def logistic_dataset_gen_data(num, w, dim, temp, rng_key):
"""Samples data from a standard Gaussian with binary noisy labels.
Args:
num: An integer denoting the number of data points.
w: An array of size dim x odim, the weight vector used to generate labels.
dim: An integer denoting the number of input... | 5,334,515 |
def sech(x):
"""Computes the hyperbolic secant of the input"""
return 1 / cosh(x) | 5,334,516 |
def generate_output_files(variants, output_consequences, output_dataframe):
"""Postprocess and output final tables."""
# Rearrange order of dataframe columns
variants = variants[
['Name', 'RCVaccession', 'GeneSymbol', 'HGNC_ID',
'RepeatUnitLength', 'CoordinateSpan', 'IsProteinHGVS', 'Trans... | 5,334,517 |
def main(country='Spain',
randomized=True,
num_points=2,
date_begin='2018-01-01', date_end='2018-01-02',
hourly_data=True,
api_key='953235aa4e74fcb593bd59c2b548d03a',
specific_coordinates=[],
interval=6):
"""
Generates hourly or daily weather data f... | 5,334,518 |
def _map_triples_elements_to_ids(
triples: LabeledTriples,
entity_to_id: EntityMapping,
relation_to_id: RelationMapping,
) -> MappedTriples:
"""Map entities and relations to pre-defined ids."""
if triples.size == 0:
logger.warning('Provided empty triples to map.')
return torch.empty(... | 5,334,519 |
def pinf_two_networks(grgd: Tuple[float, float],
k: Tuple[float, float] = (3, 3),
alpha_i: Tuple[float, float] = (1, 1),
solpoints: int = 10,
eps: float = 1e-5,
method: str = "hybr"):
"""Find the fixed poin... | 5,334,520 |
def uncapped_flatprice_goal_reached(chain, uncapped_flatprice, uncapped_flatprice_finalizer, preico_funding_goal, preico_starts_at, customer) -> Contract:
"""A ICO contract where the minimum funding goal has been reached."""
time_travel(chain, preico_starts_at + 1)
wei_value = preico_funding_goal
uncapp... | 5,334,521 |
def depfile_name(request, tmp_path_factory):
"""A fixture for a temporary doit database file(s) that will be removed after running"""
depfile_name = str(tmp_path_factory.mktemp('x', True) / 'testdb')
def remove_depfile():
remove_db(depfile_name)
request.addfinalizer(remove_depfile)
return d... | 5,334,522 |
def _convert_v3_response_to_v2(pbx_name, termtype, command, v3_response):
"""
Convert the v3 response to the legacy v2 xml format.
"""
logger.debug(v3_response)
obj = {
'command': {'@cmd': command, '@cmdType': termtype, '@pbxName': pbx_name}
}
if v3_response.get('error') is not None:... | 5,334,523 |
def calculate(dbf, comps, phases, mode=None, output='GM', fake_points=False, broadcast=True, parameters=None, **kwargs):
"""
Sample the property surface of 'output' containing the specified
components and phases. Model parameters are taken from 'dbf' and any
state variables (T, P, etc.) can be specified... | 5,334,524 |
def is_negative(value):
"""Checks if `value` is negative.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is negative.
Example:
>>> is_negative(-1)
True
>>> is_negative(0)
False
>>> is_negative(1)
False
.. versi... | 5,334,525 |
def get_optimizer_noun(lr, decay, mode, cnn_features, role_features):
""" To get the optimizer
mode 0: training from scratch
mode 1: cnn fix, verb fix, role training
mode 2: cnn fix, verb fine tune, role training
mode 3: cnn finetune, verb finetune, role training"""
if mode == 0:
set_tra... | 5,334,526 |
def lan_manifold(
parameter_df=None,
vary_dict={"v": [-1.0, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1.0]},
model="ddm",
n_rt_steps=200,
max_rt=5,
fig_scale=1.0,
save=False,
show=True,
):
"""Plots lan likelihoods in a 3d-plot.
:Arguments:
parameter_df: pandas.core.frame.D... | 5,334,527 |
def test_parse_optional_type_in_docstring():
"""Parse optional types in docstring."""
docstring = """
Parameters:
x (int): X value.
y (int, optional): Y value.
Keyword Args:
z (int, optional): Z value.
"""
arguments = Arguments()
arguments.add(Ar... | 5,334,528 |
def test_gc_cmd(vim_bot, text, cmd_list, text_expected, cursor_pos):
"""Test gc command."""
_, _, editor, vim, qtbot = vim_bot
editor.set_text(text)
cmd_line = vim.get_focus_widget()
for cmd in cmd_list:
qtbot.keyClicks(cmd_line, cmd)
assert cmd_line.text() == ""
assert editor.toPl... | 5,334,529 |
def test_his_write_with_args(mock):
# GIVEN
"""
Args:
mock:
"""
envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
time_serie = [
(datetime(2020, 1, 1, tzinfo=pytz.utc).isoformat() + " UTC", 100),
(datetime(2020, 1, 2, tzinfo=pytz.utc).isoformat() + " UTC", 200)]
... | 5,334,530 |
def _loc_str_to_pars(loc, x=None, y=None, halign=None, valign=None, pad=_PAD):
"""Convert from a string location specification to the specifying parameters.
If any of the specifying parameters: {x, y, halign, valign}, are 'None', they are set to
default values.
Returns
-------
x : float
y ... | 5,334,531 |
def query_yes_no(question, default="no"):
"""
Ask a yes/no question via raw_input() and return their answer.
:param str question: a string that is presented to the user.
:param str default: the presumed answer if the user just hits <Enter>.
:return bool: True for "yes" or False for "no"
"""
... | 5,334,532 |
def skeda_from_skedadict(line_dict, filing_number, line_sequence, is_amended):
"""
We can either pass the header row in or not; if not, look it up.
"""
line_dict['transaction_id'] = line_dict['transaction_id'][:20]
line_dict['line_sequence'] = line_sequence
line_dict['superseded_by_amendment'] =... | 5,334,533 |
def oracle_to_date(string2convert, fmt, nlsparam=None):
"""
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions183.htm
TO_DATE(char [, fmt [, 'nlsparam' ] ])
TO_DATE converts char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of DATE datatype.
The fmt is a datetime mo... | 5,334,534 |
def replace_whitespace(s, rep=' '):
"""Replace any length white spaces in the given string with a replacement.
Parameters
----------
s : str
The string in which any length whitespaces should be replaced.
rep : Optional[str]
The string with which all whitespace should be replaced. By... | 5,334,535 |
def add_s3_prefix(s3_bucket):
"""
Ensure a bucket has the s3:// prefix
:param s3_bucket: string - The bucket name
"""
s3_prefix = 's3://'
return prefix(s3_bucket, s3_prefix) | 5,334,536 |
def main(args=None):
"""
:param args:
:return:
"""
args = sys.argv[1:] if args is None else args
parser = argparse.ArgumentParser()
parser.add_argument('emg_path',
nargs='*',
default=sys.stdin,
help="The path to '.emt'... | 5,334,537 |
def test_provider_system_hook_block_loop_empty(change_dir):
"""Verify the hook call works properly."""
output = tackle('.', context_file='loop_empty.yaml', no_input=True)
assert len(output['empty']) == 0 | 5,334,538 |
def test_tree_intersection_third(balanced_bst):
"""Test tree intersection."""
assert tree_intersection(balanced_bst, BST([10, 12, 14, 16])) == {10, 12, 16} | 5,334,539 |
async def handle_xml_response(request):
""" Faking response """
response = load_data("equipment_data.xml")
return aiohttp.web.Response(
content_type="text/xml",
body=response
) | 5,334,540 |
def plugin_prefs(parent, cmdr, is_beta):
"""
Return a TK Frame for adding to the EDMC settings dialog.
"""
global listbox
frame = nb.Frame(parent)
nb.Label(frame, text="Faction Name:").grid(row=0,column=0)
nb.Label(frame, text="System Name").grid(row=0,column=1)
faction_entry = nb.E... | 5,334,541 |
def test_runner_handle_general_exception_in_module_setup(with_dec_classpath, local_config, tmpdir, mock_pm):
"""
Check that if we got exception in the module setup no one test executed.
:return:
"""
import pytest
var_dir = _ensure_var_dir(tmpdir)
xunit_file = _ensure_xunit_file_empty(var_dir... | 5,334,542 |
def Conv1D_positive_r(x, kernel_size):
"""index of r is hard-coded to 2!"""
out1 = Conv1D(1, kernel_size=kernel_size, padding='valid', activation='linear')(x)
out2 = Conv1D(1, kernel_size=kernel_size, padding='valid', activation='linear')(x)
out3 = Conv1D(1, kernel_size=kernel_size, padding='valid', act... | 5,334,543 |
def remove_innermost_template_usage(raw_code: str) -> str:
"""
If the code does not include templates, should return the exact same code
FIXME: check if any task is templated
"""
_temp_code = raw_code
template_types = get_all_template_types(raw_code)
_temp_code = replace_template_type(_temp_code, templat... | 5,334,544 |
def decrypt(text, key):
"""Decrypt the supplied text and return the result.
Args:
text (str): The text to decrypt.
key (str): The key with which to perform the decryption.
"""
return transform(text, key, True) | 5,334,545 |
def modify_replication_task(ReplicationTaskArn=None, ReplicationTaskIdentifier=None, MigrationType=None, TableMappings=None, ReplicationTaskSettings=None, CdcStartTime=None, CdcStartPosition=None, CdcStopPosition=None, TaskData=None):
"""
Modifies the specified replication task.
You can\'t modify the task e... | 5,334,546 |
def psi_gauss_1d(x, a: float = 1.0, x_0: float = 0.0, k_0: float = 0.0):
"""
Gaussian wave packet of width a and momentum k_0, centered at x_0
:param x: mathematical variable
:param a: Amplitude of pulse
:param x_0: Mean spatial x of pulse
:param k_0: Group velocity of pulse
"""
re... | 5,334,547 |
def get(address, limit=LIMIT):
"""
Recursively dereferences an address.
Returns:
A list containing ``address``, followed by up to ``limit`` valid pointers.
"""
result = []
for i in range(limit):
# Don't follow cycles, except to stop at the second occurrence.
if result.co... | 5,334,548 |
def elemwise_checker(op, expected_f, gap=None, test_dtypes=None,
grad_test=True, name=None, gap_grad=None):
"""Return the appropriate test class for the elemwise on sparse.
:param op: Op to test.
:expected_f: Function use to compare. This function must act
on dense mat... | 5,334,549 |
def plot_segments(track_generator, get_figure=False, plot_3D=False):
"""Plot the characteristic track segments from an OpenMOC simulation.
This method requires that tracks have been generated by a TrackGenerator.
Each segment is colored by the ID of the unique FSR it is within.
Parameters
--------... | 5,334,550 |
def find_availability_by_year(park, campground, year, months=range(1, 13)):
"""
Parameters
----------
park : str
campground : str
year : str
months : list
list of months as str or int. Default is `range(1, 13)`
Returns
-------
list
list of weekend availability... | 5,334,551 |
def seconds(value=None, utc=True, **kwargs):
"""
Converts value to seconds. If value is timedelta or struc_time, it will be just converted to seconds.
If value is datetime instance it will be converted to milliseconds since epoch (UTC). If value is number,
it's assumed that it's in milliseconds, so it w... | 5,334,552 |
def fix_mocov2_state_dict(state_dict):
"""
Ref: https://bit.ly/3cDfGVA
"""
new_state_dict = {}
for k, v in state_dict.items():
if k.startswith("model.encoder_q."):
k = k.replace("model.encoder_q.", "")
new_state_dict[k] = v
return new_state_dict | 5,334,553 |
def do_flatten(lists):
"""Flatten multiple lists
Takes a list of lists and returns a single list of the contents.
"""
for item in itertools.chain.from_iterable(lists):
yield item | 5,334,554 |
def write_metadata(audio_format, filepath, title, artist=None, album=None):
"""Write the metadata to the audiofile"""
if audio_format == 'mp3':
write_mp3_metadata(filepath, title, artist, album)
else:
write_metadata_other_formats(
audio_format, filepath, title, artist, album) | 5,334,555 |
def get_perspective(image, contours, ratio):
"""
This function takes image and contours and returns perspective of this contours.
:param image: image, numpy array
:param contours: contours, numpy array
:param ratio: rescaling parameter to the original image
:return: warped image
"""
poin... | 5,334,556 |
def init_integer(m):
"""Initializes weights according to a Uniform distribution."""
a = -1.
b = 1.
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.uniform_(m.weight, a=a, b=b)
nn.init.uniform_(m.bias, a=a, b=b)
m.weight.data.ceil_()
m.bias.data.ceil_() | 5,334,557 |
def processFilesOpen(filename, filetype='file', subname='', zptr=None,
**kwargs):
"""
Open a file for processing. If it is a compressed file, open for
decompression.
:param filetype: 'zip' if this is a zip archive.
:param filename: name of the file (if a zip archive, this is t... | 5,334,558 |
def test_from_settings():
"""Test that from_settings converts application settings."""
expected = {'a': 1, 'b': 2}
actual = from_settings({'DATABASE_A': 1, 'DATABASE_B': 2})
assert actual == expected | 5,334,559 |
def load_model_selector(folder_path):
"""Load information about stored model selection
Parameters
----------
folder_path : str
path where .model_selector_result files are stored
Returns
-------
ModelSelector
Information about model selection for each partition
"""
r... | 5,334,560 |
def train_run():
"""
Runs the loop that trains the agent.
Trains the agent on the goal-oriented chatbot task. Training of the agent's neural network occurs every episode that
TRAIN_FREQ is a multiple of. Terminates when the episode reaches NUM_EP_TRAIN.
"""
print('Training Started...')
ep... | 5,334,561 |
def do_handshake(holdtime):
"""Does a handshake with the binary"""
optparam = "\x02\x06\x01\x04\x00\x01\x00\x01"
send_pkt(BGP_OPEN, flat(
4,
"AA",
p16b(holdtime),
"AAAA",
len(optparam),
optparam,
word_size = 8,
))
# Receive the two packages fr... | 5,334,562 |
def generate_expired_date():
"""Generate a datetime object NB_DAYS_BEFORE_DELETING_LIVE_RECORDINGS days in the past."""
return timezone.now() - timedelta(
days=settings.NB_DAYS_BEFORE_DELETING_LIVE_RECORDINGS
) | 5,334,563 |
def make_dummy_authentication_request_args() -> Dict[str, bytes]:
"""Creates a request to emulate a login request.
Returns:
Dict[str, bytes]: Authenticator dictionary
"""
def _make_dummy_authentication_request_args():
args = {
"username": ["foobar".encode()],
"p... | 5,334,564 |
def add_experiment_images_to_image_info_csv(image_info_df, experiment_xml_file):
"""
Goes through the xml file of the experiment and adds the info of its images to the image info dataframe.
If the gene name is missing in the experiment, then this experiment is considered invalid.
:param image_info_df: ... | 5,334,565 |
def dedup(iterable: Iterable[T], key: Optional[Callable[[T], U]] = None) -> Iterator[T]:
"""
List unique elements.
>>> tuple(dedup([5, 4, 3, 5, 3, 3]))
(3, 4, 5)
"""
return uniq(sorted(iterable, key=key), key) | 5,334,566 |
def get_product(barcode):
"""
Return information of a given product.
"""
return utils.fetch('api/v0/product/%s' % barcode) | 5,334,567 |
def knn_matcher(arr2, arr1, neighbours=2, img_id=0, ratio_threshold=0.75):
"""Computes the inlier matches for given descriptor ararys arr1 and arr2
Arguments:
arr2 {np.ndarray} -- Image used for finding the matches (train image)
arr1 {[type]} -- Image in which matches are found (test image)
... | 5,334,568 |
def get_virtual_network_gateway_bgp_peer_status(peer: Optional[str] = None,
resource_group_name: Optional[str] = None,
virtual_network_gateway_name: Optional[str] = None,
opts:... | 5,334,569 |
def check_wrs2_tiles(wrs2_tile_list=[], path_list=[], row_list=[]):
"""Setup path/row lists
Populate the separate path and row lists from wrs2_tile_list
Filtering by path and row lists separately seems to be faster than
creating a new path/row field and filtering directly
"""
wrs2_tile_fmt ... | 5,334,570 |
def cat(file_path: str) -> str:
"""pathlib.Path().read_textのshortcut
Args:
file_path (str): filepath
Returns:
str: file内の文字列
Example:
>>> cat('unknown.txt')
"""
file_path = pathlib.Path(file_path)
if file_path.is_file():
return file_path.read_text()
re... | 5,334,571 |
def test_check_gdf(gdf, exc, pattern):
"""Test GeoDataFrame validation function."""
with pytest.raises(exc) as err:
check_gdf(gdf)
assert err.match(re.escape(pattern))
assert check_gdf(GeoDataFrame(geometry=[POLY])) is None | 5,334,572 |
def test_deep_index(tree: Group):
"""Test deep indexing"""
node = tree[(1, 0)]
assert tree.index(node) == (1, 0) | 5,334,573 |
def _get_role_by_name(role_name):
"""
Get application membership role
Args:
role_name (str): role name.
Returns:
int: application membership role id.
"""
base_request = BaseRequest()
settings = Settings()
params = {
'filter': 'name',
'eq': role_n... | 5,334,574 |
def parse_filename(filename, is_adversarial=False, **kwargs):
"""Parse the filename of the experment result file into a dictionary of settings.
Args:
filename: a string of filename
is_adversarial: whether the file is from experiments/GIB_node_adversarial_attack.
"""
if is_adversaria... | 5,334,575 |
def WHo_mt(dist, sigma):
"""
Speed Accuracy model for generating finger movement time.
:param dist: euclidian distance between points.
:param sigma: speed-accuracy trade-off variance.
:return: mt: movement time.
"""
x0 = 0.092
y0 = 0.0018
alpha = 0.6
x_min = 0.006
x_max = 0.... | 5,334,576 |
def find_next_sibling_position(element, tag_type):
"""
Gets current elements next sibling's (chosen by provided tag_type) actual character position in html document
:param element: Whose sibling to look for, type: An object of class bs4.Tag
:param tag_type: sibling tag's type (e.g. p, h2, div, span etc... | 5,334,577 |
def on_create(data):
"""Create a game lobby"""
user = data['username']
session_id = request.sid
if data['players_number'] == 'join':
return
players_number = int(data['players_number'])
if session_id in USERS and USERS[session_id]['room'] != '':
print (session_id + " already in a ... | 5,334,578 |
def CheckOutput(cmd, **kwargs):
"""Call subprocess.check_output to get output.
The subprocess.check_output return type is "bytes" in python 3, we have
to convert bytes as string with .decode() in advance.
Args:
cmd: String of command.
**kwargs: dictionary of keyword based args to pass ... | 5,334,579 |
def one_hot(arr, n_class=0):
"""Change labels to one-hot expression.
Args:
arr [np.array]: numpy array
n_class [int]: number of class
Returns:
oh [np.array]: numpy array with one-hot expression
"""
if arr is None:
return None
if isinstance(arr, list) or isinstan... | 5,334,580 |
def boost_nfw_at_R(R, B0, R_scale):
"""NFW boost factor model.
Args:
R (float or array like): Distances on the sky in the same units as R_scale. Mpc/h comoving suggested for consistency with other modules.
B0 (float): NFW profile amplitude.
R_scale (float): NFW profile scale radius.
... | 5,334,581 |
def get_swatches(root):
"""Get swatch elements in the SVG"""
swatches = {}
for node in descendants(root):
if "hasAttribute" not in dir(node) or not node.hasAttribute("id"):
continue
classname = extract_class_name(node.getAttribute("id"))
if classname:
swatches... | 5,334,582 |
def chunks(l, n):
"""
Split list in chunks - useful for controlling memory usage
"""
if n < 1:
n = 1
return [l[i:i + n] for i in range(0, len(l), n)] | 5,334,583 |
def sync_active_stable_monitors(db_session: SessionLocal, project: Project):
"""Syncs incident monitors."""
monitor_plugin = plugin_service.get_active_instance(
db_session=db_session, project_id=project.id, plugin_type="monitor"
)
if not monitor_plugin:
log.warning(f"No monitor plugin is... | 5,334,584 |
def services() -> None:
"""Services.""" | 5,334,585 |
def patch_d2_meta_arch():
"""
D2Go requires interfaces like prepare_for_export/prepare_for_quant from meta-arch in
order to do export/quant, this function applies the monkey patch to the original
D2's meta-archs.
"""
def _check_and_set(cls_obj, method_name, method_func):
if hasattr(cls_... | 5,334,586 |
def env_config(magic_dir):
"""Provides a config file with environment variables."""
if os.sys.platform == 'win32':
config_filename = 'envs_win.yaml'
else:
config_filename = 'envs.yaml'
dotenv_filename = 'test.env'
config = magic_dir / config_filename
dotenv = magic_dir / dotenv_... | 5,334,587 |
def UserLevelAuthEntry(val=None):
"""Provide a 2-tuple of user and level
* user: string
* level: oneof(ACCESS_LEVELS)
currently: GUEST, USER, ADMIN
"""
if len(val) != 2:
raise ValueError('UserLevelAuthEntry entry needs to be a 2-tuple '
'(name, ac... | 5,334,588 |
def schedule_registration_notif(subscriber, *args, **kwargs):
"""
Schedule to send a notification once.
:param models.Subscriber subscriber: subscriber to send notification to.
:kwargs seconds: seconds to enqueue notification in.
"""
queue_time = kwargs.pop('seconds', 5)
job_ti... | 5,334,589 |
def test_has_expected_attributes():
"""Ensure registers mapped to Batteries/BMS are represented in the model."""
expected_attributes = set()
for i in range(60):
name = InputRegister(i + 60).name.lower()
if name.endswith('_h'):
continue
elif name.endswith('_l'):
... | 5,334,590 |
def parseCookie(headers):
"""Bleargh, the cookie spec sucks.
This surely needs interoperability testing.
There are two specs that are supported:
Version 0) http://wp.netscape.com/newsref/std/cookie_spec.html
Version 1) http://www.faqs.org/rfcs/rfc2965.html
"""
cookies = []
# There can't... | 5,334,591 |
def get_system_metrics():
"""
For keys in fields
>>> from serverstats import get_system_metrics
>>> fields = dict()
>>> dl = get_system_metrics()
>>> _fields = {
... 'cpu': ['usage_percent', 'idle_percent', 'iowait',
... 'avg_load_15_min', 'avg_load_5_min', 'avg_load_1_m... | 5,334,592 |
def FilterKeptAttachments(
is_description, kept_attachments, comments, approval_id):
"""Filter kept attachments to be a subset of last description's attachments.
Args:
is_description: bool, if the comment is a change to the issue description.
kept_attachments: list of ints with the attachment ids for a... | 5,334,593 |
def test_ptyshell_file_stage () :
""" Test pty_shell file staging """
conf = rut.get_test_config ()
shell = sups.PTYShell (saga.Url(conf.job_service_url), conf.session)
txt = "______1______2_____3_____"
shell.write_to_remote (txt, "/tmp/saga-test-staging")
out = shell.read_from_remote ("/tmp... | 5,334,594 |
def scan_fixtures(path):
"""Scan for fixture files on the given path.
:param path: The path to scan.
:type path: str
:rtype: list
:returns: A list of three-element tuples; the app name, file name, and relative path.
"""
results = list()
for root, dirs, files in os.walk(path):
... | 5,334,595 |
def invocations():
"""Do an inference on a single batch of data. In this sample server, we take data as CSV, convert
it to a pandas data frame for internal use and then convert the predictions back to CSV (which really
just means one prediction per line, since there's a single column.
"""
data = Non... | 5,334,596 |
def main(argv=None):
"""The main event"""
try:
if 'piaplib.book.__main__' not in sys.modules:
import piaplib.book.__main__
else:
piaplib.book.__main__ = sys.modules["""piaplib.book.__main__"""]
if piaplib.book.__main__.__name__ is None:
raise ImportError("Failed to import piaplib.book.__main__")
excep... | 5,334,597 |
def today() -> date:
"""
**today**
returns today's date
:return present date
"""
return datetime.datetime.now().date() | 5,334,598 |
def get_word_size(word,font_size):
"""get's the dimansions of any given word for any giving font size"""
Font=ImageFont.truetype(FONT, font_size)
return Font.getsize(word) | 5,334,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.