content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def isValidListOrRulename(word: str) -> bool:
"""test if there are no accented characters in a listname or rulename
so asciiletters, digitis, - and _ are allowed
"""
return bool(reValidName.match(word)) | 4,900 |
def capture(source, img_num, raw_path, grayscale_path):
"""
:param source: 视频源
:param img_num: 需要获取的人脸图像数目
:param raw_path: 原始图片的保存路径
:param grayscale_path: 人脸灰度图的保存路径
:return: 无
"""
# 记录已经截取的人脸图像数目
img_count = 0
# 开始截取
while cap.isOpened():
ok, frame = ... | 4,901 |
def glyph_has_ink(font: TTFont, name: Text) -> bool:
"""Checks if specified glyph has any ink.
That is, that it has at least one defined contour associated.
Composites are considered to have ink if any of their components have ink.
Args:
font: the font
glyph_name: The name of the ... | 4,902 |
def test_list_algorithms(client):
"""Test get list of active learning models"""
response = client.get("/api/algorithms")
json_data = response.get_json()
assert "classifier" in json_data.keys()
assert "name" in json_data["classifier"][0].keys()
assert isinstance(json_data, dict) | 4,903 |
async def async_setup_entry(hass, entry, async_add_entities):
"""
Set up n3rgy data sensor
:param hass: hass object
:param entry: config entry
:return: none
"""
# in-line function
async def async_update_data():
"""
Fetch data from n3rgy API
This is the place to pr... | 4,904 |
def main():
""" Process command line arguments and run the script """
bp = BrPredMetric()
result = bp.Run()
return result | 4,905 |
def step(init_distr,D):
"""
"""
for k in init_distr.keys():
init_distr[k] = D[init_distr[k]]()
return init_distr | 4,906 |
def from_json(data: JsonDict) -> AttributeType:
"""Make an attribute type from JSON data (deserialize)
Args:
data: JSON data from Tamr server
"""
base_type = data.get("baseType")
if base_type is None:
logger.error(f"JSON data: {repr(data)}")
raise ValueError("Missing require... | 4,907 |
def ftduino_find_by_name(name):
"""
Returns the path of the ftDuino with the specified `name`.
:param name: Name of the ftDuino.
:return: The path of the ftDuino or ``None`` if the ftDuino was not found.
"""
for path, device_name in ftduino_iter():
if device_name == name:
re... | 4,908 |
def init_config_file(
odin_config_full_path,
circuit_list,
architecture_file,
output_netlist,
memory_addr_width,
min_hard_mult_size,
min_hard_adder_size,
):
"""initializing the raw odin config file"""
# Update the config file
file_replace(
odin_config_full_path,
... | 4,909 |
def test_from_str_returns_ulid_instance(api, valid_bytes_128):
"""
Assert that :func:`~ulid.api.from_str` returns a new :class:`~ulid.ulid.ULID` instance
from the given bytes.
"""
value = base32.encode(valid_bytes_128)
instance = api.from_str(value)
assert isinstance(instance, ulid.ULID)
... | 4,910 |
def test_nonable_fields(declaration):
"""Tests that nonable fields are supported and correctly handled"""
if declaration == 'typing':
from typing import Optional
class Foo(object):
a = field(type_hint=Optional[int], check_type=True)
b = field(type_hint=Optional[... | 4,911 |
def spectral_entropy (Sxx, fn, flim=None, display=False) :
"""
Compute different entropies based on the average spectrum, its variance,
and its maxima [1]_ [2]_
Parameters
----------
Sxx : ndarray of floats
Spectrogram (2d).
It is recommended to work with PSD to be con... | 4,912 |
def get_pmt_numbers(channels, modules, pmts_buffer, pmt_lookup):
"""Fills pmts_buffer with pmt numbers corresponding to channels, modules according to pmt_lookup matrix:
- pmt_lookup: lookup matrix for pmt numbers. First index is digitizer module, second is digitizer channel.
Modifies pmts_buffer in-place.... | 4,913 |
def _percentages(self):
"""
An extension method for Counter that
returns a dict mapping the keys of the Counter to their percentages.
:param self: Counter
:return: a dict mapping the keys of the Counter to their percentages
"""
# type: () -> dict[any, float]
length = float(sum(count for ... | 4,914 |
def find_best_word_n(draw, nb_letters, path):
"""
"""
lexicon = get_lexicon(path, nb_letters)
mask = [is_word_in_draw(draw, word) for word in lexicon["draw"]]
lexicon = lexicon.loc[mask]
return lexicon | 4,915 |
def feature_reader(path):
"""
Reading the feature matrix stored as JSON from the disk.
:param path: Path to the JSON file.
:return out_features: Dict with index and value tensor.
"""
features = json.load(open(path))
features = {int(k): [int(val) for val in v] for k, v in features.items()}
... | 4,916 |
def locate_all_occurrence(l, e):
"""
Return indices of all element occurrences in given list
:param l: given list
:type l: list
:param e: element to locate
:return: indices of all occurrences
:rtype: list
"""
return [i for i, x in enumerate(l) if x == e] | 4,917 |
def UVectorFromAngles(reflection):
"""
Calculate the B&L U vector from bisecting geometry
angles
"""
u = np.zeros((3,), dtype='float64')
# The tricky bit is set again: Busing & Levy's omega is 0 in
# bisecting position. This is why we have to correct for
# stt/2 here
om = np.deg2rad... | 4,918 |
def to_pillow_image(img_array, image_size=None):
"""Convert an image represented as a numpy array back into a
Pillow Image object."""
if isinstance(image_size, (numbers.Integral, np.integer)):
image_size = (image_size, image_size)
img_array = skimage.img_as_ubyte(img_array)
img = pil_image.... | 4,919 |
def new_session_dir(rootdir, pid, sid):
"""
Creates a path to a new session directory.
Example:
<DATA_ROOT>/p0/session_2014-08-12_p0_arm1
"""
date_str = datetime.date.today().strftime('%Y-%m-%d')
session_dir = os.path.join(
rootdir,
pid,
'session_' + date_str + '_... | 4,920 |
def calibrateImage(contours, img, arm1, outfile):
""" Perform camera calibration using both images.
This code saves the camera pixels (cX,cY) and the robot coordinates
(the (pos,rot) for ONE arm) all in one pickle file. Then, not in
this code, we run regression to get our desired mapping from pixe... | 4,921 |
def getter_collector(): # noqa
"""
This function is the main function of the toolkit.
It performs two roles:
1) Collects configurations for all devices in the inventory,
based on NAPALM support.
These configurations are saved in the configs/ directory using the following convention:
<hos... | 4,922 |
def seq_to_sentence(seq: Iterator[int], vocab: Vocab, ignore: Iterator[int]) -> str:
"""Convert a sequence of integers to a string of (space-separated) words according to a vocabulary.
:param seq: Iterator[int]
A sequence of integers (tokens) to be converted.
:param vocab: Vocab
A Torchtext... | 4,923 |
def teardown_module():
""" teardown any state that was previously setup with a setup_module
method.
"""
os.chdir(saved_cwd) | 4,924 |
def p_sub_directory_stmt(p):
"""sub_directory_stmt : SUB_DIRECTORY_ID COLON WORD"""
p[0] = Node("sub_directory", value=p[3]) | 4,925 |
def estimate_exposures(imgs, exif_exp, metadata, method, noise_floor=16, percentile=10,
invert_gamma=False, cam=None, outlier='cerman'):
"""
Exposure times may be inaccurate. Estimate the correct values by fitting a linear system.
:imgs: Image stack
:exif_exp: Exposure times read from image metadata
:met... | 4,926 |
def plot_confusion_matrix(cm, cms, classes, cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
cm: confusion matrix in perecentage
cms: standard deviation error from cm
classes: Name of each label
"""
plt.figure()
plt.imshow(cm, interpolation='neare... | 4,927 |
def test_only_specials():
"""
Tests passwords that only contain special characters and are under 8 chars.
"""
passwords = ["!!!!", '???', '****', '%%%%%%%%', '$$$$', '@@@@@']
for p in passwords:
assert check_password(p) == 0.25 | 4,928 |
def indicators(bot, update):
""" Display enabled indicators """
chat_id = update.message.chat_id
user_id = 'usr_{}'.format(chat_id)
_config = users_config[user_id]
update.message.reply_text('Configured indicators ... ')
for indicator in _config.indicators:
... | 4,929 |
def default_reverse(*args, **kwargs):
"""
Acts just like django.core.urlresolvers.reverse() except that if the
resolver raises a NoReverseMatch exception, then a default value will be
returned instead. If no default value is provided, then the exception will
be raised as normal.
NOTE: Any excep... | 4,930 |
def _backup_file(filename):
"""Renames a given filename so it has a `-YYYY-MM-DD-HHMMSS` suffix"""
dt_now = datetime.datetime.now()
move_filename = "{}-{}-{}-{}-{}{:02d}{:02d}".format(filename, dt_now.year,
dt_now.month, dt_now.day, dt_now.hour, dt_now.minute, dt_now.second
)
print("Backing up \"{}\" to \... | 4,931 |
def get_company_periods_up_to(period):
""" Get all periods for a company leading up to the given period, including the given period
"""
company = period.company
return (company.period_set
.filter(company=company, end__lte=period.end)) | 4,932 |
def format_count(
label: str, counts: List[int], color: str, dashed: bool = False
) -> dict:
"""Format a line dataset for chart.js"""
ret = {
"label": label,
"data": counts,
"borderColor": color,
"borderWidth": 2,
"fill": False,
}
if dashed:
ret["borde... | 4,933 |
def main():
"""
Main
"""
# parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--server", action="store_true",
help="run server")
parser.add_argument("-c", "--client", action="store_true",
help="run clien... | 4,934 |
def test_initialize_file(ds_from_uvfits, test_outfile):
"""Test initializing file onto disk."""
ds = ds_from_uvfits
ds.initialize_save_file(test_outfile)
ds.data_array = None
ds.flag_array = None
ds.nsample_array = None
ds.noise_array = None
ds_in = DelaySpectrum()
ds_in.read(test_ou... | 4,935 |
def detect_ripples(eeg):
"""Detect sharp wave ripples (SWRs) from single channel eeg (AnalogSignalArray).
"""
# Maggie defines ripples by doing:
# (1) filter 150-250
# (2) hilbert envelope
# (3) smooth with Gaussian (4 ms SD)
# (4) 3.5 SD above the mean for 15 ms
# (5) full ripple ... | 4,936 |
def usage():
""" Usage function
"""
print("Usage: %s <json conf file>" % sys.argv[0])
sys.exit(0) | 4,937 |
def cymdtodoy(str):
"""cymdtodoy(str) -> string
Convert a legal CCSDS time string with the date expressed as a month and day
to a simple time string with the date expressed as a day-of-year."""
try:
(year, mon, day, hour, min, sec) = cymdtoaymd(str)
doy = aymdtodoy(year, mon, day, hour, min, sec)
except... | 4,938 |
def configured_hosts(hass):
"""Return a set of the configured hosts."""
"""For future to use with discovery!"""
out = {}
for entry in hass.config_entries.async_entries(DOMAIN):
out[entry.data[CONF_ADDRESS]] = {
UUID: entry.data[UUID],
CONF_ADDRESS: entry.data[CONF_ADDRESS... | 4,939 |
def load_model(model_name, weights, model_paths, module_name, model_params):
"""Import model and load pretrained weights"""
if model_paths:
sys.path.extend(model_paths)
try:
module = importlib.import_module(module_name)
creator = getattr(module, model_name)
model = creator(... | 4,940 |
def generate_keys(directory: str, pwd: bytes = None) -> (ec.EllipticCurvePrivateKey, ec.EllipticCurvePublicKey):
"""
Generate the public and private keys
Generated keys have a default name, you should rename them
This can be done with os.rename()
:param directory: folder where the keys are made
... | 4,941 |
def test_notebooks():
"""
Run all notebooks in the directories given by the list `notebook_paths`.
The notebooks are run locally using [treon](https://github.com/ReviewNB/treon)
and executed in each directory so that local resources can be imported.
Returns:
num_errors (int): Number of not... | 4,942 |
def _iter_sample(
logp_dlogp_func: Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]],
model_ndim: int,
draws: int,
tune: int,
step: Union[NUTS, HamiltonianMC],
start: np.ndarray,
random_seed: Union[None, int, List[int]] = None,
callback=None,
):
"""
Yield one chain in one pro... | 4,943 |
def get_storage_config_by_data_type(result_table_id):
"""
根据rt_id获取存储配置列表
:param result_table_id:rtid
:return: response:存储配置列表
"""
return DataStorageConfig.objects.filter(result_table_id=result_table_id, data_type="raw_data") | 4,944 |
def separate_args(args: List[str]) -> (List[str], List[str]):
"""Separate args into preparser args and primary parser args.
Args:
args: Raw command line arguments.
Returns:
A tuple of lists (preparser_args, mainparser_args).
"""
preparser_args = []
if args and args[0].startswith... | 4,945 |
def send_to_stream(stream, msg):
"""
Pickle & send to stdout a message.
Used primarily to communicate back-and-forth with a separately launched ztv process.
"""
if isinstance(msg, str):
msg = (msg,)
pkl = pickle.dumps(msg)
stream.write(pkl + '\n' + end_of_message_message)
stream... | 4,946 |
def test_string_map_key_index():
"""
Tests string map key indexes across all set names, index names, and
index paths.
"""
lib.backup_and_restore(
lambda context: create_indexes(lib.create_string_map_key_index),
None,
lambda context: check_indexes(lib.check_map_key_index, "foobar")
) | 4,947 |
def lookup_alive_tags_shallow(repository_id, start_pagination_id=None, limit=None):
""" Returns a list of the tags alive in the specified repository. Note that the tags returned
*only* contain their ID and name. Also note that the Tags are returned ordered by ID.
"""
query = (Tag
.select(Tag.id, ... | 4,948 |
def plotLevelSubsystems(Model, graph_reactions, fig_dpi=100):
"""
Computes the frequencies of the subsystems of the reactions appearing
in the specified graph level which have the specified macrosystem
"""
GEM = Model.GEM
macrosystems = ['Amino acid metabolism', 'Carbohydrate metabolism', 'Cell ... | 4,949 |
def getLesson(request):
"""
Get the JSON representation for a lesson.
"""
print("getLesson called...")
lesson_id = None
if 'lesson_id' in request.matchdict:
lesson_id = request.matchdict['lesson_id']
if lesson_id is None:
# This should return an appropriate error about not ... | 4,950 |
def config():
"""Modify spaceconfig files"""
pass | 4,951 |
def vector3d(mode,xdata,ydata,zdata,udata,vdata,wdata,scalardata=None,fig=None,zscale=500.,vector_color=(0,0,0),vector_cmap=None,alpha=1.0,vector_mode='2darrow', scale=1, spacing=8., set_view=None):
"""
fig: integer or string, optional. Figure key will plot data on corresponding mlab figure, if it exists, or cr... | 4,952 |
def make_daysetting_from_data(data):
""" Constructs a new setting from a given dataset. This method will automatically
instantiate a new class matching the type of the given dataset. It will fill
all values provided by the dataset and then return the created instance """
factory = {
"color": Col... | 4,953 |
def read_report(file) -> Optional[Report]:
"""
Reads the report meta-data section of the file.
:param file: The file being read from.
:return: The report section of the file.
"""
# Use a peeker so we don't read beyond the end of the header section
peeker = line_peeker(file)
... | 4,954 |
def get_valid_segment(text):
""" Returns None or the valid Loki-formatted urn segment for the given input string. """
if text == '':
return None
else:
# Return the converted text value with invalid characters removed.
valid_chars = ['.', '_', '-']
new_text = ''
for c... | 4,955 |
def on_camera_image(cli, new_im):
""" Handle new images, coming from the robot. """
global last_im
last_im = new_im | 4,956 |
def get_aimpoint_offsets():
"""
Get most recent aimpoint offset values
:returns: tuple of dy_acis_i, dz_acis_i, dy_acis_s, dz_acis_s (arcsec)
"""
info_file = os.path.join(opt.data_root, 'info.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
process_time = Time(opt.proce... | 4,957 |
def cmd_ci(argv, args):
"""
Usage:
localstack ci <subcommand> [options]
Commands:
init Initialize CI configuration for a new repository
repos List continuous integration repositories
Options:
--provider=<> CI provider (default: travis)
--repo=<> Repos... | 4,958 |
def save_dataset(ds: object, target_dir: str, context_folder=None):
"""Copies the dataset graph into the provided target directory.
EXPERIMENTAL/UNSTABLE
Parameters
----------
ds:
the dataset graph to save
target_dir
the target directory to save to
context_folder
a ... | 4,959 |
def mparse(filename, staticObstacleList=list(), **kwargs):
"""
Parses a map file into a list of obstacles
@param filename The file name of the map file
@return A list of obstacles
"""
polyList = kwargs.get("nodes", list())
obstacleList = list()
try:
if filename is not None:
... | 4,960 |
def install_pip_packages(python_executable: str,
pip_packages: typing.List[str]) -> bool:
"""Install pip packages for the specified python.
Args:
python_executable: Python executable used to install pip packages.
pip_packages: List of pip packages to install.
Raises:
subproc... | 4,961 |
def sort_f_df(f_df):
"""Sorts f_df by s_idx first then by l_idx.
E.g. for scenario 0, see all decision alternatives in order,
then scenario 1, scenario 2, etc.
Parameters
----------
f_df : pandas.DataFrame
A dataframe of performance values, `f`, with indexes for the
scenario, `... | 4,962 |
def get_empath_scores(text):
"""
Obtains empath analysis on the text. Takes the dictionary mapping categories to
scores, which is produced by passing the text to empath, and returns the scores.
Args:
text: string containing text to perform empath analysis on
Returns:
A list of empa... | 4,963 |
def ending_counts(sequences):
"""Return a dictionary keyed to each unique value in the input sequences list
that counts the number of occurrences where that value is at the end of
a sequence.
For example, if 18 sequences end with DET, then you should return a
dictionary such that your_starting_... | 4,964 |
def sqlite_insert(engine, table_name, data):
"""
Inserts data into a table - either one row or in bulk.
Create the table if not exists.
Parameters
----------
engine: sqlalchemy engine for sqlite
uri: string
data: dict
Returns
-------
bool
"""
dtype = type(data)
... | 4,965 |
def _fit_solver(solver):
"""
Call ``fit`` on the solver. Needed for multiprocessing.
"""
return solver.fit() | 4,966 |
def flatten(l):
"""
recursively turns any nested list into a regular list (using a DFS)
"""
res = []
for x in l:
if (isinstance(x, types.ListType)):
res += flatten(x)
else:
res.append(x)
return res | 4,967 |
def test_trial_heartbeat_not_updated_inbetween(exp, trial):
"""Test that the heartbeat of a trial is not updated before wait time."""
trial_monitor = TrialPacemaker(trial, wait_time=5)
trial_monitor.start()
time.sleep(1)
trials = exp.fetch_trials_by_status("reserved")
assert trial.heartbeat.re... | 4,968 |
def build_column_hierarchy(param_list, level_names, ts_columns, hide_levels=[]):
"""For each parameter in `param_list`, create a new column level with parameter values.
Combine this level with columns `ts_columns` using Cartesian product."""
checks.assert_same_shape(param_list, level_names, axis=0)
pa... | 4,969 |
def emitlabel(start):
"""emit the labelling functions"""
printf("static void %Plabel1(NODEPTR_TYPE p) {\n"
"%1%Passert(p, PANIC(\"NULL tree in %Plabel\\n\"));\n"
"%1switch (%Parity[OP_LABEL(p)]) {\n"
"%1case 0:\n")
if Tflag:
printf("%2%Pnp = p;\n");
printf("%2STATE_LABEL(p) = %Pstate(OP_LABEL(p), 0, 0);\n%2break;... | 4,970 |
def gradient_descent(f, xk, delta = 0.01, plot=False, F = None, axlim = 10):
"""
f: multivariable function with 1 array as parameter
xk : a vector to start descent
delta : precision of search
plot : option to plot the results or not
F : the function f expressed with 2 arrays in argument (X... | 4,971 |
def exercise_dict(show_result=True):
"""Exercise 2: Basic Dictionary Manipulations
Notebook: PCP_python.ipynb"""
if show_result is False:
return
student_dict = {123: ['Meier', 'Sebastian'], 456: ['Smith', 'Walter']}
print(student_dict)
student_dict[789] = ['Wang', 'Ming']
print(... | 4,972 |
def _mark_workflow_as_deleted_in_db(workflow):
"""Mark workflow as deleted."""
workflow.status = RunStatus.deleted
current_db_sessions = Session.object_session(workflow)
current_db_sessions.add(workflow)
current_db_sessions.commit() | 4,973 |
def unregister_dialect(name): # real signature unknown; restored from __doc__
"""
Delete the name/dialect mapping associated with a string name.
csv.unregister_dialect(name)
"""
pass | 4,974 |
def _get_cells(obj):
"""Extract cells and cell_data from a vtkDataSet and sort it by types."""
cells, cell_data = {}, {}
data = _get_data(obj.GetCellData())
arr = vtk2np(obj.GetCells().GetData())
loc = vtk2np(obj.GetCellLocationsArray())
types = vtk2np(obj.GetCellTypesArray())
for typ in VT... | 4,975 |
def check_X(X, enforce_univariate=False, enforce_min_instances=1):
"""Validate input data.
Parameters
----------
X : pd.DataFrame
enforce_univariate : bool, optional (default=False)
Enforce that X is univariate.
enforce_min_instances : int, optional (default=1)
Enforce minimum n... | 4,976 |
def parse_amount(value: int) -> Decimal:
"""Return a scaled down amount."""
return Decimal(value) / Decimal(AMOUNT_SCALE_FACTOR) | 4,977 |
def log(fun, user, message, debug=True):
# type: (str, str, str, bool) -> None
"""
Log in a CSV file
Header is:
"time", "command", "user_id", "message"
Time is in local-time
:rtype: None
"""
_log = (
datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S")
+ ... | 4,978 |
def post_mode(data):
"""
Example:
data = {'name': "EACH_RANDOM", 'fade_duration': 1000, 'delay_duration': 1000, }
"""
requests.post(f'http://{ip}/api/mode', data=data) | 4,979 |
async def _delete_session(bot, guild):
"""Deletes the session for the given guild."""
session_data = data.remove(bot, __name__, 'data', guild_id=guild.id, safe=True)
if not session_data:
raise CBException("Session does not exist.")
channel_id, webhook_id = session_data['channel'], session_data['... | 4,980 |
def svn_ra_do_update2(*args):
"""
svn_ra_do_update2(svn_ra_session_t session, svn_ra_reporter3_t reporter,
void report_baton, svn_revnum_t revision_to_update_to,
char update_target, svn_depth_t depth,
svn_boolean_t send_copyfrom_args, svn_delta_editor_t update_editor,
void upda... | 4,981 |
def resolve(schema, copy=False):
"""Resolve schema references.
:param schema: The schema to resolve.
:return: The resolved schema.
"""
from jsonschemaplus.schemas import metaschema
from jsonschemaplus.schemas import hyperschema
_substitutions = {'%25': '%', '~1': '/', '~0': '~'}
de... | 4,982 |
def test_truncate_wide_end(all_terms):
"""Ensure that terminal.truncate has the correct behaviour for wide characters."""
@as_subprocess
def child(kind):
from blessed import Terminal
term = Terminal(kind)
test_string = u"AB\uff23" # ABC
assert term.truncate(test_string, 3) =... | 4,983 |
def sentiwords_tag(doc, output="bag"):
"""Tag doc with SentiWords polarity priors.
Performs left-to-right, longest-match annotation of token spans with
polarities from SentiWords.
Uses no part-of-speech information; when a span has multiple possible
taggings in SentiWords, the mean is returned.
... | 4,984 |
def _GetCommandTaskIds(command):
"""Get a command's task ids."""
# A task count is the number of tasks we put in the command queue for this
# command. We cap this number to avoid a single command with large run count
# dominating an entire cluster. If a task count is smaller than a run count,
# completed task... | 4,985 |
def save_orchestrator_response(url, jsonresponse, dryrun):
"""Given a URL and JSON response create/update the corresponding mockfile."""
endpoint = url.split("/api/")[1].rstrip("/")
try:
path, identifier = endpoint.rsplit("/", maxsplit=1)
except ValueError:
path, identifier = None, endpo... | 4,986 |
def test_get_function_and_class_names(code, target):
"""Test get_function_and_class_names function."""
res = get_function_and_class_names(code)
assert sorted(res) == sorted(target) | 4,987 |
def aggregate_responses(instrument_ids, current_user, patch_dstu2=False):
"""Build a bundle of QuestionnaireResponses
:param instrument_ids: list of instrument_ids to restrict results to
:param current_user: user making request, necessary to restrict results
to list of patients the current_user has... | 4,988 |
def compute_bleu(reference_corpus, translation_corpus, max_order=4,
use_bp=True):
"""Computes BLEU score of translated segments against one or more references.
Args:
reference_corpus: list of references for each translation. Each
reference should be tokenized into a list of tokens.
... | 4,989 |
def flip(inputDirection: direction) -> direction:
"""
Chooses what part of the general pointer to flip, by DP%2 == CC rule, providing the following flow:
(0,0) -> (0,1)
(0,1) -> (1,1)
(1,1) -> (1,0)
(1,0) -> (2,0)
(2,0) -> (2,1)
(2,1) -> (3,1)
(3,1) -> (3,0)
(3,0) -> (0,0)
:p... | 4,990 |
def save(request):
"""Update the column levels in campaign_tree table with the user's input from the data warehouse frontend."""
if any(request["changes"]):
query = 'UPDATE campaign_tree SET '
query += ', '.join([f"""levels[{index + 1}] = trim(regexp_replace(%s, '\s+', ' ', 'g'))"""
... | 4,991 |
def netmiko_prompting_del(task):
"""
Some commands prompt for confirmation:
nxos1# del bootflash:/text.txt
Do you want to delete "/text.txt" ? (yes/no/abort) [y] y
"""
# Manually create Netmiko connection
net_connect = task.host.get_connection("netmiko", task.nornir.config)
fi... | 4,992 |
def test_non_existent_route(client: FlaskClient) -> None:
"""Test getting non-existant page."""
res = client.get("/")
assert res.status_code == 404
assert b"The requested URL was not found on the server" in res.data | 4,993 |
def print_options_data(ticker: str, export: str):
"""Scrapes Barchart.com for the options information
Parameters
----------
ticker: str
Ticker to get options info for
export: str
Format of export file
"""
data = barchart_model.get_options_info(ticker)
print(tabulate(da... | 4,994 |
def _print_model(server, user_key, device_type_model):
"""
Print the model for a given device type
:param device_type_model: Device type ID to print the model for
"""
name = None
model = []
parameters = _get_parameters(server, user_key)
parameters = parameters['deviceParams']
try:
... | 4,995 |
def parse_xiaomi(self, data, source_mac, rssi):
"""Parser for Xiaomi sensors"""
# check for adstruc length
i = 9 # till Frame Counter
msg_length = len(data)
if msg_length < i:
_LOGGER.debug("Invalid data length (initial check), adv: %s", data.hex())
return None
# extract frame ... | 4,996 |
def test_md009_bad_configuration_br_spaces_invalid():
"""
Test to verify that a configuration error is thrown when supplying the
br_spaces value is not an integer in the proper range.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
"--set",
"plugins.md009.br... | 4,997 |
def parse_ipv6_addresses(text):
"""."""
addresses = ioc_grammars.ipv6_address.searchString(text)
return _listify(addresses) | 4,998 |
def test_blank_lines_below_marker():
"""Empty lines between direct and fenced code block are OK."""
# This type of usage should be avoided.
directives = fenced_block_node_directives()
assert len(directives) == 1
marker = directives[0]
assert marker.type == phmdoctest.direct.Marker.CLEAR_NAMES
... | 4,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.