content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def boolean(entry, option_key="True/False", **kwargs):
"""
Simplest check in computer logic, right? This will take user input to flick the switch on or off
Args:
entry (str): A value such as True, On, Enabled, Disabled, False, 0, or 1.
option_key (str): What kind of Boolean we are setting. W... | 24,800 |
def verify_args(args, arg_infos, function_name):
""" Verifies that a list of arguments matches a list of argument descriptions in a HAT file
"""
# check number of args
if len(args) != len(arg_infos):
sys.exit(
f"Error calling {function_name}(...): expected {len(arg_infos)} arguments ... | 24,801 |
def save(image, path):
"""Save and extract a docker image to a directory.
Parameters
----------
image : str
A unique identifier for a docker image.
path : str
A directory to extract the image to.
"""
# Use a temporary file because docker save (or actually tar underneath)
... | 24,802 |
def remove_job(cursor, arguments):
"""Remove a job from job table.
Examples:
python main.py --remove job --job_id 7
python main.py -r job -j 7
python main.py --remove job --job_title sales
python main.py -r job -t sales
:param cursor: Cursor for SQL command execution.
... | 24,803 |
def edge_preserving_filter(ref_map: np.ndarray, guided_image: np.ndarray,
window_size: int, epsilon: float = 1e-10) -> np.ndarray:
"""
Perform edge - preserving filtering on the newly created reference map.
:param ref_map: Classification reference map.
:param guided_image: Gu... | 24,804 |
def logout(ctx, provider):
"""Logout from a provider."""
AuthCmd(ctx, provider).logout() | 24,805 |
def preprocess_annotated_utterance(
annotated_utterance: str,
not_entity: str = NOT_ENTITY,
) -> List[str]:
"""Character Level Entity Label Producer
Named-entity of each character is extracted by XML-like annotation.
Also, they would be collected in a list conform to the order o... | 24,806 |
def test_channel_tag_wrong_type(init_lst_proc):
"""Raise a type error when a wrong type is set for the channel number."""
wrong_type = "42"
with pytest.raises(TypeError) as exc_info:
init_lst_proc.channel_tag = wrong_type
exc_msg = exc_info.value.args[0]
assert exc_msg == "Channel number mus... | 24,807 |
def invitation_code_created(sender, email, **kwargs):
"""Send confirmation email to user."""
email_module_name = setting('BETA_EMAIL_MODULE', 'hunger.email')
email_module = importlib.import_module(email_module_name)
email_function_name = setting('BETA_EMAIL_CONFIRM_FUNCTION', 'beta_confirm')
email_f... | 24,808 |
def generate_constant_table(
name: str,
constants: List[Constant],
*,
data_type: str = "LREAL",
guid: str = "",
lookup_by_key: bool = False,
**kwargs
) -> Tuple[str, str]:
"""
Generate a GVL constant table, with no interpolation.
Parameters
----------
name : str
... | 24,809 |
def filter_stop_words(text):
"""
Filter all stop words from a string to reduce headline size.
:param text: text to filter
:return: shortened headline
"""
words = filter(lambda w: not w in s, text.split())
line = ""
l = 0
for w in words:
if l < 20:
line += w + " "... | 24,810 |
def importPublicKey(publickey):
""" Cette fonction permet de exporter la clé public,
elle prend en paramètre use clé public """
return RSA.importKey(publickey) | 24,811 |
def _format_contact(resource, key):
"""
Return the contact field with the correct values.
This is mainly stripping out the unecessary fields from the telecom part of
the response.
"""
contacts = resource.pop(key)
resource[key] = []
for contact in contacts:
contact["telecom"] = _... | 24,812 |
def get_day_type(date):
"""
Returns if a date is a weeday or weekend
:param date datetime:
:return string:
"""
# check if date is a datetime.date
if not isinstance(date, datetime.date):
raise TypeError('date is not a datetime.date')
day_type = ""
if date.weekday() in (0, 1, ... | 24,813 |
def case_insensitive_equals(name1: str, name2: str) -> bool:
"""
Convenience method to check whether two strings match, irrespective of their case and any surrounding whitespace.
"""
return name1.strip().lower() == name2.strip().lower() | 24,814 |
def plot3(distances, mean_fc_all,
track_names, track_palette,
p_adjs,
output_fig,
ylim=[-0.3, 0.6],
yticks=[-0.3,0,0.3,0.6],
p_th1=0.05,
p_th2=0.001,
):
"""
"""
ys = {track_name: [] for track_name in track_names}
for... | 24,815 |
def get_access_token(cmd, subscription=None, resource=None, scopes=None, resource_type=None, tenant=None):
"""
get AAD token to access to a specified resource.
Use 'az cloud show' command for other Azure resources
"""
if resource is None and resource_type:
endpoints_attr_name = cloud_resourc... | 24,816 |
def ensure_listable(obj):
"""Ensures obj is a list-like container type"""
return obj if isinstance(obj, (list, tuple, set)) else [obj] | 24,817 |
def merge_dicts(*dicts: dict) -> dict:
"""Merge dictionaries into first one."""
merged_dict = dicts[0].copy()
for dict_to_merge in dicts[1:]:
for key, value in dict_to_merge.items():
if key not in merged_dict or value == merged_dict[key]:
merged_dict[key] = value
... | 24,818 |
def main():
"""Main script"""
# Load data
train_data = pd.read_csv('data/train.csv')
test_data = pd.read_csv('data/test.csv')
y_train = train_data.SalePrice
x_train = train_data.drop(['SalePrice'], axis=1)
x_test = test_data
# Encoding data
x_train = pd.get_dummies(x_train)
x_t... | 24,819 |
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
for moves in _winner_moves():
if all(board[i][j] is X for (i, j) in moves):
return X
elif all(board[i][j] is O for (i, j) in moves):
return O
return None | 24,820 |
def specified_kwargs(draw, *keys_values_defaults: KVD):
"""Generates valid kwargs given expected defaults.
When we can't realistically use hh.kwargs() and thus test whether xp infact
defaults correctly, this strategy lets us remove generated arguments if they
are of the default value anyway.
"""
... | 24,821 |
def add_image():
"""User uploads a new landmark image, and inserts into db."""
imageURL = request.form.get("imageURL")
landmark_id = request.form.get("landmark_id")
new_image = LandmarkImage(landmark_id=landmark_id,
imageurl=imageURL)
db.session.add(new_image)
d... | 24,822 |
def merge(link1: Node, link2: Node) -> Node:
"""
Merge two linklists.
Parameters
-----------
link1: Node
link2: Node
Returns
---------
out: Node
Notes
------
"""
link = Node(None)
ptr = link
while link1 and link2:
if link1.val <= link2.val:
... | 24,823 |
def l1_norm_optimization(a_i, b_i, c_i, w_i=None):
"""Solve l1-norm optimization problem."""
cvx.solvers.options['show_progress'] = not CVX_SUPRESS_PRINT
# Non-Weighted optimization:
if w_i is None:
# Problem must be formulated as sum |P*x - q|
P = cvx.matrix([[cvx.matrix(a_i)], [cvx.ma... | 24,824 |
def set_order(market, order_type, amount, price, keys, stop_price=None):
"""
Create an order
Arguments:
market (str) : market name,
order_type (str) : may be "limit", "market", "market_by_quote",
"limit_stop_loss"
amount (float) : positive if BUY order, and negative for SELL
... | 24,825 |
def convert_ts(tt):
"""
tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
>>> tt = time.strptime("23.10.2012", "%d.%m.%Y")
>>> convert_ts(tt)
1350950400
tt: time.struct_time(tm_year=1513, tm_mon=1, tm_mday=1, tm_ho... | 24,826 |
def data_context_path_computation_context_path_comp_serviceuuid_optimization_constraint_name_post(uuid, tapi_common_name_and_value=None): # noqa: E501
"""data_context_path_computation_context_path_comp_serviceuuid_optimization_constraint_name_post
creates tapi.common.NameAndValue # noqa: E501
:param uuid... | 24,827 |
def receive_github_hook(request):
"""a hook is sent on some set of events, specifically:
push/deploy: indicates that the content for the repository changed
pull_request: there is an update to a pull request.
This function checks that (globally) the event is valid, and if
so, ... | 24,828 |
def get_onewire_status(code):
"""
Determine and display an XBee's OneWire sensor status, if enabled.
Args:
code (int): The status code included in the packet.
"""
opts = ("A/D sensor read", 0x01, "temperature sensor read", 0x02, "water present", 0x60)
text = ""
for i in range(0, le... | 24,829 |
def main():
"""Parse dictionary for unique stems and save them as a file."""
unique_stems = set()
pattern = '([^aeiou]*?)([aeoiu].*)'
with open('../inputs/words.txt') as file:
for word in file:
stems = re.findall(pattern, word.lower().rstrip())
if stems:
... | 24,830 |
def dice(y, t, normalize=True, class_weight=None,
ignore_label=-1, reduce='mean', eps=1e-08):
""" Differentable Dice coefficient.
See: https://arxiv.org/pdf/1606.04797.pdf
Args:
y (~torch.Tensor): Probability
t (~torch.Tensor): Ground-truth label
normalize (bool, optional):... | 24,831 |
def read_start_params(path_or_database):
"""Load the start parameters DataFrame.
Args:
path_or_database (pathlib.Path, str or sqlalchemy.MetaData)
Returns:
params (pd.DataFrame): see :ref:`params`.
"""
database = load_database(**_process_path_or_database(path_or_database))
opt... | 24,832 |
def load_single_rec_into_tables_obj(src_dbreq,
schema_engine,
psql_schema,
rec_id):
""" Return Tables obj loaded from postgres. """
if len(psql_schema):
psql_schema += '.'
tables = create_tabl... | 24,833 |
def calcCovariance(modes):
"""Return covariance matrix calculated for given *modes*."""
if isinstance(modes, Mode):
array = modes._getArray()
return np.outer(array, array) * modes.getVariance()
elif isinstance(modes, ModeSet):
array = modes._getArray()
return np.dot(arra... | 24,834 |
def sparse_tensor_value_to_texts(value):
"""
Given a :class:`tf.SparseTensor` ``value``, return an array of Python strings
representing its values.
This function has been modified from Mozilla DeepSpeech:
https://github.com/mozilla/DeepSpeech/blob/master/util/text.py
# This Source Code Form is... | 24,835 |
def test_query_avax_balances(rotkehlchen_api_server):
"""Test query the AVAX balances when multiple accounts are set up works as
expected.
"""
async_query = random.choice([False, True])
setup = setup_balances(
rotki=rotkehlchen_api_server.rest_api.rotkehlchen,
ethereum_accounts=None,... | 24,836 |
def coding_problem_45(rand5):
"""
Using a function rand5() that returns an integer from 1 to 5 (inclusive) with uniform probability, implement a
function rand7() that returns an integer from 1 to 7 (inclusive).
Note: for n >= 24, rand5() ** n is a multiple of 7 and therefore rand5() ** 24 % 7 is an unb... | 24,837 |
def handle_rss_api(output, kwargs):
""" Special handler for API-call 'set_config' [rss] """
name = kwargs.get('keyword')
if not name:
name = kwargs.get('name')
if not name:
return None
feed = config.get_config('rss', name)
if feed:
feed.set_dict(kwargs)
else:
... | 24,838 |
def progress(job_id, user: User = Depends(auth_user), db: Session = Depends(get_db)):
"""
Get a user's progress on a specific job.
"""
job = _job(db, job_id)
check_job_user(db, user, job)
progress = rules.get_progress_report(db, job, user)
return progress | 24,839 |
def addToMap(eeobject, vis_params=None, *unused_args):
"""Adds a layer to the default map instance.
Args:
eeobject: the object to add to the map.
vis_params: a dictionary of visualization parameters. See
ee.data.getMapId().
*unused_args: unused arguments, left for compatibility with th... | 24,840 |
def getRoom(borough):
"""Return a JSON dataset for property type of airbnb listing"""
prpt = db.session.query(data.Borough,
data.Room_Type, data.Price, data.Review_Rating, data.review_scores_cleanliness,
data.review_scores_value, data.host_response_rate).... | 24,841 |
def get_info(name_file, what='V', parent_folder='txt_files'):
"""Get data from txt file and convert to data list
:param name_file : name of the file, without txt extension
:param what : V = vertices, E = edges, R = pose
:param parent_folder"""
file_path = get_file_path(name_file, parent_folder)
... | 24,842 |
def receive_message(
sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE):
"""Receive a raw BSON message or raise socket.error."""
header = _receive_data_on_socket(sock, 16)
length = _UNPACK_INT(header[:4])[0]
actual_op = _UNPACK_INT(header[12:])[0]
if operation != actual_op:
... | 24,843 |
def cycle_interval(starting_value, num_frames, min_val, max_val):
"""Cycles through the state space in a single cycle."""
starting_in_01 = (starting_value - min_val) / (max_val - min_val)
grid = np.linspace(starting_in_01, starting_in_01 + 2.,
num=num_frames, endpoint=False)
grid ... | 24,844 |
def commit_ref_info(repos, skip_invalid=False):
"""
Returns a dict of information about what commit should be tagged in each repo.
If the information in the passed-in dictionary is invalid in any way,
this function will throw an error unless `skip_invalid` is set to True,
in which case the invalid ... | 24,845 |
def function(x, axis=0, fast=False):
"""
Estimate the autocorrelation function of a time series using the FFT.
:param x:
The time series. If multidimensional, set the time axis using the
``axis`` keyword argument and the function will be computed for every
other axis.
:param ax... | 24,846 |
def find_binaries(*args, **kwargs):
"""Given images data, return a list of dicts containing details of
all binaries in the image which can be identified with image_id or
image_tag.
One of image_id or image_tag must be specified.
:params: See `find_image`
:exception: exceptions.ImageNotFound
... | 24,847 |
def _readFastaFile(filepath):
"""Read a FASTA file and yields tuples of 'header' and 'sequence' entries.
:param filepath: file path of the FASTA file
:yields: FASTA entries in the format ('header', 'sequence').
The 'header' string does not contain the '>' and trailing white spaces.
The 'se... | 24,848 |
def solve_version(d):
""" solve version difference,
argument map d is deepcopied.
"""
# make copy
d = copy.deepcopy(d)
v = d.get('version', 0)
# functions in _update
for f in _update_chain[v:]:
d = f(d)
return d | 24,849 |
def start_elasticsearch_service(port=None, asynchronous=False):
"""
Starts the ElasticSearch management API (not the actual elasticsearch process.
"""
from localstack.services.es import es_api
port = port or config.PORT_ES
return start_local_api("ES", port, api="es", method=es_api.serve, asynch... | 24,850 |
def regexp_ilike(expr, pattern):
"""
---------------------------------------------------------------------------
Returns true if the string contains a match for the regular expression.
Parameters
----------
expr: object
Expression.
pattern: object
A string containing the regular expression to match against... | 24,851 |
def extract_frames(width, height, video_filename, video_path, frames_dir, overwrite=False, start=-1, end=-1, every=1):
"""
Extract frames from a video using decord's VideoReader
:param video_path: path of the video
:param frames_dir: the directory to save the frames
:param overwrite: to overwrite fr... | 24,852 |
def make_tree(path):
"""Higher level function to be used with cache."""
return _make_tree(path) | 24,853 |
def cmd(f):
"""Decorator to declare class method as a command"""
f.__command__ = True
return f | 24,854 |
def clean():
"""Remove all .py[co] files"""
local("find . -name '*.py[co]' -delete") | 24,855 |
def small_prior():
"""Give string format of small uniform distribution prior"""
return "uniform(0, 10)" | 24,856 |
def retrieve_panelist_ranks(panelist_id: int,
database_connection: mysql.connector.connect
) -> List[Dict]:
"""Retrieve a list of show dates and the panelist rank for the
requested panelist ID"""
cursor = database_connection.cursor()
query = ("SELE... | 24,857 |
def maxPixel(rpl):
"""maxPixel(rpl)
Computes the max pixel spectrum for the specified ripple/raw spectrum object."""
xs = epq.ExtremumSpectrum()
for r in xrange(0, rpl.getRows()):
dt2.StdOut.append(".")
if dt2.terminated:
break
for c in xrange(0, rpl.getColumns()):
... | 24,858 |
def test_floordiv():
"""Ensures that add works correctly."""
floordiv = _MathExpression() // 2
assert floordiv(5) == 2 | 24,859 |
def skip_device(name):
""" Decorator to mark a test to only run on certain devices
Takes single device name or list of names as argument
"""
def decorator(function):
name_list = name if type(name) == list else [name]
function.__dict__['skip_device'] = name_list
return functio... | 24,860 |
def conv1d(inputs,
filters,
kernel_size,
strides=1,
padding='valid',
data_format='channels_last',
dilation_rate=1,
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=init_ops.zeros_initia... | 24,861 |
def _transform(ctx):
"""Implementation for the transform rule."""
if ctx.attr.command and not ctx.attr.transform:
fail(("Target '%s' specifies 'command = ...', but this attribute is ignored when no pattern" +
" is supplied with the 'transform' attribute") % (ctx.label.name))
lines = [... | 24,862 |
def check_constraints(
df: pd.DataFrame, schema: dict
) -> List[Union[ConstraintError, ConstraintTypeError]]:
"""
Check table field constraints.
Arguments:
df: Table.
schema: Table schema (https://specs.frictionlessdata.io/table-schema).
Returns:
A list of errors.
"""
... | 24,863 |
def consolidate_fully(
inputs: Iterable[Tuple[core.Key, xarray.Dataset]],
*,
merge_kwargs: Optional[Mapping[str, Any]] = None,
combine_kwargs: Optional[Mapping[str, Any]] = None,
) -> Tuple[core.Key, xarray.Dataset]:
"""Consolidate chunks via merge/concat into a single (Key, Dataset) pair."""
concat... | 24,864 |
def first(items: Iterator[T]) -> Optional[T]:
"""Return the first item of the iterator."""
return next(items, None) | 24,865 |
def plot_precision_recall_curve(
precisions: Sequence[float], recalls: Sequence[float],
title: str = 'Precision/Recall curve'
) -> matplotlib.figure.Figure:
"""
Plots the precision recall curve given lists of (ordered) precision
and recall values.
Args:
precisions: list ... | 24,866 |
def Serialize(obj):
"""Return a binary serialized version of object.
Depending on the serialization method, some complex objects or input
formats may not be serializable.
UTF-8 strings (by themselves or in other structures e.g. lists) are always
supported.
Args:
obj: any object
Returns:
str, po... | 24,867 |
def getDragObject(parent: QWidget, item: Union['SourceListWidgetItem', 'DestTreeWidgetItem']) -> QDrag:
"""Instantiate QDrag of type application/draggerItem with corresponding QMimeData
Parameters
----------
parent: QWidget
item: Union['SourceListWidgetItem', 'DestTreeWidgetItem']
Returns
... | 24,868 |
def test_parse_xml_file(template_id, tmp_path, expected_mprage):
"""Test function `_parse_xml_file`."""
from clinica.iotools.converters.adni_to_bids.adni_json import _parse_xml_file
xml_file = _write_xml_example(tmp_path, template_id=template_id)
scan_metadata = _parse_xml_file(xml_file)
expected_s... | 24,869 |
def test_base_params():
"""Test default params object matches base params"""
param_url = ('https://raw.githubusercontent.com/jonescompneurolab/'
'hnn-core/test_data/base.json')
params_base_fname = op.join(hnn_core_root, 'param', 'base.json')
if not op.exists(params_base_fname):
... | 24,870 |
def test_higher_order():
"""`cwt` & `ssq_cwt` CPU & GPU outputs agreement."""
if not CAN_GPU:
return
tsigs = TestSignals(N=256)
x = tsigs.par_lchirp()[0]
x += x[::-1]
kw = dict(order=range(3), astensor=False)
for dtype in ('float32', 'float64'):
os.environ['SSQ_GPU'] = '0'
... | 24,871 |
def get_soup(url):
"""
Makes a request to the given url and returns a BeautifulSoup instance of Soup
"""
res = requests.get(url)
if not res.content:
return None
soup = BeautifulSoup(res.content, "lxml")
return soup | 24,872 |
def spectrogam_pearson_correlation(template_name, template_list, data_list, args):
"""
:param template_name: name of the templates
:param template_list: list of the templates
:param data_list: list of the data
:return: pearson correlation evaluation of each generated syllables wrt the template elem... | 24,873 |
def _grow_segment(segment, addition):
"""Combine two segments into one, if possible."""
if _eq(segment[-1], addition[0]): # append addition
return segment + addition[1:]
elif _eq(segment[-1], addition[-1]): # append reversed addition
return segment + list(reversed(addition[:-1]))
elif ... | 24,874 |
def test_postgres_index_setup_tables(index_driver, database_conn):
"""
Tests that the postgres index database gets set up correctly.
"""
# postgres
c = database_conn.execute("""
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public'
AND table_ty... | 24,875 |
def generate_headers(src_files, out_root, doc_root):
"""Generate headers with a Python methoddef array and html
documentation tables for the listed source files.
The list should contain tuples of names and paths:
[(desired-method-def-name, cpp-file-path),...]
The name is used for the gene... | 24,876 |
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the Proliphix thermostats. """
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
host = config.get(CONF_HOST)
import proliphix
pdp = proliphix.PDP(host, username, password)
add_devices(... | 24,877 |
def test_subscribe_to_queue(caplog):
"""Test subscribing to a queue (producer-consumer), callback functions and unsubscribe."""
mock_cb1 = mock.Mock()
mock_cb2 = mock.Mock()
offline = OfflineTransport()
offline.connect()
with caplog.at_level(logging.INFO):
offline._subscribe(
... | 24,878 |
def test_validate_extension_invalid() -> None:
"""It returns False when extension is invalid."""
assert not toml.validate_extension("file.xml") | 24,879 |
def dsmoothlist_by_deform_exp(deform_exp, ag_mode):
"""
Automatically extract the selected artificial generations for training and validation set:
'Resp': ['respiratory_motion', 'single_frequency', 'mixed_frequency', 'zero'],
'NoResp': ['single_frequency', 'mixed_frequency', 'zero'],
'Si... | 24,880 |
def test_stopwords_custom():
"""Assert that custom stopwords are removed."""
normalizer = Normalizer(stopwords=False, custom_stopwords=["b"])
assert normalizer.transform([["a b"]])["corpus"][0] == ["a"] | 24,881 |
def test_file_listing_serialization(database, tmpdir):
"""Test serialization of file handles."""
view = UploadFileSerializer()
filename = 'data.json'
with database.session() as session:
manager = WorkflowGroupManager(session=session, fs=FileSystemStorage(basedir=tmpdir))
user_id = model.... | 24,882 |
def RunHeuristicAnalysis(analysis):
"""Performs heuristic analysis on a MasterFlakeAnalysis.
Args:
analysis (MasterFlakeAnalysis): The analysis to run heuristic results on.
Results are saved to the analysis itself as a list of FlakeCulprit
urlsafe keys.
"""
suspected_revisions = IdentifySus... | 24,883 |
def get_data_reader(header: Header) -> Callable[[BinaryIO], Tuple]:
"""Make a binary reader function for data."""
names = get_data_names(header)
format_ = ""
for name in names:
if "CH" in name:
format_ += "h"
elif "Pulse" in name:
format_ += "L"
elif "Lo... | 24,884 |
def proximal_region_finder(readers, region, comments=True):
"""
Returns an iterator that yields elements of the form [ <original_interval>, <closest_feature> ].
Intervals are GenomicInterval objects.
"""
primary = readers[0]
features = readers[1]
either = False
if region == 'Upstream':... | 24,885 |
def test_api_mediawiki(monkeypatch):
"""The api_mediawiki test using mocks."""
result = "OpenClassrooms est une école en ligne..."
def mock_summary(*args, **kwargs):
return result
monkeypatch.setattr(
MediawikiApi, 'search', mock_summary)
wikipedia = MediawikiApi()
assert wiki... | 24,886 |
def check_fnr(fnr: str, d_numbers=True, h_numbers=False, logger: Callable = lambda _x: None) -> bool:
"""
Check if a number is a valid fødselsnumber.
Args:
fnr: A string containing the fodselsnummer to check
h_numbers: False (the default) if h-numbers should be accepted
d_numbers: Tr... | 24,887 |
def test_should_raise_if_format_error():
"""
Test exception is raised if docstring syntax error
"""
docstring_error = '''
:param p1
'''
with pytest.raises(MlVToolException) as e:
parse_docstring(docstring_error)
assert isinstance(e.value.__cause__, ParseError) | 24,888 |
def get_case_list_from_cls(test_cls_list):
"""
将测试类转化为测试用例
:return:
"""
test_list = []
for test_cls in test_cls_list:
test_cases = unittest.TestLoader().loadTestsFromTestCase(test_cls)
test_list.append(test_cases)
return test_list | 24,889 |
def plot_image(pig_img_aug, label, rows):
"""Plots the augmented image"""
log.info('Plotting augmented image...')
global num
num = num + 1
plt.subplot(rows, 5, num)
plt.title(label)
plt.imshow(pig_img_aug) | 24,890 |
def align_times(sync_behavioral, sync_neural, score_thresh=0.9999,
ignore_poor_alignment=False, return_model=False, verbose=False):
"""Align times across different recording systems.
Parameters
----------
sync_behavioral : 1d array
Sync pulse times from behavioral computer.
... | 24,891 |
def check_media(url):
"""Check if something is available or has a new hash
Checks if url is available, uf yes, download and hash it, then see if it has changed
Args:
url: A complete url to something
Returns:
0 if available and no change.
1 if not available.
2 if it... | 24,892 |
def breed(tree1, tree2):
"""My breeding function.
Basically makes a copy of tree1, and swaps sub-trees with tree2 at
a random depth. Pretty much relies on my simplistic tree structure.
I have no fucking clue if this will work. I can't even debug it since
I have no way of printing my tree.
Rig... | 24,893 |
def tuple_from_iterable(val: Iterable[Any]) -> Tuple[Any, ...]:
"""Builds a tuple from an iterable.
Workaround for https://github.com/python-attrs/attrs/issues/519
"""
return tuple(val) | 24,894 |
def merge_vocabs(vocabs, vocab_size=None):
"""
Merge individual vocabularies (assumed to be generated from disjoint
documents) into a larger vocabulary.
Args:
vocabs: `torchtext.vocab.Vocab` vocabularies to be merged
vocab_size: `int` the final vocabulary size. `None` for no limit.
R... | 24,895 |
def read_g_char(in_name, pop="ESP", debug=False):
"""
Read charges and energy from a Gaussian log file.
Parameters
----------
in_name : str
Name of the file to read
pop : str, optional
Kind of charge to read, mulliken or esp
debug : bool, optional
Return extra energy... | 24,896 |
def mrs(ctx, group_project_filter, label, merge):
"""
List and manage merge requests of GitLab projects.
Filter syntax:
- foo/bar ... projects that have "bar" in their name,
in groups that have "foo" in their name
- foo/ ... filter for groups only, match any project
- /bar ... filter for... | 24,897 |
def count_nonzero(X, axis=None, sample_weight=None):
"""A variant of X.getnnz() with extension to weighting on axis 0
Useful in efficiently calculating multilabel metrics.
Parameters
----------
X : sparse matrix of shape (n_samples, n_labels)
Input data. It should be of CSR format.... | 24,898 |
def isolate_shape_axis(base, target, axis_list = ['X','Y','Z']):
"""
Given a base mesh, only take axis movement on the target that is specified in axis_list.
Args:
base (str): The base mesh that has no targets applied.
target (str): The target mesh vertices moved to a different po... | 24,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.