content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def write_annotation_image(
parser: SimpleAnnotationParser,
image_size: InputDataSize,
label_color_dict: Dict[str, RGB],
output_image_file: Path,
background_color: Optional[Any] = None,
label_name_list: Optional[List[str]] = None,
):
"""
JSONファイルに記載されているアノテーション情報を、画像化する。
JSONファイルは、An... | 25,400 |
def linkgen(osversion, radioversion=None, softwareversion=None, altsw=None, temp=False, sdk=False):
"""
Generate debrick/core/radio links for given OS, radio, software release.
:param osversion: OS version, 10.x.y.zzzz.
:type osversion: str
:param radioversion: Radio version, 10.x.y.zzzz. Can be g... | 25,401 |
def reload(name: str) -> types.ModuleType:
"""
Finalize and reload a plugin and any plugins that (transitively) depend on it. We try to run all finalizers in
dependency order, and only load plugins that were successfully unloaded, and whose dependencies have been
successfully reloaded. If a plugin fails... | 25,402 |
def load_from_config(config_path, **kwargs):
"""Load from a config file. Config options can still be overwritten with kwargs"""
with open(config_path, "r") as config_file:
config = json.load(config_file)
config.update(kwargs)
return TokenizationConfig(**config) | 25,403 |
def get_tecogan_monitors(monitor):
"""
Create monitors for displaying and storing TECOGAN losses.
"""
monitor_vgg_loss = MonitorSeries(
'vgg loss', monitor, interval=20)
monitor_pp_loss = MonitorSeries(
'ping pong', monitor, interval=20)
monitor_sum_layer_loss = MonitorSeries(
... | 25,404 |
def mock_message_callback(*args):
"""
Test message callback is called
"""
print(*args) | 25,405 |
def user_based_filtering_recommend(new_user,user_movies_ids,movies_num,n_neighbor,movies_ratings):
""" This function return number of recommended movies based on user based filtering using
cosine similarity to find the most similar users to the new user
it returns movies_num of movies from the top ranked ... | 25,406 |
def test_export_traces_chunks_only():
"""
Testing exporting traces considering the area file
"""
exporter = TraceExporter()
exporter.load_and_export(
flags_to_update=
{
"RM_ROITrace": 3,
"GDM_outputType": "chunks_only",
"GDM_chunkPostStim": 2, # ... | 25,407 |
def query_ps_from_wcs(w):
"""Query PanStarrs for a wcs.
"""
nra,ndec = w.array_shape[1:]
dra,ddec = w.wcs.cdelt[:2]
c = wcs.utils.pixel_to_skycoord(nra/2.,ndec/2.,w)
ddeg = np.linalg.norm([dra*nra/2,ddec*ndec/2])
pd_table = query(c.ra.value,c.dec.value,ddeg)
# Crop sources to those in t... | 25,408 |
def permute(x, in_shape='BCD', out_shape='BCD', **kw):
""" Permute the dimensions of a tensor.\n
- `x: Tensor`; The nd-tensor to be permuted.
- `in_shape: str`; The dimension shape of `x`. Can only have characters `'B'` or `'C'` or `'D'`,
which stand for Batch, Channel, or extra Dimensions. The de... | 25,409 |
def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Parameters
----------
data
A 2D numpy array of shape (N, M).
row_labels
A list or array of length N with the label... | 25,410 |
def assert_is_normal_rpyc(f):
"""
Analyze the structure of a single rpyc file object for correctness.
Does not actually say anything about the _contents_ of that section, just that we were able
to slice it out of there.
If succesful, returns the uncompressed contents of the first storage slot.
... | 25,411 |
def retrieve_s3_object_contents(s3_obj, bucket=os.environ["ARTIFACTS_BUCKET"]):
"""Retrieve S3 object contents."""
return json.loads(
s3.get_object(Bucket=bucket, Key=s3_obj)["Body"].read().decode("utf-8")
) | 25,412 |
def test_molchoose_correct():
"""Tests that the correct data is returned from a trial csv document"""
test = [[1,'A01B01','A01','B01','6.5','OC(=O)[C@H](Cc1ccc(O)cc1)NS(=O)(=O)c2ccc(cc2)c3ccccc3',7,12,'>98','Gen-5']]
test_frame = pd.DataFrame(test, columns=['Index','Tag','atag','btag','pIC50_MMP12','Smiles... | 25,413 |
def substract_li(cfg, data, lats, lons, future_exp):
"""Difference between historical and future fields."""
pathlist = data.get_path_list(short_name='pr', exp='historical')
ar_diff_rain = np.zeros((len(lats), len(lons), len(pathlist)))
mism_diff_rain = np.zeros(len(pathlist))
mwp_hist_rain = np.zer... | 25,414 |
def identify_jobs_to_update(file_path, jobs):
"""identify jobs to update."""
name_map = {}
for job in jobs:
cluster = get_desired_cluster(file_path, job)
if cluster != job.get("cluster", ""):
name_map[job["name"]] = cluster
return name_map | 25,415 |
def clear():
"""
Clears the current Cytoscape session, if any.
"""
try:
requests.delete(rest.get_url('session')).ok
except requests.exceptions.ConnectionError:
print("Error: Connection refused: is Cytoscape started?")
raise | 25,416 |
def bootstrap_storage_bucket(project_id, bucket_name, google_credentials):
"""
Bootstrap the bucket used to store Terraform state for projects.
Args:
project_id:
The ID of the project to create the bucket in.
bucket_name:
The name of the bucket to create.
goo... | 25,417 |
def ValidateBucketForCertificateAuthority(bucket_name):
"""Validates that a user-specified bucket can be used with a Private CA.
Args:
bucket_name: The name of the GCS bucket to validate.
Returns:
A BucketReference wrapping the given bucket name.
Raises:
InvalidArgumentException: when the given b... | 25,418 |
def ingest(excel_file, db_name, table_name, db_type="pgsql", schema=None):
"""Ingest the file into the database table."""
logging.info(
f"file = {excel_file}, db = {db_name}, table = {table_name}, db type = {db_type}"
)
# Create database engine
db = db_provider.get(db_type)
engine = db.... | 25,419 |
def test_sumcovariancenormsmetric_compute_metric():
"""Test Sum of Covariance Norms compute metric."""
generator = SumofCovarianceNormsMetric()
time = datetime.datetime.now()
# Multiple tracks and truths present at two timesteps
tracks = {Track(states=[GaussianState(state_vector=[[1], [2], [1], [2... | 25,420 |
def write_csv_data(tsk, csv_data, filelabel, spc_array):
""" Write the csv data dictionary into the correct type of csv
or text file
"""
if 'freq' in tsk:
final_csv_data = {}
for key in csv_data['freq']:
final_csv_data[key] = csv_data['freq'][key]
if csv_data['sc... | 25,421 |
def login_with_invalid_username_and_valid_password(users, i, iterations=10):
"""Login with invalid username and valid password.
"""
with When(f"users try to login with invalid username and valid password #{i}"):
for i in range(iterations):
random_user = dict(users[random.randint(0, len(u... | 25,422 |
def save_sample(generator, saved_samples, batches_done, sample_path):
"""
Save a sample of generated images.
Args:
generator: The generator model.
saved_samples: The directory to save the sample images.
batches_done: The number of batches done.
sample_path: path where to sav... | 25,423 |
def load_train_val(seq_len, batch_size, dataset="hollywood2"):
"""
This returns two dataloaders correponding to the train and validation sets. Each
iterator yields tensors of shape (N, 3, L, H, W) where N is the batch size, L is
the sequence length, and H and W are the height and width of the frame.
... | 25,424 |
def SLC_burst_copy(SLC, SLC_par, TOPS_par, SLC_out, SLC_out_par, burst_num, drflg='-', SLC_par2='-', logpath=None):
"""
| Copy selected burst from Sentinel-1 TOPS SLC to a file
| Copyright 2014, Gamma Remote Sensing, v1.3 21-Oct-2014 awi/clw
Parameters
----------
SLC:
(input) Sentin... | 25,425 |
def update_to_v25(config_dict):
"""Major changes for V2.5:
- Option webpath is now station_url
- Drivers are now in their own package
- Introduction of the station registry
"""
major, minor = get_version_info(config_dict)
if major + minor >= '205':
return
try:
# webpa... | 25,426 |
def checkIfMeshId(projectPath, mesh, name, meshID):
"""Checks if exists another Object having the same name as the mesh
This function asks the user what to do.
If the object is not a mesh, gets all the children meshes
Args:
projectPath: a str with the path where the exported file wi... | 25,427 |
def initialize(repo_path):
"""Instance creation"""
global RepoExecs
RepoExecs = ExecutionsStorage(repo_path=repo_path) | 25,428 |
def read_params_file(config_path: str) -> json:
"""Read the and open the params.yaml file
Args:
config_path (str): yaml config file
Returns:
yaml: yaml file
"""
with open(config_path) as yaml_file:
config = yaml.safe_load(yaml_file)
return config | 25,429 |
def test_read_xml_files(tmp_path):
"""Test function `_read_xml_files`."""
from clinica.iotools.converters.adni_to_bids.adni_json import _read_xml_files
with pytest.raises(IndexError, match="No ADNI xml files"):
_read_xml_files()
xml_path = tmp_path / "xml_files"
xml_path.mkdir()
os.chdi... | 25,430 |
def fullmatch(regex, string, flags=0):
"""Emulate python-3.4 re.fullmatch()."""
matched = re.match(regex, string, flags=flags)
if matched and matched.span()[1] == len(string):
return matched
return None | 25,431 |
def html2text(html: str) -> str:
""" Change HTML to help torenizer and return text """
# Replace <br/> with PERIOD+NEW_LINE
html = re.sub(r'(\s*<br\s?\/\s*>)+', '. \n', html)
html = re.sub(r'<br\s?\/?>', '. \n', html)
html = re.sub(r'\s*(</?em>)\s*', r' \1 ', html)
html = re.sub(r'\s*(</?stron... | 25,432 |
def config_settings(event):
""" opens the configuration """
global PROMPTING
shell_telemetry.track_key('F1')
PROMPTING = True
config = azclishell.configuration.CONFIGURATION
answer = ""
questions = {
"Do you want command descriptions": "command_description",
"Do you want par... | 25,433 |
def set_dim(
fig: matplotlib.figure.Figure,
width: float = 398.3386,
fraction_of_line_width: float = 1,
ratio: float = (5 ** 0.5 - 1) / 2,
) -> None:
"""Set aesthetic figure dimensions to avoid scaling in latex.
Default width is `src.constants.REPORT_WIDTH`.
Default ratio is golden ratio, w... | 25,434 |
def _is_class(module: Any, member: Type, clazz: Type) -> bool:
"""
Validates if a module member is a class and an instance of a CoreService.
:param module: module to validate for service
:param member: member to validate for service
:param clazz: clazz type to check for validation
:return: True... | 25,435 |
def word_boundary(queries, count, degree, parallel=True, **kwargs):
"""
run augmentation on list of sentences
:param queries: sentences to augment
:type queries: list
:param count: number of output for each query
:type count: int
:param degree: degree of augmentation, takes value between 0 a... | 25,436 |
def myFunction(objectIn):
"""What you are supposed to test."""
return objectIn.aMethodToMock() + 2 | 25,437 |
def read_config(filename, section):
""" Reads a section from a .ini file and returns a dict object
"""
parser = ConfigParser()
parser.read(filename)
dic = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
dic[item[0]] = i... | 25,438 |
def get_training_set_count(disc):
"""Returns the total number of training sets of a discipline and all its
child elements.
:param disc: Discipline instance
:type disc: models.Discipline
:return: sum of training sets
:rtype: int
"""
training_set_counter = 0
for child in disc.get_desc... | 25,439 |
def _check_type(var, _type):
"""
Genie returns generally unuseful type errors from the rest api. This
function wraps an "isinstance() -> assert" call with a more helpful
message.
"""
if not isinstance(var, _type):
raise GenieError('Invalid type. Expected %s but got %s: %s', _type,
... | 25,440 |
def test_backends_mixins_history_mixin_clean_history(fs):
"""Tests the clean_history method of the HistoryMixin."""
# pylint: disable=invalid-name
history = HistoryMixin()
# Add history events
events = [
{"command": "foo"},
{"command": "bar"},
{"command": "foo"},
{"... | 25,441 |
def search_dir(path, dir_name, type):
"""Search directory in certain path"""
target_path = ""
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isdir(item_path):
if lambda_fun(dir_name, item, type):
target_path = item_path
... | 25,442 |
def lazy_import(module_name, callback=None):
"""Returns a proxy module object that will lazily import the given module the first
time it is used.
Example usage::
# Lazy version of `import tensorflow as tf`
tf = lazy_import("tensorflow")
# Other commands
# Now the module i... | 25,443 |
def _top_k(array, k):
"""Returns top k values and their indices along the last axis of the array.
This function serves the same purpose as jax.lax.top_k, but in a more XLA
friendly manner for TPUs:
(1) On TPUs, we use one-hot matrix multiplications to select the top k values.
This convoluted way of obtai... | 25,444 |
def time_to_accuracy(raw_metrics, tag, threshold):
"""Calculate the amount of time for accuracy to cross a given threshold.
Args:
raw_metrics: dict mapping TensorBoard tags to list of MetricPoint.
tag: string name of accuracy metric.
threshold: the desired model accuracy.
Returns:
float, amoun... | 25,445 |
def AddArguments(parser):
"""Adds command-line arguments for platform fields.
Args:
parser: argparser.ArgumentParser object.
"""
parser.add_argument(
'--os',
help=('For multi-platform manifest lists, specifies the operating '
'system.'))
parser.add_argument(
'--os-version',... | 25,446 |
def create_stencil(image_shape, smooth):
"""The stencil is a mask that will enable a smooth transition between blocks. blocks will be multiplied
by the stencil so that when they are blitted to the image, transition between them are smoothed out.
image 1: 1 1 1 1 1 1 1 , image 2: 2 2 2 2 2 2 2, stencil: .25 ... | 25,447 |
def evaluate_drivable(gt_dir: str, result_dir: str) -> None:
"""Evaluate drivable area."""
evaluate_segmentation(gt_dir, result_dir, 3, 17) | 25,448 |
def a_m_to_P(a, m):
"""Compute the orbital period given the semi-major axis and total mass.
Parameters
----------
{a}
{m}
"""
return 2*np.pi * np.sqrt(a**3 / (G * m)) | 25,449 |
def _async_attr_mapper(attr_name, val):
"""The `async` attribute works slightly different than the other bool
attributes. It can be set explicitly to `false` with no surrounding quotes
according to the spec."""
if val in [False, 'False']:
return ' {}=false'.format(attr_name)
elif val:
... | 25,450 |
def wrap(val: Any) -> Value:
"""Wraps the given native `val` as Protobuf `Value` message.
Supports converting collection/array of primitives types to `Value` message:
* numpy array of primitives.
* list of primitives.
* generator of finite no. of primitives.
Generally, wrapping only supports w... | 25,451 |
def to_transform_msg(transform):
"""Convert a `Transform` object to a Transform message."""
msg = geometry_msgs.msg.Transform()
msg.translation = to_vector3_msg(transform.translation)
msg.rotation = to_quat_msg(transform.rotation)
return msg | 25,452 |
def print_pos_neg(num):
"""Print if positive or negative in polarity level
>>> print_pos_neg(0.8)
'positive'
>>> print_pos_neg(-0.5)
'negative'
"""
if num > 0:
return "positive"
elif num == 0:
return "neutral"
else:
return "negative" | 25,453 |
def delete_volume_op(name: str, namespace: str):
"""
Creates a kfp.dsl.ContainerOp that deletes a volume (Kubernetes Resource).
Parameters
----------
name : str
namespace : str
Returns
-------
kfp.dsl.ContainerOp
"""
kind = "PersistentVolumeClaim"
return kubernetes_resour... | 25,454 |
def distal(combo):
""" Returns the distal subspecies from a combo
:param combo: int representation of origin combination
:return: int representation of the distal origin
>>> distal(combine(CAS, DOM)) == DOM
True
"""
return combo & _DISTAL_MASK | 25,455 |
def get_eval_dataset(files, ftDict, axes = [2], splits = None, one_hot = None, moments = None, **kwargs):
"""
Get the preprocessed evaluation dataset
Args:
files (list): list of tfrecords to be used for evaluation
Returns:
A tf.data.Dataset of evaluation data.
"""
dataset = get_dataset... | 25,456 |
async def test_ndim_array_indexes(dut):
"""Test getting and setting values of multi-dimensional array indexes."""
cocotb.start_soon(Clock(dut.clk, 1000, "ns").start())
dut.array_2d.value = [[0xF0, 0xE0, 0xD0, 0xC0], [0xB0, 0xA0, 0x90, 0x80]]
await Timer(1000, "ns")
# Check indices
_check_val... | 25,457 |
def connect_to_nr_of_measurements_stream(context, stream):
"""Get the number of measurements server-sent-events."""
context.sse_messages = []
for message in SSEClient(f"{context.base_api_url.format('')}/nr_measurements"): # pragma: no cover-behave
context.sse_messages.append(message)
if str... | 25,458 |
def test_scatter_nd_func_small_update(lock):
"""
Feature: ALL To ALL
Description: test cases for bool input of ScatterNdUpdate
Expectation: the result match to numpy implementation
"""
inputx = Tensor(np.array([True, False, True, False, True, True, False, True]), mstype.bool_)
indices = Tens... | 25,459 |
def getTopApSignals(slot_to_io):
""" HLS simulator requires that there is an ap_done at the top level """
# find which slot has the s_axi_control
for slot, io_list in slot_to_io.items():
if any('s_axi' in io[-1] for io in io_list):
# note the naming convention
ap_done_source = [f'{io[-1]}_in' fo... | 25,460 |
def get_line_style(image: Image = None) -> int:
"""
Get line style of the specified image.
The line style will be used when drawing lines or shape outlines.
:param image: the target image whose line style is to be gotten. None means it is the target image
(see set_target() and get_target())
... | 25,461 |
def make_polygon_for_earth(lat_bottom_left, lon_bottom_left, lat_top_right, lon_top_right):
"""
Divides the region into two separate regions (if needed) so as to handle the cases where the regions
cross the international date
:param lat_bottom_left: float (-90 to 90)
:param lon_bottom_left: float (... | 25,462 |
def train_coral(s_dataloaders, t_dataloaders, val_dataloader, test_dataloader, metric_name, seed, **kwargs):
"""
:param s_dataloaders:
:param t_dataloaders:
:param kwargs:
:return:
"""
s_train_dataloader = s_dataloaders
t_train_dataloader = t_dataloaders
autoencoder = AE(input_dim=... | 25,463 |
def first_nonzero_coordinate(data, start_point, end_point):
"""Coordinate of the first nonzero element between start and end points.
Parameters
----------
data : nD array, shape (N1, N2, ..., ND)
A data volume.
start_point : array, shape (D,)
The start coordinate to check.
end_p... | 25,464 |
def l1_distance(prediction, ground_truth):
"""L1 distance difference between two vectors."""
if prediction.shape != ground_truth.shape:
prediction, ground_truth = np.squeeze(prediction), np.squeeze(ground_truth)
min_length = min(prediction.size, ground_truth.size)
return np.abs(prediction[:min_length] - gro... | 25,465 |
def decode(match_id: str) -> Match:
"""Decode a match ID and return a Match.
>>> decode("QYkqASAAIAAA")
Match(cube_value=2, cube_holder=<Player.ZERO: 0>, player=<Player.ONE: 1>, crawford=False, game_state=<GameState.PLAYING: 1>, turn=<Player.ONE: 1>, double=False, resign=<Resign.NONE: 0>, dice=(5, 2), leng... | 25,466 |
def _valid_proto_paths(transitive_proto_path):
"""Build a list of valid paths to build the --proto_path arguments for the ScalaPB protobuf compiler
In particular, the '.' path needs to be stripped out. This mirrors a fix in the java proto rules:
https://github.com/bazelbuild/bazel/commit/af3605862047f7b553b... | 25,467 |
def update_stats_objecness(obj_stats, gt_bboxes, gt_labels, pred_bboxes, pred_labels, pred_scores, mask_eval=False,
affordance_stats=None, gt_masks=None, pred_masks=None, img_height=None, img_width=None, iou_thres=0.3):
"""
Updates statistics for object classification and affordance detecti... | 25,468 |
def load_schema(rel_path: str) -> Dict:
"""
Loads a schema from a relative path of the caller of this function.
:param rel_path: Relative path from the caller. e.g. ../schemas/schema.json
:return: Loaded schema as a `dict`.
"""
caller_path = Path((inspect.stack()[1])[1]).parent
fp = (caller_... | 25,469 |
def bquantize(x, nsd=3, abstol=eps, reltol=10 * eps):
"""Bidirectionally quantize a 1D vector ``x`` to ``nsd`` signed digits.
This method will terminate early if the error is less than the specified
tolerances.
The quantizer details are repeated here for the user's convenience:
The quantizer ... | 25,470 |
def timezone_keys(
*,
# allow_alias: bool = True,
# allow_deprecated: bool = True,
allow_prefix: bool = True,
) -> SearchStrategy[str]:
"""A strategy for :wikipedia:`IANA timezone names <List_of_tz_database_time_zones>`.
As well as timezone names like ``"UTC"``, ``"Australia/Sydney"``, or
`... | 25,471 |
def seg_to_bdry(seg, connectivity=1):
"""Given a borderless segmentation, return the boundary map."""
strel = generate_binary_structure(seg.ndim, connectivity)
return maximum_filter(seg, footprint=strel) != \
minimum_filter(seg, footprint=strel) | 25,472 |
def depthwise_conv2d(x, filters, strides, padding, data_format="NHWC", dilations=1):
"""Computes a 2-D depthwise convolution given 4-D input x and filters arrays.
Parameters
----------
x
Input image *[batch_size,h,w,d]*.
filters
Convolution filters *[fh,fw,d]*.
strides
T... | 25,473 |
def OUTA():
"""
The OUTA Operation
"""
control_signal = gen_control_signal_dict()
opcode_addr = gen_opcode_addr_component_dict()
mc_step_addr = gen_microcode_step_addr_component_dict()
input_sig_addr = gen_input_signal_addr_component_dict()
templates = []
# Step 2 - A -> OUT
a... | 25,474 |
def test_fit_returns_self(estimator_instance):
"""Check that fit returns self."""
estimator = estimator_instance
fit_args = _make_args(estimator, "fit")
assert (
estimator.fit(*fit_args) is estimator
), f"Estimator: {estimator} does not return self when calling fit" | 25,475 |
def incidence_matrices(G, V, E, faces, edge_to_idx):
"""
Returns incidence matrices B1 and B2
:param G: NetworkX DiGraph
:param V: list of nodes
:param E: list of edges
:param faces: list of faces in G
Returns B1 (|V| x |E|) and B2 (|E| x |faces|)
B1[i][j]: -1 if node i is tail of edge... | 25,476 |
def get_hosts_ram_total(nova, hosts):
"""Get total RAM (free+used) of hosts.
:param nova: A Nova client
:type nova: *
:param hosts: A set of hosts
:type hosts: list(str)
:return: A dictionary of (host, total_ram)
:rtype: dict(str: *)
"""
hosts_ram_total = dict() #dict of (host... | 25,477 |
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-ascii characters,
and converts spaces to hyphens. For use in urls and filenames
From Django's "django/template/defaultfilters.py".
"""
_slugify_strip_re = re.compile(r'[^\w\s-]')
_slugify_hyphenate_re = re.compil... | 25,478 |
def wpr(c_close, c_high, c_low, period):
"""
William %R
:type c_close: np.ndarray
:type c_high: np.ndarray
:type c_low: np.ndarray
:type period: int
:rtype: (np.ndarray, np.ndarray)
"""
size = len(c_close)
out = np.array([np.nan] * size)
for i in range(period - 1, ... | 25,479 |
def delete_action_log(request, log_id):
"""
View for delete the action log.
This view can only access by superuser and staff.
"""
action = get_object_or_404(ActionLog, id=log_id)
if action.status == 0 or action.status == 1:
messages.error(request, "Cannot delete the Action log that is r... | 25,480 |
def hsla_to_rgba(h, s, l, a):
""" 0 <= H < 360, 0 <= s,l,a < 1
"""
h = h % 360
s = max(0, min(1, s))
l = max(0, min(1, l))
a = max(0, min(1, a))
c = (1 - abs(2*l - 1)) * s
x = c * (1 - abs(h/60%2 - 1))
m = l - c/2
if h<60:
r, g, b = c, x, 0
elif h<120:
r, g,... | 25,481 |
def prioritize(paths: Dict[int, Path], purpose: str) -> Optional[Path]:
"""Returns highest-priority and existing filepath from ``paths``.
Finds existing configuration or data file in ``paths`` with highest
priority and returns it, otherwise returns ``None``.
"""
for key in sorted(paths.keys(), reve... | 25,482 |
def traverse(d, path):
"""Return the value at the given path from the given nested dict/list"""
for k in path.split('.'):
if k.isdigit():
k = int(k)
d = d[k]
return d | 25,483 |
def _bundle_name_with_extension(ctx):
"""Returns the name of the bundle with its extension.
Args:
ctx: The Skylark context.
Returns:
The bundle name with its extension.
"""
return _bundle_name(ctx) + _bundle_extension(ctx) | 25,484 |
def test_qt_api_ini_config(testdir, monkeypatch, option_api):
"""
Test qt_api ini option handling.
"""
from pytestqt.qt_compat import qt_api
monkeypatch.delenv("PYTEST_QT_API")
testdir.makeini("""
[pytest]
qt_api={option_api}
""".format(option_api=option_api))
testdir.... | 25,485 |
def call(args):
"""
Call args in a subprocess and display output on the fly.
Return or raise stdout, stderr, returncode
"""
if TRACE: print('Calling:', ' '.join(args))
with subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding='utf-8'
... | 25,486 |
def main():
"""Executa o simulador."""
print("\n------------------------- SIMULADOR -------------------------\n")
custo_max = round(
float(
input(
"""Qual é o custo máximo que você está
disposto a pagar?
::: R$"""
)
)
)
print()
custo_ = flo... | 25,487 |
def cvt_axisang_t_o2i(axisang, trans):
"""-correction: t_r, R_rt_r. outer to inner"""
trans -= get_offset(axisang)
return axisang, trans | 25,488 |
def test_valkeep_without_columns():
"""Testing the ColDrop pipeline stage."""
df = pd.DataFrame([[1, 4], [4, 5], [5, 11]], [1, 2, 3], ['a', 'b'])
res_df = ValKeep([4, 5]).apply(df)
assert 1 not in res_df.index
assert 2 in res_df.index
assert 3 not in res_df.index | 25,489 |
def processData(dict, valuename, timename='Aika', multiplier=1.0):
"""Process "raw" OData dict and strip only the time and value.
Also convert time to UTC and hydrodynamics model (COHERENS) format.
Parameters
----------
dict: dictionary
Data dictionary as received from OData fetcher
valuename:... | 25,490 |
def get_current_year():
"""Returns current year
"""
return str(datetime.date.today().year) | 25,491 |
def test_dict_init():
"""
Tests Config.__init__() using input of dictionary type.
For inner structure check Config.flatten() is used.
"""
#Slashed-structured dictionary initialization
init_dict = {'a' : 1, 'b/c' : 2, 'b/d' : 3}
exp_flat = {'a': 1, 'b/c': 2, 'b/d': 3}
config = Config(ini... | 25,492 |
def parse_ans(text):
"""
Parses the given text as an answer set, i.e., a sequence of predicate
statements. Returns a (possibly empty) tuple of Predicate objects.
"""
return parser.parse_completely(
text,
parser.Rep(PredicateStatement),
devour=devour_asp
) | 25,493 |
def get_xyz(data):
"""
:param data: 3D data
:return: 3D data coordinates
第1,2,3维数字依次递增
"""
nim = data.ndim
if nim == 3:
size_x, size_y, size_z = data.shape
x_arange = np.arange(1, size_x+1)
y_arange = np.arange(1, size_y+1)
z_arange = np.arange(1, s... | 25,494 |
async def test_hls_stream(hass, hass_client):
"""
Test hls stream.
Purposefully not mocking anything here to test full
integration with the stream component.
"""
await async_setup_component(hass, "stream", {"stream": {}})
# Setup demo HLS track
source = generate_h264_video()
stream... | 25,495 |
def test_zip_exception_03():
"""
Test zip: zip with tuple of 1 dataset
"""
logger.info("test_zip_exception_03")
data1 = ds.TFRecordDataset(DATA_DIR_1, SCHEMA_DIR_1)
try:
dataz = ds.zip((data1))
dataz = dataz.repeat(2)
num_iter = 0
for _, item in enumerate(dataz.... | 25,496 |
def wc_proximal_gradient(L, mu, gamma, n, verbose=1):
"""
Consider the composite convex minimization problem
.. math:: F_\\star \\triangleq \\min_x \\{F(x) \\equiv f_1(x) + f_2(x)\\},
where :math:`f_1` is :math:`L`-smooth and :math:`\\mu`-strongly convex,
and where :math:`f_2` is closed convex and... | 25,497 |
def basic_output_filter(
filtered_prefixes=None,
filtered_patterns=None,
):
"""
Create a line filtering function to help output testing.
:param filtered_prefixes: A list of byte strings representing prefixes that will cause
output lines to be ignored if they start with one of the prefixes. By d... | 25,498 |
def all_asset_types_for_shot(shot, client=default):
"""
Args:
shot (str / dict): The shot dict or the shot ID.
Returns:
list: Asset types from assets casted in given shot.
"""
path = "shots/%s/asset-types" % shot["id"]
return sort_by_name(raw.fetch_all(path, client=client)) | 25,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.