content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def log(level, msg):
"""
level 0 : info
level 1 : warning
level 2 : error
msg : message(str)
"""
dent = " "
print(dent * level + msg) | 5,328,500 |
def esv(value, args=''):
"""
Use ESV API to get a Bible Passage
http://www.esvapi.org/v2/rest/passageQuery?key=IP&passage=Gen+1:5-10&output-format=plain-text
Looking for [[bible PASSAGE]]
Usage::
{{ text|esv}}
{{ text|esv:"option1:value,option2:value"}}
"""
if BIBL... | 5,328,501 |
def exec_func_shell(func, d, runfile, cwd=None):
"""Execute a shell function from the metadata
Note on directory behavior. The 'dirs' varflag should contain a list
of the directories you need created prior to execution. The last
item in the list is where we will chdir/cd to.
"""
# Don't let ... | 5,328,502 |
def books(db_path, auth, username, scrape):
"""Save books for a specified user, e.g. rixx"""
db = sqlite_utils.Database(db_path)
try:
data = json.load(open(auth))
token = data["goodreads_personal_token"]
user_id = data["goodreads_user_id"]
except (KeyError, FileNotFoundError):
... | 5,328,503 |
def main() -> None:
"""Make a jazz noise here"""
args = get_args()
# Create writer for outfile
out_flds = [
'source', 'unit', 'location_name', 'location_type', 'variable_name',
'variable_desc', 'collected_on', 'value', 'medium'
]
writer = csv.DictWriter(args.outfile, out_flds)
... | 5,328,504 |
def box_nms(bboxes, scores, labels, threshold=0.5, mode='union'):
"""Non maximum suppression.
source: https://github.com/kuangliu/pytorch-retinanet
Args:
bboxes: (tensor) bounding boxes, sized [N,4].
scores: (tensor) bbox scores, sized [N,].
threshold: (float) overlap threshold.
mod... | 5,328,505 |
def abs_length_diff(trg, pred):
"""Computes absolute length difference
between a target sequence and a predicted sequence
Args:
- trg (str): reference
- pred (str): generated output
Returns:
- absolute length difference (int)
"""
trg_length = len(trg.split(' '))
pr... | 5,328,506 |
def CDLEVENINGSTAR(data: xr.DataArray, penetration: float = 0.3) -> xr.DataArray:
"""
Evening Star (Pattern Recognition)
Inputs:
data:['open', 'high', 'low', 'close']
Outputs:
double series (values are -1, 0 or 1)
"""
return multiple_series_call(talib.CDLEVENINGSTAR, data, ds.TIM... | 5,328,507 |
def cern_authorized_signup_handler(resp, remote, *args, **kwargs):
"""Handle sign-in/up functionality.
:param remote: The remote application.
:param resp: The response.
:returns: Redirect response.
"""
# Remove any previously stored auto register session key
session.pop(token_session_key(re... | 5,328,508 |
def cr2_to_pgm(cr2_fname, pgm_fname=None, dcraw='dcraw', clobber=True, **kwargs): # pragma: no cover
""" Convert CR2 file to PGM
Converts a raw Canon CR2 file to a netpbm PGM file via `dcraw`. Assumes
`dcraw` is installed on the system
Note:
This is a blocking call
Arguments:
cr2... | 5,328,509 |
def asset_from_iconomi(symbol: str) -> Asset:
"""May raise:
- DeserializationError
- UnsupportedAsset
- UnknownAsset
"""
if not isinstance(symbol, str):
raise DeserializationError(f'Got non-string type {type(symbol)} for iconomi asset')
symbol = symbol.upper()
if symbol in UNSUPP... | 5,328,510 |
def ConvertHashType(value):
"""
Attempt to convert a space separated series of key=value pairs into a dictionary
of pairs. If any value fails to split successfully an error will be raised.
:param value: Space delimited string of key-value pairs
:return: Dictionary of key-value pairs.
"""
co... | 5,328,511 |
def ts_dct_from_estsks(pes_idx, es_tsk_lst, rxn_lst, thy_dct,
spc_dct, run_prefix, save_prefix):
""" build a ts queue
"""
print('\nTasks for transition states requested...')
print('Identifying reaction classes for transition states...')
# Build the ts_dct
ts_dct = {}
... | 5,328,512 |
def parse_msig_storage(storage: str):
"""Parse the storage of a multisig contract to get its counter (as a
number), threshold (as a number), and the keys of the signers (as
Micheline sequence in a string)."""
# put everything on a single line
storage = ' '.join(storage.split('\n'))
storage_regex... | 5,328,513 |
def adjust_spines(ax, spines):
"""
removing the spines from a matplotlib graphics.
taken from matplotlib gallery anonymous author.
parameters
----------
ax: a matplolib axes object
handler of the object to work with
spines: list of char
location of the spines
"""
fo... | 5,328,514 |
def doTestMethods(method, term, parm, options):
""" update SF using passed data"""
tf = file(options.trace, 'w+')
sfb = sForceApi3(dlog=tf, debug=options.debug)
ret = ['No test found for %s %s' %(method,parm)]
dtup = time.strptime('2004-04-21T12:30:59', ISO_8601_DATETIME)
dtsec = time.mkti... | 5,328,515 |
def do_index(request):
"""Render the index page."""
projects = [
(name, path)
for name, path in config.all_projects()
if request.user.can_open(path)
]
login_block = render_login_block(request)
html = util.render_template(
config.get_path('www.index_template'... | 5,328,516 |
def get_hathi_records(id):
"""
Deprecated. Yields records from the Hathi web API. But I'm using
"""
handler = XmlHandler()
url = "http://catalog.hathitrust.org/api/volumes/full/json/htid:" + id
f = urllib2.urlopen(url)
data = json.load(f)
for record in hathi_xml_yielder(data):
x... | 5,328,517 |
def extract_trajectory_to_file( # pylint: disable=R0912,R0913,R0914,R0915
nc_path,
out_path,
ref_system=None,
top=None,
nc_checkpoint_file=None,
state_index=None,
replica_index=None,
start_frame=0,
end_frame=-1,
skip_frame=1,
keep_... | 5,328,518 |
def test_PD015_fail_merge_on_pandas_object():
"""
Test that using .merge() on the pandas root object generates an error.
"""
statement = "pd.merge(df1, df2)"
tree = ast.parse(statement)
expected = [PD015(1, 0)]
actual = list(VetPlugin(tree).run())
assert actual == expected | 5,328,519 |
def sample_coll(word, urns=[], after=5, before=5, sample_size = 300, limit=1000):
"""Find collocations for word in a sample of set of book URNs"""
from random import sample
# check if urns is a list of lists, [[s1, ...],[s2, ...]...] then urn serial first element
# else the list is assumed to be o... | 5,328,520 |
def roll_array(arr: npt.ArrayLike, shift: int, axis: int = 0) -> np.ndarray:
"""Roll the elements in the array by `shift` positions along the given axis.
Parameters
----------
arr : :py:obj:`~numpy.typing.ArrayLike`
input array to roll
shift : int
number of bins to shift by
axis... | 5,328,521 |
def remove(favourites_list, ctype, pk, **options):
"""Remove a line from the favourites_list. """
instance = unpack_instance_key(favourites_list, ctype, pk)
return favourites_list.remove(instance, options=options) | 5,328,522 |
def area_rm(path):
"""
实现矢量面积统计,将面积写道属性表中,并按照面积属性进行筛选,删除面积最大的要素。
:param path:矢量文件
"""
driver = ogr.GetDriverByName('ESRI Shapefile')
poly_DS = driver.Open(path,1)
poly_lyr = poly_DS.GetLayer(0)
prosrs = poly_lyr.GetSpatialRef() #获取投影坐标信息
#print("投影坐标系为:",prosrs)
geosr... | 5,328,523 |
def eHealthClass_airFlowWave(*args):
"""eHealthClass_airFlowWave(int air)"""
return _ehealth.eHealthClass_airFlowWave(*args) | 5,328,524 |
def interactive_plot(outdir='./_output',format='ascii'):
"""
Convenience function for launching an interactive plotting session.
"""
from visclaw.plotters import Iplotclaw
ip=Iplotclaw.Iplotclaw()
ip.plotdata.outdir=outdir
ip.plotdata.format=format
ip.plotloop() | 5,328,525 |
def build_gtid_ranges(iterator):
"""Yield dicts containing most compact representation of all (timestamp, UUID, GNO) tuples
returned by given iterator. Ranges are returned in correct order and no gaps are allowed.
If input contains uninterrupted sequence of events from a single server only one range is
... | 5,328,526 |
def bp_symm_func(tensors, sf_spec, rc, cutoff_type):
""" Wrapper for building Behler-style symmetry functions"""
sf_func = {'G2': G2_SF, 'G3': G3_SF, 'G4': G4_SF}
fps = {}
for i, sf in enumerate(sf_spec):
options = {k: v for k, v in sf.items() if k != "type"}
if sf['type'] == 'G3': # Wo... | 5,328,527 |
def test_lock_error(request, mocker, runner):
"""
Lock a configuration and check for exceptions when redis fails.
"""
if not MOCKED:
pytest.xfail("need mocking")
key = request.node.name
with open("pytest.ini", "w") as config:
config.write("[pytest]\naddopts = --setup-only")
... | 5,328,528 |
def create_dummy_window(show_all=True, should_quit=False, fullscreen=False):
"""
Function to create dummy window which does nothing.
:param show_all: True if window should be shown immediately
:param should_quit: True if window should quit after user closed it
:param fullscreen: True if window shou... | 5,328,529 |
def color_RGB_to_hs(iR: float, iG: float, iB: float) -> tuple[float, float]:
"""Convert an rgb color to its hs representation."""
return color_RGB_to_hsv(iR, iG, iB)[:2] | 5,328,530 |
def remove_linked_attachments(root, atts, ns):
"""Remove linked attachments and related linkage."""
rdf_about = f"{{{ns['rdf']}}}about"
rdf_res = f"{{{ns['rdf']}}}resource"
att_ids = set([att.get(rdf_about) for att in atts])
for bib in root.iterfind("bib:*", ns):
att_to_remove = []
... | 5,328,531 |
def drawFighterPath(time, surface, fighterSprite, path):
"""Draws the path of the fighter.
fighterSprite is the sprite of the fighter.
path is the series of tiles the fighter will walk through."""
return | 5,328,532 |
def select_thread(*args):
"""
select_thread(tid) -> bool
Select the given thread as the current debugged thread. All thread
related execution functions will work on this thread. The process must
be suspended to select a new thread. \sq{Type, Synchronous function -
available as request, Notification, none ... | 5,328,533 |
def f():
"""Redefinition of the function."""
print('second f') | 5,328,534 |
def simulation_aggreation_merge(rankings, baseline, method='od'):
"""Merge rankings by running simulation of existing rankings. This would first extract relative position of different ranking results,
and relative position are considered as simulated games. The game results are sent to another ranker that gives... | 5,328,535 |
def maxOverTime(field,makeTimes=0):
"""Take the max of the values in each time step
If makeTimes is true (1) then we return a field mapping all of the times
to the average. Else we just return the max """
return GridMath.maxOverTime(field,makeTimes); | 5,328,536 |
async def test_arlo_baby_setup(hass):
"""Test that an Arlo Baby can be correctly setup in HA."""
accessories = await setup_accessories_from_file(hass, "arlo_baby.json")
await setup_test_accessories(hass, accessories)
await assert_devices_and_entities_created(
hass,
DeviceTestInfo(
... | 5,328,537 |
def assemble_docstring(parsed, sig=None):
"""
Assemble a docstring from an OrderedDict as returned by
:meth:`nd.utils.parse_docstring()`
Parameters
----------
parsed : OrderedDict
A parsed docstring as obtained by ``nd.utils.parse_docstring()``.
sig : function signature, optional
... | 5,328,538 |
def retrieve_unscoped_token(os_auth_url, access_token, protocol="openid"):
"""Request an unscopped token"""
url = get_keystone_url(
os_auth_url,
"/v3/OS-FEDERATION/identity_providers/egi.eu/protocols/%s/auth" % protocol,
)
r = requests.post(url, headers={"Authorization": "Bearer %s" % ac... | 5,328,539 |
def load_dataset(csv_path, relative_path):
"""
Inputs
---
csv_path: path to training data csv
relative_path: relative path to training data
Outputs
---
X: Training data numpy array
y: Training labels numpy array
"""
# Read CSV lines
lines = []
with open(csv_path) as ... | 5,328,540 |
def randomly_replace_a_zone() -> rd.RouteDict:
"""
读入历史数据,把每条 high quality 的 route 的一个随机的 zone 替换成新 zone
:return: rd.RouteDict: 改过的route
"""
routeDict = rd.loadOrCreate()
rng.seed(3)
new_zone_id = 'zub_fy'
i: int
rid: str
route: rd.Route
for (i, (rid, route)) i... | 5,328,541 |
def check_default_make_help(project):
"""Check that we have the expected make targets in the default
configuration"""
res = make(project, 'help')
stdout = res.stdout
# some versions of make print additional information that we need to strip
stdout = re.sub(r'make.*: Entering directory.*\n', '', ... | 5,328,542 |
def import_loop(schema, mutable, raw_data=None, field_converter=None, trusted_data=None,
mapping=None, partial=False, strict=False, init_values=False,
apply_defaults=False, convert=True, validate=False, new=False,
oo=False, recursive=False, app_data=None, context=None):
... | 5,328,543 |
def test_rectangles():
"""Test instantiating Shapes layer with a random 2D rectangles."""
# Test a single four corner rectangle
shape = (1, 4, 2)
np.random.seed(0)
data = 20 * np.random.random(shape)
layer = Shapes(data)
assert layer.nshapes == shape[0]
assert np.all(layer.data[0] == dat... | 5,328,544 |
def print_error(fmt_str, value, error_content):
"""
send errors to stdout. This displays errors on the screen.
:param int fmt_str: a Python `format string <https://docs.python.org/3/library/string.html#formatspec>`_
for the error. Can use arguments **{value}** and **{error_content}** in the format st... | 5,328,545 |
def resnet_50(inputs, block_fn=bottleneck_block, is_training_bn=False):
"""ResNetv50 model with classification layers removed."""
layers = [3, 4, 6, 3]
data_format = 'channels_last'
inputs = conv2d_fixed_padding(
inputs=inputs,
filters=64,
kernel_size=7,
strides=2,
data_format=dat... | 5,328,546 |
def _sanitize_index_element(ind):
"""Sanitize a one-element index."""
if isinstance(ind, Number):
ind2 = int(ind)
if ind2 != ind:
raise IndexError(f"Bad index. Must be integer-like: {ind}")
else:
return ind2
elif ind is None:
return None
else:
... | 5,328,547 |
def overlap_click(original, click_position, sr=44100, click_freq=2000, click_duration=0.5):
"""
:param click_position: Notice that position should be given in second
:return: wave
"""
cwave = librosa.clicks(np.array(click_position), sr=44100, click_freq=4000, click_duration=0.05) / 2
original, w... | 5,328,548 |
def vigenere(plaintext: str, *, key: str) -> str:
"""Vigenère cipher (page 48)
- `plaintext` is the message to be encrypted
- `key` defines the series of interwoven Caesar ciphers to be used
"""
plaintext = validate_plaintext(plaintext)
key = validate_key(key)
cycled_cipher_alphabet = iter... | 5,328,549 |
def generateVtTick(row, symbol):
"""生成K线"""
tick = VtTickData()
tick.symbol = symbol
tick.vtSymbol = symbol
tick.lastPrice = row['last']
tick.volume = row['volume']
tick.openInterest = row['open_interest']
tick.datetime = row.name
tick.openPrice = row['open']
tick.highPrice ... | 5,328,550 |
def hartigan_map_mutations(tree, genotypes, alleles, ancestral_state=None):
"""
Returns a Hartigan parsimony reconstruction for the specified set of genotypes.
The reconstruction is specified by returning the ancestral state and a
list of mutations on the tree. Each mutation is a (node, parent, state)
... | 5,328,551 |
def padArray(ori_array, pad_size):
"""
Pads out an array to a large size.
ori_array - A 2D numpy array.
pad_size - The number of elements to add to each of the "sides" of the array.
The padded 2D numpy array.
"""
if (pad_size > 0):
[x_size, y_size] = ori_array.shape
lg_... | 5,328,552 |
def finish_subprocess(proc, cmdline, cmd_input=None, ok_exit_codes=None):
"""Ensure that the process returned a zero exit code indicating success"""
if ok_exit_codes is None:
ok_exit_codes = [0]
out, err = proc.communicate(cmd_input)
ret = proc.returncode
if ret not in ok_exit_codes:
... | 5,328,553 |
def _gmapsusage(filename):
"""
Construct a usage string.
"""
usage = "{} <mapps_image_dump_file> [path_to_mapps_config_file]".format(
filename)
# Print usage string.
print("\n[Usage]: python {}\n".format(usage)) | 5,328,554 |
def browse():
"""
A simple browser that doesn't deal with queries at all
"""
page = int(request.args.get("page", 1))
includeHistory = request.args.get("includeHistory", False)
results_per_page, search_offset = results_offset(page)
searchIndex = "history" if includeHistory else "latest"... | 5,328,555 |
def argmax(pda: pdarray) -> np.int64:
"""
Return the index of the first occurrence of the array max value.
Parameters
----------
pda : pdarray
Values for which to calculate the argmax
Returns
-------
np.int64
The index of the argmax calculated from the pda
Raises
... | 5,328,556 |
def log_cumsum(probs, dim=1, eps=1e-8):
"""Calculate log of inclusive cumsum."""
return torch.log(torch.cumsum(probs, dim=dim) + eps) | 5,328,557 |
def iou_coe_Slice_by_Slice(output, target, threshold=0.5, axis=(2, 3,4), smooth=1e-5):
"""Non-differentiable Intersection over Union (IoU) for comparing the similarity
"""
pre = tf.cast(output > threshold, dtype=tf.float32)
truth = tf.cast(target > threshold, dtype=tf.float32)
inse = tf.reduce_sum(... | 5,328,558 |
def simulation(num_simulations: int, st: np.array(), ct: np.array(), pt: np.array(), st_ind: np.array()):
"""
Compute Monte Carlo simulation to generate stock paths
for basket option pricing. Here we are computing both
the call option and the put option.
Args:
int: number of simulations num... | 5,328,559 |
def main_timing_test_blackbox(datapoints, model: CompressionModel, bbstream: BlackBoxBitstream):
"""
Timing test for the black box algorithm
"""
enc_times = []
for single_x_raw in tqdm(datapoints, desc='encoding (black box)'):
init_bits = len(bbstream)
tstart = time.time()
b... | 5,328,560 |
def plot_stat(data_source, fig_location=None, show_figure=False):
"""
Processes input data and plots the bar graph displaying number of accidents
:param data_source: Data used to plot the graph
:param fig_location: Folder where graph will be saved
:param show_figure: If set to True shows graph
:... | 5,328,561 |
def fetch_step(step_key, stdio_url, parse_gtest, parse_suppression):
"""Fetches data about a single build step."""
step = BuildStep.get(step_key)
if step.is_fetched:
return
step.fetch_timestamp = datetime.datetime.now()
step.put()
try:
stdio_response = urlfetch.fetch(stdio_url, deadline=URLFETCH_DE... | 5,328,562 |
def load_ipython_extension(ipython: 'IPython.InteractiveShell') -> None:
"""Initialize magics commands and initialize the ``abcjs`` library
``abcjs`` is initialized by loading the Javascript library and assigning it
to the window global ``ABCJS``.
:param ipython: The active IPython instance
"""
... | 5,328,563 |
def pprint_int_dict(int_dict, indent=4, descending=False):
"""Prints the given dict with int values in a nice way.
Parameters
----------
int_dict : list
A dict object mapping each key to an int value.
"""
sorted_tup = sorted(int_dict.items(), key=lambda x: x[1])
if descending:
... | 5,328,564 |
def splitTrainTestDataList(list_data, test_fraction=0.2, sample_size=None, replace=False, seed=None):
"""
Split a list of data into train and test data based on given test fraction.
Each data in the list should have row for sample index, don't care about other axes.
:param list_data: List of data to sa... | 5,328,565 |
def create_hyperbounds(hyperparameters):
"""
Gets the bounds of each hyperspace for sampling.
Parameters
----------
* `hyperparameters` [list, shape=(n_hyperparameters,)]
Returns
-------
* `hyperspace_bounds` [list of lists, shape(n_spaces, n_hyperparameters)]
- All combinations... | 5,328,566 |
def race_from_string(str):
"""Convert race to one of ['white', 'black', None]."""
race_dict = {
"White/Caucasian": 'white',
"Black/African American": 'black',
"Unknown": None,
"": None
}
return race_dict.get(str, 'other') | 5,328,567 |
def _handling_alias_parameters(lgbm_params):
# type: (Dict[str, Any]) -> None
"""Handling alias parameters."""
for alias_group in _ALIAS_GROUP_LIST:
param_name = alias_group["param_name"]
alias_names = alias_group["alias_names"]
for alias_name in alias_names:
if alias_n... | 5,328,568 |
def test_client_disarm(server, client):
"""Should call the API and disarm the system."""
html = """[
{
"Poller": {"Poller": 1, "Panel": 1},
"CommandId": 5,
"Successful": true
}
]"""
server.add(
responses.POST,
"https://example.com/api/p... | 5,328,569 |
def test_wrap_coordinates(coords, origin, wgs84):
""" Test whether coordinates wrap around the antimeridian in wgs84 """
lon_under_minus_170 = False
lon_over_plus_170 = False
if isinstance(coords[0], list):
for c in coords[0]:
c = list(transform(origin, wgs84, *c))
if c[0... | 5,328,570 |
def filter_dfg_contain_activity(dfg0, start_activities0, end_activities0, activities_count0, activity, parameters=None):
"""
Filters the DFG keeping only nodes that can reach / are reachable from activity
Parameters
---------------
dfg0
Directly-follows graph
start_activities0
S... | 5,328,571 |
def test_sigma_dut_suite_b_rsa(dev, apdev, params):
"""sigma_dut controlled STA Suite B (RSA)"""
check_suite_b_192_capa(dev)
logdir = params['logdir']
with open("auth_serv/rsa3072-ca.pem", "r") as f:
with open(os.path.join(logdir, "suite_b_ca_rsa.pem"), "w") as f2:
f2.write(f.read()... | 5,328,572 |
def get_header_keys(files_dict,keys):
"""
Save important keywords from pre-swarp input files headers.
"""
for i in files_dict.keys():
cont = 1
with open('%s.hdr'%i,'w') as out_hdr:
for _file in files_dict[i]:
output = sp.check_output("dfits {} | egrep '{}' ".f... | 5,328,573 |
def generate_secret_key(length=16):
"""
Generates a key of the given length.
:param length: Length of the key to generate, in bytes.
:type length: :class:`int`
:returns: :class:`str` -- The generated key, in byte string.
"""
return get_random_bytes(length) | 5,328,574 |
def fetch_data(ctx, remote, startpoint, aset, nbytes, all_):
"""Get data from REMOTE referenced by STARTPOINT (short-commit or branch).
The default behavior is to only download a single commit's data or the HEAD
commit of a branch. Please review optional arguments for other behaviors
"""
from hanga... | 5,328,575 |
def nouveau_flux(title: str, link: str, description: str) -> parse:
"""
Crée un nouveau flux RSS.
Parameters
----------
title : str
Titre du flux RSS.
link : str
Lien vers le flux RSS.
description : str
Description générale du contenu.
Returns
-------
pa... | 5,328,576 |
def benchmark(repo, runscript, wrapcmd, tag):
"""Run benchmark build."""
f = "bench.%s.%s.sh" % (repo, tag)
u.verbose(1, "... running %s" % f)
if os.path.exists(f):
rmfile(f)
try:
with open(f, "w") as wf:
wf.write("#!/bin/sh\n")
wf.write("set -x\n")
if flag_gomaxprocs:
wf.wri... | 5,328,577 |
def select_all_rows_from_table(context, table):
"""Select number of all rows from given table."""
cursor = context.connection.cursor()
try:
cursor.execute("SELECT count(*) as cnt from {}".format(table))
results = cursor.fetchone()
assert len(results) == 1, "Wrong number of records re... | 5,328,578 |
def get_open_strain_data(
name, start_time, end_time, outdir, cache=False, buffer_time=0, **kwargs):
""" A function which accesses the open strain data
This uses `gwpy` to download the open data and then saves a cached copy for
later use
Parameters
----------
name: str
The name... | 5,328,579 |
def extract_text(path):
""" Extract the text of all txt files in the path,
and store it in a dictionary.
Return the dic with the structure:
key : 'filename' (without .txt extension and without the page number)
value : 'text'
"""
from tqdm import tqdm
files_to_search = os.path.join(path,'*.txt')
data_dic =... | 5,328,580 |
def extract_app_name_key():
"""
Extracts the application name redis key and hash from the request
The key should be of format:
<metrics_prefix>:<metrics_application>:<ip>:<rounded_date_time_format>
ie: "API_METRICS:applications:192.168.0.1:2020/08/04:14"
The hash should be of format:
... | 5,328,581 |
def load(filename, fs, duration, flipud = True, display=False, **kwargs):
"""
Load an image from a file or an URL
Parameters
----------
filename : string
Image file name, e.g. ``test.jpg`` or URL.
fs : scalar
Sampling frequency of the audiogram (in Hz)
... | 5,328,582 |
def get_status(lib, device_id):
"""
A function of reading status information from the device
You can use this function to get basic information about the device status.
:param lib: structure for accessing the functionality of the libximc library.
:param device_id: device id.
"""
... | 5,328,583 |
def query_by_image_objects(image_path, weights_path, cfg_path, names_path,
confidence_threshold=0.5, save=False):
"""Processes user-uploaded image to retrieve similar images from database.
First, all the objects in the image are detected using the :method:
``rubrix.images.detect... | 5,328,584 |
def suspend_supplier_services(client, logger, framework_slug, supplier_id, framework_info, dry_run):
"""
The supplier ID list should have been flagged by CCS as requiring action, but double check that the supplier:
- has some services on the framework
- has `agreementReturned: false`
- has not... | 5,328,585 |
def get_events():
"""Get events from meetup website, parse them and return a list of dicts"""
group = os.environ['MEETUP_GROUP']
url = f'https://www.meetup.com/{group}/events/'
resp = HTMLSession().get(url, timeout=10)
if not resp.ok:
raise ConnectionError(
f"Received http {resp... | 5,328,586 |
def get_campaigns_with_goal_id(campaigns, goal_identifer):
"""Returns campaigns having the same goal_identifier passed in the args
from the campaigns list
Args:
campaigns (list): List of campaign objects
gaol_identifier (str): Global goal identifier
Returns:
tuple (campaign_goa... | 5,328,587 |
def test_training_cli(generator_args, training_args, network_args,
monkeypatch):
"""this tests that the training CLI validates the schemas
and executes its logic. Calls to generator, network and training
are minimally mocked.
"""
args = {
"run_uid": "test_uid",
... | 5,328,588 |
def tautologically_define_state_machine_transitions(state_machine):
"""Create a mapping of all transitions in ``state_machine``
Parameters
----------
state_machine : super_state_machine.machines.StateMachine
The state machine you want a complete map of
Returns
-------
dict
... | 5,328,589 |
def test_load_labware_result(well_plate_def: LabwareDefinition) -> None:
"""It should have a LoadLabwareResult model."""
result = LoadLabwareResult(
labwareId="labware-id",
definition=well_plate_def,
calibration=(1, 2, 3),
)
assert result.labwareId == "labware-id"
assert res... | 5,328,590 |
def test_check_name_typographicsubfamilyname():
""" Check name table: TYPOGRAPHIC_SUBFAMILY_NAME entries. """
check = CheckTester(googlefonts_profile,
"com.google.fonts/check/name/typographicsubfamilyname")
RIBBI = "montserrat/Montserrat-BoldItalic.ttf"
NON_RIBBI = "montserrat/M... | 5,328,591 |
def jump_pfd(data, *args, **kwargs):
"""
Uses refined searching stategies to greedily jump to a node in the
search lattice.
AG's feature_permutation returns feature importances that aren't
additive and thus don't sum up to equal the model's loss function.
Which is why I normalize the permutatio... | 5,328,592 |
def topk_errors(preds: Tensor, labels: Tensor, ks: List[int]):
"""
Computes the top-k error for each k.
Args:
preds (array): array of predictions. Dimension is N.
labels (array): array of labels. Dimension is N.
ks (list): list of ks to calculate the top accuracies.
"""
num_t... | 5,328,593 |
def extract_data_from_inspect(network_name, network_data):
"""
:param network_name: str
:param network_data: dict
:return: dict:
{
"ip_address4": "12.34.56.78"
"ip_address6": "ff:fa:..."
}
"""
a4 = None
if network_name == "host":
a4 = "127.0.0.... | 5,328,594 |
def solveSudoku(fileName = "", showResults = False, showTime = False, matrix = []):
"""
Solves a Sudoku by prompting the sudoku or reading a text file containing the sudoku or by directly
taking the matrix as a variable and either shows the solution or returns it. Can also tell the execution time
(Any o... | 5,328,595 |
def set_callback_timeout(timeout):
"""
Set the default timeout (in seconds) for DSWaitedCallback.
In case of a deadlock, the wait function will exit after the timeout period.
Args:
timeout (int): timeout(s) to be used to end teh wait in DSWaitedCallback in case of a deadlock.
Raises:
... | 5,328,596 |
def test_create_metadata_from_parsed_metadatafil(_innhold):
"""
GIVEN the content(XML) of a METS/XML file
WHEN calling the method create_metadata_from_parsed_metadatafil()
THEN check that the returned Arkivuttrekk domain object is correct
"""
expected = Metadata(
obj_id=UUID("df5... | 5,328,597 |
def vertexval(val, size):
"""Converto to row,col or raise GTP error."""
val = val.lower()
if val == 'pass':
return None
letter = str(val[0])
number = int(val[1:], 10)
if not 'a' <= letter <= 'z':
raise GTPError('invalid vertex letter: {!r}'.format(val))
if number < 1:
... | 5,328,598 |
def v0abs(x_ratio, distance_source, lr_angle, br_angle):
""" Returns the norm for the velocity reference v_0"""
vy_comp = vly(x_ratio, distance_source, lr_angle, br_angle) - (1.-x_ratio)*voy(lr_angle)
vz_comp = vlz(x_ratio, distance_source, lr_angle, br_angle) - (1.-x_ratio)*voz(lr_angle, br_angle)
#vy ... | 5,328,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.