content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def io_loop():
"""
Create new io loop for each test, and tear it down after.
"""
loop = salt.ext.tornado.ioloop.IOLoop()
loop.make_current()
try:
yield loop
finally:
loop.clear_current()
loop.close(all_fds=True) | 5,348,600 |
def inverse_sphere_distances(batch, dist, labels, anchor_label):
"""
Function to utilise the distances of batch samples to compute their
probability of occurence, and using the inverse to sample actual negatives to the resp. anchor.
Args:
batch: torch.Tensor(), batch ... | 5,348,601 |
def add_module_path(folder):
"""Adds a new search path to the list of search paths."""
import os
__path__.append(os.path.abspath(folder)) | 5,348,602 |
def get_recording(sleeps=False):
"""Get list of recorded steps.
:param sleeps: set False to exclude recording sleeps
"""
# TODO. atm will always use CLICK
# TODO. Add examples
global recording # pylint: disable=W0602
output = []
top = None
action_name = "Click"
for item in reco... | 5,348,603 |
def wrap_onspace(text, width):
"""
A word-wrap function that preserves existing line breaks
and most spaces in the text. Expects that existing line
breaks are posix newlines (\n).
"""
return reduce(lambda line, word, width=width: '%s%s%s' %
(line, ' \n'[(len(line[line.rfind('\n... | 5,348,604 |
def xsd_simple_type_factory(elem, schema, parent):
"""
Factory function for XSD simple types. Parses the xs:simpleType element and its
child component, that can be a restriction, a list or an union. Annotations are
linked to simple type instance, omitting the inner annotation if both are given.
"""
... | 5,348,605 |
def test_add_user_to_group(onefs_client, created_user, created_group):
"""Ensure that a user can be added to a group successfully."""
assert onefs_client.add_user_to_group(
user_name=created_user[0],
group_name=created_group[0],
) is None | 5,348,606 |
def setup_logger(run_mode="training", log_level=10, console_logging=True):
"""
Call logger create module and setup the logger for current run
params: run_mode - str - optional - Default - training
params: log_level - int - optional - Default - 20 - INFO
params: console_logging - Boolean - optional -... | 5,348,607 |
def amen_solve(A, f, x0, eps, kickrank=4, nswp=20, local_prec='n',
local_iters=2, local_restart=40, trunc_norm=1, max_full_size=50, verb=1):
""" Approximate linear system solution in the tensor-train (TT) format
using Alternating minimal energy (AMEN approach)
:References: Sergey Dolgov,... | 5,348,608 |
def get_vss(ts, tau_p):
""" Compute candidates of VS for specified task tau_p """
if tau_p == None:
return []
C, T, D = extract(ts)
R = rta(C, T)
_VS = _get_vs(C, T, R, task_name_to_index(ts, tau_p))
_VS.sort()
VS = []
vs = Server(0, 0, None)
# ignore duplicates
for s i... | 5,348,609 |
def groupby(
entities: Iterable["DXFEntity"], dxfattrib: str = "", key: "KeyFunc" = None
) -> Dict[Hashable, List["DXFEntity"]]:
"""
Groups a sequence of DXF entities by a DXF attribute like ``'layer'``,
returns a dict with `dxfattrib` values as key and a list of entities
matching this `dxfattrib`.
... | 5,348,610 |
def py_binary(name,
srcs=[],
deps=[],
main=None,
base=None,
**kwargs):
"""python binary. """
target = PythonBinary(name,
srcs,
deps,
main,
... | 5,348,611 |
def train_test_split(data_filepath, num_train=10, num_test=10):
"""Split a dataset into training and test sets."""
df = pd.read_csv(data_filepath, sep=',', header=None)
data = df.values
train = data[:2*num_train, :]
test = data[2*num_train:2*(num_train+num_test), :]
ind = np.argsort(train[:,-1... | 5,348,612 |
def get_filings(app: Flask = None):
"""Get a filing with filing_id."""
r = requests.get(f'{app.config["LEGAL_URL"]}/internal/filings')
if not r or r.status_code != 200:
app.logger.error(f'Failed to collect filings from legal-api. {r} {r.json()} {r.status_code}')
raise Exception
return r.... | 5,348,613 |
def _uno_struct__setattr__(self, name, value):
"""Sets attribute on UNO struct.
Referenced from the pyuno shared library.
"""
return setattr(self.__dict__["value"], name, value) | 5,348,614 |
def load_imgs_from_tree(data_dir, img_sub_folder=None, fovs=None, channels=None,
dtype="int16", variable_sizes=False):
"""Takes a set of imgs from a directory structure and loads them into an xarray.
Args:
data_dir (str):
directory containing folders of images
... | 5,348,615 |
def register():
"""Registers the user."""
if g.user:
return redirect(url_for('user_home'))
error = None
if request.method == 'POST':
if not request.form['username']:
error = 'You have to enter a username'
elif not request.form['email'] or '@' not in request.form['em... | 5,348,616 |
def test_single_while_2():
"""
Feature: JIT Fallback
Description: Test fallback with control flow.
Expectation: No exception.
"""
@ms_function
def control_flow_while():
x = Tensor(7).astype("int32")
y = Tensor(0).astype("int32")
while x >= y:
y += x
... | 5,348,617 |
def build_and_predict_model(ml_input_df):
"""
Create a standardized feature matrix X and target array y.
Returns the model and accuracy statistics
"""
import cuml
from cuml.metrics import confusion_matrix
feature_names = ["college_education", "male"] + [
"clicks_in_%d" % i for i in ... | 5,348,618 |
def codes_new_from_file(fileobj, product_kind, headers_only=False):
"""
@brief Load in memory a message from a file for a given product.
The message can be accessed through its id and will be available\n
until @ref grib_release is called.\n
\b Examples: \ref get_product_kind.py "get_product_kind.p... | 5,348,619 |
def list_resources(path, long_format=None, relations=False):
"""List resources in a given DMF workspace.
Args:
path (str): Path to the workspace
long_format (bool): List in long format flag
relations (bool): Show relationships, in long format
Returns:
None
"""
t = C... | 5,348,620 |
def calc_streamtemp(tas):
""" Global standard regression equation from Punzet et al. (2012)
Calculates grid cell stream temperature based on air temperature
Both input and output temperature are in K"""
# global constants, taken from Punzet et al., 2012
c0 = 32; c1 = -0.13; c2 = 1.94
... | 5,348,621 |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
# nothing more to process
return proc_data | 5,348,622 |
def _extractor_image_dependencies():
"""Defines external repositories necessary for extractor images."""
go_repository(
name = "com_github_bazelbuild_bazelisk",
importpath = "github.com/bazelbuild/bazelisk",
tag = "v1.3.0",
)
go_repository(
name = "com_github_mitchellh_go... | 5,348,623 |
def get_station_info(my_token, station_id):
"""
This function gets all the information on the station
----------
Input:
my_token (str)
token generated from "token request page"
station_id (str)
----------
Output:
dictionary of station information
"""
station_url = '{}stations/{}'.format(base_url, s... | 5,348,624 |
def start(task):
"""
Start cache and start the Stanford parser
"""
startCache(task)
startServer(task.stanfordParserConfig()) | 5,348,625 |
def test_salt_cp(master, minion, salt_cp, tempfiles):
"""
Test copying a file from the master to the minion
"""
tfile = tempfile.NamedTemporaryFile(delete=True)
tfile.close()
dest = tfile.name
try:
contents = "id: foo"
sls = tempfiles.makeslsfile(contents)
assert mast... | 5,348,626 |
def json_response(f, *args, **kwargs):
"""Wrap a view in JSON.
This decorator runs the given function and looks out for ajax.AJAXError's,
which it encodes into a proper HttpResponse object. If an unknown error
is thrown it's encoded as a 500.
All errors are then packaged up with an appropriate Con... | 5,348,627 |
def tests_pyenv(session: nox_poetry.Session):
"""
Runs pytest with coverage on the latest patch of each available pyenv minor python version at least 3.7.
"""
_run_tests(session) | 5,348,628 |
def check_fit_input(coordinates, data, weights, unpack=True):
"""
Validate the inputs to the fit method of gridders.
Checks that the coordinates, data, and weights (if given) all have the same
shape. Weights arrays are raveled.
Parameters
----------
coordinates : tuple of arrays
Ar... | 5,348,629 |
def main():
"""
Main
:return: void
"""
a = ProbabilityTable({"Werewolf": 3, "Possessed": 1, "Villager": 8, "Bodyguard": 1, "Medium": 1, "Seer": 1},
["Player1", "Player2", "Player3", "Player4", "Player5", "Player6", "Player7", "Player8",
"Player9... | 5,348,630 |
def _sigint_handler(sig, frame):
"""Signal handler for ^C."""
global polite_stop
if not polite_stop:
print('Stop requested. Regression will stop safely at next iteration. '
'Press ^C again to force quit.')
polite_stop = True
else:
print('Force quitting now.')
... | 5,348,631 |
def get_logger(name, handler=logging.StreamHandler(sys.stderr), level=logging.DEBUG):
"""
encapsulate get logger operation
:param name: logger name
:param handler: logger handler, default is stderr
:param level: logger level, default is debug
:return: logger
"""
logger = logging.getLogge... | 5,348,632 |
def update_params(layers, param_grads, learning_rate):
"""
Function to update the parameters of the given layers with the given gradients
by gradient descent with the given learning rate.
"""
for layer, layer_backprop_grads in zip(layers, param_grads):
for param, grad in zip(layer.get_params... | 5,348,633 |
def get_local_beneficiaries(map_lat: float, map_lng: float, map_zoom: int) -> DataFrame:
"""Return only projects that are fairly close to the map's centre."""
return beneficiaries[
(map_lat - 100 / map_zoom < beneficiaries.lat) &
(beneficiaries.lat < map_lat + 100 / map_zoom) &
(map_lng... | 5,348,634 |
def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Build html reveal.js slides from markdown in docs/ dir")
p... | 5,348,635 |
def main(model=None, new_model_name="imasc", output_dir="IMaSC", n_iter=10):
"""Set up the pipeline and entity recognizer, and train the new entity."""
random.seed(0)
if model is not None:
nlp = spacy.load(model) # load existing spaCy model
print("Loaded model '%s'" % model)
else:
... | 5,348,636 |
def imayavi_remove_source(src):
"""Safely remove a specific vtk source
Args:
src (vtk_data_source): vtk data source to remove
"""
src.stop()
try:
try:
src.data.release_data()
except TraitError:
src.data.release_data_flag = 1
src.cell_scalars_n... | 5,348,637 |
def lines_to_word_occurrences(in_file, stdout):
"""For each line of input, output (word, 1) for each word in the line"""
for line in in_file:
for word in WORD_RE.findall(line):
_write(stdout, word, 1) | 5,348,638 |
def create_atoms(atoms, atom_dict):
"""Transform the atom types in a molecule (e.g., H, C, and O)
into the indices (e.g., H=0, C=1, and O=2).
"""
atoms = [atom_dict[a] for a in atoms]
return np.array(atoms) | 5,348,639 |
def uint2float(A,bits,x_min,x_max=None):
"""
Converts uint[bits] to the corresponding floating point value in the range [x_min,x_max].
"""
if x_max is None:
x_min,x_max = x_range(x_min)
return x_min + (x_max - x_min) * A / ((1 << bits) - 1) | 5,348,640 |
def test_get_all_pos_error():
"""Check that we get an error when we don't specify qso."""
cat = catalog.Catalog("foo")
with pytest.raises(ValueError, match="Only know how to do QSOs right now"):
cat.get_all_pos()
return | 5,348,641 |
def partCmp(verA: str, verB: str) -> int:
"""Compare parts of a semver.
Args:
verA (str): lhs part to compare
verB (str): rhs part to compare
Returns:
int: 0 if equal, 1 if verA > verB and -1 if verA < verB
"""
if verA == verB or verA == "*" or verB == "*":
return 0
if int(verA) > int(verB):
return 1
... | 5,348,642 |
def plot_clustering(X, Y_hat,
color=[1, 0, 0],
mode='outer',
show=False,
savefn=''):
"""Plot boundaries produced by segmentation."""
# Initialize subplots
fg, ax = plt.subplots(ncols=1, figsize=(10, 10))
# Plot prediction
... | 5,348,643 |
def OrigPosLemConcordancer(sentences, annots, textMnt, wordType="word", nrows=10):
"""Output HTML for the text (including lemma and pos tags) identified by the AQAnnotation (typically a sentence annotation).
Below the sentence (in successive rows) output the original terms, parts of speech, and lemma terms for... | 5,348,644 |
def get_args(**kwargs):
"""Generate cli args
Arguments:
kwargs[dict]: Pair value in which key is the arg and value a tuple with the help message and default value
Returns:
Namespace: Args namespace object
"""
parser = argparse.ArgumentParser()
for key, (help, default) in kwa... | 5,348,645 |
def dispfps(handler, n=100):
"""Average iterations per second over last n iterations.
Args:
handler (generator): Generator that yields data.
n (int, optional): Number of iterations to average over. Defaults to 100.
Yields:
pyobj: Forwards data from handler
"""
times = deque... | 5,348,646 |
def show_hidden_article(request, id):
"""
展示隐藏的文章
"""
db = connect_mongodb_database(request)
article = db.articles.find_one({
'Id':int(id), 'IsPublic': False
})
if article is None:
return HttpResponse(404)
return render_admin_and_back(request, 'show-hidden-article.html',... | 5,348,647 |
def MakeNormalPmf(mu, sigma, num_sigmas, n=201):
"""Makes a PMF discrete approx to a Normal distribution.
mu: float mean
sigma: float standard deviation
num_sigmas: how many sigmas to extend in each direction
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
... | 5,348,648 |
def _val_from_env(env, attr):
"""Transforms env-strings to python."""
val = os.environ[env]
if attr == 'rules':
val = _rules_from_env(val)
elif attr == 'wait_command':
val = int(val)
elif attr in ('require_confirmation', 'no_colors'):
val = val.lower() == 'true'
return va... | 5,348,649 |
def histogram(a, bins, ranges):
"""
Examples
--------
>>> x = np.random.uniform(0., 1., 100)
>>> H, xedges = np.histogram(x, bins=5, range=[0., 1.])
>>> Hn = histogram(x, bins=5, ranges=[0., 1.])
>>> assert np.all(H == Hn)
"""
hist_arr = np.zeros((bins,), dtype=a.dtype)
return ... | 5,348,650 |
def testfile(path, shell='/bin/sh', indent=2, env=None, cleanenv=True,
debug=False, testname=None):
"""Run test at path and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same list with actual output, diff)
diff is a generator... | 5,348,651 |
def is_valid_python_code(src_string: str):
"""True if, and only if, ``src_string`` is valid python.
Valid python is defined as 'ast.parse(src_string)` doesn't raise a ``SyntaxError``'
"""
try:
ast_parse(src_string)
return True
except SyntaxError:
return False | 5,348,652 |
def rss_format_export_post():
"""
:return:
"""
try:
payload = request.get_json(force=True) # post data in json
except:
payload = dict(request.form) # post data in form encoding
if 'link' in payload:
link = read_value_list_or_not(payload, 'link')
else:
link... | 5,348,653 |
def send_file(app, name, content_type, file_like, node, user):
"""Upload file to OSF."""
file_like.seek(0)
with app.test_request_context():
upload_url = storage_utils.get_waterbutler_upload_url(
user,
node,
path=name,
)
requests.put(
upload_url... | 5,348,654 |
def on_command(name: Union[str, CommandName_T],
*,
logger: Logger,
checkfunc: Callable[[CommandSession], bool] = None,
wait_for: Callable[[], bool] = None,
cooldown: int = 0,
use_default_infolog: bool = True,
aliase... | 5,348,655 |
def fillOrders(barberId, start, end, step=1):
"""
Создаёт заказы для барбера с iD = barberId
:param: barberId: id барбера
:type: int
:param start: время начало работы
:type: datetime.datetime
:param end: время конца работы
:type: datetime.datetime
:param step: время с которым будет с... | 5,348,656 |
async def urlcheck(
api: vq.API,
event: vq.Event(),
sender: vq.Sender()
):
"""
Update data for user
"""
link = re.fullmatch(
config.LINK_PATTERN, event.object.message.text
)
if event.object.message.peer_id > vq.PEER:
if not re.fullmatch(
config.LINK_PATTE... | 5,348,657 |
def SetUp(filename, rel_path=RELATIVE_TEST_PATH):
""" SetUp returns a parsed C Program."""
if not os.path.exists(PICKLE_FILE):
KVStore.CreateNewStore(PICKLE_FILE, redhawk.GetVersion())
return G.GetLanguageSpecificTree(os.path.join(rel_path, filename),
PICKLE_FILE, language='c') | 5,348,658 |
def setup_agents(model, initial_locations):
"""Load the simulated initial locations and return a list
that holds all agents.
"""
initial_locations = initial_locations.reshape(2, model["n_types"], 30000)
agents = []
for typ in range(model["n_types"]):
for i in range(model["n_agents_by_t... | 5,348,659 |
def properties_to_csv(prop_dict : dict, csv_filename : str,
epoch_key : str, append : bool=True) -> None:
"""
Writes a CSV summarizing how training is going by comparing the properties
of the generated structures during evaluation to the training set. Also
writes the properties to ... | 5,348,660 |
async def get_active_infraction(
ctx: Context,
user: MemberOrUser,
infr_type: str,
send_msg: bool = True
) -> t.Optional[dict]:
"""
Retrieves an active infraction of the given type for the user.
If `send_msg` is True and the user has an active infraction matching the `infr_t... | 5,348,661 |
def __compute_optical_function_vs_s(transporter, particles, optical_function_name):
# todo Adjust
"""
Compute values of optical function vs s for one particle, which coordinates are x_min, theta_x_min, ...
or x_mean - delta_x, ...
:param transporter: transport function
:param particles: BunchCon... | 5,348,662 |
def plot_arb_images(label, data, label_string):
"""
Neatly displays arbitrary numbers of images from the camera
returns fig
Parameters:
-----------
label: array of values that each image is labeled by, e.g. time
data: array of arrays of image data
label_string: string describing label,... | 5,348,663 |
def listGslbServer(**kargs):
""" List the Servers of KT Cloud GSLB.
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
* Examples: print(gslb.listGslbServer(zone='KR-M'))
"""
my_apikey, my_secretkey = c.read_config()
if not 'zone' in kargs:
return c.printZon... | 5,348,664 |
def imencode(image, pix_fmt=IM_RGB, quality=DEFAULT_QUALITY):
"""
Encode image into jpeg codec
Adapt convert image pixel color with pix_fmt
Parameters
----------
image: source
pix_fmt: format of pixel color. Default: RGB
quality: JPEG quality image.
Returns
-------
... | 5,348,665 |
def db_load(infile, outfile, db_type):
""" Calls the linux db_load command to load up the database files
The command is:
db_load -c duplicates=1, -f infile -T
-t [ btree | hash | queue | recno ] outfile
"""
assert db_type is "btree" or db_type is "hash" or \
... | 5,348,666 |
def split_train_test_data(X, Y, train_rate):
"""
将数据集划分为训练集与测试集
:param X: 数据集的特征
:param Y: 数据集的标签
:param train_rate: 训练集的比例
:return: 训练集的特征;训练集的标签;测试集的特征;测试集的标签
"""
number = len(X)
number_train = int(number * train_rate)
number_test = number - number_train
train_X = []
tr... | 5,348,667 |
def nonsingular_concat(X, vector):
"""Appends vector to matrix X iff the resulting matrix is nonsingular.
Args:
X (np.array): NxM Matrix to be appended to
vector (np.array): Nx1 vector to be appended to X
Returns:
new_X (np.array): Nx(M+1) Matrix or None
"""
# Cast vector to matrix
... | 5,348,668 |
def get_oxidation_state(element: Union[str, Element]) -> int:
"""Get a typical oxidation state
If it doesn't exist in the database, 0 is returned.
Args:
element (str/ Element): Input element
Return:
Oxidation state of the element.
"""
try:
return oxidation_state_dic... | 5,348,669 |
def __quality_indexes(
graph: nx.Graph,
communities: object,
scoring_function: Callable[[object, object], float],
summary: bool = True,
) -> object:
"""
:param graph: NetworkX/igraph graph
:param communities: NodeClustering object
:param summary: boolean. If **True** it is returned an a... | 5,348,670 |
def test_non_positive_integer_max_exclusive003_1571_non_positive_integer_max_exclusive003_1571_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=maxExclusive and value=-1 and
document value=-5
"""
assert_bindings(
schema="msData/datatypes/Facets/nonPositiveInteg... | 5,348,671 |
def serve_scripts(scripts):
""" Combines one or more script files into one and embeds them in the
small autoCSP JavaScript framework. """
debug = DEBUG and not LOCKED_MODE
views_path = os.path.expanduser(PATHS['VIEWS'])
with open(views_path + 'static/sha256.js', 'r') as f:
sha256js = f.r... | 5,348,672 |
def readFromDB_DSC_authorityKey(authorityKey: bytes, connection: Connection) -> DocumentSignerCertificate:
"""Reading from database"""
try:
logger.info("Reading DSC object from database with authority key.")
return connection.getSession().query(DocumentSignerCertificateStorage).filter(DocumentSi... | 5,348,673 |
def history_report(history, config=None, html=True):
"""
Test a model and save a history report.
Parameters
----------
history : memote.HistoryManager
The manager grants access to previous results.
config : dict, optional
The final test report configuration.
html : bool, opt... | 5,348,674 |
def matrix_reduce():
"""
reduce
:return:
"""
isses = tf.InteractiveSession()
# 对角值
X = tf.constant([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]])
logger.info("X\n%s" % X.eval())
logger.info("tf.reduce_sum(X)\n {0}".format(tf.reduce_sum(X).eval()))
logger.info("tf.reduce_sum(X,axis=... | 5,348,675 |
def derive_from_dem(dem):
"""derive slope and flow direction from a DEM.
Results are returned in a dictionary that contains references to
ArcPy Raster objects stored in the "in_memory" (temporary) workspace
"""
# set the snap raster for subsequent operations
env.snapRaster = dem
# ... | 5,348,676 |
def from_error_details(error: str, message: str, stacktrace: Optional[str]) -> BidiException:
"""Create specific WebDriver BiDi exception class from error details.
Defaults to ``UnknownErrorException`` if `error` is unknown.
"""
cls = get(error)
return cls(error, message, stacktrace) | 5,348,677 |
def tangential_proj(u, n):
"""
See for instance:
https://link.springer.com/content/pdf/10.1023/A:1022235512626.pdf
"""
return (ufl.Identity(u.ufl_shape[0]) - ufl.outer(n, n)) * u | 5,348,678 |
def test_no_env(argv, expected):
"""Test outside of any supported CI env.
:param iter argv: Mock sys.argv.
:param dict expected: Expected return value of get_arguments().
"""
environ = dict(PATH='.')
actual = get_arguments(['download'] + argv, environ)
assert actual == expected | 5,348,679 |
def _RemoveEdges(tris, match):
"""tris is list of triangles.
er is as returned from _MaxMatch or _GreedyMatch.
Return list of (A,D,B,C) resulting from deleting edge (A,B) causing a merge
of two triangles; append to that list the remaining unmatched triangles."""
ans = []
triset = set(tris)
... | 5,348,680 |
def viewdata(data):
"""Prints out readable information of the output of getSearchData"""
print('_' * 50)
print('Number of Results: ' + str(data[0]['numResults']))
print('\nSearchURL: ' + data[0]['searchURL'])
print('_' * 50)
i = 1
for m in data[1]:
print(str(i) + '. ')
for... | 5,348,681 |
def cli():
"""Extinct Gaming CLI Tools""" | 5,348,682 |
def get_course_authoring_url(course_locator):
"""
Gets course authoring microfrontend URL
"""
return configuration_helpers.get_value_for_org(
course_locator.org,
'COURSE_AUTHORING_MICROFRONTEND_URL',
settings.COURSE_AUTHORING_MICROFRONTEND_URL
) | 5,348,683 |
def sumDwellStateSub(params):
"""Threaded, sums dwell times with 1 day seeing no change & accounting for fractional days"""
(dfIn,dwellTime,weight) = params
dfOut = dfIn.copy(deep=True)
while dwellTime > 1:
if dwellTime > 2:
increment = 1
else:
increment = dwellT... | 5,348,684 |
def launch_attacker_view():
"""
Accepts a JSON payload with the following structure:
{
"target": "nlb-something.fqdn.com",
"attacker": "1.2.3.4"
}
If the payload parses correctly, then launch a reverse shell listener using pexpect.spawn
then spawn the auto-sploit.sh tool and ente... | 5,348,685 |
def stretch(alignment, factor):
"""Time-stretch the alignment by a constant factor"""
# Get phoneme durations
durations = [factor * p.duration() for p in alignment.phonemes()]
alignment = copy.deepcopy(alignment)
alignment.update(durations=durations)
return alignment | 5,348,686 |
def train(epoch, train_loader, model, contrast, criterion_l, criterion_ab, optimizer, opt):
"""
one epoch training
"""
model.train()
contrast.train()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
l_loss_meter = AverageMeter()
ab_loss_meter = Aver... | 5,348,687 |
def create_issue_digraph(epics_stories):
"""Return a graph representation of all issues.
Blocking dependencies are modelled as graph edges.
"""
log.info('creating graph...')
graph = nx.DiGraph()
for epic, stories in epics_stories.items():
for issue in stories:
graph.add... | 5,348,688 |
def loadmesh(basedirMesh, ptcode=None, meshname=None, invertZ=True, fname=None):
""" Load Mesh object, flip z and return Mesh
meshname includes ctcode
"""
if fname is None:
try:
mesh = vv.meshRead(os.path.join(basedirMesh, ptcode, meshname))
except FileNotFoundError:
... | 5,348,689 |
def get_transport(socket, host, kerberos_service_name, auth_mechanism='NOSASL',
user=None, password=None):
"""
Creates a new Thrift Transport using the specified auth_mechanism.
Supported auth_mechanisms are:
- None or 'NOSASL' - returns simple buffered transport (default)
- 'PLAIN... | 5,348,690 |
def _read_node( data, pos, md_total ):
"""
2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2
The quantity of child nodes.
The quantity of metadata entries.
Zero or more child nodes (as specified in the header).
"""
child_count = data[ pos ]
pos += 1
md_count = data[ pos ]
pos += 1
for i in range( child_count ):
pos, m... | 5,348,691 |
def _large_flag_fit(x, yDat, yFit, initz, speciesDict, minSize, errBound):
"""
Attempts to more robustly fit saturated lyman alpha regions that have
not converged to satisfactory fits using the standard tools.
Uses a preselected sample of a wide range of initial parameter guesses
designed to fit sa... | 5,348,692 |
def mse_large_arrays_masked(dataA: 'LargeArray', dataB: 'LargeArray', mask: 'LargeArray',
dtype: Type, batchSizeFlat=1e8):
"""
Compute MSE between two HDF datasets, considering elements where the mask is set to true (one).
Computation is performed in batches to decrease memory re... | 5,348,693 |
def test_shell_cmd_inputs_1():
"""additional input with provided position"""
my_input_spec = SpecInfo(
name="Input",
fields=[
(
"inpA",
attr.ib(
type=str,
metadata={"position": 1, "help_string": "inp1", "argstr":... | 5,348,694 |
def xml_elem_or_str_to_text(elem_or_xmlstr, default_return=""):
"""
Return string with all tags stripped out from either etree element or xml marked up string
If string is empty or None, return the default_return
>>> root = etree.fromstring(test_xml)
>>> xml_elem_or_str_to_text(test_xml, None)... | 5,348,695 |
def sequence_equals(sequence1, sequence2):
"""
Inspired by django's self.assertSequenceEquals
Useful for comparing lists with querysets and similar situations where
simple == fails because of different type.
"""
assert len(sequence1) == len(sequence2), (len(sequence1), len(sequence2))
for i... | 5,348,696 |
def test_load_external():
"""
This function tests if a model that has been trained on a different computer can be loaded and used on a different
computer.
"""
x = np.linspace(-10.0, 10.0, 2000)
y = x ** 2
x = np.reshape(x, (x.shape[0], 1))
estimator = MRMP()
estimator.load_nn("save... | 5,348,697 |
def create_or_update_user_profile(sender, instance, created, **kwargs):
"""If the User is being created and does not have a UserProfile model, create one."""
if created or not hasattr(instance, 'userprofile'):
UserProfile.objects.create(user=instance)
instance.profile.save() | 5,348,698 |
def extract_parameters_by_usrDict(preModel, preDict, usrModel, usrDict, paraDim):
"""
Extract desired parameters from a pretrained embedding model based on user dictionary
"""
if paraDim not in [32, 64, 128, 256]:
raise RuntimeError("We only support 32, 64, 128, 256 dimensions now")
fi = op... | 5,348,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.