content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mktime(t):
"""mktime(tuple) -> floating point number
Convert a time tuple in local time to seconds since the Epoch."""
tm_year = t[0]
tm_mon = t[1] - 1
tm_mday = t[2]
tm_hour = t[3]
tm_min = t[4]
tm_sec = t[5]
date = JS("new Date(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hou... | 57,300 |
def ports_reader(personalities, kext_path):
"""
Read binary data offsets and extract available ports
"""
if DARWIN_VERSION < '16':
sys.exit('macOS version before Sierra not yet supported')
kext_blob = kext_path
with open(kext_blob, 'rb') as bin_data:
for hexinfo in personalities... | 57,301 |
def test_edit_the_user_password_that_does_not_exist(admin_client):
"""
...
"""
response = admin_client.post(
"/api/user/password/", {"user_id": 10000, "password": "1234"}
)
assert response.status_code == 404 | 57,302 |
def package_matrix(request, pkg=None, arch=None):
"""
Generate a build matrix for one or more specs.
"""
# Unique package names and os options
packages = (
Spec.objects.exclude(build=None).values_list("name", flat=True).distinct()
)
failed_packages = (
Spec.objects.filter(bui... | 57,303 |
def parse_args(argv):
"""
Parse list of strings into argparse.Namespace()
Arguments:
argv
a list of strings, typically contents of sys.argv
WARNING: if argv is malformed, the process will exit. Avoid using this function in tests.
"""
description = ("Copy directory structure and fi... | 57,304 |
def _PlcReady(timeout=1):
"""Returns True if PLC AIO node reports actuator state is 'ready'."""
t_start = time.time()
while time.time() - t_start < timeout:
ready = (listener.status_msg and (listener.status_msg.detwist_state ==
actuator_types.kActuatorStateReady))
if... | 57,305 |
def convert_dataframe(metrics: List[Metric]) -> pd.DataFrame:
"""
convert_dataframe converts list of metric to pandas DataFrame
"""
fields = ['date', 'point']
columns = {'date': 'ds', 'point': 'y'}
return pd.DataFrame([{f: getattr(m, f) for f in fields} for m in metrics]).rename(columns=columns) | 57,306 |
def retire_stub():
"""Retire Stub (staff only)
Prevent a stub from showing up in the random display and from being used in
any ideas."""
pass | 57,307 |
def test_acartesian2():
"""Test acartesian2"""
one = np.array([[1, 2, 3],
[4, 5, 6]], int)
two = np.array([[7, 8],
[9, 10],
[11, 12]], int)
three = np.array([[13]], int)
assert array_set_equals(one, utils.acartesian2(one))
assert array... | 57,308 |
def check_or_create_folder(filename):
"""
Creates a folder to the indicated path to be able to write files in it
"""
import os
if not os.path.isdir(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
return | 57,309 |
def fail():
"""Useful token for e.g. close_receiver (if that's unexpected)"""
pass | 57,310 |
def cleanup(dstt=None, inv=None, avars=None):
"""
Cleanup the various transient elements of a test and Ansible run.
Parameters:
dstt (DSTTopology): An optional DSTTopology object to cleanup.
inv (file object): An optional file descriptor pointer to an Ansible inventory file to remove.
... | 57,311 |
def assert_array_equal(x: xarray.core.dataarray.DataArray, y: numpy.float64):
"""
usage.xarray: 3
"""
... | 57,312 |
def linear_shap_corr(model, data):
""" Linear SHAP (corr 1000)
"""
return LinearExplainer(model, data, nsamples=1000).shap_values | 57,313 |
def ind2sub(ind, shape, out=None):
"""Convert linear indices into sub indices (i, j, k).
The rightmost dimension is the most rapidly changing one
-> if shape == [D, H, W], the strides are therefore [H*W, W, 1]
Parameters
----------
ind : tensor_like
Linear indices
shape : (D,) vect... | 57,314 |
def get_repo_prs(r, state, base, session):
"""
Get all pull requests of a given repository
:param r: repository name 'author/repo-name'
:param state: state of the PR
:param base: base branch
:param session: open and authenticated session
:type r: string
:type stat... | 57,315 |
def register():
"""Register user"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("firstname"):
return apology("must provide FIR... | 57,316 |
def test_s3fetchyaml_with_destination_int(mock_s3):
"""Yaml overwrites destination key that's not a string."""
input = [1, 2, 3]
yaml_loader = yaml.YAML()
string_stream = io.StringIO()
yaml_loader.dump(input, string_stream)
mock_s3.side_effect = [{'Body': string_stream.getvalue()}]
context ... | 57,317 |
def format_sse(data: str, event=None) -> str:
"""Formats a string and an event name in order to follow the event stream convention.
>>> format_sse(data=json.dumps({'abc': 123}), event='Jackson 5')
'event: Jackson 5\\ndata: {"abc": 123}\\n\\n'
"""
msg = f'data: {data}\n\n'
if event is not None:... | 57,318 |
async def async_setup_entry(hass, config, async_add_entities):
"""Adds HomeWizard Energy to the list of senros."""
_LOGGER.info("Setting up sensor for HomeWizard Energy.")
# services.register_services(hass)
async_add_entities([HWEP1MeterSensor(config, hass)], True) | 57,319 |
async def _unpack_message(session: Session, enc_message: bytes) -> Tuple[str, str, str]:
"""Decode a message using the DIDComm v1 'unpack' algorithm."""
try:
wrapper = JweEnvelope.from_json(enc_message)
except ValidationError:
raise WalletError("Invalid packed message")
alg = wrapper.pr... | 57,320 |
def test_debug(clickrunner):
""" Test that debug mode shows the default folders """
result = clickrunner.invoke(
osa.cli.entrypoint, ['--debug', 'static_inventory', 'generate'])
assert "OpenStack-Ansible folder is" in result.output
assert "User overrides folder is" in result.output
assert "W... | 57,321 |
def minweight_match_realmxeigs(a, b, metricfn=None,
pass_indices_to_metricfn=False, eps=1e-9):
"""
Matches the elements of `a` and `b`, whose elements are assumed to either real or one-half of a conjugate pair.
Matching is performed by minimizing the weight between elements,
... | 57,322 |
def save_links_to_db(entries, user_db_port=None, user=None, password=None):
"""
Saves links and dbnames to the local project database.
:param entries: List(tuple) of lists(tuples), with pairs 'dbname - url'
:param user_db_port: Port for connecting to local Sources table through ssh tunneling, if used.
... | 57,323 |
def _invert_aliases():
"""Reverse the alias dictionary to be a lookup from command to aliases."""
out = _defaultdict(list)
for alias, name in ALIASES.items():
out[name].append(alias)
return out | 57,324 |
def get_positive_expectation(p_samples, average=True):
"""Computes the positive part of a JS Divergence.
Args:
p_samples: Positive samples.
average: Average the result over samples.
Returns:
th.Tensor
"""
log_2 = math.log(2.)
Ep = log_2 - tlx.softplus(- p_samples)
if... | 57,325 |
def setbit(byte, offset, value):
"""
Set a bit in a byte to 1 if value is truthy, 0 if not.
"""
if value:
return byte | (1 << offset)
else:
return byte & ~(1 << offset) | 57,326 |
def insertDoubleQuote(string, index):
""" Insert a double quote in the specified string at the specified index and return the string."""
return string[:index] + '\"' + string[index:] | 57,327 |
def walk(top, maxdepth):
"""Scan through directories to a given recursion depth.
See https://stackoverflow.com/a/35316298
TODO: make Python 2.x compatible
"""
top = os.path.normpath(top)
dirs, nondirs = [], []
for entry in os.scandir(top):
(dirs if entry.is_dir() else nondirs).append(entry.path)
yield top, d... | 57,328 |
def title_cloud(cat, rate, year):
"""
Makes a word cloud of movie and TV show titles.
Parameters
----------
cat: list
List of genres we want to filter out from the dataframe.
rate: list
List of ratings we want to filter out from the dataframe.
year: int, float
Fi... | 57,329 |
def run_one_epoch_aae(model, x, y, num_critic=1, clip_value=0.01, train=True, optimizer=None,
batch_size=None, return_loss=True, loss_weight=[1., 1., 1.],
loss_fn_cls=nn.CrossEntropyLoss(), loss_fn_reg=nn.MSELoss(),
loss_fn_critic=nn.L1Loss(),
epoch=0... | 57,330 |
def And(*seq):
""" Return boolean expression ``x1 and x2 and ...``.
"""
c = Logic.convert
return Logic.And(*map(c, seq)) | 57,331 |
def powerlaw(x, a, b, c):
"""Powerlaw function used by fitting software to characterise uncertainty."""
return a * x**b + c | 57,332 |
def step_impl(context, email):
"""
:type context: behave.runner.Context
"""
user_exists = get_user_model().objects.filter(
email=email
).exists()
context.test_case.assertFalse(user_exists, "User should not exist %s" % email) | 57,333 |
def wait_for_cursor(cursor):
"""Waits for the Hive operation to be completed
Arguments:
cursor {pyhive.hive.Cursor} -- cursor object
"""
status = cursor.poll().operationState
while status in (TOperationState.INITIALIZED_STATE, TOperationState.RUNNING_STATE):
logs = cursor.f... | 57,334 |
def quatFromXYZW(xyzw, seq):
"""Convert quaternion from XYZW (pybullet convention) to arbitrary sequence."""
assert (
len(seq) == 4 and "x" in seq and "y" in seq and "z" in seq and "w" in seq
), "Quaternion sequence {} is not valid, please double check.".format(seq)
inds = ["xyzw".index(axis) fo... | 57,335 |
def manage(verbose, log_file):
"""A high-level interface to admin scripts for deepfigures."""
log_level = logging.DEBUG if verbose else logging.INFO
if log_file:
logging.basicConfig(
filename=log_file,
filemode='a',
format=LOG_FORMAT,
level=l... | 57,336 |
def validate(str, mode):
"""
regex example
mail address:
^[a-z][a-z0-9_\.]+@[a-z]+(\.[a-z]+)+$
phone number:
^1[3-9]\d{9}$
fixed line:
^0[1,2,4-9][0-9]\d{0,1}$
Chinese:
^[\u4E00-\u9FA5]
ref:
https://github.com/cdoco/learn-regex-zh
... | 57,337 |
def readPeakList(peak_file):
"""
Read in list of peaks to delete from peaks_file. Comment lines (#) and
blank lines are ignored.
"""
f = open(peak_file,'r')
peak_list = f.readlines()
f.close()
peak_list = [l for l in peak_list if l[0] != "#" and l.strip() != ""]
peak_list = [... | 57,338 |
def parse_coordinates(raw_coordinates):
"""Parses cell coordinates from text."""
return {ast.literal_eval(x) for x in ast.literal_eval(raw_coordinates)} | 57,339 |
def array_view_from_vector_container(
container: "itkt.VectorContainer", ttype=None
) -> np.ndarray:
"""Get an Array view with the content of the vector container"""
import itk
container_template = itk.template(container)
IndexType = container_template[1][0]
# Find container type
if ttype ... | 57,340 |
def convert_linear_problem_to_dual(model, sloppy=False, infinity=None, maintain_standard_form=True, prefix="dual_", dual_model=None): # NOQA
"""
A mathematical optimization problem can be viewed as a primal and a dual problem. If the primal problem is
a minimization problem the dual is a maximization probl... | 57,341 |
def test_fail_with_bad_recipe_file(runner: CliRunner) -> None:
"""It exits if recipe file is not a python file."""
result = runner.invoke(
__main__.main, ["tests/console_test_input.txt", "-", "tests/console_test_input.txt"]
)
assert result.exit_code == 1 | 57,342 |
def snake_case(text):
"""Converts `text` to snake case.
Args:
text (str): String to convert.
Returns:
str: String converted to snake case.
Example:
>>> snake_case('This is Snake Case!')
'this_is_snake_case'
.. versionadded:: 1.1.0
.. versionchanged:: 4.0.0
... | 57,343 |
def testInstChngMsgThrottling(nodeSet, looper, up, viewNo):
"""
2 nodes out of 4 keep on sending INSTANCE_CHANGE messages as they
find the master to be slow but since we need 3 out of 4 (n-f) to say that
master is slow for a view change to happen, a view change does not happen
but the nodes finding ... | 57,344 |
def chunkify(tsd, seq_len):
"""
Splits a TimeSeriesDataset into chunks of length seq_len
Args:
tsd: TimeSeriesDataset object
seq_len: length of the subsequences to return
Returns: numpy arrays with chunks of size seq_len
"""
x, y = [], []
for s in tsd:
for i in ra... | 57,345 |
def create_survey(
title: str,
hide_votes: bool,
is_anonymous: bool,
description: str,
question_author_name_field_visible: bool,
limit_question_characters_enabled: bool,
limit_question_characters: int,
author: User) -> Dict[str, str]:
"""
Create ne... | 57,346 |
def remove_batch_dimension(shape: tuple) -> tuple:
"""Set the batch dimension to None as it does not matter for the
Network interface."""
shape = list(shape)
shape[0] = None
shape = tuple(shape)
return shape | 57,347 |
async def test_state_attributes(hass):
"""Test light state attributes."""
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_LIGHT, ATTR_XY_COLOR: (0.4, 0.4), ATTR_BRIGHTNESS: 25},
blocking=True,
)
state = hass.states.get(ENTITY_LIGHT)... | 57,348 |
def on_publish(client, userdata, result):
"""
Callback following message receipt by server
"""
print('Published to mqtt broker') | 57,349 |
def load(path):
"""Load an image from given path. Automatically de-compresses."""
file, reason = filesystem.open(path, 'rb')
if file:
## print(f'Length: {file.proxy.size(path)[0]}')
readSignature = string.char(file.readString(len(OCIFSignature)))
if readSignature == OCIFSignature:
... | 57,350 |
def main():
"""Обработчик игры."""
args = argparser.parse_args()
if args.help:
print_rules()
field = Field(width=args.width, height=args.height)
field.set_bombs(bombs_count=args.bombs_count)
start_time = time.time()
while True:
print_field(field)
while True:
... | 57,351 |
def compute_windows(numpy_image, patch_size, patch_overlap):
"""Create a sliding window object from a raster tile.
Args:
numpy_image (array): Raster object as numpy array to cut into crops
Returns:
windows (list): a sliding windows object
"""
if patch_overlap > 1:
raise Valu... | 57,352 |
def append_sys_path(folder_path):
"""Appends a path to sys.path
"""
if folder_path not in sys.path:
sys.path.append(folder_path) | 57,353 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the Demo config entry."""
await async_setup_platform(hass, {}, async_add_entities) | 57,354 |
def reindex_featured_entries():
"""Reindexes records having at least one future entry which is now in the past."""
service = current_communities.service
now = datetime.utcnow().isoformat()
@unit_of_work()
def reindex_community(hit, uow=None):
community = service.record_cls.pid.resolve(hit["... | 57,355 |
def date_to_format(value, target_format):
"""Convert date to specified format"""
if target_format == str:
if isinstance(value, datetime.date):
ret = value.strftime("%d/%m/%y")
elif isinstance(value, datetime.datetime):
ret = value.strftime("%d/%m/%y")
elif isinsta... | 57,356 |
def printWelcome():
"""
Print initial program load text.
"""
print("ADSB Range: Display the range of ADS-B receivers.") | 57,357 |
def test_get_os_platform_alternative_formats(name, tmp_path):
"""Support different ways of building the string."""
source, result = name
filepath = tmp_path / "os-release"
filepath.write_text(
dedent(
"""
ID={}
VERSION_ID="20.04"
""".format(
so... | 57,358 |
def _extend_header(outfile, basepath, headvars):
"""
Rewrites the header with the information from the new tracks.
Parameters
----------
outfile : hdf5 file
New grid file to write to.
basepath : str, optional
Path in the grid where the tracks are stored. The default value appli... | 57,359 |
def fetch_file(file_id: str, chunk: int = None, verify: bool = False) -> FileStatus:
"""Fetches file information
Args:
file_id: The id of the file to fetch
chunk: (Optional) If included, fetches a single chunk instead of the entire file.
verify: (Optional) If included, fetches file vali... | 57,360 |
def __get_settings(file_name):
"""
Opens the settings file associated to a csv file and returns it.
:param file_name: The path to settings file.
:type file_name: str
:return: The settings.
:rtype: dict[str, str]
"""
settings = {}
if not file_name.endswith('.setting'):
file_n... | 57,361 |
def set_device(args, distributed=False, rank=0):
""" set parameter to gpu or cpu """
if torch.cuda.is_available():
if isinstance(args, list):
return (set_gpu(item, distributed, rank) for item in args)
elif isinstance(args, dict):
return {key:set_gpu(args[key], distributed... | 57,362 |
def plot_days_usage(
dataframe, groups_column,
x_column, y_column,
xlabel, ylabel, title="", colors_dict={},
xticks=None):
"""
Plot the dataframe values for each groups column unique value
Args:
dataframe: pandas DataFrame
groups_column: name of the column for which the plots... | 57,363 |
def oned_const_vel_bump(g=3.5,total=10000):
"""
make figure for traveling bump
"""
dat = oned_simple.SimDat(g=g,q=0,zshift=.1,T=total)
# get four bumps at four equal time intervals. use second half of sim,
# use velocity to determine time intervals
# Peaks of phase plot over time ... | 57,364 |
def load_pendigits(random_state=None, return_X_y=False, subset='kriegel11'):
"""Load and return the pendigits dataset.
Kriegel's structure (subset='kriegel11') :
=============== =======
anomalous class class 4
n_samples 9868
n_outliers 20
n_features 16
contamination 0... | 57,365 |
def article_published_today(link):
""" Compares the date the article was written with today's date."""
soup = lvm.soup_session(link)
todays_date = (date.today() - timedelta(0)).strftime("%B %#d, %Y") # The # is platform specific
date_to_check = soup.find('time', attrs={'class': 'date'})
return date_to_check ==... | 57,366 |
def test_states(posterior):
"""RVs are stored correctly."""
assert isinstance(posterior.states, _RandomVariableList)
assert len(posterior.states[0].shape) == 1 | 57,367 |
def get_parser():
"""
Returns the parser for the command line tool.
:return: parser
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(description = 'MNIST initialization and normalization benchmark.')
parser.add_argument('-epochs', dest = 'epochs', type = int,
... | 57,368 |
def nearest_neighbor(left_gdf, right_gdf, k_neighbors=1, return_left_columns=True, return_right_columns=True):
"""
For each point in left_gdf, find closest point in right GeoDataFrame and return them.
Adapted from https://stackoverflow.com/questions/62198199/k-nearest-points-from-two-dataframes-with-geopand... | 57,369 |
def on_message(unused_client, unused_userdata, message):
"""Callback when the device receives a message on a subscription."""
payload = str(message.payload)
print('Received message \'{}\' on topic \'{}\' with Qos {}'.format(
payload, message.topic, str(message.qos))) | 57,370 |
def load_sequences_from_file(path, voc_path):
"""
Used for reading sentences or sequences of slots.
Splits input lines into lists of words and performs word to id transformation.
:param path: path to txt file with data
:param voc_path: path to json file with word to id vocabulary
:return: torch ... | 57,371 |
def lambda_handler(event, context):
""" main function """
try:
for region in get_regions():
stop_instances(get_untagged_instances(region), region)
return {
"statusCode": 200,
"body": "successfully shutted down all untagged instances",
}
except:
... | 57,372 |
async def test_valid_path(opp):
"""Test for a valid path."""
if not os.path.isdir(TEST_DIR):
os.mkdir(TEST_DIR)
create_file(TEST_FILE)
opp.config.allowlist_external_dirs = {TEST_DIR}
config = {"sensor": {"platform": "folder", CONF_FOLDER_PATHS: TEST_DIR}}
assert await async_setup_compon... | 57,373 |
def _inplace_sort_by_id(unsorted_list):
"""Takes a list of dicts each of which has an '@id' key,
sorts the elements in the list by the value of the @id key.
Assumes that @id is unique or the dicts have a meaningul < operator
"""
if not isinstance(unsorted_list, list):
return
sorted_list ... | 57,374 |
def sphinx_load_test():
"""Return function to perform 'live' Sphinx inventory load test."""
from sphinx.util.inventory import InventoryFile as IFile
def func(path):
"""Perform the 'live' inventory load test."""
with path.open("rb") as f:
try:
IFile.load(f, "", os... | 57,375 |
def bimhaw_bootstrap(cx):
"""Configure bimhaw and shells in system to PHASE 1.
PHASE 1 is a loadout profile which is used to then install more
advanced environments.
"""
# make a python virtual env to install it at first and set the
# shells
cx.run("mkdir -p $HOME/tmp")
cx.run("python... | 57,376 |
def position() -> s.SearchStrategy[pos.Position]:
"""Generates a random Position.
Returns:
A new search strategy.
"""
return s.builds(pos.Position) | 57,377 |
def get_gpg_keys(conn, dns):
"""
Grab pgpKeyInfo records (base64 encoded gpg keys) for the key attribute
entries in LDAP, returning a dict {key_attr: pgpKeyInfo}
"""
r = {}
for dn in dns:
data = get_dn_attribute(conn, dn, '(objectClass=pgpKeyInfo)',
'pgpKey')
if not d... | 57,378 |
def get_pandas_field_metadata(pandas_col_metadata, field_name):
"""
Fetch information for a given column. The column statistics returned
will be a bit different depending on if the types in the column are a
number or a string. 'NAN' values are stripped from statistics and don't
even show up in outpu... | 57,379 |
def upgrade(service_id, start_first=True, complete_previous=False, imageUuid=None, auto_complete=False,
batch_size=1, interval_millis=10000, replace_env_name=None, replace_env_value=None):
"""Upgrades a service
Performs a service upgrade, keeping the same configuration, but otherwise
pulling new i... | 57,380 |
def predict_single_image(model, image):
"""
Predict the bounding box quads for a single image
:param model:
:param image:
:return:
"""
im_resized, (ratio_h, ratio_w) = east_utils.resize_image(image)
im_resized = cv2.cvtColor( im_resized, cv2.COLOR_BGR2RGB)
image_batch = np.expand_di... | 57,381 |
def get_reduced_string(
text: list[int], suffix_arr: list[int], lms_suffixes: list[int]
) -> tuple[list[int], bool]:
"""
>>> suffix_arr = [10, 0, 1, 2, 3, 4, 6, 8, 5, 7, 9]
>>> lms_suffixes = [6, 8, 10]
>>> get_reduced_string("AAAAACACAG", suffix_arr, lms_suffixes)
([1, 2, 0], False)
"""
... | 57,382 |
def add_cez_to_map(
folium_map: folium.Map,
exclusion_json_path: Optional[str] = None,
add_layer_control: bool = False,
) -> folium.Map:
"""Add polygons of the Chernobyl Exclusion Zone (CEZ) to a folium map.
Args:
folium_map (folium.Map): [description]
exclusion_json_path (Optional[... | 57,383 |
def test_atomic_unsigned_int_enumeration_nistxml_sv_iv_atomic_unsigned_int_enumeration_1_4(mode, save_output, output_format):
"""
Type atomic/unsignedInt is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/unsignedInt/Schema+Instance/NISTSchema-SV-IV-atomic-unsignedI... | 57,384 |
def gridappsdvolttron(config_path, **kwargs):
"""Parses the Agent configuration and returns an instance of
the agent created using that configuration.
:param config_path: Path to a configuration file.
:type config_path: str
:returns: Gridappsdvolttron
:rtype: GridAPPSDVolttron
"""
try:... | 57,385 |
def attach_crash_report(code, data):
"""
Attach crash report data
@param code: Unique phone code
@type code: str
@param data: Dictionary data for the phone, passed from client in the 'data' request field
@type data: dict
"""
collection = settings.MONGO['extra_data']
collection.insert... | 57,386 |
def is_valid_if_yes_definition(definition):
"""
Returns true if the if_yes definition is valid.
str -> bool
"""
if definition.count(constants.QUESTION_DENOTE) < 2 or definition[0] != constants.QUESTION_DENOTE:
return False
# First char is white space so it needs to be removed.
if_tr... | 57,387 |
def get_route_count(device, table, protocol, active=True, output=None):
"""
Get total route count for each table via 'show route target_route extensive'
Args:
device (`obj`): Device object
table (`str`): Table name such as `inet.0`, `inet6.0`
protocol (`str`): Protocol name such as ... | 57,388 |
def dt_get_geis_type():
"""
>>> old_state = test_config.setup(url="https://jwst-serverless-mode.stsci.edu")
>>> factory.get_filetype("data/e1b09593u.r1h")
'geis'
>>> test_config.cleanup(old_state)
""" | 57,389 |
def get_dataset(folder, url):
""" Returns the corresponding file name for the desired dataset """
return os.path.join(folder, get_filename_url(url)[0]) | 57,390 |
async def test_validate_cron_trigger_multi_checks(db: Session, scheduler: Scheduler):
"""
_validate_cron_trigger runs 60 checks to be able to validate limit low as one minute.
If we would run the check there one time it won't catch scenarios like:
If the limit is 10 minutes and the cron trigger configur... | 57,391 |
def deep_replace(arr, x, y):
"""
Help function for extended_euclid
"""
for i in range(len(arr)):
element = arr[i]
if type(element) == list:
arr[i] = deep_replace(element, x, y)
else:
if element == x:
arr[i] = y
return arr | 57,392 |
def get_imgaug_transform(cfg: DictConfig) -> iaa.Sequential:
"""Create simple data transform pipeline that resizes images."""
data_transform = iaa.Resize(
{
"height": cfg.data.image_resize_dims.height,
"width": cfg.data.image_resize_dims.width,
}
)
return iaa.Sequ... | 57,393 |
def inerIntra(groupes, centres):
"""Calcul de l'inertie intra-groupe d'une liste de groupes"""
inerGroupeList = []
i = 0
for centre in centres:
inerGroupeList.append(inerGroupe(groupes[i], centre))
i = i + 1
inersum = 0
for iner in inerGroupeList:
inersum += iner
retu... | 57,394 |
def get_portf_perf(s):
""" xxx """
df = datetime.datetime.now() - timedelta(days=370)
connection = pymysql.connect(host=DB_SRV,
user=DB_USR,
password=DB_PWD,
db=DB_NAME,
chars... | 57,395 |
def _pretty_print(icylister, printer_func, with_timestamp=True, filter_fields=None):
"""
Reads the stream until the next metadata block appears and optionally enriches it with the current timestamp.
Than calls the printer function to print the metadata. Does this until KeyboardInterrupt is received.
You... | 57,396 |
def k_prototypes(X, n_clusters, gamma, init, n_init, max_iter, verbose):
"""k-prototypes algorithm"""
assert len(X) == 2, "X should be a list of Xnum and Xcat arrays"
# List where [0] = numerical part of centroid and
# [1] = categorical part. Same for centroids.
Xnum, Xcat = X
# Convert to nump... | 57,397 |
def ROT_THREE():
"""
ROT_THREE
Lifts second and third stack item one position up, moves top down
to position three.
"""
... | 57,398 |
def save_audio(wav_file):
"""
Stream audio from an input device and save it.
"""
p = pyaudio.PyAudio()
device = find_device(p, ["input", "mic", "audio"])
device_info = p.get_device_info_by_index(device)
channels = int(device_info['maxInputChannels'])
stream = p.open(
format=FOR... | 57,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.