content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def define_data_download_flags():
"""Add flags specifying data download arguments."""
flags.DEFINE_string(
name="data_dir", default="/tmp/movielens-data/",
help=flags_core.help_wrap(
"Directory to download and extract data."))
flags.DEFINE_enum(
name="dataset", default=None,
enu... | 5,287,300 |
def inject_os_git_vars(spec_file):
"""
Determine the OpenShift version variables as dictated by the Origin
shell utilities and overwrite the specfile to reflect them. A line
with the following syntax is expected in the specfile:
%global os_git_vars
This line will be overwritten to add the git ... | 5,287,301 |
def test_memoization():
"""Test that memoization works"""
# We need an object we can memoize
class Obj(object): # pylint: disable=too-few-public-methods
"""Object to memoize"""
pass
called = [0]
@utils.memoize
def func(_):
"""Memoized"""
called[0] += 1
obj ... | 5,287,302 |
def power_factor(s: np.ndarray) -> np.ndarray:
"""Given a numpy array of complex values, compute power factor.
If the power factor is lagging, a positive value will be returned.
If the power factor is leading, a negative value will be returned.
Reference:
Power System Analysis and Design, 5th Edit... | 5,287,303 |
def reset_test_sheet(create_test_sheet, test_data, spreadsheet_client, drive_client):
"""Reset spreadsheet values between tests."""
spreadsheet_id = create_test_sheet["spreadsheetId"]
spreadsheet_client.values().batchClear(
spreadsheetId=spreadsheet_id,
body={"ranges": ["users!A1:end", "hac... | 5,287,304 |
def test_scaled_and_translated_images():
"""Test scaled and translated images."""
viewer = ViewerModel()
np.random.seed(0)
data = np.random.random((10, 10, 10))
viewer.add_image(data)
viewer.add_image(data[::2], scale=[2, 1, 1], translate=[10, 0, 0])
assert viewer.dims.range[0] == (0, 20 - 2... | 5,287,305 |
def pad_factor(input_image, spatial_dims, factor):
"""Pad `input_image` (N,C,H,W) such that H and W are divisible by `factor`."""
if isinstance(factor, int) is True:
factor_H = factor
factor_W = factor_H
else:
factor_H, factor_W = factor
H, W = spatial_dims[0], spatial_dims[1]
... | 5,287,306 |
def zeropad(data, m=2):
"""Pad with zeros to make an array with an even multiple of m voxels in all dimensions
"""
if data.ndim < 2 or data.ndim > 3:
raise RuntimeError('Unsupported number of dimensions {}. We only supports 2 or 3D arrays.'.format(data.ndim))
if data.ndim == 2:
... | 5,287,307 |
def print_execution_path():
"""
Print execution path to the stdout
"""
print("Actual execution path is :\n{")
for p in sys.path:
print("\t{},".format(p))
print("}") | 5,287,308 |
def download_all_databases(altdir=None):
"""
Download the databases for a user. It will put them in the default location
unless altdir is specified.
:param altdir: output directory
:return: nothing
"""
phageout = phagedb
clustout = clustersdb
outdir = os.path.dirname(phageout)
i... | 5,287,309 |
def main( argv ):
"""
Script execution entry point
@param argv Arguments passed to the script
@return Exit code (0 = success)
"""
# imports when using this as a script
import argparse
# create and configure an argument parser
parser = argparse.ArgumentParser(
... | 5,287,310 |
def h2fk5(rh, dh, drh, ddh, pxh, rvh):
"""
Wrapper for ERFA function ``eraH2fk5``.
Parameters
----------
rh : double array
dh : double array
drh : double array
ddh : double array
pxh : double array
rvh : double array
Returns
-------
r5 : double array
d5 : double... | 5,287,311 |
def test_pipeline_runner_main_with_context_relative_working_dir(
pipeline_cache_reset):
"""Run main with context with relative working directory."""
expected_notify_output = ['steps', 'on_success', 'on_failure']
with patch_logger('pypyr.steps.echo', logging.NOTIFY) as mock_log:
out = pipelin... | 5,287,312 |
def Connect(*args, **kwargs):
"""Factory function for connection.Connection."""
return connection.Connection(*args, **kwargs) | 5,287,313 |
def get_post_by_user(user: str, start=None, end=None, now=None):
"""TODO: Docstring for get_user.
:user: TODO
:returns: TODO
"""
if start is not None and end is not None:
posts = Post.objects.filter(create_date__gte=start, create_date__lte=end, user__user_id=user)
elif start is not Non... | 5,287,314 |
def solve_lp_puzzle(lp, boxsize):
"""Solve a linear program Sudoku and return puzzle dictionary."""
lp.simplex()
for col in lp.cols:
col.kind = int
lp.integer()
return lp_to_dict(lp, boxsize) | 5,287,315 |
def show_error_info(title, message, unknown_error=False, netflix_error=False):
"""Show a dialog that displays the error message"""
prefix = (30104, 30102, 30101)[unknown_error + netflix_error]
return xbmcgui.Dialog().ok(title, (common.get_local_string(prefix) + '\r\n' +
... | 5,287,316 |
def is_token_expired(token):
"""Checks if given token is valid"""
try:
decoding = jwt.decode(token, config['jwt_secret'], config['jwt_algorithm'])
return False
except jwt.ExpiredSignatureError:
return True | 5,287,317 |
def _getIdsFromQuery(queryString, syn, downloadLocation):
"""Helper function that extracts the ids out of returned query."""
if re.search('from syn\\d', queryString.lower()):
tbl = syn.tableQuery(queryString, downloadLocation=downloadLocation)
check_for_id_col = filter(lambda x: x.get('id'), t... | 5,287,318 |
def get_sshkey(sshkey):
"""
Get start ip for ip range
CLI Example:
.. code-block:: bash
salt 'maas-node' maasng.get_sshkey sshkey
salt-call maasng.get_sshkey sshkey
"""
try:
return list_sshkeys()[sshkey]
except KeyError:
return {"error": "SSH key not found ... | 5,287,319 |
def process_image(in_img_path: Path, out_img_dir: Path) -> Dict[Path, Path]:
""" Extract EXIF data from image and return path mapping """
with open(in_img_path, "rb") as image_file_stream:
image = Image(image_file_stream)
if hasattr(image, "datetime_original"):
out_img_name = make_na... | 5,287,320 |
def get_vars_maybe_avg(var_names, ema, **kwargs):
"""utility for retrieving polyak averaged params."""
vars_tf = []
for vn in var_names:
vars_tf.append(get_var_maybe_avg(vn, ema, **kwargs))
return vars_tf | 5,287,321 |
def parallel_exec_transform_with_prettyprint( # noqa: C901
transform: Codemod,
files: Sequence[str],
*,
jobs: Optional[int] = None,
unified_diff: Optional[int] = None,
include_generated: bool = False,
generated_code_marker: str = _DEFAULT_GENERATED_CODE_MARKER,
format_code: bool = False... | 5,287,322 |
def _create_lineage_by_table_name(
metadata: OpenMetadata,
from_table: str,
to_table: str,
service_name: str,
database: str,
query: str,
):
"""
This method is to create a lineage between two tables
"""
try:
from_raw_name = get_formatted_entity_name(str(from_table))
... | 5,287,323 |
def freeze(*args, **kwargs):
"""
When a node is frozen none of its inputs will be requested when they change, the node will use the inputs that existed at the time of freezing until the node is unfrozen.
Returns: `string[]` In query mode the list of currently frozen or unfrozen nodes. The list is in three ... | 5,287,324 |
def open_files(
file_names: List[str], mode: str = "readonly"
) -> Tuple[List[fits.HDUList], List[np.ndarray]]:
"""Gets the HDULS and data handles for all the files in file_names.
This is a convience function to opening multiple FITS files using
memmap.
Args:
file_names (List[s... | 5,287,325 |
def multi_to_single(y, combinations):
"""Convert multilabel indices to singlelabel strings."""
single = []
for y_i in y:
y_i_str = ", ".join([str(i) for i in y_i])
single.append(combinations.index(y_i_str))
return single | 5,287,326 |
def main():
"""
Main function
"""
global _DEBUG_
_DEBUG_ = False
global tpb_url
global tpb_categories
global transmission_rcp
global tvdbapi_tag
# Init locals variables
serie_title = None
search_type = None
serie_season = ""
serie_episode = ""
seeders_min =... | 5,287,327 |
def read_csv(csv_folder: str, split: str, word_limit: int) -> Tuple[list, list, Counter]:
"""
Read CSVs containing raw training data, clean sentences and labels, and do
a word-count.
Parameters
----------
csv_folder : str
Folder containing the dataset in CSV format files
split : st... | 5,287,328 |
def fill_nan_pixels(image, noise_distribution=None):
"""Replace *in-place* `NaN` values in `image` by zeros or by random noise.
Images containing `NaN` values generate undesired harmonics with wavelet
image cleaning. This function should be used to "fix" images before each
wavelet image cleaning.
... | 5,287,329 |
def _parse_taxa_report(local_path, **kwargs):
"""Return a dict of taxa_name to read_counts."""
out, abundance_sum = {}, 0
with open(local_path) as taxa_file:
for line_num, line in enumerate(taxa_file):
line = line.strip()
tkns = line.split('\t')
if not line or len... | 5,287,330 |
def build_conservation_status_message(data: list[str]) -> str:
"""
Builds a string describing the conservation status of the species.
:param data: Data containing conservation status information
:return: Description of the conservation status (or empty if no data)
"""
if data:
return CON... | 5,287,331 |
def get_col_reduced_right(A, symb, T = None, return_internals = False):
"""
Takes a polynomial matrix A(s) and returns a unimod Transformation T(s)
such that A(s)*T(s) (i.e. right multiplication) is col_reduced.
Approach is taken from appendix of the PHD-Thesis of S. O. Lindert (2009)
:args:
... | 5,287,332 |
def test_opf_no_controllables_vs_pf():
""" Comparing the calculation results of PF and OPF in a simple network with non-controllable
elements """
# boundaries
vm_max = 1.3
vm_min = 0.9
max_line_loading_percent = 100
# create network
net = pp.create_empty_network()
b1 = pp.create_... | 5,287,333 |
def save_fig(fig, path):
""" Saves figure.
Args:
fig: Object with the graph.
path: Directory to save the graph.
"""
fig.savefig(path) | 5,287,334 |
def test_sample_sheet_not_found(tmp_file):
"""
Test that providing :py:const:`riboviz.params.MULTIPLEX_FQ_FILES`
and a non-existent :py:const:`riboviz.params.SAMPLE_SHEET` file
returns a non-zero exit code.
:param tmp_file: Path to temporary file, to write configuration to
:type tmp_file: str o... | 5,287,335 |
def ivarName(value, position):
"""A name of a class."""
if not value[0] == '_' or not value[1].islower():
return Error(
'BadInstanceVariableName', 'Instance variable names start with _ and not be capitalized', position, LINES)
return None | 5,287,336 |
def verilog_value_to_int(verilog_value):
""" Convert VerilogValue model to width, value, value_format """
width = None
if verilog_value.plain_decimal:
return width, int(verilog_value.plain_decimal), ValueFormat.PLAIN
if verilog_value.width:
width = int(verilog_value.width)
if veri... | 5,287,337 |
def create_quiz_form(quiz):
"""Create quiz form with all its question choices,
shuffle the choices for quiz page"""
form = QuizForm()
for i in range(10):
form.questions[i].answers.choices = [
quiz.questions[i].correct_answer,
quiz.questions[i].wrong_answer_1,
... | 5,287,338 |
def drop_zeros_ctg(fhr: np.array, uc: np.array, time: np.array) -> Tuple[np.array, np.array, np.array]:
"""
Removes all missingvalues, encoded as zeros
Args:
uc, fhr signals: (np.arrays) 1D signals
time: (np.array) 1D time signal
Output: Tuple(np.arrays) filtered FHR and ... | 5,287,339 |
def report_and_reset_timings():
"""Returns the pass timings report and resets the LLVM internal timers.
Pass timers are enabled by ``set_time_passes()``. If the timers are not
enabled, this function will return an empty string.
Returns
-------
res : str
LLVM generated timing report.
... | 5,287,340 |
def force_delete_service_account(service_account_email, db=None):
"""
Delete from our db the given user service account by email.
Args:
service_account_email (str): user service account email
db(str): db connection string
"""
session = get_db_session(db)
sa = (
session.q... | 5,287,341 |
def transform_coords(x: Union[DataArray, Dataset],
targets: Union[str, Iterable[str]],
graph: GraphDict,
*,
rename_dims: bool = True,
keep_aliases: bool = True,
keep_intermediate: bool = True,
... | 5,287,342 |
def Answer_f(text):
"""
:param text: The "text" of this Answer
"""
return '\\begin{block}{Answer}\n' + text + '\n\\end{block}\n' | 5,287,343 |
def push(args, label, config):
"""
Push/update a configuration.
"""
if not label:
raise ValueError("label can't be empty.")
if not config:
raise ValueError("config can't be empty.")
if not os.path.isfile(config):
raise ValueError("configuration file doesn't exist.")
... | 5,287,344 |
def gather_states(ii):
"""
Return the current state (position/probability/bias) of walkers in a given window.
Parameters
----------
ii : integer
The index of the umbrella to get the state of.
Returns
-------
state : list
The state of window ii.
"""
retu... | 5,287,345 |
def word_embeddings_rbo(list1, list2, p, index2word, word2vec, norm):
"""Complete RBO analysis (lower bound, residual, point estimate).
``list`` arguments should be already correctly sorted iterables and each
item should either be an atomic value or a set of values tied for that
rank. ``p`` is the proba... | 5,287,346 |
def drop_na_inputs(*, input_data: pd.DataFrame) -> pd.DataFrame:
"""
Check model inputs for na values and filter them
based on the ones the model knows how to handle.
"""
validated_data = input_data.copy()
new_vars_with_na = [
var
for var in config.model_config.inputs
if... | 5,287,347 |
def read_img():
"""
Reads image file and change color format
"""
img = cv2.imread('.media/learn-colors.jpg')
# print(img.shape)
# cv2.imshow('ImageWindow', img)
# cv2.waitKey()
# covert to rgb
b, g, r = cv2.split(img)
rgb_img = cv2.merge([r, g, b])
# show both images in... | 5,287,348 |
def geojsonfeature(source, params=''):
"""
:params: A string with the following optional tokens:
"properties:field:srid"
"""
parse = re.search(r'(?P<properties>((\w+)(,\w+)*)?)(:(?P<field>(\w+)?))?(:(?P<srid>(\d+)?))?', params)
if parse:
parse = parse.groupdict()
else:
... | 5,287,349 |
def add_flat_pages_parish(apps, schema_editor):
"""
Adds all default flat pages for the parish site.
"""
pages = (
# Gemeinde
("gemeinde", "gruppen", "Gruppen und Kreise", "", 110, ""),
("gemeinde", "gruppen/bildungskreis", "Bildungskreis", "", 115, ""),
("gemeinde", "mit... | 5,287,350 |
def expected_return_time(M, backward=False):
"""Find the expected returning time.
Parameters
----------
M: :class:`~numpy.ndarray` (dimension n x n, where n is the cell number)
The transition matrix.
backward: bool (default False)
Whether the backward transition will... | 5,287,351 |
def att_moment_metric(mass, att_moment):
"""
This function calculates the metric for the attitude moment. It does not consider moments of inertia for the
satellite, nor passive sources of moment
:param mass:
:param att_moment:
:return:
"""
return np.float64(1.25 * (att_moment / mass)).cl... | 5,287,352 |
def get_largest_area(rect: Rect, points: Sequence[Point]) -> int:
"""Find the largest bounded area around all the points.
This basically is creating a voronai using the manhattan distance, and throwing out any ties.
If any of the cells are on the edge of the diagram, we declare their area to be infinite, a... | 5,287,353 |
def body_part_to_headers_and_data(part):
"""
convert part (of multi-part body) to headers dict and content. de-serializes json if content-type is
application/json.
:param part: BodyPart decoded by MultipartDecoder
:return: tuple pair of headers dict and content
"""
if b'application/json' in... | 5,287,354 |
def flip_marker_states(aut):
"""
Return an automaton that has all marker states flipped
@param aut: Input automaton
@type aut: L{Automaton}
@return: Flipped automaton of L{aut}
@rtype: L{Automaton}
"""
new_aut = aut.copy()
for state in new_aut.get_states():
flip_single_ma... | 5,287,355 |
def find_all_presented_sfs(stim_df, ecc_step=1, ecc_range=(1, 12), size=1080,
max_visual_angle=24, stimulus_mask=None):
"""Find average spatial frequency presented in eccentricity bands for each stimulus.
Only works on square images.
Returns a dataframe with the average spatial ... | 5,287,356 |
def do_default_training(cmdline_args, stories, additional_arguments):
"""Train a model."""
train_dialogue_model(domain_file=cmdline_args.domain,
stories_file=stories,
output_path=cmdline_args.out,
dump_stories=cmdline_args.dump_stories,... | 5,287,357 |
def test_small_domain_stats():
"""Test of the size of the results for a simple domain."""
fuzzer = dnstwister.dnstwist.DomainFuzzer('abc.com')
fuzzer.fuzz()
assert breakdown(fuzzer.domains) == {
'Addition': 26,
'Bitsquatting': 13,
'Homoglyph': 26,
'Hyphenation': 2,
... | 5,287,358 |
def encapsulateTable(string_table,column_labels, caption,ttype=None):
"""Uses the output of makeTables to render a complete latex table"""
if ttype in ("kolmDiff3","kolmDiff3_","kolmSamp_","kolmSamp","textCorr","allFloat"):
header="\\begin{table*}[h!]\n\\begin{center}\n\\begin{tabular}{| l |"+" c |"*(st... | 5,287,359 |
def normalized_bar_plot(results_df):
"""
Bar plot of the normalized erros
:param results_df: data frame with the model`s cross-validation errors.
:return:
"""
normalized_df = results_df.copy()
normalized_df.iloc[:,1:]=(results_df.iloc[:,1:].copy())/results_df.iloc[:,1:].max()
normalized_... | 5,287,360 |
def convert_datetime(inpt):
"""Return value of input
dateTime formating assumed according to ISO standard:
* http://www.w3.org/TR/NOTE-datetime
* https://www.w3.org/TR/xmlschema-2/#dateTime
Examples: 2016-09-20T12:00:00, 2012-12-31T06:30:00Z,
2017-01-01T18:00:00+01:00
:rtype: da... | 5,287,361 |
def bulk_to_temp_transform( db, bulk_plate_barcode, pca_plates ):
"""
returns a transform for consumption by echo_csv
"""
from twistdb.sampletrack import Sample, PlateType
pd = primer_dict( db, pca_plates )
rows = []
primer_ct = defaultdict(int)
layout = db.query(PlateType).get('SPTT_0... | 5,287,362 |
def gaussian1d_variant1(x, *p):
"""
Create a normalised gaussian (Area == 1) from mean and variance
:param x: [numpy array] x axis data (array/list)
:param p: [Tuple] (mean , variance)
Area of gaussian is 1 --> A = 1/(c*sqrt(2pi))
Returns a Gaussian array one value for each x valu... | 5,287,363 |
def evtimer(request, ettype, config_id, query=''):
"""
[メソッド概要]
タイマー管理するイベントを管理する
[引数]
ettype : イベント管理種別('cron' or 'timer')
config_id : イベント管理するシステム設定ID
"""
logger.logic_log('LOSI00001', 'ettype=%s, config_id=%s' % (ettype, config_id))
result = False
# イベントサーバーチェック
... | 5,287,364 |
def restore(db, chunk_delay, measurement_delay, precision):
"""Restore from a backup."""
if not os.path.exists(DIR):
print(f'Backup dir "{DIR}" does not exist')
sys.exit(-1)
measurements = MEASUREMENTS
if not measurements:
if GZIP:
files = [f[:-3] for f in os.listdir... | 5,287,365 |
def dc_node(request, hostname, data=None):
"""
Show (:http:get:`GET </dc/(dc)/node/(hostname)>`),
create (:http:post:`POST </dc/(dc)/node/(hostname)>`),
change (:http:put:`PUT </dc/(dc)/node/(hostname)>`) or
remove (:http:delete:`DELETE </dc/(dc)/node/(hostname)>`)
a compute node (hostname) asso... | 5,287,366 |
def get_appliance_api_type(appliance_type: ErdApplianceType) -> Type:
"""Get the appropriate appliance type"""
_LOGGER.debug(f"Found device type: {appliance_type}")
if appliance_type == ErdApplianceType.OVEN:
return OvenApi
if appliance_type == ErdApplianceType.FRIDGE:
return FridgeApi
... | 5,287,367 |
def parseDateTag(tag: bs4.element.Tag) -> str:
"""Parse date tag.
:param tag: html table data element
:return: date string
"""
date = datetime.strptime(tag.text, '%m/%d/%Y').strftime(DATE_FORMAT)
return date | 5,287,368 |
def get_utm_zone(lon):
""" Calculate UTM zone.
Arguments:
lon: float
Longitude, in degrees. West: negative, East: positive.
Returns:
zone: int
UTM zone number.
"""
zone = int(1+(lon+180.0)/6.0)
return zone | 5,287,369 |
def test_feed_from_annotations_with_1_annotation(factories):
"""If there's 1 annotation it should return 1 entry."""
feed = rss.feed_from_annotations(
[factories.Annotation()], _annotation_url(), mock.Mock(), "", "", ""
)
assert len(feed["entries"]) == 1 | 5,287,370 |
def init_migrate():
"""
具体要进行的操作
该脚本是一个初始化migrate
"""
session = inject.instance(MainDBSession)
with CommitContext(session):
pass
logger.info("print_test success") | 5,287,371 |
def create_eyelid_follicle_system(driver_object="", selected_vertices=(), surface_mesh_name=""):
"""
creates follicle drivens that drives the joints that are driven by the driver controllers.
This is a complicated system that requires these steps:
1. select vertices.
2. get the closest UV from the s... | 5,287,372 |
def test_pds4_orbnum_coverage_lookup_table_multiple(self):
"""Test various ORBNUM coverage from look-up table in configuration."""
post_setup(self)
config = "../config/maven.xml"
updated_config = "working/maven.xml"
plan = "working/maven_orbnum.plan"
with open(plan, "w") as p:
p.write("... | 5,287,373 |
def create_chassis(world: b2World, vertices: List[b2Vec2], densities: List[float]) -> b2Body:
"""
Creates a chassis to be the body of the car.
"""
if len(vertices) != len(densities):
raise Exception('vertices and densities must be same length')
# Create body definition
body_def ... | 5,287,374 |
def napalm_cli(task, commands, hostname=None, username=None, password=None,
driver=None, timeout=60, optional_args=None):
"""
Run commands on remote devices using napalm
Arguments:
commands (list): list of commands to execute on the device
hostname (string, optional): default... | 5,287,375 |
def _create_zero_states(model: RecurrentLM) -> ActivationDict:
"""Zero-initialized states if no init state is provided.
Returns
-------
init_states : ActivationTensors
Dictionary mapping (layer, name) tuple to zero-tensor.
"""
init_states: ActivationDict = {
a_name: torch.zeros(... | 5,287,376 |
def vocab_test(words_by_author):
"""Compare author vocabularies using the Chi Squared statistical test."""
chisquared_by_author = dict()
for author in words_by_author:
if author != 'unknown':
# Combine corpus for author & unknown & find 1000 most-common words.
combined_corpu... | 5,287,377 |
def append_iqa_scores(df):
"""Load image quality assessment scores and append to a dataframe of observation records"""
# Sort user IDs by number of observations (in the current dataset) per user
scores = load_iqa_scores()
first_result = list(scores.values())[0]
for key in first_result.keys():
... | 5,287,378 |
def _setup_entities(hass, device_ids: List):
"""Set up Tuya Climate."""
device_manager = hass.data[DOMAIN][TUYA_DEVICE_MANAGER]
entities = []
for device_id in device_ids:
device = device_manager.deviceMap[device_id]
if device is None:
continue
entities.append(TuyaHaCl... | 5,287,379 |
def _iterateOverDicts(ob, func):
"""
This function iterates a function over a nested dict/list
see https://stackoverflow.com/questions/32935232/python-apply-function-to-values-in-nested-dictionary
"""
assert type(ob) == dict, '**** _iterateOverDicts requires a dict input'
for k, v in ob.it... | 5,287,380 |
def multiple_quantum_elements():
"""Let us investigate the success probability of the quantum search with multiple marked elements.
We perform Grover iterates to amplify the marked subspace.
"""
n_iterations = 3
# Number of queries to database oracle.
queries = n_iterations * 2 + 1
# De... | 5,287,381 |
def mask_rcnn_functional(config: dict) -> tf.keras.Model:
"""
Construct a model in functional API
Args:
config: General MaskRCNN config, dict
Returns: tf.keras.Model:
"""
# Prevent creating keras names with index increment.
# It is important for weights setting from training to infe... | 5,287,382 |
def ast_from_input(input, mode, transformer, parser):
"""converts a source input into an AST
- input : the source to be converted
- mode : 'exec', 'eval' or 'single'
- transformer : the transfomer instance to use to convert
the nested tuples into the AST
XXX: transformer co... | 5,287,383 |
def solace_delete_client_username(options):
""" Deletes users / profiles / acl's where neccesary.
Has a shutdown only mode which only shutdowns the user
Has a force remove now mode which kills everything!
Shutdown User
Delete User
"""
for environment in options.environment:
sola... | 5,287,384 |
def CvSepFilter_init_gaussian_kernel(*args):
"""
init_gaussian_kernel(CvMat kernel, double sigma=-1)
CvSepFilter_init_gaussian_kernel(CvMat kernel)
"""
return _cv.CvSepFilter_init_gaussian_kernel(*args) | 5,287,385 |
def handle_delalias(bot, ievent):
""" arguments: <aliasfrom> - delete alias. """
try: what = ievent.args[0]
except IndexError:
ievent.missing('<what>')
return
aliases = ievent.chan.data.aliases
try:
if aliases:
del aliases[what]
ievent.chan.save()
... | 5,287,386 |
def print_to_terminal(self, step, data, count, unassigned_array_length, method, re=False, second_pass=False):
"""
Prints some information to the terminal if verbose == True
"""
if (re is False) and (second_pass is False):
print('')
print('Beginning analysis...')
print('')
... | 5,287,387 |
def get_num_params(vocab_size, num_layers, num_neurons):
"""Returns the number of trainable parameters of an LSTM.
Args:
vocab_size (int): The vocabulary size
num_layers (int): The number of layers in the LSTM
num_neurons (int): The number of neurons / units per layer
Returns:
... | 5,287,388 |
def serialize_model_object(obj):
"""
Serialize model into a dict representable as JSON
Args:
obj (django.db.models.Model): An instantiated Django model
Returns:
dict:
A representation of the model
"""
# serialize works on iterables so we need to wrap object in a list,... | 5,287,389 |
def secure_clauses(file_system: FileSystem, clauses: List[Clause]) -> List[Arc]:
"""Construct a "safe" version of the given renaming clauses and update the file system.
The resulting sequence is a reordered copy of the given clauses, with potentially the
insertion of intermediate renamings, in such a way t... | 5,287,390 |
def plot_ramp_current_example():
"""
Example for get_ramp_current
"""
current = get_ramp_current(10, 25, b2.ms, 20 * b2.uamp, 50 * b2.uamp, append_zero=True)
data = current.values[:, 0] / b2.uamp
plt.plot(data, lw=3)
plt.title("get_ramp_current(10, 25, b2.ms, 20*b2.uamp, 50*b2.uamp, append_z... | 5,287,391 |
def test_fully_exit_fullscreen(session):
"""
4. Fully exit fullscreen.
[...]
To fully exit fullscreen a document document, run these steps:
1. If document's fullscreen element is null, terminate these steps.
2. Unfullscreen elements whose fullscreen flag is set, within
document's t... | 5,287,392 |
def create_benchmark_result(
project_id: str,
study_id: str,
benchmark_id: str,
data_sets: Union[DataSet, List[DataSet], DataSetCollection],
) -> BenchmarkResult:
"""Creates a benchmark result.
Parameters
----------
project_id
The id of the parent project.
study_id
T... | 5,287,393 |
def claims_scroll(curr_page, scroll_status):
"""Performs the query to get claims on the specified page."""
if curr_page is None:
curr_page = 0
if scroll_status == "next":
if curr_page >= 0:
curr_page += 1
elif scroll_status == "init":
curr_page = 0
else:
... | 5,287,394 |
def test_functionality(remote_sample, tmp_path):
"""Functionality test."""
tmp_path = str(tmp_path)
sample_patch = str(remote_sample("stainnorm-source"))
patch_pre = imread(sample_patch)
patch_pre = imresize(patch_pre, scale_factor=0.5)
patch = patch_pre[0:256, 0:256]
batch = torch.from_nump... | 5,287,395 |
def init():
"""
initialisation funtion for animation
"""
p.set_data([],[])
p_highlight.set_data([], [])
highlight_path.set_data([], [])
return p, p_highlight, highlight_path | 5,287,396 |
def print_sort(G):
"""Execute topological_sort and print the result.
Args:
G (Graph): A DAG.
Returns:
None
"""
print(list(nx.topological_sort(G))) | 5,287,397 |
def add_text(img, text, coords=(0.02, 0.95), fontsize=0.03, fill=(0, 0, 0)):
"""
Adds text to a provided image in numpy.ndarray format.
Coords are in relative position
"""
from PIL import Image, ImageDraw, ImageFont
img *= 255
img = Image.fromarray(img.astype(np.uint8))
width, height = i... | 5,287,398 |
def test_install_editable_from_git_with_https(script, tmpdir):
"""
Test cloning from Git with https.
"""
url_path = 'pypa/pip-test-package.git'
local_url = _github_checkout(url_path, tmpdir, egg='pip-test-package')
result = script.pip('install', '-e', local_url, expect_error=True)
result.ass... | 5,287,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.