content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_duplicate_tag_raises():
"""Check that code conflicts across different files raises"""
with pytest.raises(ValueError, match=r"Duplicate tag key: *"):
CodeList.from_directory("variable", TEST_DATA_DIR / "duplicate_tag_raises") | 56,600 |
def binary_to_decimal(binary):
"""
Converts a binary number into a decimal number.
"""
decimal = 0
index = 0
while binary > 0:
last = binary % 10
binary = binary / 10
decimal += (last * (2 ** index))
index += 1
return decimal | 56,601 |
def stopall(pidevice):
"""Stop motion of all axes and mask the "error 10" warning.
@type pidevice : pipython.gcscommands.GCSCommands
"""
try:
pidevice.StopAll()
except GCSError as exc:
if gcserror.E10_PI_CNTR_STOP != exc: # error 10 is just a warning that the device has been stopped... | 56,602 |
def namelist(names: list) -> str:
"""
Format a string of names like 'Bart, Lisa & Maggie'
:param names: an array containing hashes of names
:return: a string formatted as a list of names separated
by commas except for the last two names, which
should be separated by an ampersa... | 56,603 |
def update_wrapper():
"""Copy wrapped function information."""
def do_nothing(): "Doing nothing."
def wrapper():
"""Wraps a function that does nothing."""
return do_nothing()
wrapper_alias = functools.update_wrapper(wrapper, do_nothing)
return wrapper_alias is wrapper and wrapper.... | 56,604 |
def bande_noire_gauche(haut, larg, larg_bande):
"""
Colorie une bande noire de largeur larg_band a gauche de la fenetre
"""
for y in range(haut):
for x in range(larg):
if x < larg_bande:
graph.plot(y, x)
return | 56,605 |
def makeFlowField(a,b,c):
""" Make a vector from 3 components
<div class=jython>
makeVector(a,b,c) = [a,b,c]
</div>
"""
return DerivedGridFactory.createFlowVectors(a,b,c) | 56,606 |
def test_make_pod_with_init_containers():
"""
Test specification of a pod with initContainers
"""
assert api_client.sanitize_for_serialization(make_pod(
name='test',
image_spec='jupyter/singleuser:latest',
cmd=['jupyterhub-singleuser'],
port=8888,
image_pull_polic... | 56,607 |
def arraytodk3d(x):
"""
Convert back 1d array of independent elements to correct complex array fft-style
"""
nmesh = round(x.shape[0]**(1/3.))
y = numpy.zeros((nmesh, nmesh, nmesh/2+1), dtype = numpy.complex128)
# Structure saved-
# - first the real and complex part of N*N*(N/2-1) element... | 56,608 |
def handler(context, inputs):
"""
Create IPAM object,
define deaalocate_ip function
and start deallocation function
"""
ipam = IPAM(context, inputs)
IPAM.do_deallocate_ip = do_deallocate_ip
return ipam.deallocate_ip() | 56,609 |
def _n_centred_onedgaussian_Inorm(pars, I=None, sigma=None):
"""
Returns a function that provides the sum
over N 1D gaussians, where N is the length of
I,sigma *OR* N = len(pars) / 2
The background "height" is assumed to be zero (you must "baseline" your
spectrum before fitting)
pars - a... | 56,610 |
def classic_example_1(n, m):
"""
Prints a multiplication table for numbers from 1 to n multiplied
by numbers from 1 to m, where n and m are the given parameters.
Preconditions: n and m are positive integers.
"""
# -------------------------------------------------------------------------
# C... | 56,611 |
def prepare_plot_dir(dirpath):
"""
Add a trailing / to the plot dir if missing and creat dir if needed.
:param dirpath: path of existing or planned directory
:return: dirpath with / as the final character
"""
# add a slash to filename if it wasn't provided.
if dirpath[-1] != '/':
di... | 56,612 |
def o목록(message):
"""제가 지원하는 기능들을 알려줘요."""
return ', '.join(_목록()) +" 같은게 있어요!" | 56,613 |
def test_full_x_remove_z(init_full_x_remove_z):
"""Test if full x removed z is properly initialized and can fetch from 2 of its 3 parents"""
experiment = experiment_builder.load(name="full_x_remove_z")
assert experiment.refers["adapter"].configuration == [
{"change_type": "noeffect", "of_type": "co... | 56,614 |
def batch_process_tare_torque(plot=False):
"""Processes all tare torque data."""
runs = os.listdir("Data/Raw/Tare-torque")
runs = sorted([int(run) for run in runs])
rpm = np.zeros(len(runs))
taretorque = np.zeros(len(runs))
for n in range(len(runs)):
rpm[n], taretorque[n] = process_tare_... | 56,615 |
def testvolc(compareto,volcfiles,runshortname):
"""Performing the volcanic test
Input: compaareto = the flag to decide whether to compare to LENS2 or B1850 or both
volcfiles = the file listing for the volcanic test for your test case
runshortname = the shortname for labelling the test case... | 56,616 |
def parse_select_job_input_file(file):
""" INPUT
file = micrographs_ctf.star file used as input to the Select job
RETURNS
ordered_list_of_micrographs = list of entries as they appear in the input file, e.g.: [ _rlnMicrographName1, _rlnMicrographName2, ... ]
"""
print(" >>> P... | 56,617 |
def selectordialog(args):
"""
Emulates a selector control that is lvalues compatible for subsequent conditionals in Kodi settings
args is a list of strings that is kwarg 'like'.
'id=myid': (Required) where myid is the settings.xml id that will be updated
The plain id will contain the actual inde... | 56,618 |
def get_pronto_data():
"""
Download pronto data, unless already downloaded
"""
download_if_needed('https://s3.amazonaws.com/pronto-data/open_data_year_one.zip',
'open_data_year_one.zip') | 56,619 |
def pull_table():
"""Scrapes the wiki to pull some relevant information.
Scrapes the wiki for information on adventurers and dragons,
including rarity, general availability, and name. This data
is then serialized and written to a .json as a nested
dictionary.
"""
adv_url = "https://dra... | 56,620 |
def cli(cli_context, config, provider):
"""
Flintrock
A command-line tool and library for launching Apache Spark clusters.
"""
cli_context.obj['provider'] = provider
if os.path.isfile(config):
with open(config) as f:
config_raw = yaml.safe_load(f)
config_map = c... | 56,621 |
def help(q=1,doc=1,lng="string",l=1,pdt="uint",pm=1,ppt="uint",psm=1,rm=1,so=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/help.html
-----------------------------------------
help is undoable, queryable, and NOT editable.
With no arguments, help tells how to use help. If a c... | 56,622 |
async def test_coordinates_function_as_state(opp):
"""Test coordinates function."""
opp.states.async_set("test.object", "32.87336,-117.22943")
assert location.find_coordinates(opp, "test.object") == "32.87336,-117.22943" | 56,623 |
def yices_remove_type_name(name):
"""Removes the name from its attachment to the type."""
libyices.yices_remove_type_name(str2bytes(name)) | 56,624 |
def create_hmac_hash(hmac_payload: str, hmac_secret_key: str) -> str:
"""Returns sha256 HMAC hexdigest."""
if hmac_secret_key is None:
raise RuntimeError('hmac_secret_key cannot be None, please set a secret for the application in dotenv file!')
return new(
hmac_secret_key.encode('utf-8'),
... | 56,625 |
def loadIUPACcompatibilities(IUPAC, useGU):
"""
Generating a hash containing all compatibilities of all IUPAC RNA NUCLEOTIDES
"""
compatible = {}
for nuc1 in IUPAC: # ITERATING OVER THE DIFFERENT GROUPS OF IUPAC CODE
sn1 = list(IUPAC[nuc1])
for nuc2 in IUPAC: # ITERATING OVER THE D... | 56,626 |
def update_offer_viewed(offer_counter, merged_data, consumer_id, offer_id, offer_end):
"""
Update the dataframe with information related to an offer
being viewed.
"""
i = get_row_indices(merged_data, consumer_id, offer_id)
merged_data.at[i[offer_counter], "offer_viewed"] = True
retu... | 56,627 |
def autoparse(fn: Callable, verbose: bool=False) -> dict:
"""
Parse parameters from the command line, according to the signature and
docstring of a function
:param fn: callable with type hints and docstring
:param verbose: if True, will print the arguments parsed
:return: dictionary containing... | 56,628 |
def to_fullspec(rs, es, hds):
"""
Rotationally symmetric dump of a list of each to fullspec
"""
output = []
for idx in range(0, len(rs)):
row = {"r": [rs[idx]], "e": [es[idx]], "d": hds[idx] * 2}
output.append(row)
return output | 56,629 |
def try_run(cmd):
"""Try running the command and return its output on success, None on failure"""
logger.debug("running: %s", ' '.join(cmd))
try:
return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
return None | 56,630 |
def command_generation():
"""Adds a generate cell to Notebook."""
return jsonify(generate(request.json["query"], request.json["context"])) | 56,631 |
def summarize_text(df):
"""Summarize the text in the dataframe. Uses cache where possible
Fills in the gaps otherwise.
Performs this replacement in-place.
"""
ID_TO_SUMMARY_PATH = "cord_uid_to_summaries_short.pkl"
with open(os.path.join(DATA_DIR, ID_TO_SUMMARY_PATH), "rb") as f:
cord... | 56,632 |
def rubric_model_to_dict(obj, fields=None, exclude=None, ct_id=None):
"""
Returns a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the retur... | 56,633 |
def require_moderator_email_prereqs_are_satisfied():
"""Raises an exception if, for any reason, moderator emails cannot be sent.
"""
if not feconf.REQUIRE_EMAIL_ON_MODERATOR_ACTION:
raise Exception(
'For moderator emails to be sent, please ensure that '
'REQUIRE_EMAIL_ON_MODE... | 56,634 |
def render_hip(hipfile, rop, frames):
"""Render a range of frames from a Houdini .hip file.
Environment Variables
---------------------
PATH: required
Your PATH environment variable *must* be configured so that the worker
can run the `hython` executable.
Parameters
----------
... | 56,635 |
def get_uniq_list(data):
"""
列表去重并保持顺序(数据量大时效率不高)
:param data: list
:return: list
"""
ret = list(set(data))
ret.sort(key=data.index)
return ret | 56,636 |
def parse_mval_string(fa_mval_s, fa_mode):
"""Parse formamide m-value string.
Args:
fa_mval_s (str): formamide m-value string.
fa_mode (str): formamide mode (see FA_MODE_LABELS).
Returns:
str, fun: formamide m-value string and function for parsing.
"""
# Evaluate formamide... | 56,637 |
def train_val_test_split(messages, labels, split_frac, random_seed=None):
"""
Zero Pad input messages
:param messages: Input list of encoded messages
:param labels: Input list of encoded labels
:param split_frac: Input float, training split percentage
:return: tuple of arrays train_x, val_x, tes... | 56,638 |
async def delete_anime(
*,
session: aio_session.AsyncSession = fastapi.Depends(
dependencies.get_session),
anime_id: pydantic.UUID4,
current_patron: patron_model.Patron = fastapi.Depends( # pylint: disable=unused-argument
dependencies.get_current_active_superuser),
):
"""Deletes an ... | 56,639 |
def test_validate_shcd_cabling_invalid_ip():
"""Test that the `canu validate shcd-cabling` command errors on invalid IP address."""
invalid_ip = "999.999.999.999"
with runner.isolated_filesystem():
generate_test_file(test_file)
result = runner.invoke(
cli,
[
... | 56,640 |
def jaccard_similarity(mat):
"""
get jaccard similarity matrix
:param mat: scipy.sparse.csc_matrix
:return: similarity matrix of nodes
"""
# make it a binary matrix
mat_bin = mat.copy()
mat_bin.data[:] = 1
col_sum = mat_bin.getnnz(axis=0)
ab = mat_bin.dot(mat_bin.T)
aa = np.... | 56,641 |
def mnist_dataset(
split: str,
has_labels: bool,
flatten_images: bool,
device_batch_size: int,
repeat: bool,
shuffle: bool,
drop_remainder: bool,
seed: Optional[int] = None,
multi_device: bool = True,
reshuffle_each_iteration: bool = True,
dtype: str = "float32",
) -> tf.data... | 56,642 |
def favorite_mange(manga_id):
"""
endpoint: /manga/<manga_id>/favorite
method: POST
response:
total: total_favorited
status: False
"""
user = User.query.get(g.uid)
user_manga = UsersManga.query.filter_by(
user_uid=g.uid,
manga_id=manga_id
).first()
if ... | 56,643 |
async def recognize(args: argparse.Namespace, core: Voice2JsonCore) -> None:
"""Recognize intent from sentence(s)."""
import networkx as nx
import rhasspynlu
from .train import WordCasing
# Make sure profile has been trained
assert core.check_trained(), "Not trained"
# Load settings
la... | 56,644 |
def get_plugins(
user_id : Optional[int] = None,
search_term : Optional[str] = None,
) -> List[str]:
"""
Return a list of registered plugins.
"""
return get_api_connector().get_plugins(user_id=user_id, search_term=search_term) | 56,645 |
def mv_data_dir(target):
"""
Move data_dir to {target} location, refineable in case data_dir is a mounted volume or object storage and needs special treatments
:return:
"""
from django_productline.context import PRODUCT_CONTEXT
os.rename(PRODUCT_CONTEXT.DATA_DIR, target) | 56,646 |
def get_tile_rect(x, y):
"""Converts tile indices to a pygame.Rect"""
return Rect(x*SIZE, y*SIZE, SIZE, SIZE) | 56,647 |
def checkBlockageQHull(plane1,plane2,planeB,nargout=1):
"""
Using ConvexHull.
This is slower, but worth having as it's more intuitive.
We can use this to have a third opinion.
Check wheter plane1 and plane2 are blocked by planeB.
plane1, plane2, planeB are simple planes defined in the
re... | 56,648 |
def getLinks(laneID):
"""getLinks(string) -> list((string, bool, bool, bool))
A list containing ids of successor lanes together with priority, open and foe.
"""
return _getUniversal(tc.LANE_LINKS, laneID) | 56,649 |
def calc_center_position(pos: Tuple[int, int]):
"""
ボックスの中央の座標を取得する
Parameters
----------
pos : (int,int)
ボックスの座標(左上を原点とし、(横、縦)する)
Returns
-------
position : (int,int)
ボックスの中央の座標
"""
box_size = calc_box_size(row, column)
pos_x, pos_y = pos
return (PADLEF... | 56,650 |
def quicksort(array, lower = 0, upper = 1., threshold = 100):
"""
Parallel quicksort an array in place.
:param array: The array to sort.
:param lower: The minimum value in the array.
:param upper: The maximum value in the array.
:param threshold: The size threshold at which to switch to insertio... | 56,651 |
def test_sentencizer_en_float_numbers():
"""
Separators in float numbers, URLs, emails, abbreviations (like 'Mr.')
are not taking into account.
"""
segmenter = Sentencizer()
text = 'With a 0.99 probability this sentence will be ' \
'tokenized in 2 sentences.'
docs_chunks = segment... | 56,652 |
def ws_sheet_names(xlsx_file, log_on_open=True):
"""Return the sheet names in the XLSX file."""
if log_on_open:
log('SCAN: [!c]{:s}[!/c]', xlsx_file)
with closing(load_ro_workbook(xlsx_file)) as wb:
return [str(i) for i in wb.sheetnames] | 56,653 |
def main():
"""
Sets up a terminal and runs it.
"""
try:
miniterm = Miniterm(PORT, BAUDRATE, PARITY, rtscts=RTSCTS,
xonxoff=XONXOFF, echo=ECHO)
except serial.SerialException as e:
sys.stderr.write("could not open port %r: %s\n" % (PORT, e))
sys.exi... | 56,654 |
def readgpio(ctx, gpio_id):
"""Read a gpio pin
\f
"""
gpioutils.setup(gpio_id)
pinstatus = gpioutils.read(gpio_id)
print('Pin {0} is {1}'.format(gpio_id, pinstatus)) | 56,655 |
def process_citeauthor(
s: str,
lang: str,
**kwargs
) -> str:
"""
Transforms all citeauthor to [cite]. For example:
``'This is from \citeauthor{Pizarro}, and that is from \citeauthor{cite1, cite2}'`` to
``'This is from [author], and that is from [authors]'``.
:param s: Latex... | 56,656 |
def normalize_newlines(text):
"""Normalizes CRLF and CR newlines to just LF."""
# text = force_text(text)
re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines
return re_newlines.sub('\n', text) | 56,657 |
def power_curve_se_42m140():
"""Power curve for Senvion 4.2M140
Extracted by hand from offial spec-sheet at:
https://www.senvion.com/global/en/products-services/wind-turbines/4xm/
"""
wind_speeds = np.hstack(([0., 1., 2., 3.], np.arange(4, 27, step=2), [27., 40.]))
generation_kw = [0., 0., 0., 0... | 56,658 |
def load_service(config_path, base_config=None):
"""Loads a service configuration.
Args:
config_path: Path the service configuration to load.
base_config: The shared configuration to include in this service.
Returns:
name: The service name
service: The service manager.
"""
... | 56,659 |
def close_ring(coordinates):
"""
checks if the first and last points of a ring are equal and closes the ring
"""
if not points_equal(coordinates[0], coordinates[len(coordinates) - 1]):
coordinates.append(coordinates[0])
return coordinates | 56,660 |
def check_families(trace_events, families, event_definitions):
"""
Looks for event types found in the trace that are not specified in the
event definitions.
:param trace_events: Events found in the trace (filtered by family).
:param families: Families to look for.
:param event_definitions: Even... | 56,661 |
def broken_search(nums, target):
"""
Функция должна вернуть индекс элемента, равного k
Eсли такой есть в массиве (нумерация с нуля).
Если элемент не найден, функция должна вернуть -1
Изменять массив нельзя.
"""
return binary_s(nums, target, left=0, right=len(nums)-1) | 56,662 |
def str_to_timedelta(td_str):
"""
Returns a timedelta parsed from the native string output of a timedelta.
Timedelta displays in the format ``X day(s), H:MM:SS.ffffff``
Both the days section and the microseconds section are optional and ``days``
is singular in cases where there is only one day.
... | 56,663 |
def plot_training_performance(train_loss, val_loss,
samples_per_bucket: int, n_iterations: int, path='./training'):
""" Plotting for training/validation curves.
training_losses, validation_losses = {'cz_loss': [], 'a_loss': [], 'l2_loss': []}, {'cz_loss': []}
"""
plt.close(... | 56,664 |
def main():
"""Allows the user to manipulate a graphical circle object"""
the_circle = GraphicalCircle((0, 0), 100) # Make a graphical circle object
print("Program done") | 56,665 |
def download_file(url, download_dir, path=None, clobber=False):
"""
thanks to: https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py
path : str
local path to download to.
"""
if path is None:
local_filename = os.path.join(download_dir, url... | 56,666 |
def get_distribution_strategy():
"""Returns the current `DistributionStrategy` object.
Prefer to use `get_tower_context()` or `get_cross_tower_context()`
instead when possible.
Returns:
A `DistributionStrategy` object. Inside a
`with distribution_strategy.scope()` block, it returns
`distribution_s... | 56,667 |
def main():
"""Command line parser."""
arguments = docopt(__doc__, version=__version__)
kit = get_kit(arguments['CONF'])
if arguments['shell']:
run_shell(kit)
elif arguments['server']:
run_server(
kit,
local=arguments['--local'],
port=int(arguments['--port']),
debug=arguments['... | 56,668 |
def exists_project_slug(slug):
"""
Whether the slug has been taken by an existing project of any
kind.
"""
return bool(ActiveProject.objects.filter(slug=slug)
or ArchivedProject.objects.filter(slug=slug)
or PublishedProject.objects.filter(slug=slug)) | 56,669 |
def main(args):
"""
Main entry point for program
:param args:
:return:
"""
desc = """
Version {version}
Annotates NDEx with INDRA and optionally loads networks into
NDEx (http://ndexbio.org).
To connect to NDEx server a configuration file must be passed
into --conf par... | 56,670 |
def clean_cache(cachedir, log, limit=100):
"""Remove cached images
Args:
cachedir (str): Path to image cache
log (obj): Logger for debug
limit (int): Number of hours to keep cached image
"""
limit *= 3600
use_by = time.time() - limit
log.debug("Cache Age: {}".format(u... | 56,671 |
def test_run_c2_config() -> None:
"""Run a C2 style Optimization task from a config file.
This checks for the integrity of the c2 style config file
The eval_func is set at run time to mock_ORBIT
"""
with open(OPT_CONFIG_FILE_NAME, "r") as cfg_file:
cfg = hjson.load(cfg_file)
cfg.pop(... | 56,672 |
def test_augment_observation():
"""Test that the last 40 elements of obs array are sliced off correctly."""
env = MT10()
for i in range(env.num_tasks):
env.set_task(i)
obs, _, _, _ = env.step(env.action_space.sample())
assert obs[-10:][i] == 1
obs = env.reset()
assert... | 56,673 |
def coupling_rate():
"""Return fraction of women by age who will form a couple that year."""
path_marriage = os.path.join(INPUT_DIR, 'ONS/cohabitationandcohortanalyses11.xls')
path_births = os.path.join(INPUT_DIR, 'ONS/birthsbyparentscharacteristics2014final.xls')
n_female = n_age_sex().values[:, 1]
... | 56,674 |
def set_tree_topology(tree, tree2):
"""
Changes the topology of tree to match tree2
trees must have nodes with the same names
"""
nodes = tree.nodes
nodes2 = tree2.nodes
for node in tree:
node2 = nodes2[node.name]
# set parent
if node2.parent:
node.pare... | 56,675 |
def merge_dupes(list_cxs, cutoff, func=cp.bader_score, npasses=1):
"""
cxs: list of sets
Requires multiple passes to be more certain of fewer complex pairs passing
the merge threshold. But higher passes results in overcollapse when cutoff
< 1.
"""
cxs = list(list_cxs)
cxs_remaining = lis... | 56,676 |
def mock_producer_send(monkeypatch):
"""Mock KafkaProducer send method."""
monkeypatch.setattr(KafkaProducer, "send", lambda *args, **kargs: None) | 56,677 |
def convertSQL_LIKE2REGEXP(sql_like_pattern):
"""Convert a standard SQL LIKE pattern to a REGEXP pattern.
Function that transforms a SQL LIKE pattern to a supported python
regexp. Returns a python regular expression (i.e. regexp).
sql_like_pattern[in] pattern in the SQL LIKE form to be converted.
... | 56,678 |
def _write_prop(outstream, key, value, tab):
"""Write out a property."""
if value is None:
return
# this may use custom string converter (e.g codepoint labels)
value = str(value)
if not value:
return
if '\n' not in value:
outstream.write('{}: {}\n'.format(key, value))
... | 56,679 |
def diag(tensor: ChargeArray) -> Any:
"""
Return a diagonal `BlockSparseTensor` from a `ChargeArray`, or
return the diagonal of a `BlockSparseTensor` as a `ChargeArray`.
For input of type `BlockSparseTensor`:
The full diagonal is obtained from finding the diagonal blocks of the
`BlockSparseTensor`, ta... | 56,680 |
def test_check_response_length_invalid(input):
"""
Test if "check_response_length()" raises an ShdlcResponseError if the
response length is wrong.
"""
cmd = ShdlcCmdGetSystemUpTime()
with pytest.raises(ShdlcResponseError):
cmd.check_response_length(input) | 56,681 |
def _setup(app):
"""Hooks for actions performed before each request.
"""
if settings.ROLLBAR_API_KEY:
@app.before_first_request
def init_rollbar(): # pylint: disable=unused-variable
"""If rollbar is not installed but ROLLBAR_API_KEY is set, there
will be an exception... | 56,682 |
def box_heightmap(box: BoxCorner, hm: HeightMap, qp_a: QP, qp_b: QP) -> Contact:
"""Returns contact between a box corner and a height map."""
# Note that this only checks box corners against height map surfaces, and is
# missing box planes against height map points.
pos, vel = qp_a.to_world(box.corner)
pos = ... | 56,683 |
def rjmcmc_chisq_convergence(k, thin=1, sparse=False,
split=True, merge_cells=True,
correction=True,
use_likelihood_ratio=False,
class_lookup=None,
min_expected_count=5):
... | 56,684 |
def mastermind(choice):
"""
In this function, a random number is generated and replaced by underscores. The player has to guess the number within a given number of tries
Parameters
----------
choice: Str
this is the choice of game the player has entered
"""
choice1=''... | 56,685 |
def printVlans(vlans):
"""
Prints vlans from array to console.
TODO: Fix extra None in implementation. APPEARS TO BE USELESS
Author:
David J. Stern
Date:
DEC 2017
Parameters:
vlans: (int[]): Array of Virtual Local Area Network (VLAN) numbers
Returns:
(none)
... | 56,686 |
def remove_vars_match(mat,fmla):
""" Remove the variables bindings from a match. This is used to
prevent variable capture when applying the match to premises. Make sure free variables
are not captured by fmla """
res = dict((s,v) for s,v in mat.iteritems() if il.is_ui_sort(s))
sympairs = [(s,v) for ... | 56,687 |
def test_sql_endpoint():
"""Verify that /program/entity/sql/ endpoint exists"""
url = '/rulings/wic/federal/sql/'
response = client.get(url)
assert response.status_code == status.HTTP_200_OK
assert 'JSON_TO_RECORDSET' in response.data | 56,688 |
def str_exp(exp, ak, den, diff=0.05):
"""
Function that returns a string k^(a/den) if the absolute difference between
the value a/den and the exponent ak is below diff.
Arguments:
exp -- initial string (given by the previous best estimation)
ak -- slope
den -- denominator of th... | 56,689 |
def plot_dynamics(state_dynamics, condition, path, **kwargs):
"""
Plot the dynamics of the states for each session.
"""
fname_cfg = {'prefix':'',
'suffix':''}
fname_cfg.update(kwargs)
for i, ts in enumerate(state_dynamics):
_ = pl.figure(figsize=(18,1... | 56,690 |
def search(*, common: dict = Depends(common_parameters), type: SearchTypes):
"""Perform a search."""
if common["query_str"]:
models = [get_class_by_tablename(t) for t in type]
results = composite_search(
db_session=common["db_session"],
query_str=common["query_str"],
... | 56,691 |
def stack(x, axis=0):
"""Join a sequence of tensors along a new axis """
return T.stack(x, axis=axis) | 56,692 |
def or_value(
maybe_value: typing.Optional[typing.Any],
fallback_value: typing.Any,
) -> typing.Any:
"""Return maybe_value if not None; otherwise, return fallback_value.
Parameters
----------
maybe_value
The value to test and return if it is not None.
fallback_value
The valu... | 56,693 |
def parse_arguments(solving_methods):
"""
Main CLI for interfacing with Monte Carlo Sudoku Solver.
Arguments:
solving_methods: tuple(str)
Methods for solving sudoku puzzles.
Returns:
argparse.Namespace
Argparse namespace containg CLI inputs.
"""
parser ... | 56,694 |
def form_from_fields(name, form=forms.Form, fields={}):
"""
Returns a forms.Form class with a name, `name`, a Form baseclass, `form`, and
a dictionary of fields, `fields`.
"""
return DeclarativeFieldsMetaclass(name, (form,), fields) | 56,695 |
def make_enumeration(entries, divider=', '):
"""
:param entries:
:param divider:
:return:
"""
enumeration = {
'type': 'enumeration',
'entries': entries,
'divider': divider
}
return enumeration | 56,696 |
def list_available_node_types():
"""returns the friendly names of all available node types
"""
return list(type_map.keys()) | 56,697 |
async def test_lesscss_minify(client):
""" testing css and less minify option """
Minify(app=app, html=False, cssless=True, js=False)
resp = await client.get("/cssless")
data = await resp.get_data()
assert b"<style>body{color:red;}</style>" == data | 56,698 |
def sitk_binary_fill_holes(labels: np.ndarray,
fill_border: bool = True,
iterations: Union[int, bool] = False,
kernel_radius: int = 4,
max_length: int = 45,
in_place: bool = True,
... | 56,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.