content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_env(env_name: str) -> str:
"""
Safely read an environment variable.
Raises errors if it is not defined or it is empty.
:param env_name: the name of the environment variable
:return: the value of the environment variable
"""
if env_name not in os.environ:
raise KeyError(f"{env_name} not defined")
env_... | 5,337,800 |
def image_resize_and_sharpen(image, size, preserve_aspect_ratio=False, factor=2.0):
"""
Create a thumbnail by resizing while keeping ratio.
A sharpen filter is applied for a better looking result.
:param image: PIL.Image.Image()
:param size: 2-tuple(width, height)
:param pre... | 5,337,801 |
def callHgsql(database, command):
""" Run hgsql command using subprocess, return stdout data if no error."""
cmd = ["hgsql", database, "-Ne", command]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
cmdout, cmderr = p.communicate()
if p.returncode != 0:
# keep comma... | 5,337,802 |
def validate_mash(seq_list, metadata_reports, expected_species):
"""
Takes a species name as a string (i.e. 'Salmonella enterica') and creates a dictionary with keys for each Seq ID
and boolean values if the value pulled from MASH_ReferenceGenome matches the string or not
:param seq_list: List of OLC Se... | 5,337,803 |
def style_strokes(svg_path: str, stroke_color: str='#ff0000',
stroke_width: float=0.07559055) -> etree.ElementTree:
"""Modifies a svg file so that all black paths become laser cutting paths.
Args:
svg_path: a file path to the svg file to modify and overwrite.
stroke_color: the... | 5,337,804 |
def preview_pipeline(
pipeline: Pipeline, domain_retriever: DomainRetriever, limit: int = 50, offset: int = 0
) -> str:
"""
Execute a pipeline but returns only a slice of the results, determined by `limit` and `offset` parameters, as JSON.
Return format follows the 'table' JSON table schema used by pan... | 5,337,805 |
def redirect_to_url(url):
"""
Return a bcm dictionary with a command to redirect to 'url'
"""
return {'mode': 'redirect', 'url': url} | 5,337,806 |
def get_xml_tagged_data(buffer, include_refstr=True):
"""
figure out what format file it is and call the
respective function to return data for training
:param buffer:
:param include_refstr: during training do not need refstr
:return:
"""
if len(buffer) > 1 and 'http://www.elsevier.com/... | 5,337,807 |
async def test_successful_config_flow(hass, mqtt_mock):
"""Test a successful config flow."""
# Initialize a config flow
result = await _flow_init(hass)
# Check that the config flow shows the user form as the first step
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["ste... | 5,337,808 |
async def helppanel(ctx):
"""
Send out the student leadership panel.
:param ctx: Context
:return: None
"""
await helpdirectory.send_help_panel(ctx) | 5,337,809 |
def de_dup(
data: pd.DataFrame,
drop_duplicates_kwargs: Dict[str, Any] = {},
) -> pd.DataFrame:
"""Drop duplicate rows
"""
return data.drop_duplicates(**drop_duplicates_kwargs) | 5,337,810 |
def get_task_defs(workspace: str, num_validators: int, num_fullnodes: int) -> dict:
"""
Builds a dictionary of:
family -> current_task_def
task_def can be used to get the following when updating a service:
- containerDefinitions
- volumes
- placementConstraints
NOTE: on... | 5,337,811 |
def gruml(source_code_path, **kwargs):
"""driver function of GRUML.
"""
gruml = GRUML()
print('Generating RUML for source code at: {}'.format(source_code_path))
gruml.get_source_code_path_and_modules(source_code_path)
gruml.get_driver_path_and_driver_name(
kwargs.get('use_case', None),
... | 5,337,812 |
def get_terms(cmd, urn=None, publisher=None, offer=None, plan=None):
"""
Get the details of Azure Marketplace image terms.
:param cmd:cmd
:param urn:URN, in the format of 'publisher:offer:sku:version'. If specified, other argument values can be omitted
:param publisher:Image publisher
:param off... | 5,337,813 |
def encode_payload( result ):
"""JSON encodes a dictionary, named tuple, or object for sending
to the server
"""
try:
return tornado.escape.json_encode( result )
except TypeError:
if type( result ) is list:
return [ tornado.escape.json_encode( r ) for r in result ]
... | 5,337,814 |
def relu(shape) -> np.ndarray:
"""
Creates a gaussian distribution numpy array with a mean of 0 and variance of sqrt(2/m).
Arguments:
shape : tuple : A tuple with 2 numbers, specifying size of the numpy array.
Returns:
output : np.ndarray : A uniform numpy array.
"""
return np.random.no... | 5,337,815 |
def reset_all():
"""Batch reset of batch records."""
_url = request.args.get("url") or request.referrer
task_id = request.form.get("task_id")
task = Task.get(task_id)
try:
count = utils.reset_all_records(task)
except Exception as ex:
flash(f"Failed to reset the selected records:... | 5,337,816 |
def update_to_report(db, data, section_name, img_path,id):
"""
Update data of report
"""
query = '''UPDATE report
SET data = "{}" ,
section_name = "{}",
image_path = "{}"
WHERE id = "{}" '''.format(data, section_name, img_path, id)
result = ge... | 5,337,817 |
def keyboard(table, day=None):
"""Handler for showing the keyboard statistics page."""
cols, group = "realkey AS key, COUNT(*) AS count", "realkey"
where = (("day", day),) if day else ()
counts_display = counts = db.fetch(table, cols, where, group, "count DESC")
if "combos" == table:
counts_... | 5,337,818 |
def fetch(uri, username='', password=''):
"""Can fetch with Basic Authentication"""
headers = {}
if username and password:
headers['Authorization'] = 'Basic ' + base64.b64encode('%s:%s' % (username, password))
headers['User-Agent'] = 'Twimonial'
f = urlfetch.fetch(uri, headers=headers)
logging.debu... | 5,337,819 |
def update_identity_provider(UserPoolId=None, ProviderName=None, ProviderDetails=None, AttributeMapping=None, IdpIdentifiers=None):
"""
Updates identity provider information for a user pool.
See also: AWS API Documentation
:example: response = client.update_identity_provider(
UserPoolI... | 5,337,820 |
def _handle_file(args):
"""
Handle the --file argument.
"""
filename = args.filename
_parse_and_output(filename, args) | 5,337,821 |
def tsCrossValidationScore(params, series,loss_function=mean_squared_error, nsplits=3, slen=1):
"""
#Parameters:
params : vector of parameters for optimization (three parameters:
alpha, beta, gamma for example
series : dataset with timeseries
sle:
... | 5,337,822 |
def test_empty_file():
"""
Test empty file
"""
empty_file = 'test/empty.json'
ephemeral = TinyDB(empty_file, storage=EphemeralJSONStorage)
assert ephemeral.get(where('name') == 'Value A') is None
ephemeral.close() | 5,337,823 |
def handle_exhibition(data: List[Dict[str, str]]):
"""
Iterates over all provided exhibition items and checks the http.StatusOK for
every valid url item.
:param data: list containing exhibition dictionary items.
"""
print("Processing exhibition item links ...")
fails = ""
for idx, item i... | 5,337,824 |
def get_psf_fwhm(psf_template: np.ndarray) -> float:
"""
Fit a symmetric 2D Gaussian to the given ``psf_template`` to
estimate the full width half maximum (FWHM) of the central "blob".
Args:
psf_template: A 2D numpy array containing the unsaturated
PSF template.
Returns:
... | 5,337,825 |
def test_structure_linecache():
"""Linecaching for structuring should work."""
@define
class A:
a: int
c = GenConverter()
try:
c.structure({"a": "test"}, A)
except ValueError:
res = format_exc()
assert "'a'" in res | 5,337,826 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
(int): Floored Square Root
"""
assert number >= 0, 'Only square root of positive numbers are valid'
start = 0
end = number
res = None... | 5,337,827 |
def add_roi_shared_config(cfg):
"""
Add config for roi shared head
"""
_C = cfg
_C.MODEL.ROI_BOX_HEAD.IN_FEATURES = []
_C.MODEL.ROI_SHARED_HEAD = CN()
_C.MODEL.ROI_SHARED_HEAD.IN_FEATURES = ["p2"]
_C.MODEL.ROI_SHARED_HEAD.POOLER_RESOLUTION = 32
_C.MODEL.ROI_SHARED_HEAD.POOLER_TYPE ... | 5,337,828 |
def test_cluster_representatives_criterion_flag(analysis, criterion, expected):
"""
Tests the user-defined method of selecting cluster representatives.
Parameters
----------
analysis : Analysis object
Created by a fixture.
criterion : str
cluster_representatives_criterion flag d... | 5,337,829 |
def check_child_update_request_from_parent(
command_msg,
leader_data=CheckType.OPTIONAL,
network_data=CheckType.OPTIONAL,
challenge=CheckType.OPTIONAL,
tlv_request=CheckType.OPTIONAL,
active_timestamp=CheckType.OPTIONAL,
):
"""Verify a properly formatted Child Update Request(from parent) com... | 5,337,830 |
def repetition_sigmoid(M):
"""
Used to model repetition-driven effects of STDP. More repetitions results in stronger increase/decrease.
"""
return 1.0/(1+np.exp(-0.2*M+10)) | 5,337,831 |
def generate_features(ids0, ids1, forcefield, system, param):
"""
This function performs a minimization of the energy and computes the matrix features.
:param ids0: ids of the atoms for the 1st protein
:param ids1: ids of the atoms for the 2nd protein
:param forcefield: forcefield for OpenMM simula... | 5,337,832 |
def extract_bow_feature_vectors(reviews, dictionary):
"""
Inputs a list of string reviews
Inputs the dictionary of words as given by bag_of_words
Returns the bag-of-words feature matrix representation of the data.
The returned matrix is of shape (n, m), where n is the number of reviews
and... | 5,337,833 |
def model_wcs_header(datamodel, get_sip=False, order=4, step=32):
"""
Make a header with approximate WCS for use in DS9.
Parameters
----------
datamodel : `jwst.datamodels.ImageModel`
Image model with full `~gwcs` in `with_wcs.meta.wcs`.
get_sip : bool
If True, fit a `a... | 5,337,834 |
def create_session():
"""Return a session to be used for database connections
Returns:
Session: SQLAlchemy session object
"""
# Produces integrity errors!
# return _Session()
# db.session is managed by Flask-SQLAlchemy and bound to a request
return db.session | 5,337,835 |
def meta_to_indexes(meta, table_name=None, model_name=None):
"""Find all the indexes (primary keys) based on the meta data
"""
indexes, pk_field = {}, None
indexes = []
for meta_model_name, model_meta in meta.iteritems():
if (table_name or model_name) and not (table_name == model_meta['Met... | 5,337,836 |
def index():
"""Render and return the index page.
This is a informational landing page for non-logged-in users, and the corp
homepage for those who are logged in.
"""
success, _ = try_func(auth.is_authenticated)
if success:
module = config.get("modules.home")
if module:
... | 5,337,837 |
def test_user_tries_deleting_his_profile_but_it_fails_partially(
rf, user_gql_client, youth_service, berth_service, mocker
):
"""Test an edge case where dry runs passes for all connected services, but the
proper service connection delete fails for a single connected service. All other
connected services... | 5,337,838 |
def _(origin, category="", default=None):
"""
This function returns the localized string.
"""
return LOCALIZED_STRINGS_HANDLER.translate(origin, category, default) | 5,337,839 |
def next_month(month: datetime) -> datetime:
"""Find the first day of the next month given a datetime.
:param month: the date
:type month: datetime
:return: The first day of the next month.
:rtype: datetime
"""
dt = this_month(month)
return datetime((dt+_A_MONTH).year, (dt+_A_MONTH).mon... | 5,337,840 |
def walk_json(d, func):
""" Walk over a parsed JSON nested structure `d`, apply `func` to each leaf element and replace it with result
"""
if isinstance(d, Mapping):
return OrderedDict((k, walk_json(v, func)) for k, v in d.items())
elif isinstance(d, list):
return [walk_json(v, func) for... | 5,337,841 |
def console_map_string_to_font(s, fontCharX, fontCharY):
"""Remap a string of codes to a contiguous set of tiles.
Args:
s (AnyStr): A string of character codes to map to new values.
The null character `'\\x00'` will prematurely end this
function.
fontChar... | 5,337,842 |
def getUser():
"""This method will be called if a GET request is made to the /user/ route
It will get the details of a specified user
Parameters
----------
username
the name of the user to get info about
Raises
------
DoesNotExist
Raised if the username provided doe... | 5,337,843 |
def _create_ppo_agent(
time_step_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec,
preprocessing_layers: types.NestedLayer,
policy_network: types.Network) -> tfa.agents.TFAgent:
"""Creates a ppo_agent."""
actor_network = policy_network(
time_step_spec.observation,
action_sp... | 5,337,844 |
def stiffness_matrix_CST(element=tetra_4()):
"""Calculate stiffness matrix for linear elasticity"""
element.volume()
B = strain_matrix_CST(element)
D = material()
print('B')
print(B)
print('V',element.V)
return element.V * np.dot(np.dot(np.transpose(B),D),B) | 5,337,845 |
def count_down(print_text, count, sleep):
"""
Print text and animation count down.
Args:
print_text (str): Enter the text to be printed.
count (int): Counter number.
sleep (float): How fast the counts is supposed to be.
Returns:
print: Count down animation.
Usage:
... | 5,337,846 |
def test_handling_core_messages(hass):
"""Test handling core messages."""
cloud = MagicMock()
cloud.logout.return_value = mock_coro()
yield from iot.async_handle_cloud(hass, cloud, {
'action': 'logout',
'reason': 'Logged in at two places.'
})
assert len(cloud.logout.mock_calls) =... | 5,337,847 |
async def can_action_member(bot, ctx: SlashContext, member: discord.Member) -> bool:
""" Stop mods from doing stupid things. """
# Stop mods from actioning on the bot.
if member.id == bot.user.id:
return False
# Stop mods from actioning one another, people higher ranked than them or themselves.... | 5,337,848 |
def CountDatasetStatistics():
"""
Count the subgraphs for the published datasets
"""
# the datasets
input_filenames = {
'Hemi-Brain': 'graphs/hemi-brain-minimum.graph.bz2',
'C. elegans D1': 'graphs/C-elegans-timelapsed-01-minimum.graph.bz2',
'C. elegans D2': 'graphs/C-elegans... | 5,337,849 |
def trim_waveform_signal(
tr: obspy.Trace,
cfg: types.ModuleType = config
) -> obspy.Trace:
"""Cut the time series to signal window
Args:
tr: time series
cfg: configuration file
Returns:
tr: trimmed time series
"""
starttime, endtime = signal_... | 5,337,850 |
def animation_plot(
x,
y,
z_data,
element_table,
ani_fname,
existing_fig,
ani_funcargs=None,
ani_saveargs=None,
kwargs=None,
):
"""
Tricontourf animation plot.
Resulting file will be saved to MP4
"""
global tf
# Subtract 1 from element table to alig... | 5,337,851 |
def preprocess_adj(adj):
"""Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation."""
# adj_appr = np.array(sp.csr_matrix.todense(adj))
# # adj_appr = dense_lanczos(adj_appr, 100)
# adj_appr = dense_RandomSVD(adj_appr, 100)
# if adj_appr.sum(1).min()<0:
# ... | 5,337,852 |
def plot_figure_one_input_resource_2(style_label=""):
"""
Plot two bar graphs side by side, with letters as x-tick labels.
latency_dev_num_non_reuse.log
"""
prng = np.random.RandomState(96917002)
#plt.set_cmap('Greys')
#plt.rcParams['image.cmap']='Greys'
# Tweak the figure size to b... | 5,337,853 |
def comp_rot_dir(self):
"""Compute the rotation direction of the winding
Parameters
----------
self : LamSlotWind
A LamSlotWind object
Returns
-------
rot_dir : int
-1 or +1
"""
MMF = self.comp_mmf_unit()
p = self.get_pole_pair_number()
# Compute rotation ... | 5,337,854 |
def search_pk(uuid):
"""uuid can be pk."""
IterHarmonicApprox = WorkflowFactory("phonopy.iter_ha")
qb = QueryBuilder()
qb.append(IterHarmonicApprox, tag="iter_ha", filters={"uuid": {"==": uuid}})
PhonopyWorkChain = WorkflowFactory("phonopy.phonopy")
qb.append(PhonopyWorkChain, with_incoming="ite... | 5,337,855 |
def _region_bulk(mode='full', scale=.6):
"""
Estimate of the temperature dependence of bulk viscosity zeta/s.
"""
plt.figure(figsize=(scale*textwidth, scale*aspect*textwidth))
ax = plt.axes()
def zetas(T, zetas_max=0, zetas_width=1):
return zetas_max / (1 + ((T - Tc)/zetas_width)**2)
... | 5,337,856 |
def training(args):
"""Train the model and frequently print the loss and save checkpoints."""
dataset = tf.data.TextLineDataset([args.corpus])
dataset = dataset.map(
lambda line: tf.decode_raw(line, tf.uint8))
dataset = dataset.flat_map(
lambda line: chunk_sequence(line, args.chunk_lengt... | 5,337,857 |
def bias(struct,subover=True,trim=True, subbias=False, bstruct=None,
median=False, function='polynomial',order=3,rej_lo=3,rej_hi=3,niter=10,
plotover=False, log=None, verbose=True):
"""Bias subtracts the bias levels from a frame. It will fit and subtract the overscan
region, trim the images... | 5,337,858 |
def _add_centered_square(ax, xy, area, lablz, text_size, **kwargs):
"""
create hinton diagram element square with variable size according to weight matrix element value
"""
size = np.sqrt(area)
textz = fto_texts(lablz)
loc = np.asarray(xy) - size/2.
rect = mpatches.Rectangle(loc, size, siz... | 5,337,859 |
def main(args={}, version=False, arguments=False):
"""set up user2edd
set up config file(s)
set up logger
:param checkOnto_: running checkOntology or not
"""
# init default
_default_logger()
# setup package path
_setup_path()
# read configuration file(s)
config = _setup_... | 5,337,860 |
def help_command(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /help is issued."""
update.message.reply_text('Тебе уже не помочь') | 5,337,861 |
def main(input_dir: Path, resample: bool):
"""Process the BAVED dataset at location INPUT_DIR."""
paths = list(input_dir.glob("?/*.wav"))
resample_dir = Path("resampled")
if resample:
resample_audio(paths, resample_dir)
write_filelist(resample_dir.glob("*.wav"), "files_all")
levels = {}... | 5,337,862 |
def _BAIL( functionName, message ):
"""
Universal failure mode message.
"""
print( "= = ERROR in function %s : %s" % ( functionName, message), file=sys.stderr )
sys.exit(1) | 5,337,863 |
def getItemStatus(selected_item, store_id, num_to_average):
""" Method pulls the stock status of the selected item in the given store
:param selected_item: current item being processed (toilet paper or hand sanitizer)
:param store_id: id of the current store
:param num_to_average: number of recent stat... | 5,337,864 |
def iter_file(file_path, options={}):
"""Opens a file at the given file_path and iterates over its
contents, yielding FecItem instances, which consist of data and
data_type attributes. The data_type attribute can be one of "header",
"summary", "itemization", "text", or "F99_text". The data attribute is ... | 5,337,865 |
def assert_equal(obj1, obj2, save_if_different=False, msg='', name1='value1', name2='value2', ignore_keys=None,
**kwargs):
"""
This will assert obj1 and obj2 are the same and it will attempt to report the difference.
NOTE*** If this is different and the objects are complicated then use the... | 5,337,866 |
def filter_and_copy_table(tab, to_remove):
""" Filter and copy a FITS table.
Parameters
----------
tab : FITS Table object
to_remove : [int ...}
list of indices to remove from the table
returns FITS Table object
"""
nsrcs = len(tab)
mask = np.zeros((nsrcs), '?')
mas... | 5,337,867 |
def _archive_logs(conn, node_type, logger, node_ip):
"""Creates an archive of all logs found under /var/log/cloudify plus
journalctl.
"""
archive_filename = 'cloudify-{node_type}-logs_{date}_{ip}.tar.gz'.format(
node_type=node_type,
date=get_host_date(conn),
ip=node_ip
)
... | 5,337,868 |
def _check_n_dim(x, n_dims):
"""Raise error if the number of dimensions of the input data is not consistent with the expected value.
Args:
x (array-like tensor): input data, shape (n_samples, I_1, I_2, ..., I_N)
n_dims (int): number of dimensions expected, i.e. N+1
"""
if not x.ndim ==... | 5,337,869 |
def reset():
"""Reset your Twitter auth information.
"""
app_dir = click.get_app_dir(APP_NAME)
path = os.path.join(app_dir, 'config.ini')
if os.path.exists(path): os.remove(path)
click.echo('Configuration has been reset.') | 5,337,870 |
def get_scripts():
"""Returns the list of available scripts
Returns:
A dict holding the result message
"""
return Response.ok("Script files successfully fetched.", {
"scripts": list_scripts()
}) | 5,337,871 |
async def invoke(
fn: callbacks.BaseFn,
*args: Any,
settings: Optional[configuration.OperatorSettings] = None,
cause: Optional[causation.BaseCause] = None,
**kwargs: Any,
) -> Any:
"""
Invoke a single function, but safely for the main asyncio process.
Used mostly for... | 5,337,872 |
def test_null_count():
""" method to test null count, should return 0 nulls """
assert test_null.null_count(s1) == 0 | 5,337,873 |
def getLatestFare(_origin, _destination, _date):
"""
_origin and _destination take airport codes , e.g. BLR for Bangalore
_date in format YYYY-MM-DD e.g.2016-10-30
Returns either:
10 latest results from the results page.
1 lastest result from the results page.
"""
try:
... | 5,337,874 |
def plot_noisy_linear_1d(axes, num_samples, weights, sigma, limits, rng):
"""
Generate and plot points from a noisy single-feature linear model,
along with a line showing the true (noiseless) relationship.
# Arguments
axes: a Matplotlib Axes object into which to plot
num_samples: nu... | 5,337,875 |
def home():
"""Renders the home page."""
return render_template(
'index.html',
title='Rococal',
year=datetime.now().year,
) | 5,337,876 |
def Dx(x):
"""Nombre de survivants actualisés.
Args:
x: l'âge.
Returns:
Nombre de survivants actualisés.
"""
return lx(x)*v**x | 5,337,877 |
def tracek(k,aee,aii,see,sii,tau=1,alpha=0):
""" Trace of recurrently connected network of E,I units, analytically determined
input:
k: spatial frequency
aee: ampltidue E to E connectivity
aii: ampltidue I to I connectivity
see: standard deviation/width of E to E connectivity
sii: standard deviation/width of I ... | 5,337,878 |
def set_working_dir_repo_root(func):
"""
Decorator for checking whether the
current working dir is set as root of repo.
If not, changes the working dir to root of repo
Returns
-------
"""
def inner(*args, **kwargs):
git_repo = git.Repo(".", search_parent_directories=True)
... | 5,337,879 |
def get_verbose_name(model_or_queryset, field):
"""
returns the value of the ``verbose_name`` of a field
typically used in the templates where you can have a dynamic queryset
:param model_or_queryset: target object
:type model_or_queryset: :class:`django.db.models.Model`, :class:`django.db.query.... | 5,337,880 |
def if_then_else(cond, t, f, span=None):
"""Conditional selection expression.
Parameters
----------
cond : PrimExpr
The condition
t : PrimExpr
The result expression if cond is true.
f : PrimExpr
The result expression if cond is false.
span : Optional[Span]
... | 5,337,881 |
def get_args() -> argparse.Namespace:
"""Get arguments."""
parser = argparse.ArgumentParser(description="Dump Instance")
parser.add_argument(
"network_state_path", type=str, help="File path to network state dump JSON."
)
parser.add_argument("--host", type=str, help="Host to bind to", default... | 5,337,882 |
def get_resources(filetype):
"""Find all HTML template or JavaScript files in the package.
Caches the results for quick access.
Parameters
----------
filetype : {'templates', 'js'}
The type of file resource needed.
Returns
-------
:class:`dict`
A dictionary mapping fil... | 5,337,883 |
def sum_fn(xnum, ynum):
""" A function which performs a sum """
return xnum + ynum | 5,337,884 |
def _process_gamemap_intents(intent: InputIntentType):
"""
Process intents for the player turn game state.
"""
player = world.get_player()
position = world.get_entitys_component(player, Position)
possible_move_intents = [InputIntent.DOWN, InputIntent.UP, InputIntent.LEFT, InputIntent.RIGHT]
... | 5,337,885 |
def categorical_iou(y_true, y_pred, target_classes=None, strict=True):
"""画像ごとクラスごとのIoUを算出して平均するmetric。
Args:
target_classes: 対象のクラスindexの配列。Noneなら全クラス。
strict: ラベルに無いクラスを予測してしまった場合に減点されるようにするならTrue、ラベルにあるクラスのみ対象にするならFalse。
"""
axes = list(range(1, K.ndim(y_true)))
y_classes = K.ar... | 5,337,886 |
def convert_string(string: str, type: str) -> str:
"""Convert the string by [e]ncrypting or [d]ecrypting.
:param type: String 'e' for encrypt or 'd' for decrypt.
:return: [en/de]crypted string.
"""
hash_string = hash_()
map_ = mapping(hash_string)
if type.lower() == 'e':
output = e... | 5,337,887 |
def create_saml_security_context(token, private_key):
"""
Create a security context for SAML token based
authentication scheme
:type token: :class:`str`
:param token: SAML Token
:type private_key: :class:`str`
:param private_key: Absolute file path of the private key of the user
:rtyp... | 5,337,888 |
def test_augment_angles():
"""
X_all1,y_all1,es_all1 = load_boxworld_data('lab2_big_60v_10t')
X_all2,y_all2,es_all2 = load_boxworld_data('lab2_big_60v_30t')
X,y,es = augment_angles(X_all1,y_all1,es_all1,36,60)
assert np.array_equal(X,X_all1)
assert np.array_equal(y,y_all1)
assert es == ... | 5,337,889 |
def _save_txt(data, file_path):
"""
将一个list的数组写入txt文件里
:param data:
:param file_path:
:return:
"""
if not isinstance(data, list):
data = [data]
with open(file_path, mode='w', encoding='utf8') as f:
f.write('\n'.join(data)) | 5,337,890 |
def cli():
"""Command Line Tool to clone and restore RDS DB instance
or cluster for Blue-Green deployments. Please the sub commands
below. You can also use the options below to get more help.
NOTE: Please ensure the RDS instance ID is stored in your environment
variable as DBINSTANCEID
"""
... | 5,337,891 |
def predictIsDeviceLeftRunning():
"""
Returns if the device is presumed left running without a real need
---
parameters:
name: -device_id
in: query
description: the device id for which the prediction is made
required: false
style: form
explode: true
... | 5,337,892 |
def load(
source: AnyPath,
wordnet: Wordnet,
get_synset_id: Optional[Callable] = None,
) -> Freq:
"""Load an Information Content mapping from a file.
Arguments:
source: A path to an information content weights file.
wordnet: A :class:`wn.Wordnet` instance with synset
i... | 5,337,893 |
def save_depth_png(depth, png, png_scale):
"""save depth map
Args:
depth (array, [HxW]): depth map
png (str): path for saving depth map PNG file
png_scale (float): scaling factor for saving PNG file
"""
depth = np.clip(depth, 0, 65535 / png_scale)
depth = (depth * png_scale)... | 5,337,894 |
def iso_time_str() -> str:
"""Return the current time as ISO 8601 format
e.g.: 2019-01-19T23:20:25.459Z
"""
now = datetime.datetime.utcnow()
return now.isoformat()[:-3]+'Z' | 5,337,895 |
def mass(snap: Snap) -> Quantity:
"""Particle mass."""
massoftype = snap._file_pointer['header/massoftype'][()]
particle_type = np.array(
np.abs(get_dataset('itype', 'particles')(snap)).magnitude, dtype=int
)
return massoftype[particle_type - 1] * snap._array_code_units['mass'] | 5,337,896 |
def nothing():
"""DO nothing."""
pass | 5,337,897 |
def _build_pytest_test_results_path(cmake_build_path):
"""
Build the path to the Pytest test results directory.
:param cmake_build_path: Path to the CMake build directory.
:return: Path to the Pytest test results directory.
"""
pytest_results_path = os.path.join(cmake_build_path, TEST_RESULTS_DI... | 5,337,898 |
async def create_object_detection_training(
train_object_detection_model_request: TrainImageModel,
token: str = Depends(oauth2_scheme),
):
"""[API router to train AutoML object detection model]
Args:
train_object_detection_model_request (TrainImageModel): [Train AutoML Object detection model re... | 5,337,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.