content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_manifest_v2_maintainer_validator_invalid_maintainer(setup_route):
"""
Ensure MaintainerValidator fails if supplied a support_email with non-ASCII characters
"""
invalid_maintainer_manifest = JSONDict(
{
"author": {
"homepage": "https://www.datadoghq.com",
... | 5,307,400 |
def draw_boxes_and_labels_to_image_with_json(image, json_result, class_list, save_name=None):
"""Draw bboxes and class labels on image. Return the image with bboxes.
Parameters
-----------
image : numpy.array
The RGB image [height, width, channel].
json_result : list of dict
The obj... | 5,307,401 |
def sampled_softmax_loss(positive_keys: tf.Tensor,
inputs: tf.Tensor,
num_samples: int,
de_config: de_config_pb2.DynamicEmbeddingConfig,
var_name: typing.Text,
service_address: typing.Text = "",
... | 5,307,402 |
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
"""Set up Netgear component."""
router = NetgearRouter(hass, entry)
try:
await router.async_setup()
except CannotLoginException as ex:
raise ConfigEntryNotReady from ex
hass.data.setdefault(DOMAIN, {})... | 5,307,403 |
def patch_plugs(phase_user_defined_state=None,
phase_diagnoses=None,
**mock_plugs):
"""Decorator for mocking plugs for a test phase.
Usage:
@plugs(my_plug=my_plug_module.MyPlug)
def my_phase_that_uses_my_plug(test, my_plug):
test.logger.info('Something: %s', my_plug.d... | 5,307,404 |
def get_hosts(r_config, r_dest):
"""
:param r_config: 主机组配置[dir]
:param r_dest: 目标主机组 [str]
:return: [list]
"""
matched_str = []
rst = []
for key in r_config.keys():
if re.match(r_dest, key):
matched_str.append(key)
for key in matched_str:
rst += r_confi... | 5,307,405 |
def describe_my_user_profile():
"""
Describes a user's SSH information.
See also: AWS API Documentation
:example: response = client.describe_my_user_profile()
:rtype: dict
:return: {
'UserProfile': {
'IamUserArn': 'string',
'Name': 'string',
... | 5,307,406 |
def purge(objects):
"""purge notification or program data"""
objects = objects.lower()
if not objects:
return no_args_msg
if objects not in object_map.keys():
return error_msg
queryset = object_map[objects]
msg = "Purging {} {}".format(queryset.count(), objects)
queryset.dele... | 5,307,407 |
def mixture_channel(
val: Any,
default: Any = RaiseTypeErrorIfNotProvided) -> Sequence[
Tuple[float, np.ndarray]]:
"""Return a sequence of tuples for a channel that is a mixture of unitaries.
In contrast to `mixture` this method falls back to `unitary` if `_mixture_`
is not implemented.
A ... | 5,307,408 |
def get_dropped_pks(engine: Engine, table: Table, from_commit: str, to_commit: str) -> List[dict]:
"""
Given table_metadata, a connection, and a pair of commits, will return the list of pks that were dropped between
the two commits.
:param engine:
:param table:
:param from_commit:
:param to_... | 5,307,409 |
def xml_scale(
xml_file,
x_scale=1,
y_scale=1,
z_scale=1,
output_directory=None,
integer=True,
):
# TODO: add a csv option
"""
To rescale the cell positions within an XML file. For compatibility with
other software, or if data has been scaled after cell detection.
:param xm... | 5,307,410 |
def main():
"""Main function"""
packageDir = os.path.dirname(os.path.abspath(__file__))
root = tk.Tk()
root.iconphoto(True, tk.PhotoImage(file=os.path.join(packageDir, 'icons', 'diskimgr.png')))
myGUI = omimgrGUI(root)
# This ensures application quits normally if user closes window
root.pro... | 5,307,411 |
def get_mode_from_params(params):
"""Returns the mode in which this script is running.
Args:
params: Params tuple, typically created by make_params or
make_params_from_flags.
Raises:
ValueError: Unsupported params settings.
"""
if params.forward_only and params.eval:
raise ValueError(... | 5,307,412 |
def equadrupole(qc: BaseQCCalc, unit: Optional[str] = "Debye*Angst") -> torch.Tensor:
"""
Returns the electric quadrupole moment of the system, i.e. derivative of energy
w.r.t. electric field.
Arguments
---------
qc: BaseQCCalc
The qc calc object that has been executed.
unit: str or... | 5,307,413 |
def get(key, nodename=None):
"""
A function to get a node pillar configuration key.
CLI Example:
salt * node.get hostname
"""
return _get_property(key, nodename, None) | 5,307,414 |
def quote_logvalue(value):
"""Return a value formatted for use in a logfmt log entry.
The input is quoted if it contains spaces or quotes; otherwise returned unchanged
"""
s = str(value)
if " " in s or '"' in s:
s = s.replace('"', "\\" + '"')
return f'"{s}"'
return s | 5,307,415 |
def create_new_form_search(data):
"""Create a new form search.
:param dict data: the form search to be created.
:returns: an form search model object.
"""
form_search = FormSearch()
form_search.name = h.normalize(data['name'])
form_search.search = data['search'] # Note that this is p... | 5,307,416 |
def apply_stylespace_to_variable_font(
stylespace: statmake.classes.Stylespace,
varfont: fontTools.ttLib.TTFont,
additional_locations: Mapping[str, float],
) -> None:
"""Generate and apply a STAT table to a variable font.
additional_locations: used in subset Designspaces to express where on which o... | 5,307,417 |
def split_filename(fn, name=None,
prefix=None, suffix=None,
stack_limit=2):
"""
Ermittle einen Namen und ein Label aus dem Dateinamen,
der ggf. aus dem Aufrufstack ermittelt wird.
Zunächst "richtige" Entwicklungs- oder installierte Quellen:
>>> split_filename(... | 5,307,418 |
def test_non_compliant_vies():
"""Test a VIES response where the member state is non-compliant and
does not provide details *or* do fuzzy matching."""
try:
valid, response = vat.check_details(test_numbers[1][0], bad_info)
assert valid is None
assert response.trader_info['name'] == ba... | 5,307,419 |
def model2magcoords(
xg: dict[str, T.Any],
parm: xarray.DataArray,
lalt: int,
llon: int,
llat: int,
altlims: tuple[float, float] = None,
mlonlims: tuple[float, float] = None,
mlatlims: tuple[float, float] = None,
):
"""
Grid the scalar GEMINI output data in parm onto a regular *g... | 5,307,420 |
def flatten(master):
"""
:param dict master: a multilevel dictionary
:return: a flattened dictionary
:rtype: dict
Flattens a multilevel dictionary into a single-level one so that::
{'foo':
{'bar':
{
'a': 1,
'b': True,
... | 5,307,421 |
def test_get_save_file_size(test_data_list: list) -> None:
"""Test the get_save_file_size function
Parameters:
test_data_list (list): The list of paths to the test input data files (fixture)
Returns:
None
"""
file_size = Save(path_to_save_file=test_data_list[0]).data.file_size
assert 2... | 5,307,422 |
def network(ip):
"""Network an IP address belongs to.
Parameters
----------
ip : str
IP address.
Returns
-------
network_ip_with_prefix : str
IP address of the network with prefix.
"""
ip, prefix = netParse(ip)
return "{}/{}".format(
ipS... | 5,307,423 |
def _build_pnasnet_base(images,
normal_cell,
num_classes,
hparams,
is_training,
final_endpoint=None):
"""Constructs a PNASNet image model."""
end_points = {}
def add_and_check_endpoint(endpoin... | 5,307,424 |
def _parse_advantage_prereq(el: et.Element, function_name: str) -> str:
"""Parse a <advantage_prereq> element and its children.
Return a str of Python code that takes traits and trait_names as
arguments and evaluates to True iff the prereqs are satisfied.
"""
if el.get("has") == "no":
if le... | 5,307,425 |
def check_empty_error_response(
response: Response,
) -> None:
"""Ensure that error response do not leak informations"""
r = response.json()
assert "detail" in r
assert len(r) == 1 | 5,307,426 |
def m21_midievent_to_event(midievent):
"""Convert a music21 MidiEvent to a tuple of MIDI bytes."""
status = midievent.data + midievent.channel - 1
return (status, midievent.pitch, midievent.velocity) | 5,307,427 |
def populate_impl_map(data_model):
"""
Map symbols to implementations.
"""
impl_map = {
"==": _type_safe_equal,
"=": _type_safe_equal,
"!=": _type_safe_not_equal,
"<>": _type_safe_not_equal,
"<": numpy.less, # already checks types
"<=": numpy.less_equal, ... | 5,307,428 |
def friendly_time(d: datetime.datetime) -> str:
"""Return "minutes ago" style date"""
ad = Arrow.fromdatetime(d)
other = Arrow.fromdatetime(datetime.datetime.utcnow())
return ad.humanize(other) | 5,307,429 |
def power_set_str_v2(s: str) -> Container[Sequence]:
"""
Note: it doesn't take empty set into accout.
"""
# print all subsets of the remaining elements, with given prefix
def _power_set_str_v2(prefix: str, s: str, result) -> None:
if len(s) > 0:
# print(prefix+s[0])
... | 5,307,430 |
def build_get307_request(**kwargs: Any) -> HttpRequest:
"""Redirect get with 307, resulting in a 200 success.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pas... | 5,307,431 |
def svm_SVR_C( xM, yV, c_l, graph = True):
"""
SVR is performed iteratively with different C values
until all C in the list are used.
"""
r2_l, sd_l = [], []
for C in c_l:
print 'sklearn.svm.SVR(C={})'.format( C)
clf = svm.SVR( C = C)
clf.fit( xM, yV.A1)
yV_pred = clf.predict(xM)
r2, sd = regress_... | 5,307,432 |
def solar_declination(
doy: Union[np.ndarray, xr.DataArray]
) -> Union[np.ndarray, xr.DataArray]:
"""Solar declination from day of year [rad].
Parameters
----------
doy: array.py
day of the year (1-365)
Returns
-------
Union[np.ndarray, xr.DataArray]
solar declination [r... | 5,307,433 |
def update_headers(src_tree):
"""Main."""
print("src tree", src_tree)
for root, dirs, files in os.walk(src_tree):
py_files = fnmatch.filter(files, "*.py")
for f in py_files:
print("checking", f)
p = os.path.join(root, f)
update_license_header(p)
... | 5,307,434 |
def load_gwas(args, use_specific_targets):
"""Watch out! Pandas parser on occasion reads the column `position` as integer. Yikes."""
columns = ["variant_id", "panel_variant_id", "chromosome", "position", "non_effect_allele", "effect_allele","zscore"]
if use_specific_targets is not None:
logging.info... | 5,307,435 |
def merge_dict(d1, d2, overwrite=False):
"""Merge contents of d1 and d2 and return the merged dictionary
Note:
* The dictionaries d1 and d2 are unaltered.
* If `overwrite=False` (default), a `RuntimeError` will be raised when
duplicate keys exist, else any existing keys in d1 are silently... | 5,307,436 |
def copy_cwl_files(from_dir=CWL_PATH, to_dir=None):
"""Copy cwl files to a directory where the cwl-runner can find them.
Args:
from_dir (str): Path to directory where to copy files from (default:
the cwl directory of nlppln).
to_dir (str): Path to directory where the files should be... | 5,307,437 |
def get_args():
"""Get args from the command line."""
parser = argparse.ArgumentParser(
description='Count down the number of bottles on the wall',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n',
'--number',
he... | 5,307,438 |
def handle_not_found(error: NotFound) -> Response:
"""Render the base 404 error page."""
rendered = jsonify({'code': error.code, 'error': error.description})
response = make_response(rendered)
response.status_code = status.HTTP_404_NOT_FOUND
return response | 5,307,439 |
def train_yolo5():
"""Train YOLOv5 over a dataset in YOLO5/COCO format.
Usage:
train_yolo5 ../../datasets/Retail81 --with-coco --names object --device 1 --batch-size 32
References:
python train.py --data coco.yaml --cfg yolov5x.yaml --weights yolov5x.pt --device 1 --batch-size 16
... | 5,307,440 |
def compare_documents(sample_text_a: str, sample_text_b: str) -> float:
"""Compares two documents using spacy's bow model"""
doc_a = nlp_en(sample_text_a)
doc_b = nlp_en(sample_text_b)
return doc_a.similarity(doc_b) | 5,307,441 |
def calc_fragment_mz(pep, frag_type, frag_num, frag_charge, mod=None) -> float:
"""
Example:
pep = 'LGRPSLSSEVGVIICDISNPASLDEMAK'
frag_type = 'y'
frag_num = 10
frag_charge = 1
mod = '15,Carbamidomethyl;26,Oxidation;'
-> 1091.5037505084001
:param pep: peptide sequence
:param frag... | 5,307,442 |
def test_differ_length():
"""Test common prefix length of two strings differing in length."""
assert utils.common_prefix_length('abcd', 'ab') == 2 | 5,307,443 |
def invert_axis(document: vp.Document, invert_x: bool, invert_y: bool):
"""Inverts none, one or both axis of the document.
This applies a relative scale operation with factors of 1 or -1
on the two axis to all layers. The inversion happens relative to
the center of the bounds.
"""
bounds = docu... | 5,307,444 |
def tokenize_tweet(inputRow, fields):
"""
A simple tokenizer that takes a tweet as input and, splitting on whitespace, and returns words in the tweet
Args:
inputRow (Row): A spark sql row containing a tweet
fields (list): A list of field names which directs tokenize on which fields to use as so... | 5,307,445 |
def seq_to_kmercount(seq, kmerdict, kmersize):
"""DNA sequence and count number of kmers
in the dictionary, and return this dictionary
"""
seq = str(seq).upper()
length = len(seq) - kmersize + 1
for i in range(length):
kmer = seq[i:i+kmersize]
# select lexographically lowest km... | 5,307,446 |
def create_resource_from_db_row(row):
"""Create a resource type from a database resource row.
Args:
row (Resource): the database resource row.
Returns:
Resource: the concrete resource type.
"""
parent = (
create_resource_from_db_row(row.parent) if row.parent else None)
... | 5,307,447 |
def build_embeddings(symbolic_features, integer_features,
embeddings, large_discrete, merged_inputs,
X, test_X, train_dict, test_dict, dataset):
"""Define embedding layers/inputs"""
merged_dim = 0
for (name, values) in symbolic_features.items():
feature_name... | 5,307,448 |
def get_results(job_key):
"""
Results page for <job_key>. If job is still running, this will redirect to the same page with the link to refresh again. When its done,
the refresh link will link to the tables.
"""
job = Job.fetch(job_key, connection=current_app.redis)
### Return results
if... | 5,307,449 |
def generate_benchmark_graphs_networkx(storage_dir, num_graphs, params):
"""Generates and stores LFR benchmark graphs and clustering information.
This method generated LFR graphs using the networkx function 'LFR_benchmark_graph'. WARNING: this generator
is FLAWED, as it will not produce graphs that match t... | 5,307,450 |
def find_background_image_path(canvas_width, canvas_height, canvas_background_file):
"""Establish the path to the background file should one exist. The function copies it from wherever specified into the root.
Also checks the aspect ratio of the input file against the canvas.
Args:
canvas_heigh... | 5,307,451 |
def getFlipboardTitles():
""" Get title of all dashboard inside Config/ """
config_names = getConfigNames()
listNameDashboard = list()
rcx = 1
for config in config_names:
config = parseXmlLayout(config)
if 'details' in config and 'page_title' in config['details']:
listNam... | 5,307,452 |
def availability(url, session=None):
"""
Check HTTP status code of given URL.
200 or 301-308 is OK, else is not.
:param url: URL to check.
:type url: str
:param session: Requests session object, default is created on the fly.
:type session: requests.Session()
"""
status = getcode(u... | 5,307,453 |
def cudnnGetConvolution2dForwardOutputDim(convDesc, inputTensorDesc, filterDesc):
""""
Return the dimensions of the output tensor given a convolution descriptor.
This function returns the dimensions of the resulting 4D tensor of a 2D
convolution, given the convolution descriptor, the input tensor descr... | 5,307,454 |
def test_COSM87531_SYNE1_E4738fs():
"""
test_COSM87531_SYNE1_E4738fs : frame shift from nucleotide insertion
"""
# The given genomic mutation is:
# 6 152651608 COSM87531 C>CA
# but through some painful manual checking I realized that
# the nucleotides here are *not* the correct ones... | 5,307,455 |
def ocean_loading(time, amp, phases, lon):
"""
time is in hours from Jan 1, 1900, stationlongitude is longitude
purpose: To assess the ocean loading/gravity effect due to the
separate tidal primary components derived from the Agnew
program ( LOADF ).
produce the... | 5,307,456 |
def cancel_study(args):
"""Flag a study to be cancelled."""
if not os.path.isdir(args.directory):
return 1
lock_path = os.path.join(args.directory, ".cancel.lock")
with open(lock_path, 'a'):
os.utime(lock_path, None)
return 0 | 5,307,457 |
def makedirs(name, exist_ok=False):
"""
Replacement for Python2's version lacking exist_ok
"""
if not os.path.exists(name) or not exist_ok:
os.makedirs(name) | 5,307,458 |
def convert_ms_2_tf(tf_ckpt_path, ms_ckpt_path, new_ckpt_path):
"""
convert ms checkpoint to tf checkpoint
"""
# load MS checkpoint
ms_param_dict = load_checkpoint(ms_ckpt_path)
for name in ms_param_dict.keys():
if isinstance(ms_param_dict[name].data, Tensor):
ms_para... | 5,307,459 |
def servers():
"""Unauthorized endpoint to check for configured servers. Returns the name and ID of the server for selection
when logging in. Also indicates the current server (if one is selected)
"""
server_list = []
for s in current_app.config['LABMGR_CONFIG'].list_available_servers():
s... | 5,307,460 |
def ammonia_fake() -> (oechem.OEMol, oechem.OEAtomBase):
"""
Creates an ammonia molecule with fake Wiberg bond orders. Also returns
the trivalent nitrogen in the molecule
"""
ammonia = oechem.OEMol()
oechem.OESmilesToMol(ammonia, "N")
oechem.OEAddExplicitHydrogens(ammonia)
fake_wbo = [1... | 5,307,461 |
def check_token():
""" Token checking endpoint.
---
get:
summary: Check the validity of a token.
description: This endpoint checks for the validity of a given authentication token.
parameters:
- token: The token to check.
responses:
200:
... | 5,307,462 |
def subgrid(
A: xr.Dataset, subgrid_spec: Tuple[int, int, int, int], stagger: str = "outer"
) -> xr.Dataset:
"""Make a ROMS xarray Dataset on a horizontal subgrid"""
# Suppese xi_rho and eta_rho allways present
# imax = len(A.xi_rho)
# jmax = len(A.eta_rho)
# How about slicing, inner or outer ... | 5,307,463 |
def format_decimal(number):
"""Formats `number` for current locale."""
attan = Xuanzang.get_attan()
return attan.format_decimal(number) | 5,307,464 |
def build_docs(
verbose: bool, dry_run: bool, docs_only: bool, spellcheck_only: bool, package_filter: Tuple[str]
):
"""Build documentation in the container."""
params = BuildCiParams()
ci_image_name = params.airflow_image_name
check_docker_resources(verbose, ci_image_name)
doc_builder = DocParam... | 5,307,465 |
def _get_requirements_for_dict(node):
"""
..code:: python
Dict(expr* keys, expr* values)
"""
for key, value in zip(node.keys, node.values):
yield from get_requirements(value) | 5,307,466 |
def optimization_for_fishfeed_substitution(fishfeed_table, lipidmicro,
protmicro, carbmicro, watermicro,
ashmicro, incorporation_rate,
MJ_kgcarb, MJ_kgprot, MJ_kglip):
"""Returns the subs... | 5,307,467 |
def remove_repeating_characters(sentence):
"""
remove non alphaneumeric characters which repeat more than 3 times by its 3 occurrence (e.g. ----- to ---)
:param sentence:
:return:
"""
sentence = re.sub('(\W)\\1{3,}', '\\1', sentence)
return sentence.strip() | 5,307,468 |
def get_args() -> argparse.Namespace:
"""Get args."""
parser = argparse.ArgumentParser()
parser.add_argument("-u", "--username", required=True, type=str, help="Zenfolio username")
parser.add_argument("-p", "--password", required=True, type=str, help="Zenfolio password")
parser.add_argument("-b", "--... | 5,307,469 |
def unlink(ctx, fsname, fspath, username=None):
"""
delete link\n
FSNAME: fs name
FSPATH: fs path
"""
client = ctx.obj['client']
if not fsname:
click.echo('fs delete must provide fsname.', err=True)
sys.exit(1)
valid, response = client.delete_link(fsname, fspath, username... | 5,307,470 |
def crossover(p_1, p_2, r_cross):
"""
order 1 crossover / OX / order crossover
:param p_1: parent 1
:param p_2: parent 2
:param r_cross: rate of crossover
"""
if random.random() < r_cross:
c1, c2 = p_1.copy(), p_2.copy()
pt_1 = random.randint(0, len(p_1)-1)
pt_2 = ran... | 5,307,471 |
def tree_to_treesegment(canvas, t, make_node=TextWidget,
make_leaf=TextWidget, **attribs):
"""
Convert a Tree into a ``TreeSegmentWidget``.
:param make_node: A ``CanvasWidget`` constructor or a function that
creates ``CanvasWidgets``. ``make_node`` is used to convert
... | 5,307,472 |
def test_delete():
"""
Tests to remove the named group
"""
mock = MagicMock(return_value={"retcode": 0})
with patch.dict(pw_group.__salt__, {"cmd.run_all": mock}):
assert pw_group.delete("a") | 5,307,473 |
def borrow_for_color_red(base_color_dict, from_left, from_right):
"""!
@brief Borrows colors for the base color red.
@param base_color_dict Dictionary with arrays of all the base colors.
@param from_left Boolean flag for recursive calls, if we came from the left.
@param from_right Boolean fla... | 5,307,474 |
def requestPdpContextActivationReject():
"""REQUEST PDP CONTEXT ACTIVATION REJECT Section 9.5.5"""
a = TpPd(pd=0x8)
b = MessageType(mesType=0x45) # 01000101
c = SmCause()
packet = a / b / c
return packet | 5,307,475 |
def assemble_pybel(stmts, out_file_prefix):
"""Return a PyBEL Assembler"""
stmts = ac.filter_belief(stmts, 0.95)
stmts = ac.filter_top_level(stmts)
pba = PybelAssembler(stmts, name='INDRA/REACH Korkut Model',
description='Automatically assembled model of '
... | 5,307,476 |
def add_month(year, month, delta):
"""
Helper function which adds `delta` months to current `(year, month)` tuple
and returns a new valid tuple `(year, month)`
"""
year, month = divmod(year * 12 + month + delta, 12)
if month == 0:
month = 12
year = year - 1
return year, month | 5,307,477 |
def extractTime(line):
"""
extracts date or time from an event file input line
and returns a datetime object.
"""
dt = line.split(None, 1)[0]
if len(dt) > 20:
print(dt, 'Invalid dateTime string')
return
#print('extractTime : ', line )
d, t = dt.split('_')
day,... | 5,307,478 |
def ramp(width=32, height=32, density=0.25):
"""Support downward forces on a ramp."""
return staircase(width, height, density, num_stories=1) | 5,307,479 |
def zeros(shape, backend=TensorFunctions):
"""
Produce a zero tensor of size `shape`.
Args:
shape (tuple): shape of tensor
backend (:class:`Backend`): tensor backend
Returns:
:class:`Tensor` : new tensor
"""
return Tensor.make([0] * int(operators.prod(shape)), shape, ba... | 5,307,480 |
def getInitFile():
"""
function: get init file
input : NA
output : NA
"""
if isSupportSystemOs():
return INIT_FILE_REDHAT
else:
return INIT_FILE_SUSE | 5,307,481 |
def compare(returns, benchmark, aggregate=None, compounded=True,
round_vals=None, prepare_returns=True):
"""
Compare returns to benchmark on a
day/week/month/quarter/year basis
"""
if prepare_returns:
returns = _utils._prepare_returns(returns)
benchmark = _utils._prepare_benc... | 5,307,482 |
def __get_job_obj(profile):
"""Return the 'job' object in the profile."""
with open(profile, 'rt') as json_fobj:
data = json.load(json_fobj)
return data['jobs'][0] | 5,307,483 |
def getconfloc() :
""" Renvoie la configuration total des localisations"""
cfg = configparser.ConfigParser()
cfg.read(clt_path)
location = {}
for i in cfg.options('Locations') :
location[i] = getlocation(i)
return location | 5,307,484 |
def _handle_component(component, model_path: str) -> None:
"""
Handle component and inject URI into link component geometry
"""
if isinstance(component, Link):
for link_component in component.aggregate_order:
# TODO: are there other types we need to consider?
if isinstanc... | 5,307,485 |
def gen_sample_img(dataset, model=None, idx=None):
""" Plot 3d poses, real, with noise and decode from vae model if a model is provided
pass 'idx' to select samples otherwise idx will be randomly generated
"""
# select random samples
nsamples = 15
if idx is None:
idx = np.random.choi... | 5,307,486 |
def median(r):
"""Return the median of an iterable of numbers.
The median is the point at which half the numbers are lower than it and
half the numbers are higher. This gives a better sense of the majority
level than the mean (average) does, because the mean can be skewed by a few
extreme numbers ... | 5,307,487 |
def flatten_evidence(stmts, collect_from=None):
"""Add evidence from *supporting* stmts to evidence for *supported* stmts.
Parameters
----------
stmts : list of :py:class:`indra.statements.Statement`
A list of top-level statements with associated supporting statements
resulting from bui... | 5,307,488 |
def get_binary_image(image):
"""Converts image to black and white"""
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
(thresh, black_white_image) = cv2.threshold(
gray_image, 150, 255, cv2.THRESH_BINARY_INV)
return thresh, black_white_image | 5,307,489 |
def plt():
"""
Prints any symbols found in the .plt section if it exists.
"""
print_symbols_in_section('.plt', '@plt') | 5,307,490 |
def analyze_sentiment(text):
"""
Sends a request to the Google Natural Language API to analyze
the sentiment of the given piece of text.
"""
request = language_service.documents().analyzeSentiment(
body={
'document': {
'type': 'PLAIN_TEXT',
'content': text,
... | 5,307,491 |
def php_array_slice(_array, _offset, _length=None, _preserve=False):
"""
>>> input = Array("a", "b", "c", "d", "e")
>>> php_array_slice(input, 2)
{0: 'c', 1: 'd', 2: 'e'}
>>> php_array_slice(input, -2, 1)
{0: 'd'}
>>> php_array_slice(input, 0, 3)
{0: 'a', 1: 'b', 2: 'c'}
>>> php_arra... | 5,307,492 |
def scale_clips(boxes, canvas_area, density=0.40):
"""
Resizes and returns cropped words based on canvas area, density, and word complexity
Input:
`boxes` user words pandas dataframe
`canvas_area` total area of canvas
`density` float of desired area to fill on canvas
Output:
... | 5,307,493 |
def make_root_cgroups():
"""
Build a CGroups object for the topmost cgroup
:return: CGroups for most-encompassing cgroup
:rtype: CGroupConfigurator
"""
def path_maker(hierarchy, _):
return os.path.join(BASE_CGROUPS, hierarchy)
return CGroupConfigurator("root", path_maker) | 5,307,494 |
def test_generate_integration_context(mocker, tmpdir):
"""
Given
- A yaml file and fake example file
When
- generating the yml ouputs from the examples
Then
- Ensure the outputs are inserted correctly
"""
from demisto_sdk.commands.generate_outputs.generate_context import \
... | 5,307,495 |
def create_snippet(text):
"""
:param text:
:return:
"""
if len(text) < 500:
return text
initial_cut = text[:550]
last_index_of_space = initial_cut.rfind(' ')
last_index_of_semicolon = initial_cut.rfind(';')
last_index_of_comma = initial_cut.rfind(',')
last_index_of_per... | 5,307,496 |
def test_single_dimension_attr():
"""
If you only provide one of width or height, the other should not be added.
"""
ttag = r"""{% generateimage 'testspec' source=img -- width="50" %}"""
clear_imagekit_cache()
attrs = get_html_attrs(ttag)
assert_false('height' in attrs) | 5,307,497 |
def create_parser(argv=None):
"""Create CLI arguments and sub-arguments parsers.
"""
if argv is None:
argv = sys.argv[1:]
argparser = argparse.ArgumentParser(description='rerobots API command-line client', add_help=False)
argparser.add_argument('-h', '--help', dest='print_help',
... | 5,307,498 |
def test_sheva_nah_ending_ai_m_kh():
"""`sheva` before `qamats|patah`, `hiriq`, `khaf-sofit|mem-sofit` is `sheva-nah` (sheva-nah-ending-ai-m|kh)"""
word = r"הָאָבְנָיִם" # ha-ov-na-im (Exodus 1:15)
parts = [
"he",
"qamats-gadol",
"alef",
"qamats-qatan",
"vet",
... | 5,307,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.