content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def autolabel(rects, ax):
"""
Attach a text label above each bar displaying its height
"""
for rect in rects:
height = rect.get_height()
if height==1: # 2 for log2
height=rect.get_y()
ax.text(rect.get_x() + rect.get_width()/2., .65*height,
'%.1... | 5,319,100 |
def cleanUp(filePath1, filePath2):
"""
アノテート後のファイルを削除し、
アノテート時に作成したバックアップファイルを元のファイル名に直す.
Parameters
----------
filePath1 : str
比較元ファイルのパス
filePath2 : str
比較対象ファイルのパス
"""
os.remove(filePath1)
os.remove(filePath2)
os.rename(filePath1+".tmp", filePath1)
os.... | 5,319,101 |
def returns_player(method):
"""
Decorator: Always returns a single result or None.
"""
def func(self, *args, **kwargs):
"decorator"
rfunc = returns_player_list(method)
match = rfunc(self, *args, **kwargs)
if match:
return match[0]
else:
ret... | 5,319,102 |
def tracks(date):
"""
Query the charts/beatport/tracks endpoint for the given date.
Data available on Fridays.
https://api.chartmetric.com/api/charts/beatport
**Parameters**
- `date`: string date in ISO format %Y-%m-%d
**Returns**
A list of dictionary of tracks on Beatport ch... | 5,319,103 |
def test_pass_concat_by_reference() -> None:
"""Test concatenated storages as pass-by-reference arguments."""
inc = TestNamespace()
incArgRef = inc.addArgument("R", IntType.u(16))
incArgVal = inc.emit_load(incArgRef)
incAdd = AddOperator(incArgVal, IntLiteral(0x1234))
inc.emit_store(incArgRef, i... | 5,319,104 |
def cos_sim(A_mat, B_vec):
"""
item-vevtorの行列(またはベクトル)が与えられた際にitem-vevtor間のコサイン類似度行列を求める
"""
d = np.dot(A_mat, B_vec) # 各ベクトル同士の内積を要素とする行列
# 各ベクトルの大きさの平方根
A_norm = (A_mat ** 2).sum(axis=1, keepdims=True) ** .5
B_norm = (B_vec ** 2).sum(axis=0, keepdims=True) ** .5
# それぞれのベクトルの大きさの平方根で... | 5,319,105 |
def _check_that_names_are_not_used_multiple_times(list_of_tuples, when):
"""Check that names of nodes are not assigned multiple times.
Tuples in the list have either one or two elements. The first element in the two
element tuples is the name and cannot occur twice.
Examples
--------
>>> _chec... | 5,319,106 |
def parse_dtype(space):
"""Get a tensor dtype from a OpenAI Gym space.
Args:
space: Gym space.
Returns:
TensorFlow data type.
"""
if isinstance(space, gym.spaces.Discrete):
return tf.int32
if isinstance(space, gym.spaces.Box):
return tf.float32
raise NotImplementedError() | 5,319,107 |
def tf_efficientnet_b2_ap(pretrained=True, **kwargs):
""" EfficientNet-B2. Tensorflow compatible variant """
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
out_indices = [1, 2, 4, 6]
model = _gen_efficientnet(
'tf_efficientnet_b2_ap', channel_multiplier=1.1, depth_multipli... | 5,319,108 |
def plot_ld_curves(ld_stats, stats_to_plot=[], rows=None, cols=None,
statistics=None, fig_size=(6,6), dpi=150, r_edges=None,
numfig=1, cM=False, output=None, show=False):
"""
Plot single set of LD curves
LD curves are named as given in statistics
ld_stats is th... | 5,319,109 |
def main():
"""initialize:
configuration parsing
complete logger
Bot
"""
# config File
path = '/'.join((os.path.abspath(__file__).replace('\\', '/')).split('/')[:-1])
config = configparser.RawConfigParser()
config.read(os.path.join(path, 'config.ini'), encoding='utf8')
api_confi... | 5,319,110 |
def onehottify_2d_array(a):
"""
https://stackoverflow.com/questions/36960320/convert-a-2d-matrix-to-a-3d-one-hot-matrix-numpy
:param a: 2-dimensional array.
:return: 3-dim array where last dim corresponds to one-hot encoded vectors.
"""
# https://stackoverflow.com/a/46103129/ @Divakar
def a... | 5,319,111 |
def getUserCompetencies(cnx, exceptUserIDs):
"""
Returns array of persons with their competences as values
"""
competencies = {}
cnx = establishDBConnection(dbconfig)
cursor = cnx.cursor()
placeholder = '%s'
placeholders = ', '.join(placeholder for unused in exceptUserIDs)
query = ("... | 5,319,112 |
def add_induct_def(name, T, eqs):
"""Add the given inductive definition.
The inductive definition is specified by the name and type of
the constant, and a list of equations.
For example, addition on natural numbers is specified by:
('plus', nat => nat => nat,
[(plus(0,n) = n, plus(Suc(m), n) ... | 5,319,113 |
def outbound_sync_listener():
"""Initialize a delta outbound sync with Azure Active Directory."""
LOGGER.info("Starting outbound sync listener...")
while True:
try:
queue_entry = peek_at_queue("outbound_queue", TENANT_ID)
LOGGER.info(
"Received queue entry %s... | 5,319,114 |
def cropDetectionSegments(ffBinRead, segmentList, cropSize = 64):
""" Crops small images around detections.
ffBinRead: read FF bin structure
segmentList: list of coordinate tuples [(x1, y1), (x2, y2),...]
cropSize: image square size in pixels (e.g. 64x64 pixels)"""
ncols = ffBinRead.ncols - 1... | 5,319,115 |
def delete_site_request(site_id):
"""Request deletion of a site."""
site = InventorySite.query.filter_by(id=site_id).first()
if site is None:
abort(404)
return render_template('inventory/manage_site.html', site=site) | 5,319,116 |
def test_strat_name():
"""Test strat names"""
sarr = stratarray([3, 2])
for i, strat in enumerate(["s0", "s1", "s2", "s3", "s4"]):
assert strat == sarr.strat_name(i) | 5,319,117 |
def test_collect_order(testdir):
"""Check tests collection order."""
directory = testdir.copy_example("tests/data/collect_order")
result = testdir.runpytest(directory, "--collect-only")
result.stdout.re_match_lines(
[
"collected 6 items",
"<TestCaseYamlModule .*b/test_cas... | 5,319,118 |
def twoD_Gaussian(tup, amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
""" A 2D Gaussian to be used to fit the cross-correlation
Args:
tup (tuple):
A two element tuple containing the (x,y) coordinates where the 2D Gaussian will be evaluated
amplitude (float):
The am... | 5,319,119 |
def generate_synthetic_example(n_stations=65, lat_lims=(45, 50), lon_lims=(10, 20), u_0=0, A=.1, phi_2=60, B=.01, phi_4=20, amplitude_noise=.05):
"""
Helper function to generate a simple synthetic example.
Constant anisotropy in entire region.
:param n_stations: Number of stations in study area
:pa... | 5,319,120 |
def test_compile_cache_auto_detect():
"""
Feature: Compile cache.
Description: Test whether the compile cache auto-detection function can run successfully.
Expectation: success.
"""
run_twice_with_different_networks("run_lenet.py", "run_network_with_weights.py", "./lenet_auto_detect",
... | 5,319,121 |
def _extractStringType(newTypeName, newProperty, propDict, modelTypes, modelFileContainer):
"""extract the specific string type depending on the given format
and return the specific type
Keyword arguments:
newType -- current type name
newProperty -- current property
propDict -- dict of the prop... | 5,319,122 |
def get_palette(col, col_unique=None, as_dict=True):
"""Get palette for column.
Parameters
----------
col : {'subject_name', 'model', 'scaling', 'cell_type', str}
The column to return the palette for. If we don't have a particular
palette picked out, the palette will contain the strings... | 5,319,123 |
def _transfer_sha_between_repos(source_repo, dest_repo, sha):
"""
Transfer a SHA from one repo to another.
Args:
* source_repo (Path)
* dest_repo (Path)
* sha,
"""
command = [
"ostree",
"--repo={}".format(dest_repo),
"pull-local",
"{}".format(source_re... | 5,319,124 |
def array2hist(array, hist, errors=None):
"""Convert a NumPy array into a ROOT histogram
Parameters
----------
array : numpy array
A 1, 2, or 3-d numpy array that will set the bin contents of the
ROOT histogram.
hist : ROOT TH1, TH2, or TH3
A ROOT histogram.
errors : num... | 5,319,125 |
def test_specific_indicator_retrieval(tc):
"""Retrieve a specific indicator by filtering based on indicator."""
indicators = tc.indicators()
filter = indicators.add_filter()
filter.add_indicator('422AD421127685E3EF4A44B546258107')
indicators.retrieve()
assert(len(indicators) == 1) | 5,319,126 |
def test_least_squares_copy_jacobian():
"""
Test if Jacobian matrix is copied or scaled inplace
"""
jacobian = np.identity(5)
original_jacobian = jacobian.copy()
data = np.array([1, 2, 3, 4, 5], dtype=float)
least_squares(jacobian, data, weights=None, copy_jacobian=True)
npt.assert_allcl... | 5,319,127 |
def adjust_update_rules_for_fixed_nodes(predecessor_node_lists, truth_tables, fixed_nodes):
"""
Adjust "update rules" matrix and its free element vector so that the fixed nodes will end up in their fixed
states on each time step automatically, with no manual interventions required.
:param predecessor_n... | 5,319,128 |
def read_nuget(self, config, excl=None, mapping=None):
"""
Parse nuget packages.config and run read_csslib on each line
"""
if not self.env.MCS:
return
src = self.path.find_resource(config)
if src:
handler = PackageHandler(self, excl, mapping)
parser = xml.sax.make_parser()
parser.setContent... | 5,319,129 |
def obs_data():
"""
Dictionary with variables as top keys and available observations
directly below. For each observation data set, path and file pattern must
be defined.
"""
meta_dict = {
# ------------------------------------------------------------------------
# 2m temperature
'... | 5,319,130 |
def define_radius(event):
""" Calculates the radius by measuring the distance
between user-defined lines.
"""
xy = plt.ginput(1)
startx = event.xdata
starty = event.ydata
x = [startx, xy[0][0]]
y = [starty, xy[0][1]]
print "x of line", x
print "y of line", y
# The radius is ... | 5,319,131 |
def prompt_user(calender, type, glob=False):
"""
Prompt the user with what will be created on JIRA.
:param Dict calender: The calender to verify
:param Bool glob: Is this a Global Board
:param String type: What type of calender is this
"""
print('SPS will create the following Quarters and S... | 5,319,132 |
async def remove_old_cancel_indicator_files():
""" In case there are old cancel indicator files that are present and wasn't cleaned up properly, delete them
Old files defined as having an age greater than 1 hour
"""
for filename in os.listdir(CANCEL_PATH):
path = os.path.join(CANCEL_PATH, file... | 5,319,133 |
def create_class_prediction_error_chart(classifier, X_train, X_test, y_train, y_test):
"""Create class prediction error chart.
Tip:
Check Sklearn-Neptune integration
`documentation <https://docs-beta.neptune.ai/essentials/integrations/machine-learning-frameworks/sklearn>`_
for the full ... | 5,319,134 |
def footer_embed(message: str, title) -> Embed:
"""
Constructs embed with fixed green color and fixed footer showing website, privacy url and rules url.
:param message: embed description
:param title: title of embed
:return: Embed object
"""
content_footer = (
f"Links: [Website]({co... | 5,319,135 |
def _get_signal_space(S, NP, verbose=False, threshold=None, NSIG=None,
criteria='aic'):
"""todo
"""
from .criteria import aic_eigen, mdl_eigen
# This section selects automatically the noise and signal subspaces.
# NSIG being the number of eigenvalues corresponding to signals.
... | 5,319,136 |
def _discover_courses(session, di, lvl, total):
"""Hidden method for discovering courses on studyportal.
Args:
session (requests.Session, or equivalent): session for making requests.
di (int): Discipline id number.
lvl (str): Degree level string (e.g. bachelor, master, etc)
tota... | 5,319,137 |
def joins_for_results(basetables, external_info):
"""
Form and return the `results` table
"""
# Get one table per result_type, then stack them,
# kind_problem
# kind_pathproblem
#
# Concatenation with an empty table triggers type conversion to float, so don't
# include empty ta... | 5,319,138 |
def save_texture_channels(data, base_fname):
""" Save a N depth image as N images of depth 1. """
data.reshape((data.shape + (1,))[:3])
depth = data.shape[2]
base, ext = os.path.splitext(base_fname)
fstr = "%%s-%%0%dd%%s" % int(math.log10(data.shape[2]) + 1)
for i in range(depth):
fname ... | 5,319,139 |
def newton_wedge_fringe_sep(alpha, wavelength):
"""Calculate the separation between fringes for an optical flat with angle
alpha."""
d = wavelength/(2*np.sin(alpha))
return d | 5,319,140 |
def hs_classify(scope):
"""
A mapper ``Function -> (Dimension -> [HaloLabel]`` describing what type of
halo exchange is expected by the various :class:`TensorFunction`s in a
:class:`Scope`.
"""
mapper = {}
for f, r in scope.reads.items():
if not f.is_TensorFunction:
conti... | 5,319,141 |
def train_test_split(shp, savedir, config, client = None):
"""Create the train test split
Args:
shp: a filter pandas dataframe (or geodataframe)
savedir: directly to save train/test and metadata csv files
client: optional dask client
Returns:
None: train.shp and test.shp ar... | 5,319,142 |
async def test_generate_alert(mocker):
"""Test alert generation"""
logfile = open(test_log,"r")
mocker.patch('http_log_monitoring.http_log_monitoring.HttpMonitoring.stream_logs',
mock_logs)
log_monitor = HttpMonitoring(logfile, 2)
await log_monitor.traffic_counter()
log_monitor.... | 5,319,143 |
def parse_list_from_string(value):
"""
Handle array fields by converting them to a list.
Example:
1,2,3 -> ['1','2','3']
"""
return [x.strip() for x in value.split(",")] | 5,319,144 |
def add_evaluation_args(parser):
"""Evaluation arguments."""
group = parser.add_argument_group('validation', 'validation configurations')
group.add_argument('--eval-batch-size', type=int, default=None,
help='Data Loader batch size for evaluation datasets.'
'De... | 5,319,145 |
def notebook_fullwidth():
"""Set the Jupyter Notebook width to the maximum page width
"""
if in_ipynb():
#pylint: disable=import-outside-toplevel
from IPython.core.display import display, HTML
#pylint: enable=import-outside-toplevel
display(HTML("<style>.container { width:10... | 5,319,146 |
def merge(d1, d2):
"""Merge to dicts into one.
Args:
d1 (dict): dataset 1
d2 (dict): dataset 2
Returns:
dict: merged dict
"""
return dict(itertools.chain(list(d1.items()), list(d2.items()))) | 5,319,147 |
def run(config_file):
"""
runs the NEAT algorithm to train a neural network to play pong.
:param config_file: location of config file
:return: Void
"""
config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
neat.DefaultSpeciesSet, neat.DefaultStagnatio... | 5,319,148 |
def is_valid(number):
"""
Check if number is roman
:param number: string to check
:type number: str
:return: True or False
:rtype: bool
"""
return re.match(
r"^(M{0,3})(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$", number
) | 5,319,149 |
def test_create_account(an_account):
"""
:param an_account: takes a fixture
tests if an account is created successfully
"""
assert an_account.iban == "tr1"
assert an_account.balance == 1000 | 5,319,150 |
def lammps_created_gsd(job):
"""Check if the mdtraj has converted the production to a gsd trajectory for the job."""
return job.isfile("prod.gsd") | 5,319,151 |
def has_open_quotes(s):
"""Return whether a string has open quotes.
This simply counts whether the number of quote characters of either type in
the string is odd.
Returns
-------
If there is an open quote, the quote character is returned. Else, return
False.
"""
# We check " first... | 5,319,152 |
def get_task(name, context=None, exception_if_not_exists=True):
"""
Returns item for specified task
:param name: Name of the task
:param context: Lambda context
:param exception_if_not_exists: true if an exception should be raised if the item does not exist
:return: Task item, raises exception i... | 5,319,153 |
def GetResourceReference(project, organization):
"""Get the resource reference of a project or organization.
Args:
project: A project name string.
organization: An organization id string.
Returns:
The resource reference of the given project or organization.
"""
if project:
return resources.R... | 5,319,154 |
def pauli_block_y(M, norb):
"""
y compoenent of a matrix, see pauli_block
"""
ret = zeros_like(M)
tmp = (M[:norb, norb:] * 1j + M[norb:, :norb] * (-1j)) / 2
ret[:norb, norb:] = tmp * (-1j)
ret[norb:, :norb] = tmp * 1j
return tmp, ret | 5,319,155 |
def permission_required_raise(perm, login_url=None, raise_exception=True):
"""
A permission_required decorator that raises by default.
"""
return permission_required(perm, login_url=login_url, raise_exception=raise_exception) | 5,319,156 |
def test_section_start_section_property_bad_section():
"""Test Section start_section property with invalid section data."""
section_file = Section()
section_file.read = utils.mock_read('')
with pytest.raises(EOFError):
assert section_file.start_section
with pytest.raises(EOFError):
a... | 5,319,157 |
def add(img, stateimg, channel, amount):
"""Add a given amount to a color channel of `stateimg`, and
store the result in `img`. Overflow is clipped.
Parameters
----------
img : (M, N, 3) ndarray of uint8
Output image.
stateimg : (M, N, 3) ndarray of uint8
Input image.
chann... | 5,319,158 |
def filled(a: numpy.ndarray, fill_value: bool):
"""
usage.matplotlib: 1
"""
... | 5,319,159 |
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
"""Old way of setting up Zigbee Home Automation lights."""
pass | 5,319,160 |
def list_objects(root_checkpointable):
"""Traverse the object graph and list all accessible objects.
Looks for `Checkpointable` objects which are dependencies of
`root_checkpointable`. Includes slot variables only if the variable they are
slotting for and the optimizer are dependencies of `root_checkpointable`... | 5,319,161 |
def get_dips_value_around_300(l_cusp):
"""
300°付近の凹みの L* 値および、それを指す Hue の Index を計算する。
"""
dips_300 = np.min(l_cusp[DIPS_300_SAMPLE_ST:DIPS_300_SAMPLE_ED])
dips_300_idx = np.argmin(l_cusp[DIPS_300_SAMPLE_ST:DIPS_300_SAMPLE_ED])
dips_300_idx += DIPS_300_SAMPLE_ST
return dips_300, dips_300_idx | 5,319,162 |
def get_filtered_enviro_df(lat_filter, long_filter):
"""
This function takes the latitude and longitude filters and queries the
database to obtain City of Chicago Environmental complaint and enforcement
information that fits within those filters. A pandas dataframe of filtered
database information ... | 5,319,163 |
def is_valid_time_stamp_normal_response(response):
"""
Returns true if a time_stamp_normal response is valid.
str -> bool
"""
try:
respones_to_datetime(response, constants.DATETIME_FORMATE_NORMAL)
return True
except ValueError:
return False | 5,319,164 |
def status(repo="."):
"""Returns staged, unstaged, and untracked changes relative to the HEAD.
:param repo: Path to repository or repository object
:return: GitStatus tuple,
staged - list of staged paths (diff index/HEAD)
unstaged - list of unstaged paths (diff index/working-tree)
... | 5,319,165 |
def test_list_nmtokens_enumeration_2_nistxml_sv_iv_list_nmtokens_enumeration_3_2(mode, save_output, output_format):
"""
Type list/NMTOKENS is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/NMTOKENS/Schema+Instance/NISTSchema-SV-IV-list-NMTOKENS-enumeration-3.xsd",
... | 5,319,166 |
def find_best_capacity_value(desired_capacity, data_file='data/capacities.csv'):
"""Return the closest capacity to the desired one from the possible capacity combinations.
Parameters
----------
desired_capacity: float
The desired capacity value needed for the circuit.
data_file: str
Re... | 5,319,167 |
def _qt(add_row, secondary_dict_ptr, cols, key):
"""
This sub-function is called by view_utils.qt to add keys to the secondary_dict and
is NOT meant to be called directly.
"""
if cols[key]:
if cols[key] in secondary_dict_ptr:
return add_row, secondary_dict_ptr[cols[key]]
... | 5,319,168 |
def conv_to_schedule(src: datetime) -> str:
"""Convert given datetime to schedule date string."""
return datetime.strftime(src, FMT_STD) | 5,319,169 |
def test_get_xml_skip_xml_combine(
vaski_query: VaskiQuery, mock_requests_get_multiple_rows: MagicMock
) -> None:
"""Test that XMLCombine is skipped when there at least two data rows."""
assert vaski_query.get_xml() is None | 5,319,170 |
def create(title):
"""Create a Tk root
title - a title for the application
"""
assert isinstance(title, str)
root = tk.Tk()
root.title = title
rx.concurrency.TkinterScheduler(root)
return root | 5,319,171 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up Homekit lock."""
hkid = config_entry.data["AccessoryPairingID"]
conn = hass.data[KNOWN_DEVICES][hkid]
@callback
def async_add_service(service):
if service.short_type != ServicesTypes.LOCK_MECHANISM:
r... | 5,319,172 |
def bounding_boxes_to_tensor(bboxes: List[dict], image_size: Tuple[int, int],
cell_size: Tuple[int, int], classes: List[str],
device: torch.device) -> Tuple[torch.Tensor]:
"""
Converts a list of bounding boxes to a tuple of tensors
(multiple bounding... | 5,319,173 |
def _mock_download_file(filename: str, output_file_path: Optional[Path] = None,
_validate_checksum: bool = False) -> None:
"""
Creates an empty file at the given output_file_path
"""
output_file_path = Path('test_output') if output_file_path is None else output_file_path
outp... | 5,319,174 |
def compartment_size_uncommon_keys(base):
"""
Provide a model with different amounts metabolites for each compartment.
"""
base.add_metabolites(
[cobra.Metabolite(i, compartment='ml') for i in "ABCD"])
base.add_metabolites(
[cobra.Metabolite(i, compartment='om') for i in "EFG"])
... | 5,319,175 |
def steady_state_step(population: list, reproduction_pipeline: list, insert, probes = (), evaluation_op = ops.evaluate):
"""An operator that performs steady-state evolution when placed in an (otherwise
generational) pipeline.
This is a metaheuristic component that can be parameterized to define many kinds ... | 5,319,176 |
def get_gym_environs():
""" List all valid OpenAI ``gym`` environment ids. """
return [e.id for e in gym.envs.registry.all()] | 5,319,177 |
def single_classic_cv_evaluation(
dx_train, dy_train, name, model, sample_weight, scoring, outer_cv,
average_scores_across_outer_folds, scores_of_best_model, results,
names, random_state):
"""Non nested cross validation of single model."""
if (isinstance(scoring, list) or isinstance(scor... | 5,319,178 |
def get_extension_context(ext_name, **kw):
"""Get the context of the specified extension.
All extension's module must provide `context(**kw)` function.
Args:
ext_name (str) : Module path relative to `nnabla_ext`.
kw (dict) : Additional keyword arguments for context function in a extension ... | 5,319,179 |
def resolve_byprop(prop, value, minimum=1, timeout=FOREVER):
"""Resolve all streams with a specific value for a given property.
If the goal is to resolve a specific stream, this method is preferred over
resolving all streams and then selecting the desired one.
Keyword arguments:
prop -- The St... | 5,319,180 |
def create_plot(model_filenames, ncols=3, projection=None, nplots_increment=0):
"""Create base figure for multipanel plot.
Creates matplotlib figure and set of axis that corespond to
the number of models that should be plotted.
Parameters
----------
model_filenames: OrderedDict
Ordered... | 5,319,181 |
def get_sample_records(n):
"""get sample records for testing"""
tsk, target = get_sample_task()
inps, ress = [], []
for i in range(n):
inps.append(MeasureInput(target, tsk, tsk.config_space.get(i)))
ress.append(MeasureResult((i + 1,), 0, i, time.time()))
return list(zip(inps, ress)) | 5,319,182 |
def build_get_boolean_tfft_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get boolean array value [true, false, false, true].
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azu... | 5,319,183 |
def grøn(tekst: str):
"""
Farv en tekst der udskrives via Click grøn.
"""
return farvelæg(tekst, "green") | 5,319,184 |
def gen_peak_def(n_peaks_to_gen=None):
"""Generator for plausible peak parameters for simulated power spectra.
Parameters
----------
n_peaks_to_gen : int, optional
Number of peaks to generate. If None, picked at random from {0, 1, 2}.
Yields
------
peaks : list of list of [float, f... | 5,319,185 |
def init_config(config: Union[Dict, Path, Text, None]) -> ConfigParser:
"""
Initialize skill configuration:
1. Defaults from SDK
2. Additional locations
3. "skill.conf"
:param config:
:return:
"""
# Merge additional configs
config_paths = load_additional()
if ... | 5,319,186 |
def update(dbs, user, role_id=None, org_id=None, create_user=None):
"""
更新用户信息
:param dbs:
:param user:
:param role_id:
:param org_id:
:param create_user:
:return:
"""
try:
with transaction.manager:
if org_id and org_id != '' and org_id != 0:
d... | 5,319,187 |
def analogy_making_model(inputs, params, is_training, reuse, output_length=None):
"""Factory function to retrieve analogy-making model."""
latent_encoder = _get_network(Z_ENC_FN)
latent_decoder = _get_network(Z_DEC_FN)
outputs = analogy_seq_encoding_model(inputs, params, is_training, reuse)
with tf.variable... | 5,319,188 |
def find_element_status(tree, element, plugin_name=None):
"""
Finds the element status for a specified element
@param tree: Parsed JMX file
@param element: Name of the element to check the status for
@param plugin_name: (Optional) Name of the plugin to check the status for
"""
root = tree.ge... | 5,319,189 |
def test_model(dataloader, model, gpu=False):
"""Tests model performance on a data from dataloader and prints accuracy.
Args:
dataloader (DataLoader)
model (torchvision model)
gpu (bool): Use GPU if True, otherwise CPU
Returns:
test_acc (float): model prediction accuracy
... | 5,319,190 |
def decrypt_chunk(chunk, password=None):
"""Decrypts the given encrypted chunk with the given password and returns the decrypted chunk.
If password is None then saq.ENCRYPTION_PASSWORD is used instead.
password must be a byte string 32 bytes in length."""
if password is None:
password = s... | 5,319,191 |
def print_relevant_columns(row: pd.Series, config: configparser.ConfigParser) -> None:
"""
Prints all relevant columns for the classification with the corresponding value. Does
some preprecessing for string values (removes linebreaks, splits into multiple lines if
the text is to long...).
Parameter... | 5,319,192 |
def ensure_no_l3_drops(duthost, asic_index, packets_count):
""" Verify L3 drop counters were not incremented """
intf_l3_counters = get_pkt_drops(duthost, GET_L3_COUNTERS, asic_index)
unexpected_drops = {}
for iface, value in intf_l3_counters.items():
try:
rx_err_value = int(value[RX... | 5,319,193 |
def epochFromNice(timeToConvert=None):
""" Get the epoch time from the passed in string of the format:
YYYY-mm-dd_HH-MM-SS.UUUUUU
returns time.time() if timeToConvert is not specified """
if timeToConvert is None:
retTime = time.time()
else:
yearMonthDay, hourMinuteSec = timeToConvert.spli... | 5,319,194 |
def check_lens(rxn, k, g, f, error ):
""" Function to check the lengths of the rxn, k g, and f lists. Should always be same len.
Author:
-------
Dr. Jessica D. Haskins (jhaskins@alum.mit.edu) GitHub: @jdhask
Change Log:
----------
1/18/2022 JDH Created
""" ... | 5,319,195 |
def test_bytes_2(elf_idb):
"""
Demonstrate issue reported as #12.
Thanks to @binoopang.
This exercises fetching of flags/bytes from a segment that is not the first.
"""
api = idb.IDAPython(elf_idb)
assert (
api.idc.GetManyBytes(0x8049DF0, 0x10)
== b"\x8D\x4C\x24\x04\x83\xE4\... | 5,319,196 |
def test_datamodule_labelstudio_image():
"""Test creation of LabelStudioImageClassificationDataSource and Datamodule from images."""
download_data("https://label-studio-testdata.s3.us-east-2.amazonaws.com/lightning-flash/data.zip")
datamodule = ImageClassificationData.from_labelstudio(
train_export... | 5,319,197 |
def prepare_tensor_SVD(tensor, direction, D=None, thresh=1E-32, normalize=False):
"""
prepares and truncates an mps tensor using svd
Parameters:
---------------------
tensor: np.ndarray of shape(D1,D2,d)
an mps tensor
direction: int
if >0 returns left orthogonal decomp... | 5,319,198 |
def test_example(prt=sys.stdout):
"""Test GoeaResults in plotting package."""
# --------------------------------------------------------------------
# --------------------------------------------------------------------
# Gene Ontology Enrichment Analysis (GOEA)
# -----------------------------------... | 5,319,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.