content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def enable_logging( level='WARNING' ):
"""Enable sending logs to stderr. Useful for shell sessions.
level
Logging threshold, as defined in the logging module of the Python
standard library. Defaults to 'WARNING'.
"""
log = logging.getLogger( 'mrcrowbar' )
log.setLevel( level )
o... | 5,346,500 |
def event_detail(request, event_id):
"""
A View to return an individual selected
event details page.
"""
event = get_object_or_404(Event, pk=event_id)
context = {
'event': event
}
return render(request, 'events/event_detail.html', context) | 5,346,501 |
def variables(
metadata: meta.Dataset,
selected_variables: Optional[Iterable[str]] = None
) -> Tuple[dataset.Variable]:
"""Return the variables defined in the dataset.
Args:
selected_variables: The variables to return. If None, all the
variables are returned.
Returns:
T... | 5,346,502 |
def builder(tiledata, start_tile_id, version, clear_old_tiles=True):
"""
Deserialize a list of serialized tiles, then re-link all the tiles to
re-create the map described by the tile links
:param list tiledata: list of serialized tiles
:param start_tile_id: tile ID of tile that should be used as th... | 5,346,503 |
def data_uri(content_type, data):
"""Return data as a data: URI scheme"""
return "data:%s;base64,%s" % (content_type, base64.urlsafe_b64encode(data)) | 5,346,504 |
def next_line(ionex_file):
"""
next_line
Function returns the next line in the file
that is not a blank line, unless the line is
'', which is a typical EOF marker.
"""
done = False
while not done:
line = ionex_file.readline()
if line == '':
return line
... | 5,346,505 |
def create_database(instance, database_id):
"""Creates a Cloud Spanner database and table."""
database = instance.database(
database_id,
ddl_statements=[
"""CREATE TABLE events_batch (
record_id INT64 NOT NULL,
event_time STRING(50) N... | 5,346,506 |
def saySomething():
"""Contemplation..."""
if helpers.get_answer():
print(say_hi()) | 5,346,507 |
def last(value):
"""
returns the last value in a list (None if empty list) or the original if value not a list
:Example:
---------
>>> assert last(5) == 5
>>> assert last([5,5]) == 5
>>> assert last([]) is None
>>> assert last([1,2]) == 2
"""
values = as_list(value)
ret... | 5,346,508 |
def levup(acur, knxt, ecur=None):
"""
LEVUP One step forward Levinson recursion
Args:
acur (array) :
knxt (array) :
Returns:
anxt (array) : the P+1'th order prediction polynomial based on the P'th
order prediction polynomial, acur, and the P+1'th order
... | 5,346,509 |
def plot_dd_curves(row, col, before, after, repnames=None, log=True, **kwargs):
"""
Plots a comparison of distance dependence curves before and after scaling.
Parameters
----------
row, col : np.ndarray
Row and column indices identifying the location of pixels in ``before``
and ``af... | 5,346,510 |
def gradient_output_wrt_input(model, img, normalization_trick=False):
"""
Get gradient of softmax with respect to the input.
Must check if correct.
Do not use
# Arguments
model:
img:
# Returns
gradient:
"""
grads = K.gradients(model.output, model.input)[0]
... | 5,346,511 |
def response_GET(client, url):
"""Fixture that return the result of a GET request."""
return client.get(url) | 5,346,512 |
def load_python_object(name):
"""
Loads a python module from string
"""
logger = getLoggerWithNullHandler('commando.load_python_object')
(module_name, _, object_name) = name.rpartition(".")
if module_name == '':
(module_name, object_name) = (object_name, module_name)
try:
log... | 5,346,513 |
def test_ls_eq_v(eq_date):
"""Test Ls for the vernal equinox."""
ls = orbit.Ls(eq_date)
assert approx(ls, abs=0.05) == 0 | 5,346,514 |
def twitter_preprocess():
"""
ekphrasis-social tokenizer sentence preprocessor.
Substitutes a series of terms by special coins when called
over an iterable (dataset)
"""
norm = ['url', 'email', 'percent', 'money', 'phone', 'user',
'time', 'date', 'number']
ann = {"hashtag", "elongated", "allcaps", "repeated... | 5,346,515 |
def rotation_matrix(axis, theta):
"""
Return the rotation matrix associated with counterclockwise rotation about
the given axis by theta radians.
"""
axis = np.asarray(axis)
axis = axis / math.sqrt(np.dot(axis, axis))
a = math.cos(theta / 2.0)
b, c, d = -axis * math.sin(theta / 2... | 5,346,516 |
def get_routes(interface: Type[Interface]) -> List[ParametrizedRoute]:
"""
Retrieves the routes from an interface.
"""
if not issubclass(interface, Interface):
raise TypeError('expected Interface subclass, got {}'
.format(interface.__name__))
routes = []
for member in interface.members():
if... | 5,346,517 |
def _load_mnist_dataset(shape, path, name='mnist', url='http://yann.lecun.com/exdb/mnist/'):
"""A generic function to load mnist-like dataset.
Parameters:
----------
shape : tuple
The shape of digit images.
path : str
The path that the data is downloaded to.
name : str
T... | 5,346,518 |
def _get_realm(response):
"""Return authentication realm requested by server for 'Basic' type or None
:param response: requests.response
:type response: requests.Response
:returns: realm
:rtype: str | None
"""
if 'www-authenticate' in response.headers:
auths = response.headers['www... | 5,346,519 |
def exp_mantissa(num, base=10):
"""Returns e, m such that x = mb^e"""
if num == 0:
return 1, 0
# avoid floating point error eg log(1e3, 10) = 2.99...
exp = math.log(abs(num), base)
exp = round(exp, FLOATING_POINT_ERROR_ON_LOG_TENXPONENTS)
exp = math.floor(exp) # 1 <= mantissa < 10
m... | 5,346,520 |
def decide_if_taxed(n_taxed: set[str]) -> Callable[[str], bool]:
"""To create an decider function for omitting taxation.
Args:
n_taxed: The set containing all items, which should not be taxed.
If empty, a default set will be chosen.
Returns:
Decider function for omitting t... | 5,346,521 |
def test_total_values_for_two_separate_transactions():
"""
Tests 'total_market_value', 'total_unrealised_pnl',
'total_realised_pnl' and 'total_pnl' for single
transactions in two separate assets.
"""
ph = PositionHandler_Cash_MC()
cash_transaction_1 = tph.get_cash_leg_transaction(
'... | 5,346,522 |
def generate_two_cat_relation_heat_map():
"""
A correlation matrix for categories
"""
data = Heatmap(
z=df_categories.corr(),
y=df_categories.columns,
x=df_categories.columns)
title = 'Correlation Distribution of Categories'
y_title = 'Category'
x_title = 'Category'
... | 5,346,523 |
def build_phase2(VS, FS, NS, VT, VTN, marker, wc):
"""
Build pahase 2 sparse matrix M_P2 closest valid point term with of source vertices (nS)
triangles(mS) target vertices (nT)
:param VS: deformed source mesh from previous step nS x 3
:param FS: triangle index of source mesh mS * 3
:param NS: t... | 5,346,524 |
def test_list_input(func):
"""Test that bn.xxx gives the same output as bn.slow.xxx for list input."""
msg = "\nfunc %s | input %s (%s) | shape %s\n"
msg += "\nInput array:\n%s\n"
name = func.__name__
if name == "replace":
return
func0 = eval("bn.slow.%s" % name)
for i, a in enumerat... | 5,346,525 |
def voronoi_to_dist(voronoi):
""" voronoi is encoded """
def decoded_nonstacked(p):
return np.right_shift(p, 20) & 1023, np.right_shift(p, 10) & 1023, p & 1023
x_i, y_i, z_i = np.indices(voronoi.shape)
x_v, y_v, z_v = decoded_nonstacked(voronoi)
return np.sqrt((x_v - x_i) ** 2 + (y_v - y_i) ** 2 + (z_v - z_i) ... | 5,346,526 |
def post_update_view(request):
"""View To Update A Post For Logged In Users"""
if request.method == 'POST':
token_type, token = request.META.get('HTTP_AUTHORIZATION').split()
if(token_type != 'JWT'):
return Response({'detail': 'No JWT Authentication Token Found'}, status=status.HTTP... | 5,346,527 |
def assert_equal(actual: Tuple[int, int, int, int], desired: Tuple[int, int, int, int]):
"""
usage.scipy: 14
usage.skimage: 7
"""
... | 5,346,528 |
def _is_binary_classification(class_list: List[str]) -> bool:
"""Returns true for binary classification problems."""
if not class_list:
return False
return len(class_list) == 1 | 5,346,529 |
def virtualenv_support_dirs():
"""Context manager yielding either [virtualenv_support_dir] or []"""
# normal filesystem installation
if os.path.isdir(join(HERE, "virtualenv_support")):
yield [join(HERE, "virtualenv_support")]
elif IS_ZIPAPP:
tmpdir = tempfile.mkdtemp()
try:
... | 5,346,530 |
def create_post_like(author, post):
"""
Create a new post like given an author and post
"""
return models.Like.objects.create(author=author, post=post) | 5,346,531 |
def translate_entries(yamldoc, base_url):
"""
Reads the field `entries` from the YAML document, processes each entry that is read using the
given base_url, and appends them all to a list of processed entries that is then returned.
"""
if 'entries' in yamldoc and type(yamldoc['entries']) is list:
entries =... | 5,346,532 |
def create_task_macapp(self):
"""
To compile an executable into a Mac application (a .app), set its *mac_app* attribute::
def build(bld):
bld.shlib(source='a.c', target='foo', mac_app=True)
To force *all* executables to be transformed into Mac applications::
def build(bld):
bld.env.MACAPP = True
bld.... | 5,346,533 |
def get_in(obj, lookup, default=None):
""" Walk obj via __getitem__ for each lookup,
returning the final value of the lookup or default.
"""
tmp = obj
for l in lookup:
try: # pragma: no cover
tmp = tmp[l]
except (KeyError, IndexError, TypeError): # pragma: no cover
... | 5,346,534 |
def GetSpec(resource_type, message_classes, api_version):
"""Returns a Spec for the given resource type."""
spec = _GetSpecsForVersion(api_version)
if resource_type not in spec:
raise KeyError('"%s" not found in Specs for version "%s"' %
(resource_type, api_version))
spec = spec[resourc... | 5,346,535 |
def ips_between(start: str, end: str) -> int:
"""
A function that receives two IPv4 addresses,
and returns the number of addresses between
them (including the first one, excluding the
last one).
All inputs will be valid IPv4 addresses in
the form of strings. The last address will
always be greater than the first o... | 5,346,536 |
def configure_mail_body(msg, template_name, context):
"""Set mail body based on text and html templates.
Args:
msg (object): flask_mail.Message instance used to send mail
template_name (str): name of mail body templates (without the extension)
context (dict): Any variables needed within... | 5,346,537 |
def test_multiple_lfcs_el_simple():
"""Test sounding with multiple LFCs."""
levels, temperatures, dewpoints = multiple_intersections()
profile = parcel.parcel_profile_with_lcl(pressure=levels,
temperature=temperatures,
... | 5,346,538 |
def tmNstate(trTrg):
"""Given (newq, new_tape_sym, dir),
return newq.
"""
return trTrg[0] | 5,346,539 |
def parse_arguments(args):
"""
Parse the arguments from the user
"""
parser = argparse.ArgumentParser(
description= "Create UniRef database for HUMAnN2\n",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
"-v","--verbose",
help="additional ou... | 5,346,540 |
def _preprocess_continuous_variable(df: pd.DataFrame, var_col: str, bins: int,
min_val: float = None,
max_val: float = None) -> pd.DataFrame:
"""
Pre-processing the histogram for continuous variables by splitting the variable in buckets.
... | 5,346,541 |
def create_olaf():
"""
Creates a bird in the free space.
"""
y_coordnate = random.uniform(50,300)
new_olaf = Olaf(background_module.bg.get_width(), y_coordnate)
Olaf.olafs_list.append(new_olaf)
Olaf.collision_olaf.append(new_olaf) # To check collision | 5,346,542 |
def main() -> None:
"""
Main game logic loop shim.
"""
from providers import cpucheck
cpucheck.instantiate()
if cpucheck.is_over_limit():
return
import logic
logic.main() | 5,346,543 |
def reset_environ():
"""
Resets `os.environ` to its prior state after the fixtured test finishes.
"""
old_environ = os.environ.copy()
yield
os.environ.clear()
os.environ.update(old_environ) | 5,346,544 |
def get_pairs(labels):
"""
For the labels of a given word, creates all possible pairs
of labels that match sense
"""
result = []
unique = np.unique(labels)
for label in unique:
ulabels = np.where(labels==label)[0]
# handles when a word sense has only one occurrence
... | 5,346,545 |
def iredv(tvp,tton):
""" makes sop tvp irredundant relative to onset truth table"""
res = []
red = list(tvp)
for j in range(len(tvp)):
tvj=tvp[j]&tton #care part of cube j
if (tvj&~or_redx(red,j)) == m.const(0): # reduce jth cube to 0
red[j]=m.const(0)
else: #keep cub... | 5,346,546 |
def showPids():
""" Show Information for PIDs created in a KFD (Compute) context """
printLogSpacer(' KFD Processes ')
dataArray = []
dataArray.append(['PID', 'PROCESS NAME', 'GPU(s)', 'VRAM USED', 'SDMA USED', 'CU OCCUPANCY'])
pidList = getPidList()
if not pidList:
printLog(None, 'No KF... | 5,346,547 |
def main(argv):
"""Parse arguments, extract data, and render the linker script to file"""
# pylint: disable=too-many-locals
parsed_args = parse_arguments(argv)
template = get_template(parsed_args)
dts = pydevicetree.Devicetree.parseFile(
parsed_args.dts, followIncludes=True)
memories... | 5,346,548 |
def ridder_fchp(st, target=0.02, tol=0.001, maxiter=30, maxfc=0.5, config=None):
"""Search for highpass corner using Ridder's method.
Search such that the criterion that the ratio between the maximum of a third order
polynomial fit to the displacement time series and the maximum of the displacement
tim... | 5,346,549 |
def CommitOffsite(
backup_name,
backup_suffix=None,
output_stream=sys.stdout,
preserve_ansi_escape_sequences=False,
):
"""\
Commits data previously generated by Offsite. This can be useful when
additional steps must be taken (for example, upload) before a Backup can
be considere... | 5,346,550 |
def get_impropers(bonds):
"""
Iterate over bonds to get impropers.
Choose all three bonds that have one atom in common.
For each set of bonds you have 3 impropers where one of the noncommon atoms is out of plane.
Parameters
----------
bonds : list
List of atom ids that make up bonds... | 5,346,551 |
def plot_pain_against_activities(data):
"""Plot average pain against activities (from diary)"""
fig, axes = plt.subplots(3, 2, figsize=(15, 10), sharey=True, sharex=False)
fig.suptitle("Participant 8: activities against average pain", fontsize=13)
sns.scatterplot(x="household", y="average_... | 5,346,552 |
def get_ret_tev_return(*args):
"""get_ret_tev_return(int n) -> ea_t"""
return _idaapi.get_ret_tev_return(*args) | 5,346,553 |
def make_figure_6(prefix=None, rng=None, colors=None):
"""
Figures 6, Comparison of Performance
Ported from MATLAB Code
Nicholas O'Donoughue
24 March 2021
:param prefix: output directory to place generated figure
:param rng: random number generator
:param colors: colormap for plotting... | 5,346,554 |
def slim_form(domain_pk=None, form=None):
"""
What is going on? We want only one domain showing up in the
choices. We are replacing the query set with just one object. Ther
are two querysets. I'm not really sure what the first one does, but
I know the second one (the widget) removes the choices. Th... | 5,346,555 |
def input(*args):
"""
Create a new input
:param args: args the define a TensorType, can be either a TensorType or a shape and a DType
:return: the input expression
"""
tensor_type = _tensor_type_polymorhpic(*args)
return InputTensor(tensor_type, ExpressionDAG.num_inputs) | 5,346,556 |
def test_error_1():
"""
>>> d = {'v':'<span></span>'}
>>> try:
... print (template("<html>{{= v </html>", d))
... except ParseError as e:
... print (e)
Missing end expression }} on line <string>:1
""" | 5,346,557 |
def commong_substring(input_list):
"""Finds the common substring in a list of strings"""
def longest_substring_finder(string1, string2):
"""Finds the common substring between two strings"""
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
mat... | 5,346,558 |
def is_valid_url(url):
"""Checks if a URL is in proper format.
Args:
url (str): The URL that should be checked.
Returns:
bool: Result of the validity check in boolean form.
"""
valid = validators.url(url)
if valid:
return True
else:
return False | 5,346,559 |
def check_valid_authentication_options(options, auth_plugin_name):
"""Validate authentication options, and provide helpful error messages
:param required_scope: indicate whether a scoped token is required
"""
# Get all the options defined within the plugin.
plugin_opts = base.get_plugin_options(a... | 5,346,560 |
def codepoint_to_url(codepoint, style):
"""
Given an emoji's codepoint (e.g. 'U+FE0E') and a non-apple emoji style,
returns a url to to the png image of the emoji in that style.
Only works for style = 'twemoji', 'noto', and 'blobmoji'.
"""
base = codepoint.replace('U+', '').lower()
if sty... | 5,346,561 |
def getRNCS(ChargeSA):
"""The calculation of relative negative charge surface area
-->RNCS
"""
charge=[]
for i in ChargeSA:
charge.append(float(i[1]))
temp=[]
for i in ChargeSA:
temp.append(i[2])
try:
RNCG = min(charge)/sum([i for i in charge if i < 0.0])
... | 5,346,562 |
def handle_auth_manager_auth_exception(error):
"""Return a custom message and 403 status code"""
response_header = {'X-REQUEST-ID': util.create_request_id()}
return {'message': error.message}, 403, response_header | 5,346,563 |
def get_default_converter():
"""Intended only for advanced uses"""
return _TYPECATS_DEFAULT_CONVERTER | 5,346,564 |
def login(request):
"""
:param: request
:return: JSON data
"""
response = {}
if request.method == 'GET':
username = request.GET.get('username')
password = request.GET.get('password')
try:
usr = models.User.objects.filter(username=username, password=password)
... | 5,346,565 |
def average_win_rate(strategy, baseline=always_roll(4)):
"""Return the average win rate of STRATEGY against BASELINE. Averages the
winrate when starting the game as player 0 and as player 1.
"""
win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline)
win_rate_as_player_1 = make_averaged... | 5,346,566 |
def decode(chrom):
"""
Returns the communities of a locus-based adjacency codification
in a vector of int where each position is a node id and the value
of that position the id of the community where it belongs. To position
with the same number means that those two nodes belongs to same community.
... | 5,346,567 |
def write_video(frames, outfile, fps, frame):
"""Write frames to video output file
Args:
frames (list<numpy.ndarray[H, W, 3]>): video frames
outfile (string): path to output file
fps (int): frames per second to write
frame (tuple<int, int>): video spatial dimensions
"""
... | 5,346,568 |
def bin_search(query, data):
""" Query is a coordinate interval. Approximate binary search for the query in sorted data,
which is a list of coordinates. Finishes when the closest overlapping value of query and
data is found and returns the index in data. """
i = int(math.floor(len(data)/2)) # binary search prep
... | 5,346,569 |
def scripts(ctx, config):
"""
A CLI wrapper for some helpful scripts I use on my personal Notion.
"""
ctx.ensure_object(dict)
ctx.obj['logger'] = setup_logger()
ctx.obj['logger'].setLevel(logging.DEBUG)
ctx.obj['config'] = Config.load_config(config)
ctx.obj['logger'].debug("Parsed confi... | 5,346,570 |
def validate_config(cnf):
""" validate configuration, exit on missing item
:param cnf: config handle
"""
for config_item in ['socket_filename', 'pid_filename']:
if cnf.has_section('main') == False or cnf.has_option('main', config_item) == False:
print('configuration item main/%s ... | 5,346,571 |
def test_unexpected():
"""Tests unexpected response is returns as False"""
response = requests.models.Response()
response.status_code = 'unexpected'
assert UEM.check_http_response(response) is False | 5,346,572 |
def get_rating(business_id):
""" GET Business rating"""
rating = list(
db.ratings.aggregate(
[{"$group": {"_id": "$business", "pop": {"$avg": "$rating"}}}]
)
)
if rating is None:
return (
jsonify(
{
"success": False,
... | 5,346,573 |
def fwhm(x,y):
"""Calulate the FWHM for a set of x and y values.
The FWHM is returned in the same units as those of x."""
maxVal = np.max(y)
maxVal50 = 0.5*maxVal
#this is to detect if there are multiple values
biggerCondition = [a > maxVal50 for a in y]
changePoints = []
xPoints... | 5,346,574 |
def plan(c, destroy=False):
"""Call terraform plan."""
print('planning')
c.run('./terraform plan {}'.format('-destroy' if destroy else '')) | 5,346,575 |
def test_deckmodel_add_card():
""" GIVEN `DeckModel`'s `addCard` method,
WHEN a `Card` model is initialized and passed to addCard,
THEN check whether the card exists in the DeckModel
(i.e. that the table card contains a row where deckname=DeckModel.deckname) """
pass | 5,346,576 |
async def alert(friend):
"""
Alert the user using a service of you choice.
This has to be filled manually.
Input:
friend (str) : the email or phone_number of the friend near you.
"""
# Example
print(bcolors.WARNING + f"{friend} is near you." + bcolors.ENDC) | 5,346,577 |
def throw_job(target_pdb_dir: Path, method: str, output_score_path: Path,
qsub: bool, execute: bool, ar: str) -> None:
"""
Throw a job of the specified MQA method.
"""
target = target_pdb_dir.stem
cmd = [f'./{method}.sh', str(target_pdb_dir), str(output_score_path)]
if method in ['... | 5,346,578 |
def parse_names(input_folder):
"""
:param input_folder:
:return:
"""
name_set = set()
if args.suffix:
files = sorted(glob(f'{input_folder}/*{args.suffix}'))
else:
files = sorted(glob(f'{input_folder}/*'))
for file in files:
with open(file) as f:
for r... | 5,346,579 |
def check_dir(data_dir):
"""
Method used to validate the given data directory path
:param data_dir: Absolute path for the data directory
:type data_dir: str
:raise: Exception
"""
if not os.path.isdir(data_dir):
raise Exception("specified data dir does not exist")
if not len(os.... | 5,346,580 |
def build_charencoder(corpus: Iterable[str], wordlen: int=None) \
-> Tuple[int, Mapping[str, int], TextEncoder]:
"""
Create a char-level encoder: a Callable, mapping strings into integer arrays.
Encoders dispatch on input type: if you pass a single string, you will get
a 1D array, if you pass a... | 5,346,581 |
def main():
"""
主函数入口,用于将应用注册到httpserver,并开启事件循环
:return: None
"""
define("port", default=int(opt_server["port"]), type=int, help="Run on the given port")
print_info()
if opt_debug["open_log"] == "true":
set_log()
options.parse_command_line()
http_server = HTTPServer(appli... | 5,346,582 |
def output(angle_tree, output_qubits):
""" Define output qubits"""
if angle_tree:
output_qubits.insert(0, angle_tree.qubit) # qiskit little-endian
if angle_tree.left:
output(angle_tree.left, output_qubits)
else:
output(angle_tree.right, output_qubits) | 5,346,583 |
def send(private_key, public_key, email, subscription, payload):
"""
"""
options = {
'vapidDetails': {
'subject': 'mailto:%s' % email,
'privateKey': private_key,
'publicKey': public_key,
}
}
dic = {
'options': options,
'subscriptio... | 5,346,584 |
def Decodingfunc(Codebyte):
"""This is the version 'A' of decoding function,
that decodes data coded by 'A' coding function"""
Decodedint=struct.unpack('b',Codebyte)[0]
N=0 #number of repetitions
L=0 # length of single/multiple sequence
if Decodedint >= 0: #single
N = 1
... | 5,346,585 |
def test_lif_file(lif_file):
"""Just print the text of all headers, should give an indication of whether all
the offsets are correct."""
lif = Container(json_file=lif_file).payload
text = lif.text.value
view = lif.views[0]
for anno in view.annotations:
if anno.type.endswith('Header'):
... | 5,346,586 |
def _metric_notification_text(metric: MetricNotificationData) -> str:
"""Return the notification text for the metric."""
new_value = "?" if metric.new_metric_value is None else metric.new_metric_value
old_value = "?" if metric.old_metric_value is None else metric.old_metric_value
unit = metric.metric_un... | 5,346,587 |
def test_run_job_as_admin_with_job_requirements_and_parent_job():
"""
A basic unit test of the run() method with an administrative user and job requirements.
This test is a fairly minimal test of the run() method. It does not exercise all the
potential code paths or provide all the possible run inputs,... | 5,346,588 |
def train_dist(
domain: Text,
config: Text,
training_files: Optional[Union[Text, List[Text]]],
output: Text = rasa.shared.constants.DEFAULT_MODELS_PATH,
dry_run: bool = False,
force_training: bool = False,
fixed_model_name: Optional[Text] = None,
persist_nlu_training_data: bool = False,
... | 5,346,589 |
def run_step_sequences(
env, agent, sequence_iterator=episode_iterator, update=True, num_sequences=None
):
"""Generate sequences of steps from an environment-agent simulation.
Args:
env: An OpenAI Gym environment.
agent: An instance of `Agent`.
sequence_iterator: A generator taking ... | 5,346,590 |
def convert_image_to_nifti(path_image, path_out_dir=None):
""" converting normal image to Nifty Image
:param str path_image: input image
:param str path_out_dir: path to output folder
:return str: resulted image
>>> path_img = os.path.join(update_path('data-images'), 'images',
... ... | 5,346,591 |
def theater_chase_rainbow(strip: PixelStrip, wait_ms: int = 50):
"""Rainbow movie theater light style chaser animation.
:param strip:
:param wait_ms:
:return:
"""
for j in range(256):
for q in range(3):
for i in range(0, strip.numPixels(), 3):
strip.setPixelC... | 5,346,592 |
def wav2vec2_base() -> Wav2Vec2Model:
"""Build wav2vec2 model with "base" configuration
This is one of the model architecture used in *wav2vec 2.0*
[:footcite:`baevski2020wav2vec`] for pretraining.
Returns:
Wav2Vec2Model:
"""
return _get_model(
extractor_mode="group_norm",
... | 5,346,593 |
def check(context, verbose, files):
"""Don't modify files, just print the differences.
Return code 0 means nothing would change. Return code 1 means some files would be modified.
You can use partial and multiple file names in the FILES argument.
"""
common_fix_or_check(context, verbose, files, True... | 5,346,594 |
def dont_handle_lock_expired_mock(app):
"""Takes in a raiden app and returns a mock context where lock_expired is not processed
"""
def do_nothing(raiden, message): # pylint: disable=unused-argument
return []
return patch.object(
app.raiden.message_handler, "handle_message_lockexpired... | 5,346,595 |
def _find_spec(name, path, target=None):
"""Find a module's spec."""
meta_path = sys.meta_path
if meta_path is None:
# PyImport_Cleanup() is running or has been called.
raise ImportError("sys.meta_path is None, Python is likely "
"shutting down")
if not meta_pa... | 5,346,596 |
async def setup(bot: Bot) -> None:
"""Load the ModPings cog."""
await bot.add_cog(ModPings(bot)) | 5,346,597 |
def push_new_group_notification(username, room_id, receiver):
"""新会话通知"""
room = Room.query.get_or_404(room_id)
message = '<a href="%s">%s</a> 邀请您加入<a href="%s"> %s </a> !' % \
(url_for('user.index', username=username), username, url_for('group.home', room_id=room_id), room.name)
notificat... | 5,346,598 |
def system(_printer, ast):
"""Prints the instance system initialization."""
process_names_str = ' < '.join(map(lambda proc_block: ', '.join(proc_block), ast["processNames"]))
return f'system {process_names_str};' | 5,346,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.