text
stringlengths 5
22M
| id
stringlengths 12
177
| metadata
dict | __index_level_0__
int64 0
1.37k
|
---|---|---|---|
<jupyter_start><jupyter_text>ResultsThis notebook can be used to visualize the results stored in your Azure status table.<jupyter_code>%pip install bokeh
%pip install selenium
%pip install Pillow
from pathlib import Path
import os
import sys
import statistics
import json
from pandas.core.frame import DataFrame
import bokeh.io
from bokeh.resources import INLINE
bokeh.io.reset_output()
bokeh.io.output_notebook(INLINE)
sys.path += ['../util']
from pareto import calc_pareto_frontier
config=Path('..') / '..' / 'output' / 'scripts' / 'confs' / 'aml_search.yaml'
from archai.common.store import ArchaiStore
from archai.common.config import Config
config = Config(str(config))
aml_config = config['aml']
metric_key = config['training'].get('metric_key')
connection_str = aml_config['connection_str']
experiment_name = aml_config['experiment_name']
storage_account_name, storage_account_key = ArchaiStore.parse_connection_string(connection_str)
store = ArchaiStore(storage_account_name, storage_account_key, table_name=experiment_name)
complete = store.get_all_status_entities(status='complete')
print(f"loaded {len(complete)} entities")
import pandas as pd
import numpy as np
from bokeh.io import curdoc, export_png
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, HoverTool, Range1d
from bokeh.transform import linear_cmap
from bokeh.palettes import Viridis256
def scatter_plot(status, xkey, ykey, xlabel, ylabel, title, xlimit=None, ylimit=None, highlight_pareto=True):
points = []
max_iteration = 0
for e in status:
iteration = e['iteration'] if 'iteration' in e else 0
if iteration > max_iteration:
max_iteration = iteration
if xkey in e and ykey in e:
points += [[float(e[xkey]), float(e[ykey]), iteration]]
if len(points):
if highlight_pareto:
sorted, pareto = calc_pareto_frontier(points)
points = list(sorted)
pareto.reverse()
top_most = []
for i in pareto:
top_most += [points[i]]
del points[i]
for p in top_most:
points += [p]
labelled = []
for i, (x,y,iteration) in enumerate(points):
if highlight_pareto:
color = max_iteration + 3 if i >= len(points) - len(pareto) else iteration
else:
color = iteration
label = [f'{xlabel}: {x}, {ylabel}: {y}, iteration: {iteration}']
labelled += [[x, y, color, label]]
df = pd.DataFrame(labelled, columns=[xlabel, ylabel, 'iteration', 'label'])
source = ColumnDataSource(data=dict(x=df[xlabel], y=df[ylabel], iteration=df['iteration'],label=df['label']))
mapper = linear_cmap(field_name='iteration', palette=Viridis256 ,low=df['iteration'].min() ,high=df['iteration'].max())
curdoc().theme = 'dark_minimal'
p = figure(title=title,
width=800,
height=600)
p.background_fill_color = "black"
p.x_range = Range1d(*xlimit)
p.y_range = Range1d(*ylimit)
p.circle('x', 'y', color=mapper, source=source)
# add a hover tool to display tooltips
hover = HoverTool(tooltips=[
('Label', '@label')
])
p.add_tools(hover)
# add axis labels
p.xaxis.axis_label = xlabel
p.yaxis.axis_label = ylabel
# show the plot
show(p)
export_png(p, filename=f"{title}.png")
else:
print(f"No points found for {title}")
def get_iteration(entities, iteration, final_iteration_only = False):
result = []
count = 0
for e in entities:
if 'iteration' in e and iteration >= int(e['iteration']):
if final_iteration_only:
if 'final_val_iou' in e:
f = dict((k,e[k]) for k in e)
f['iteration'] += 1
f['val_iou'] = e['final_val_iou']
result += [e]
result += [f]
count += 1
else:
result += [e]
return result
def get_pareto_per_iteration(entities, max_iteration, xkey, ykey):
result = []
for i in range(1, max_iteration):
points = []
for e in entities:
iteration = e['iteration'] if 'iteration' in e else 0
if iteration == i:
if xkey in e and ykey in e:
points += [[float(e[xkey]), float(e[ykey]), e]]
if len(points):
sorted, pareto = calc_pareto_frontier(points)
for i in pareto:
x, y, e = sorted[i]
result += [e]
return result
range1 = [(0.001,0.017), (0.3,0.8)]
range2 = [(0, 0.30), (0.35, 0.80)]
# Set this to True to see only the pareto models after each iteration.
pareto_models_only = False
for i in range(20, 21):
status = get_iteration(complete, i)
filtered = status
if pareto_models_only:
filtered = get_pareto_per_iteration(status, i, 'mean', 'val_iou')
scatter_plot(filtered, 'mean', 'val_iou', 'Qualcomm Inference Time', 'Validation IOU', f'qualcomm iteration {i}', *range1, not pareto_models_only)
if pareto_models_only:
filtered = get_pareto_per_iteration(status, i, 'onnx_latency', 'val_iou')
scatter_plot(filtered, 'onnx_latency', 'val_iou', 'ONNX Inference Time', 'Validation IOU', f'onnx iteration {i}', *range2, not pareto_models_only)
# Create animating gif
from PIL import Image
images = []
for i in range(1,21):
img = Image.open(f'qualcomm iteration {i}.png')
images.append(img)
images[0].save('../images/animation.gif', save_all=True, append_images=images[1:], optimize=False, duration=300, loop=0)<jupyter_output><empty_output><jupyter_text>Full TrainingWhen the search is finished you can run `train_pareto.py` to fully train the final pareto models. The following shows the results of full training with 30 epochs, clearly this bumps up the accuracy considerably:<jupyter_code># No need to wait for all f1 scores to be 'complete', you can plot them as they appear.
complete = store.get_all_status_entities()
range1 = [(0.001,0.012), (0.5,0.95)]
range2 = [(0, 0.30), (0.35, 0.95)]
# take a look at the effect of full training on the pareto frontier
pareto_models_only = True
status = get_iteration(complete, 20, True)
filtered = get_pareto_per_iteration(status, 21, 'mean', 'val_iou')
scatter_plot(filtered, 'mean', 'val_iou', 'Qualcomm Inference Time', 'Validation IOU', f'full training', *range1, True)
filename = '../images/full_training.png'
if os.path.exists(filename):
os.unlink(filename)
os.rename('full training.png', '../images/full_training.png')<jupyter_output><empty_output><jupyter_text>Snapdragon ResultsThe following plot shows the F1 accuracy scores measured on Qualcomm hardware on the fully trained models with error lines on the inference times. This is showing the result of running `snp_test.py` after running `train_pareto.py` to fully train the final pareto models.<jupyter_code>from bokeh.models import TapTool, CustomJS, Div
width = 800
height = 800
def min_max(ys, miny=None, maxy=None):
for y in ys:
if miny is None or y < miny:
miny = y
if maxy is None or y > maxy:
maxy = y
return [miny, maxy]
def error_lines(source, tip_delta = 0):
err_xs = []
err_ys = []
xmins = source['xmins']
xmaxs = source['xmaxs']
original_colors = source['colors']
ys = source['ys']
if len(ys) == 0:
return [err_xs, err_ys]
names = list(source['names'])
colors = []
for name in names:
i = names.index(name)
c = original_colors[i]
y = ys[i]
x1 = xmins[i]
x2 = xmaxs[i]
err_xs.append((x1, x2))
err_ys.append((y, y))
colors += [c]
if tip_delta:
colors += [c]
err_xs.append((x1, x1))
err_ys.append((y-tip_delta, y+tip_delta))
colors += [c]
err_xs.append((x2, x2))
err_ys.append((y-tip_delta, y+tip_delta))
return [err_xs, err_ys, colors]
def scatter_plot_with_errors(source, title, filename):
hover = HoverTool(tooltips=[
('name', '@names'),
('score', '@ys'),
('inference (μs)', '@xs ± @stdev')
])
div = Div(name="tap_input", text='')
show(div)
callback = CustomJS(args={"div": div}, code="""
var tap_label_id = div.id
var index = cb_data.source.selected.indices
if (index != 'undefined' && index.length > 0) {
var selection = cb_data.source.selected.indices[0]
var data = cb_data.source.data
if ('' + data.names != 'undefined' && selection < data.names.length){
var model_id = data.names[selection]
div = $('div [data-root-id="' + tap_label_id + '"]');
div[0].innerHTML = "<div style='font-size: 16pt;padding: 5pt'>" + model_id + "</div>"
}
}
""")
taptool = TapTool(callback=callback)
curdoc().theme = 'dark_minimal'
p = figure(height=height, width=width, title=title, tools=[hover, taptool])
p.background_fill_color = "black"
ymin, ymax = min_max(source['ys'])
range = (ymax - ymin)
tip_delta = 2 * range / height
# plot them
a = p.circle('xs', 'ys', source=source, color='colors', size=5)
err_xs, err_ys, colors = error_lines(source, tip_delta)
p.multi_line(err_xs, err_ys, color=colors, line_width=1)
p.xaxis.axis_label = 'inference time (milliseconds)'
p.yaxis.axis_label = 'accuracy (f1)'
p.hover.renderers = [a]
show(p)
export_png(p, filename=filename)
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
def plot_f1_scores(entities, filename):
series = Struct(**dict(xs = [], xmins=[], xmaxs=[], stdev=[], ys=[], names=[], colors=[]))
points = []
index = 0
for e in entities:
name = e['name']
y = 0
if 'f1_10k' in e:
y = float(e['f1_10k'])
elif 'f1_1k' in e:
y = float(e['f1_1k'])
else:
continue
xmin = 0
xmax = 0
stdev = 0
x = 0
x_label = 'total_inference_avg'
if x_label in e:
avgs = json.loads(e[x_label])
avgs = [x * 1000 for x in avgs] # convert to milliseconds
x = statistics.mean(avgs)
stdev = statistics.stdev(avgs)
xmin = x - stdev
xmax = x + stdev
if x == 0:
continue
if y > 0.5:
series.xs += [x]
series.xmins += [xmin]
series.xmaxs += [xmax]
series.stdev += [stdev]
series.ys += [y]
series.names += [name]
series.colors += ['gray']
points += [[x,y,index]]
index += 1
if len(series.ys) == 0:
print("No rows found with f1_1k or f1_10k scores")
else:
# change models off the pareto to crimson.
sorted, pareto = calc_pareto_frontier(points)
# pareto = [int(x[2]) for x in sorted]
for i in pareto:
j = int(sorted[i][2])
series.colors[j] = 'limegreen'
source = DataFrame(series.__dict__)
scatter_plot_with_errors(source, 'Accuracy vs Inference Time', filename)
plot_f1_scores(complete, "../images/final_results.png")
# tap a dot so you can copy the model name from text on the page.<jupyter_output><empty_output>
|
archai/tasks/face_segmentation/aml/notebooks/results.ipynb/0
|
{
"file_path": "archai/tasks/face_segmentation/aml/notebooks/results.ipynb",
"repo_id": "archai",
"token_count": 5438
}
| 343 |
## AML Training Readme
Two scripts in this folder provide Azure ML training pipelines to the Archai Search.
The [train.py](../../train.py) script plugs in the `AmlPartialTrainingEvaluator`
async model evaluator when invoked with the [aml_search.yaml](../../confs/aml_search.yaml) configuration.
The top level [aml.py](../../aml.py) script kicks off this process setting up all the
required Azure ML resources including:
- a conda environment used to build the docker image that Azure ML uses
- a cpu cluster for running the search
- a gpu cluster for running partial training
- the datastore for the training dataset
- the datastore for downloading config info and uploading results, including the trained models
Notice that the [aml_search.yaml](../../confs/aml_search.yaml) configuration
file requires the following environment variables be defined so that it can find your Azure subscription,
and Azure ML resource group and workspace, it also needs the connection string for your storage account.
```yaml
aml:
connection_str: ${MODEL_STORAGE_CONNECTION_STRING}
subscription_id: ${AZURE_SUBSCRIPTION_ID}
resource_group: ${AML_RESOURCE_GROUP}
workspace_name: ${AML_WORKSPACE_NAME}
```
The storage account can be created using the [setup.ps1](../docker/quantizer/setup.ps1) powershell script
which uses the [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli).
[aml_training_evaluator](aml_training_evaluator.py) provides a class named
`AmlPartialTrainingEvaluator` which is an `AsyncModelEvaluator` that creates a new Azure ML Pipeline
for partial training each new batch of models provided by the Archai Search algorithm. It runs these partial
training jobs on a GPU cluster to maximize throughput.
[training_pipeline](training_pipeline.py) provides a helper function named `start_training_pipeline`
that uses the Azure ML Python SDK to create the Azure ML training pipeline.
As the search progresses and training is completed you will find the following files in your
Azure storage account:

The name of this folder is the model id, `id_113c4c240bfc5fd2eaf2f0129439251bb754ddc4` which can also
be found in your Azure storage table. The parent folder `facesynthetics` is the `experiment name` and is also
the name of your Azure storage table. This table contains the overall summary for all the models processed so far.
You can see here that Qualcomm Snapdragon processing was also done on this model, so you see the [.dlc
files](https://developer.qualcomm.com/sites/default/files/docs/snpe/overview.html) there for the model and for the
quantized version of the model and a `.csv` file containing information about inference times for this model (including
layer by layer information which is handy).
The json file contains the `ArchConfig` for the model which can be used to recreate the model
and fully train it using the [train.py](../../train.py) script.
|
archai/tasks/face_segmentation/aml/training/readme.md/0
|
{
"file_path": "archai/tasks/face_segmentation/aml/training/readme.md",
"repo_id": "archai",
"token_count": 789
}
| 344 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import argparse
import os
from archai.datasets.cv.face_synthetics import FaceSyntheticsDatasetProvider
def main():
""" This script downloads the Face Synthetics dataset to the specified folder. """
# input and output arguments
print("Starting prep_data_store...")
parser = argparse.ArgumentParser()
parser.add_argument("--path", type=str, help="root folder to place the downloaded dataset.")
args = parser.parse_args()
path = args.path
print(f'Writing Face Synthetics dataset to: {path}')
if not path or not os.path.exists(path):
raise ValueError(f'Missing path: {path}')
provider = FaceSyntheticsDatasetProvider(dataset_dir=path)
# now force the full download to happen to that root folder.
provider.get_train_dataset()
provider.get_val_dataset()
provider.get_test_dataset()
if __name__ == "__main__":
main()
|
archai/tasks/face_segmentation/data_prep/prep_data_store.py/0
|
{
"file_path": "archai/tasks/face_segmentation/data_prep/prep_data_store.py",
"repo_id": "archai",
"token_count": 315
}
| 345 |
# Facial Landmarks
This project demonstrates the use of Archai to search neural architectures for facial landmarks localization that satisfy the specified objectives, namely, models that minimize the validation error and the inference latency. We follow the general methodology described in the papers [1] and [2], which use a synthetic face dataset and MobileNet V2 as the starting backbone.
## Download the Dataset
The synthetic face dataset can be downloaded from the [FaceSynthetics repository](https://github.com/microsoft/FaceSynthetics).
## Search Space
The search space for this example is based on MobileNetV2 [3], which is a popular architecture for efficient neural networks. The search space includes parameters such as width and depth multipliers, which are commonly used to control the overall size of the models. Additionally, the search space includes parameters such as kernel size "k", expansion ratio "e", and repeatness "r", which allow for fine-grained control of the size of each stage of the model. By searching over this space, Neural Architecture Search is able to find a model structure that is both efficient and effective for the task at hand, while also removing any unnecessary complexity in each stage of the model.
## Perform Neural Architecture Search
The default parameters in the `search_config.yaml` file search models with 1/10 of the dataset and 30 epochs. These parameters can be adjusted to suit different needs.
To perform the neural architecture search, run the following command:
```bash
python search.py --config search_config.yaml --output_dir . --data_dir face_synthetics/dataset_100000
```
Note that the paths need to be modified to match what is on your system.
## Results
At the end of the search job, the following graph is generated:

The search also produces a CSV file (search-results-[date]-[time].csv) containing more details of the search results. An example of this file is included in this repository (search_results.csv).
# Training of Pareto models
To train a particular architecture identified by its ID (e.g., 58626d23) using the entire dataset and more epochs, run the following command:
```bash
torchrun --nproc_per_node=4 train.py --data-path $data_dir --output_dir $output_dir --nas_search_archid $arch_id --search_result_csv $csv_file \
--train-crop-size 128 --epochs 100 \
--batch-size 32 --lr 0.001 --opt adamw --lr-scheduler steplr --lr-step-size 100 --lr-gamma 0.5 -wd 0.00001
```
Note that this command assumes that there are 4 GPUs available.
You can also use the script train_candidate_models.py to train all models on the Pareto frontier. Note the parameters in train_candidate_models.py need to be modified to match what is on your system.
To train all models on the Pareto frontier, run the following command:
```bash
python train_candidate_models.py
```
Note that this script assumes that the search results CSV file (search_results.csv) is located in the same directory as the script. If the CSV file is located elsewhere, you can modify the csv_file variable in the script to point to the correct location.
The trained models will be saved in the models directory. You can modify the output_dir variable in the script to specify a different output directory if desired.
## Results
The training using the parameters in train_candidate_models.py produces another CSV file (search_results_with_full_validation_error.csv) with validation error data added from the training. The following graph is produced with such data:

## Quantization Aware Training
To perform QAT on a selected model, use the --qat option which utilizes the quantizable version of the model to perform the training.
If needed for higher accuracy, use the --qat_skip_layers <# of layers> to partially quantize the model with specified number of layers, from the bottom, left in floating point.
```bash
torchrun --nproc_per_node=4 train.py --data-path $data_dir --output_dir $output_dir --search_result_archid $arch_id --search_result_csv $csv \
--train-crop-size 128 --epochs 100 \
--batch-size 32 --lr 0.001 --opt adamw --lr-scheduler steplr --lr-step-size 100 --lr-gamma 0.5 -wd 0.00001 --qat
```
### Results
Floating-point model test error : 0.0197
Quantized model test error : 0.0203
## References
[1] "3D Face Reconstruction with Dense Landmarks", Microsoft Research, 2018. https://www.microsoft.com/en-us/research/publication/3d-face-reconstruction-with-dense-landmarks/
[2] "FaceSynthetics: A High-Fidelity 3D Face Dataset for Benchmarking Face Reconstruction Algorithms", Microsoft Research, 2021. https://www.microsoft.com/en-us/research/uploads/prod/2021/10/ICCV_2021_FaceSynthetics.pdf
[3] "MobileNetV2: Inverted Residuals and Linear Bottlenecks", Mark Sandler etal, 2018, https://arxiv.org/abs/1801.04381
|
archai/tasks/facial_landmark_detection/README.md/0
|
{
"file_path": "archai/tasks/facial_landmark_detection/README.md",
"repo_id": "archai",
"token_count": 1348
}
| 346 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import gc
import time
from archai.common.timing import MeasureBlockTime
def test_measure_block_time():
# Assert the basic functionality of the timer
with MeasureBlockTime("test_timer") as timer:
time.sleep(0.5)
elapsed_time = timer.elapsed
assert elapsed_time >= 0.45
# Assert if the garbage collector is disabled during the time measurement
with MeasureBlockTime("test_timer", disable_gc=True) as timer:
time.sleep(0.5)
elapsed_time = timer.elapsed
assert gc.isenabled() is False
assert elapsed_time >= 0.45
# Assert if the garbage collector is enabled after the time measurement
with MeasureBlockTime("test_timer", disable_gc=True) as timer:
time.sleep(0.5)
elapsed_time = timer.elapsed
assert gc.isenabled() is True
|
archai/tests/common/test_timing.py/0
|
{
"file_path": "archai/tests/common/test_timing.py",
"repo_id": "archai",
"token_count": 308
}
| 347 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
from typing import Optional
from random import Random
import pytest
from overrides import overrides
from archai.discrete_search.algos.evolution_pareto import EvolutionParetoSearch
from archai.discrete_search.api.search_objectives import SearchObjectives
from archai.discrete_search.api.archai_model import ArchaiModel
from archai.discrete_search.api.model_evaluator import ModelEvaluator
from archai.discrete_search.search_spaces.config import (
ArchParamTree, ConfigSearchSpace, DiscreteChoice,
)
class DummyEvaluator(ModelEvaluator):
def __init__(self, rng: Random):
self.dummy = True
self.rng = rng
@overrides
def evaluate(self, model: ArchaiModel, budget: Optional[float] = None) -> float:
return self.rng.random()
@pytest.fixture(scope="session")
def output_dir(tmp_path_factory):
return tmp_path_factory.mktemp("out")
@pytest.fixture
def tree_c2():
c = {
'p1': DiscreteChoice(list([False, True])),
'p2': DiscreteChoice(list([False, True]))
}
return c
def test_evolution_pareto(output_dir, search_space, search_objectives):
cache = []
for _ in range(2):
algo = EvolutionParetoSearch(search_space, search_objectives, output_dir, num_iters=3, init_num_models=5, seed=42)
search_space.rng = algo.rng
search_results = algo.search()
assert len(os.listdir(output_dir)) > 0
df = search_results.get_search_state_df()
assert all(0 <= x <= 0.4 for x in df["Random1"].tolist())
all_models = [m for iter_r in search_results.results for m in iter_r["models"]]
# Checks if all registered models satisfy constraints
_, valid_models = search_objectives.validate_constraints(all_models)
assert len(valid_models) == len(all_models)
cache += [[m.archid for m in all_models]]
# make sure the archid's returned are repeatable so that search jobs can be restartable.
assert cache[0] == cache[1]
def test_evolution_pareto_tree_search(output_dir, tree_c2):
tree = ArchParamTree(tree_c2)
def use_arch(c):
if c.pick('p1'):
return
if c.pick('p2'):
return
seed = 42
cache = []
for _ in range(2):
search_objectives = SearchObjectives()
search_objectives.add_objective(
'Dummy',
DummyEvaluator(Random(seed)),
higher_is_better=False,
compute_intensive=False)
search_space = ConfigSearchSpace(use_arch, tree, seed=seed)
algo = EvolutionParetoSearch(search_space, search_objectives, output_dir, num_iters=3, init_num_models=5, seed=seed, save_pareto_model_weights=False)
search_results = algo.search()
assert len(os.listdir(output_dir)) > 0
all_models = [m for iter_r in search_results.results for m in iter_r["models"]]
cache += [[m.archid for m in all_models]]
# make sure the archid's returned are repeatable so that search jobs can be restartable.
assert cache[0] == cache[1]
|
archai/tests/discrete_search/algos/test_evolution_pareto.py/0
|
{
"file_path": "archai/tests/discrete_search/algos/test_evolution_pareto.py",
"repo_id": "archai",
"token_count": 1235
}
| 348 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import pytest
import torch
from archai.discrete_search.evaluators.pt_profiler import (
TorchFlops,
TorchLatency,
TorchMacs,
TorchNumParameters,
TorchPeakCpuMemory,
TorchPeakCudaMemory,
)
from archai.discrete_search.search_spaces.nlp.transformer_flex.search_space import (
TransformerFlexSearchSpace,
)
@pytest.fixture
def search_space():
return TransformerFlexSearchSpace("gpt2")
@pytest.fixture
def models(search_space):
return [search_space.random_sample() for _ in range(5)]
@pytest.fixture
def sample_input():
return torch.zeros(1, 1, 192, dtype=torch.long)
def test_torch_num_params(models):
torch_num_params = TorchNumParameters()
num_params = [torch_num_params.evaluate(model) for model in models]
assert all(p > 0 for p in num_params)
torch_num_params2 = TorchNumParameters(exclude_cls=[torch.nn.BatchNorm2d])
num_params2 = [torch_num_params2.evaluate(model) for model in models]
assert all(p > 0 for p in num_params2)
torch_num_params3 = TorchNumParameters(exclude_cls=[torch.nn.BatchNorm2d], trainable_only=False)
num_params3 = [torch_num_params3.evaluate(model) for model in models]
assert all(p > 0 for p in num_params3)
def test_torch_flops(models, sample_input):
torch_flops = TorchFlops(forward_args=sample_input)
flops = [torch_flops.evaluate(model) for model in models]
assert all(f > 0 for f in flops)
def test_torch_macs(models, sample_input):
torch_macs = TorchMacs(forward_args=sample_input)
macs = [torch_macs.evaluate(model) for model in models]
assert all(m > 0 for m in macs)
def test_torch_latency(models, sample_input):
torch_latency = TorchLatency(forward_args=sample_input, num_warmups=2, num_samples=2)
latency = [torch_latency.evaluate(model) for model in models]
assert all(lt > 0 for lt in latency)
torch_latency2 = TorchLatency(forward_args=sample_input, num_warmups=0, num_samples=3, use_median=True)
latency2 = [torch_latency2.evaluate(model) for model in models]
assert all(lt > 0 for lt in latency2)
def test_torch_peak_cuda_memory(models, sample_input):
if torch.cuda.is_available():
torch_peak_memory = TorchPeakCudaMemory(forward_args=sample_input)
peak_memory = [torch_peak_memory.evaluate(model) for model in models]
assert all(m > 0 for m in peak_memory)
def test_torch_peak_cpu_memory(models, sample_input):
torch_peak_memory = TorchPeakCpuMemory(forward_args=sample_input)
peak_memory = [torch_peak_memory.evaluate(model) for model in models]
assert all(m > 0 for m in peak_memory)
|
archai/tests/discrete_search/evaluators/test_pt_profiler.py/0
|
{
"file_path": "archai/tests/discrete_search/evaluators/test_pt_profiler.py",
"repo_id": "archai",
"token_count": 1008
}
| 349 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import types
import torch
from transformers import GPT2Config, GPT2LMHeadModel
from archai.common.file_utils import calculate_onnx_model_size
from archai.onnx.export import export_to_onnx
from archai.onnx.export_utils import prepare_model_for_onnx, weight_sharing
from archai.onnx.onnx_forward import gpt2_onnx_forward
def test_prepare_model_for_onnx():
# Assert that the forward function is replaced with `gpt2_onnx_forward`
# and that the `c_fc` and `c_proj` layers are replaced with `torch.nn.Linear`
model = GPT2LMHeadModel(config=GPT2Config(vocab_size=1, n_layer=1))
model = prepare_model_for_onnx(model, model_type="gpt2")
assert model.forward == types.MethodType(gpt2_onnx_forward, model)
assert isinstance(model.transformer.h[0].mlp.c_fc, torch.nn.Linear)
assert isinstance(model.transformer.h[0].mlp.c_proj, torch.nn.Linear)
def test_weight_sharing():
model = GPT2LMHeadModel(config=GPT2Config(vocab_size=1, n_layer=1))
onnx_model_path = "temp_model.onnx"
export_to_onnx(model, onnx_model_path, share_weights=False)
onnx_size = calculate_onnx_model_size(onnx_model_path)
# Assert that the embedding and softmax weights are shared in the ONNX model
weight_sharing(onnx_model_path, "gpt2")
onnx_size_shared_weights = calculate_onnx_model_size(onnx_model_path)
assert onnx_size_shared_weights < onnx_size
os.remove(onnx_model_path)
|
archai/tests/onnx/test_export_utils.py/0
|
{
"file_path": "archai/tests/onnx/test_export_utils.py",
"repo_id": "archai",
"token_count": 586
}
| 350 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import shutil
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from torch import nn
from torch.utils.data import DataLoader
from archai.datasets.cv.mnist_dataset_provider import MnistDatasetProvider
from archai.trainers.cv.pl_trainer import PlTrainer
class Model(pl.LightningModule):
def __init__(self):
super().__init__()
self.linear = nn.Linear(28 * 28, 10)
def forward(self, x):
return self.linear(x)
def training_step(self, batch, batch_idx):
x, y = batch
x = x.view(x.size(0), -1)
x_hat = self.linear(x)
loss = F.cross_entropy(x_hat, y)
self.log("train_loss", loss)
return loss
def test_step(self, batch, batch_idx):
x, y = batch
x = x.view(x.size(0), -1)
x_hat = self.linear(x)
loss = F.cross_entropy(x_hat, y)
self.log("val_loss", loss)
return loss
def predict_step(self, batch, batch_idx, dataloader_idx=0):
x, y = batch
x = x.view(x.size(0), -1)
return self(x)
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=1e-3)
return optimizer
def test_pl_trainer():
# make sure tests can run in parallel and not clobber each other's dataroot.
unique_data_root = 'test_pl_trainer_dataroot'
model = Model()
trainer = PlTrainer(max_steps=1, limit_train_batches=1, limit_test_batches=1, limit_predict_batches=1)
dataset_provider = MnistDatasetProvider(root=unique_data_root)
train_dataset = dataset_provider.get_train_dataset()
val_dataset = dataset_provider.get_val_dataset()
# Assert that the trainer correctly calls `train`, `evaluate` and `predict`
trainer.train(model, DataLoader(train_dataset))
trainer.evaluate(model, DataLoader(val_dataset))
trainer.predict(model, DataLoader(val_dataset))
shutil.rmtree(unique_data_root)
shutil.rmtree("lightning_logs")
|
archai/tests/trainers/cv/test_pl_trainer.py/0
|
{
"file_path": "archai/tests/trainers/cv/test_pl_trainer.py",
"repo_id": "archai",
"token_count": 862
}
| 351 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import base64
import json
import logging
import os
import time
try:
import collections.abc as collections
except ImportError:
import collections
logger = logging.getLogger(__name__)
class FileCache(collections.MutableMapping):
"""A simple dict-like class that is backed by a JSON file.
All direct modifications will save the file. Indirect modifications should
be followed by a call to `save_with_retry` or `save`.
"""
def __init__(self, file_name, max_age=0):
super(FileCache, self).__init__()
self.file_name = file_name
self.max_age = max_age
self.data = {}
self.initial_load_occurred = False
def load(self):
self.data = {}
try:
if os.path.isfile(self.file_name):
if self.max_age > 0 and os.stat(self.file_name).st_mtime + self.max_age < time.time():
logger.debug('Cache file expired: %s', self.file_name)
os.remove(self.file_name)
else:
logger.debug('Loading cache file: %s', self.file_name)
self.data = get_file_json(self.file_name, throw_on_empty=False) or {}
else:
logger.debug('Cache file does not exist: %s', self.file_name)
except Exception as ex:
logger.debug(ex, exc_info=True)
# file is missing or corrupt so attempt to delete it
try:
os.remove(self.file_name)
except Exception as ex2:
logger.debug(ex2, exc_info=True)
self.initial_load_occurred = True
def save(self):
self._check_for_initial_load()
self._save()
def _save(self):
if self.file_name:
with os.fdopen(os.open(self.file_name, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600), 'w+') as cred_file:
cred_file.write(json.dumps(self.data))
def save_with_retry(self, retries=5):
self._check_for_initial_load()
for _ in range(retries - 1):
try:
self.save()
break
except OSError:
time.sleep(0.1)
else:
self.save()
def clear(self):
if os.path.isfile(self.file_name):
logger.info("Deleting file: " + self.file_name)
os.remove(self.file_name)
else:
logger.info("File does not exist: " + self.file_name)
def get(self, key, default=None):
self._check_for_initial_load()
return self.data.get(key, default)
def __getitem__(self, key):
self._check_for_initial_load()
return self.data.setdefault(key, {})
def __setitem__(self, key, value):
self._check_for_initial_load()
self.data[key] = value
self.save_with_retry()
def __delitem__(self, key):
self._check_for_initial_load()
del self.data[key]
self.save_with_retry()
def __iter__(self):
self._check_for_initial_load()
return iter(self.data)
def __len__(self):
self._check_for_initial_load()
return len(self.data)
def _check_for_initial_load(self):
if not self.initial_load_occurred:
self.load()
def get_cache_dir():
azure_devops_cache_dir = os.getenv('AZURE_DEVOPS_CACHE_DIR', None)\
or os.path.expanduser(os.path.join('~', '.azure-devops', 'python-sdk', 'cache'))
if not os.path.exists(azure_devops_cache_dir):
try:
os.makedirs(azure_devops_cache_dir)
except OSError:
# https://github.com/microsoft/azure-devops-python-api/issues/354
# FileExistsError is not available in python 2.7
if not os.path.exists(azure_devops_cache_dir):
raise
return azure_devops_cache_dir
DEFAULT_MAX_AGE = 3600 * 12 # 12 hours
DEFAULT_CACHE_DIR = get_cache_dir()
def get_cache(name, max_age=DEFAULT_MAX_AGE, cache_dir=DEFAULT_CACHE_DIR):
file_name = os.path.join(cache_dir, name + '.json')
return FileCache(file_name, max_age)
OPTIONS_CACHE = get_cache('options')
RESOURCE_CACHE = get_cache('resources')
# Code below this point from azure-cli-core
# https://github.com/Azure/azure-cli/blob/master/src/azure-cli-core/azure/cli/core/util.py
def get_file_json(file_path, throw_on_empty=True, preserve_order=False):
content = read_file_content(file_path)
if not content and not throw_on_empty:
return None
return shell_safe_json_parse(content, preserve_order)
def read_file_content(file_path, allow_binary=False):
from codecs import open as codecs_open
# Note, always put 'utf-8-sig' first, so that BOM in WinOS won't cause trouble.
for encoding in ['utf-8-sig', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be']:
try:
with codecs_open(file_path, encoding=encoding) as f:
logger.debug("attempting to read file %s as %s", file_path, encoding)
return f.read()
except UnicodeDecodeError:
if allow_binary:
with open(file_path, 'rb') as input_file:
logger.debug("attempting to read file %s as binary", file_path)
return base64.b64encode(input_file.read()).decode("utf-8")
else:
raise
except UnicodeError:
pass
raise ValueError('Failed to decode file {} - unknown decoding'.format(file_path))
def shell_safe_json_parse(json_or_dict_string, preserve_order=False):
""" Allows the passing of JSON or Python dictionary strings. This is needed because certain
JSON strings in CMD shell are not received in main's argv. This allows the user to specify
the alternative notation, which does not have this problem (but is technically not JSON). """
try:
if not preserve_order:
return json.loads(json_or_dict_string)
from collections import OrderedDict
return json.loads(json_or_dict_string, object_pairs_hook=OrderedDict)
except ValueError:
import ast
return ast.literal_eval(json_or_dict_string)
|
azure-devops-python-api/azure-devops/azure/devops/_file_cache.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/_file_cache.py",
"repo_id": "azure-devops-python-api",
"token_count": 2826
}
| 352 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from ...v7_0.notification.models import *
from .notification_client import NotificationClient
__all__ = [
'ArtifactFilter',
'BaseSubscriptionFilter',
'BatchNotificationOperation',
'EventActor',
'EventScope',
'EventsEvaluationResult',
'EventTransformRequest',
'EventTransformResult',
'ExpressionFilterClause',
'ExpressionFilterGroup',
'ExpressionFilterModel',
'FieldInputValues',
'FieldValuesQuery',
'GraphSubjectBase',
'IdentityRef',
'INotificationDiagnosticLog',
'InputValue',
'InputValues',
'InputValuesError',
'InputValuesQuery',
'ISubscriptionFilter',
'ISubscriptionChannel',
'NotificationAdminSettings',
'NotificationAdminSettingsUpdateParameters',
'NotificationDiagnosticLogMessage',
'NotificationEventField',
'NotificationEventFieldOperator',
'NotificationEventFieldType',
'NotificationEventPublisher',
'NotificationEventRole',
'NotificationEventType',
'NotificationEventTypeCategory',
'NotificationQueryCondition',
'NotificationReason',
'NotificationsEvaluationResult',
'NotificationStatistic',
'NotificationStatisticsQuery',
'NotificationStatisticsQueryConditions',
'NotificationSubscriber',
'NotificationSubscriberUpdateParameters',
'NotificationSubscription',
'NotificationSubscriptionCreateParameters',
'NotificationSubscriptionTemplate',
'NotificationSubscriptionUpdateParameters',
'OperatorConstraint',
'ReferenceLinks',
'SubscriptionAdminSettings',
'SubscriptionDiagnostics',
'SubscriptionEvaluationRequest',
'SubscriptionEvaluationResult',
'SubscriptionEvaluationSettings',
'SubscriptionChannelWithAddress',
'SubscriptionManagement',
'SubscriptionQuery',
'SubscriptionQueryCondition',
'SubscriptionScope',
'SubscriptionTracing',
'SubscriptionUserSettings',
'UpdateSubscripitonDiagnosticsParameters',
'UpdateSubscripitonTracingParameters',
'ValueDefinition',
'VssNotificationEvent',
'NotificationClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/released/notification/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/released/notification/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 763
}
| 353 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class WorkItemTrackingProcessTemplateClient(Client):
"""WorkItemTrackingProcessTemplate
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(WorkItemTrackingProcessTemplateClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = '5264459e-e5e0-4bd8-b118-0985e68a4ec5'
def get_behavior(self, process_id, behavior_ref_name):
"""GetBehavior.
Returns a behavior for the process.
:param str process_id: The ID of the process
:param str behavior_ref_name: The reference name of the behavior
:rtype: :class:`<AdminBehavior> <azure.devops.v7_0.work_item_tracking_process_template.models.AdminBehavior>`
"""
route_values = {}
if process_id is not None:
route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
query_parameters = {}
if behavior_ref_name is not None:
query_parameters['behaviorRefName'] = self._serialize.query('behavior_ref_name', behavior_ref_name, 'str')
response = self._send(http_method='GET',
location_id='90bf9317-3571-487b-bc8c-a523ba0e05d7',
version='7.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('AdminBehavior', response)
def get_behaviors(self, process_id):
"""GetBehaviors.
Returns a list of behaviors for the process.
:param str process_id: The ID of the process
:rtype: [AdminBehavior]
"""
route_values = {}
if process_id is not None:
route_values['processId'] = self._serialize.url('process_id', process_id, 'str')
response = self._send(http_method='GET',
location_id='90bf9317-3571-487b-bc8c-a523ba0e05d7',
version='7.0',
route_values=route_values)
return self._deserialize('[AdminBehavior]', self._unwrap_collection(response))
def export_process_template(self, id, **kwargs):
"""ExportProcessTemplate.
Returns requested process template.
:param str id: The ID of the process
:rtype: object
"""
route_values = {}
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'str')
route_values['action'] = 'Export'
response = self._send(http_method='GET',
location_id='29e1f38d-9e9c-4358-86a5-cdf9896a5759',
version='7.0',
route_values=route_values,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def import_process_template(self, upload_stream, ignore_warnings=None, replace_existing_template=None, **kwargs):
"""ImportProcessTemplate.
Imports a process from zip file.
:param object upload_stream: Stream to upload
:param bool ignore_warnings: Ignores validation warnings. Default value is false.
:param bool replace_existing_template: Replaces the existing template. Default value is true.
:rtype: :class:`<ProcessImportResult> <azure.devops.v7_0.work_item_tracking_process_template.models.ProcessImportResult>`
"""
route_values = {}
route_values['action'] = 'Import'
query_parameters = {}
if ignore_warnings is not None:
query_parameters['ignoreWarnings'] = self._serialize.query('ignore_warnings', ignore_warnings, 'bool')
if replace_existing_template is not None:
query_parameters['replaceExistingTemplate'] = self._serialize.query('replace_existing_template', replace_existing_template, 'bool')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
content = self._client.stream_upload(upload_stream, callback=callback)
response = self._send(http_method='POST',
location_id='29e1f38d-9e9c-4358-86a5-cdf9896a5759',
version='7.0',
route_values=route_values,
query_parameters=query_parameters,
content=content,
media_type='application/octet-stream')
return self._deserialize('ProcessImportResult', response)
def import_process_template_status(self, id):
"""ImportProcessTemplateStatus.
Tells whether promote has completed for the specified promote job ID.
:param str id: The ID of the promote job operation
:rtype: :class:`<ProcessPromoteStatus> <azure.devops.v7_0.work_item_tracking_process_template.models.ProcessPromoteStatus>`
"""
route_values = {}
if id is not None:
route_values['id'] = self._serialize.url('id', id, 'str')
route_values['action'] = 'Status'
response = self._send(http_method='GET',
location_id='29e1f38d-9e9c-4358-86a5-cdf9896a5759',
version='7.0',
route_values=route_values)
return self._deserialize('ProcessPromoteStatus', response)
|
azure-devops-python-api/azure-devops/azure/devops/v7_0/work_item_tracking_process_template/work_item_tracking_process_template_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_0/work_item_tracking_process_template/work_item_tracking_process_template_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 2751
}
| 354 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class ElasticNode(Model):
"""
Data and settings for an elastic node
:param agent_id: Distributed Task's Agent Id
:type agent_id: int
:param agent_state: Summary of the state of the agent
:type agent_state: object
:param compute_id: Compute Id. VMSS's InstanceId
:type compute_id: str
:param compute_state: State of the compute host
:type compute_state: object
:param desired_state: Users can force state changes to specific states (ToReimage, ToDelete, Save)
:type desired_state: object
:param id: Unique identifier since the agent and/or VM may be null
:type id: int
:param name: Computer name. Used to match a scaleset VM with an agent
:type name: str
:param pool_id: Pool Id that this node belongs to
:type pool_id: int
:param request_id: Last job RequestId assigned to this agent
:type request_id: long
:param state: State of the ElasticNode
:type state: object
:param state_changed_on: Last state change. Only updated by SQL.
:type state_changed_on: datetime
"""
_attribute_map = {
'agent_id': {'key': 'agentId', 'type': 'int'},
'agent_state': {'key': 'agentState', 'type': 'object'},
'compute_id': {'key': 'computeId', 'type': 'str'},
'compute_state': {'key': 'computeState', 'type': 'object'},
'desired_state': {'key': 'desiredState', 'type': 'object'},
'id': {'key': 'id', 'type': 'int'},
'name': {'key': 'name', 'type': 'str'},
'pool_id': {'key': 'poolId', 'type': 'int'},
'request_id': {'key': 'requestId', 'type': 'long'},
'state': {'key': 'state', 'type': 'object'},
'state_changed_on': {'key': 'stateChangedOn', 'type': 'iso-8601'}
}
def __init__(self, agent_id=None, agent_state=None, compute_id=None, compute_state=None, desired_state=None, id=None, name=None, pool_id=None, request_id=None, state=None, state_changed_on=None):
super(ElasticNode, self).__init__()
self.agent_id = agent_id
self.agent_state = agent_state
self.compute_id = compute_id
self.compute_state = compute_state
self.desired_state = desired_state
self.id = id
self.name = name
self.pool_id = pool_id
self.request_id = request_id
self.state = state
self.state_changed_on = state_changed_on
class ElasticNodeSettings(Model):
"""
Class used for updating an elastic node where only certain members are populated
:param state: State of the ElasticNode
:type state: object
"""
_attribute_map = {
'state': {'key': 'state', 'type': 'object'}
}
def __init__(self, state=None):
super(ElasticNodeSettings, self).__init__()
self.state = state
class ElasticPool(Model):
"""
Data and settings for an elastic pool
:param agent_interactive_uI: Set whether agents should be configured to run with interactive UI
:type agent_interactive_uI: bool
:param azure_id: Azure string representing to location of the resource
:type azure_id: str
:param desired_idle: Number of agents to have ready waiting for jobs
:type desired_idle: int
:param desired_size: The desired size of the pool
:type desired_size: int
:param max_capacity: Maximum number of nodes that will exist in the elastic pool
:type max_capacity: int
:param max_saved_node_count: Keep nodes in the pool on failure for investigation
:type max_saved_node_count: int
:param offline_since: Timestamp the pool was first detected to be offline
:type offline_since: datetime
:param orchestration_type: Operating system type of the nodes in the pool
:type orchestration_type: object
:param os_type: Operating system type of the nodes in the pool
:type os_type: object
:param pool_id: Id of the associated TaskAgentPool
:type pool_id: int
:param recycle_after_each_use: Discard node after each job completes
:type recycle_after_each_use: bool
:param service_endpoint_id: Id of the Service Endpoint used to connect to Azure
:type service_endpoint_id: str
:param service_endpoint_scope: Scope the Service Endpoint belongs to
:type service_endpoint_scope: str
:param sizing_attempts: The number of sizing attempts executed while trying to achieve a desired size
:type sizing_attempts: int
:param state: State of the pool
:type state: object
:param time_to_live_minutes: The minimum time in minutes to keep idle agents alive
:type time_to_live_minutes: int
"""
_attribute_map = {
'agent_interactive_uI': {'key': 'agentInteractiveUI', 'type': 'bool'},
'azure_id': {'key': 'azureId', 'type': 'str'},
'desired_idle': {'key': 'desiredIdle', 'type': 'int'},
'desired_size': {'key': 'desiredSize', 'type': 'int'},
'max_capacity': {'key': 'maxCapacity', 'type': 'int'},
'max_saved_node_count': {'key': 'maxSavedNodeCount', 'type': 'int'},
'offline_since': {'key': 'offlineSince', 'type': 'iso-8601'},
'orchestration_type': {'key': 'orchestrationType', 'type': 'object'},
'os_type': {'key': 'osType', 'type': 'object'},
'pool_id': {'key': 'poolId', 'type': 'int'},
'recycle_after_each_use': {'key': 'recycleAfterEachUse', 'type': 'bool'},
'service_endpoint_id': {'key': 'serviceEndpointId', 'type': 'str'},
'service_endpoint_scope': {'key': 'serviceEndpointScope', 'type': 'str'},
'sizing_attempts': {'key': 'sizingAttempts', 'type': 'int'},
'state': {'key': 'state', 'type': 'object'},
'time_to_live_minutes': {'key': 'timeToLiveMinutes', 'type': 'int'}
}
def __init__(self, agent_interactive_uI=None, azure_id=None, desired_idle=None, desired_size=None, max_capacity=None, max_saved_node_count=None, offline_since=None, orchestration_type=None, os_type=None, pool_id=None, recycle_after_each_use=None, service_endpoint_id=None, service_endpoint_scope=None, sizing_attempts=None, state=None, time_to_live_minutes=None):
super(ElasticPool, self).__init__()
self.agent_interactive_uI = agent_interactive_uI
self.azure_id = azure_id
self.desired_idle = desired_idle
self.desired_size = desired_size
self.max_capacity = max_capacity
self.max_saved_node_count = max_saved_node_count
self.offline_since = offline_since
self.orchestration_type = orchestration_type
self.os_type = os_type
self.pool_id = pool_id
self.recycle_after_each_use = recycle_after_each_use
self.service_endpoint_id = service_endpoint_id
self.service_endpoint_scope = service_endpoint_scope
self.sizing_attempts = sizing_attempts
self.state = state
self.time_to_live_minutes = time_to_live_minutes
class ElasticPoolCreationResult(Model):
"""
Returned result from creating a new elastic pool
:param agent_pool: Created agent pool
:type agent_pool: :class:`TaskAgentPool <azure.devops.v7_1.elastic.models.TaskAgentPool>`
:param agent_queue: Created agent queue
:type agent_queue: :class:`TaskAgentQueue <azure.devops.v7_1.elastic.models.TaskAgentQueue>`
:param elastic_pool: Created elastic pool
:type elastic_pool: :class:`ElasticPool <azure.devops.v7_1.elastic.models.ElasticPool>`
"""
_attribute_map = {
'agent_pool': {'key': 'agentPool', 'type': 'TaskAgentPool'},
'agent_queue': {'key': 'agentQueue', 'type': 'TaskAgentQueue'},
'elastic_pool': {'key': 'elasticPool', 'type': 'ElasticPool'}
}
def __init__(self, agent_pool=None, agent_queue=None, elastic_pool=None):
super(ElasticPoolCreationResult, self).__init__()
self.agent_pool = agent_pool
self.agent_queue = agent_queue
self.elastic_pool = elastic_pool
class ElasticPoolLog(Model):
"""
Log data for an Elastic Pool
:param id: Log Id
:type id: long
:param level: E.g. error, warning, info
:type level: object
:param message: Log contents
:type message: str
:param operation: Operation that triggered the message being logged
:type operation: object
:param pool_id: Id of the associated TaskAgentPool
:type pool_id: int
:param timestamp: Datetime that the log occurred
:type timestamp: datetime
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'long'},
'level': {'key': 'level', 'type': 'object'},
'message': {'key': 'message', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'object'},
'pool_id': {'key': 'poolId', 'type': 'int'},
'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}
}
def __init__(self, id=None, level=None, message=None, operation=None, pool_id=None, timestamp=None):
super(ElasticPoolLog, self).__init__()
self.id = id
self.level = level
self.message = message
self.operation = operation
self.pool_id = pool_id
self.timestamp = timestamp
class ElasticPoolSettings(Model):
"""
Class used for updating an elastic pool where only certain members are populated
:param agent_interactive_uI: Set whether agents should be configured to run with interactive UI
:type agent_interactive_uI: bool
:param azure_id: Azure string representing to location of the resource
:type azure_id: str
:param desired_idle: Number of machines to have ready waiting for jobs
:type desired_idle: int
:param max_capacity: Maximum number of machines that will exist in the elastic pool
:type max_capacity: int
:param max_saved_node_count: Keep machines in the pool on failure for investigation
:type max_saved_node_count: int
:param orchestration_type: Operating system type of the machines in the pool
:type orchestration_type: object
:param os_type: Operating system type of the machines in the pool
:type os_type: object
:param recycle_after_each_use: Discard machines after each job completes
:type recycle_after_each_use: bool
:param service_endpoint_id: Id of the Service Endpoint used to connect to Azure
:type service_endpoint_id: str
:param service_endpoint_scope: Scope the Service Endpoint belongs to
:type service_endpoint_scope: str
:param time_to_live_minutes: The minimum time in minutes to keep idle agents alive
:type time_to_live_minutes: int
"""
_attribute_map = {
'agent_interactive_uI': {'key': 'agentInteractiveUI', 'type': 'bool'},
'azure_id': {'key': 'azureId', 'type': 'str'},
'desired_idle': {'key': 'desiredIdle', 'type': 'int'},
'max_capacity': {'key': 'maxCapacity', 'type': 'int'},
'max_saved_node_count': {'key': 'maxSavedNodeCount', 'type': 'int'},
'orchestration_type': {'key': 'orchestrationType', 'type': 'object'},
'os_type': {'key': 'osType', 'type': 'object'},
'recycle_after_each_use': {'key': 'recycleAfterEachUse', 'type': 'bool'},
'service_endpoint_id': {'key': 'serviceEndpointId', 'type': 'str'},
'service_endpoint_scope': {'key': 'serviceEndpointScope', 'type': 'str'},
'time_to_live_minutes': {'key': 'timeToLiveMinutes', 'type': 'int'}
}
def __init__(self, agent_interactive_uI=None, azure_id=None, desired_idle=None, max_capacity=None, max_saved_node_count=None, orchestration_type=None, os_type=None, recycle_after_each_use=None, service_endpoint_id=None, service_endpoint_scope=None, time_to_live_minutes=None):
super(ElasticPoolSettings, self).__init__()
self.agent_interactive_uI = agent_interactive_uI
self.azure_id = azure_id
self.desired_idle = desired_idle
self.max_capacity = max_capacity
self.max_saved_node_count = max_saved_node_count
self.orchestration_type = orchestration_type
self.os_type = os_type
self.recycle_after_each_use = recycle_after_each_use
self.service_endpoint_id = service_endpoint_id
self.service_endpoint_scope = service_endpoint_scope
self.time_to_live_minutes = time_to_live_minutes
class GraphSubjectBase(Model):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None):
super(GraphSubjectBase, self).__init__()
self._links = _links
self.descriptor = descriptor
self.display_name = display_name
self.url = url
class IdentityRef(GraphSubjectBase):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param directory_alias: Deprecated - Can be retrieved by querying the Graph user referenced in the "self" entry of the IdentityRef "_links" dictionary
:type directory_alias: str
:param id:
:type id: str
:param image_url: Deprecated - Available in the "avatar" entry of the IdentityRef "_links" dictionary
:type image_url: str
:param inactive: Deprecated - Can be retrieved by querying the Graph membership state referenced in the "membershipState" entry of the GraphUser "_links" dictionary
:type inactive: bool
:param is_aad_identity: Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsAadUserType/Descriptor.IsAadGroupType)
:type is_aad_identity: bool
:param is_container: Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsGroupType)
:type is_container: bool
:param is_deleted_in_origin:
:type is_deleted_in_origin: bool
:param profile_url: Deprecated - not in use in most preexisting implementations of ToIdentityRef
:type profile_url: str
:param unique_name: Deprecated - use Domain+PrincipalName instead
:type unique_name: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'directory_alias': {'key': 'directoryAlias', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'image_url': {'key': 'imageUrl', 'type': 'str'},
'inactive': {'key': 'inactive', 'type': 'bool'},
'is_aad_identity': {'key': 'isAadIdentity', 'type': 'bool'},
'is_container': {'key': 'isContainer', 'type': 'bool'},
'is_deleted_in_origin': {'key': 'isDeletedInOrigin', 'type': 'bool'},
'profile_url': {'key': 'profileUrl', 'type': 'str'},
'unique_name': {'key': 'uniqueName', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, directory_alias=None, id=None, image_url=None, inactive=None, is_aad_identity=None, is_container=None, is_deleted_in_origin=None, profile_url=None, unique_name=None):
super(IdentityRef, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url)
self.directory_alias = directory_alias
self.id = id
self.image_url = image_url
self.inactive = inactive
self.is_aad_identity = is_aad_identity
self.is_container = is_container
self.is_deleted_in_origin = is_deleted_in_origin
self.profile_url = profile_url
self.unique_name = unique_name
class ReferenceLinks(Model):
"""
The class to represent a collection of REST reference links.
:param links: The readonly view of the links. Because Reference links are readonly, we only want to expose them as read only.
:type links: dict
"""
_attribute_map = {
'links': {'key': 'links', 'type': '{object}'}
}
def __init__(self, links=None):
super(ReferenceLinks, self).__init__()
self.links = links
class TaskAgentPoolReference(Model):
"""
:param id:
:type id: int
:param is_hosted: Gets or sets a value indicating whether or not this pool is managed by the service.
:type is_hosted: bool
:param is_legacy: Determines whether the pool is legacy.
:type is_legacy: bool
:param name:
:type name: str
:param options: Additional pool settings and details
:type options: object
:param pool_type: Gets or sets the type of the pool
:type pool_type: object
:param scope:
:type scope: str
:param size: Gets the current size of the pool.
:type size: int
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'int'},
'is_hosted': {'key': 'isHosted', 'type': 'bool'},
'is_legacy': {'key': 'isLegacy', 'type': 'bool'},
'name': {'key': 'name', 'type': 'str'},
'options': {'key': 'options', 'type': 'object'},
'pool_type': {'key': 'poolType', 'type': 'object'},
'scope': {'key': 'scope', 'type': 'str'},
'size': {'key': 'size', 'type': 'int'}
}
def __init__(self, id=None, is_hosted=None, is_legacy=None, name=None, options=None, pool_type=None, scope=None, size=None):
super(TaskAgentPoolReference, self).__init__()
self.id = id
self.is_hosted = is_hosted
self.is_legacy = is_legacy
self.name = name
self.options = options
self.pool_type = pool_type
self.scope = scope
self.size = size
class TaskAgentQueue(Model):
"""
An agent queue.
:param id: ID of the queue
:type id: int
:param name: Name of the queue
:type name: str
:param pool: Pool reference for this queue
:type pool: :class:`TaskAgentPoolReference <azure.devops.v7_1.elastic.models.TaskAgentPoolReference>`
:param project_id: Project ID
:type project_id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'int'},
'name': {'key': 'name', 'type': 'str'},
'pool': {'key': 'pool', 'type': 'TaskAgentPoolReference'},
'project_id': {'key': 'projectId', 'type': 'str'}
}
def __init__(self, id=None, name=None, pool=None, project_id=None):
super(TaskAgentQueue, self).__init__()
self.id = id
self.name = name
self.pool = pool
self.project_id = project_id
class TaskAgentPool(TaskAgentPoolReference):
"""
An organization-level grouping of agents.
:param id:
:type id: int
:param is_hosted: Gets or sets a value indicating whether or not this pool is managed by the service.
:type is_hosted: bool
:param is_legacy: Determines whether the pool is legacy.
:type is_legacy: bool
:param name:
:type name: str
:param options: Additional pool settings and details
:type options: object
:param pool_type: Gets or sets the type of the pool
:type pool_type: object
:param scope:
:type scope: str
:param size: Gets the current size of the pool.
:type size: int
:param agent_cloud_id: The ID of the associated agent cloud.
:type agent_cloud_id: int
:param auto_provision: Whether or not a queue should be automatically provisioned for each project collection.
:type auto_provision: bool
:param auto_size: Whether or not the pool should autosize itself based on the Agent Cloud Provider settings.
:type auto_size: bool
:param auto_update: Whether or not agents in this pool are allowed to automatically update
:type auto_update: bool
:param created_by: Creator of the pool. The creator of the pool is automatically added into the administrators group for the pool on creation.
:type created_by: :class:`IdentityRef <azure.devops.v7_1.elastic.models.IdentityRef>`
:param created_on: The date/time of the pool creation.
:type created_on: datetime
:param owner: Owner or administrator of the pool.
:type owner: :class:`IdentityRef <azure.devops.v7_1.elastic.models.IdentityRef>`
:param properties:
:type properties: :class:`object <azure.devops.v7_1.elastic.models.object>`
:param target_size: Target parallelism - Only applies to agent pools that are backed by pool providers. It will be null for regular pools.
:type target_size: int
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'int'},
'is_hosted': {'key': 'isHosted', 'type': 'bool'},
'is_legacy': {'key': 'isLegacy', 'type': 'bool'},
'name': {'key': 'name', 'type': 'str'},
'options': {'key': 'options', 'type': 'object'},
'pool_type': {'key': 'poolType', 'type': 'object'},
'scope': {'key': 'scope', 'type': 'str'},
'size': {'key': 'size', 'type': 'int'},
'agent_cloud_id': {'key': 'agentCloudId', 'type': 'int'},
'auto_provision': {'key': 'autoProvision', 'type': 'bool'},
'auto_size': {'key': 'autoSize', 'type': 'bool'},
'auto_update': {'key': 'autoUpdate', 'type': 'bool'},
'created_by': {'key': 'createdBy', 'type': 'IdentityRef'},
'created_on': {'key': 'createdOn', 'type': 'iso-8601'},
'owner': {'key': 'owner', 'type': 'IdentityRef'},
'properties': {'key': 'properties', 'type': 'object'},
'target_size': {'key': 'targetSize', 'type': 'int'}
}
def __init__(self, id=None, is_hosted=None, is_legacy=None, name=None, options=None, pool_type=None, scope=None, size=None, agent_cloud_id=None, auto_provision=None, auto_size=None, auto_update=None, created_by=None, created_on=None, owner=None, properties=None, target_size=None):
super(TaskAgentPool, self).__init__(id=id, is_hosted=is_hosted, is_legacy=is_legacy, name=name, options=options, pool_type=pool_type, scope=scope, size=size)
self.agent_cloud_id = agent_cloud_id
self.auto_provision = auto_provision
self.auto_size = auto_size
self.auto_update = auto_update
self.created_by = created_by
self.created_on = created_on
self.owner = owner
self.properties = properties
self.target_size = target_size
__all__ = [
'ElasticNode',
'ElasticNodeSettings',
'ElasticPool',
'ElasticPoolCreationResult',
'ElasticPoolLog',
'ElasticPoolSettings',
'GraphSubjectBase',
'IdentityRef',
'ReferenceLinks',
'TaskAgentPoolReference',
'TaskAgentQueue',
'TaskAgentPool',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/elastic/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/elastic/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 9277
}
| 355 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from .models import *
from .gallery_client import GalleryClient
__all__ = [
'AcquisitionOperation',
'AcquisitionOptions',
'Answers',
'AssetDetails',
'AzurePublisher',
'AzureRestApiRequestModel',
'CategoriesResult',
'CategoryLanguageTitle',
'Concern',
'CustomerSupportRequest',
'EventCounts',
'ExtensionAcquisitionRequest',
'ExtensionBadge',
'ExtensionCategory',
'ExtensionDailyStat',
'ExtensionDailyStats',
'ExtensionDraft',
'ExtensionDraftAsset',
'ExtensionDraftPatch',
'ExtensionEvent',
'ExtensionEvents',
'ExtensionFile',
'ExtensionFilterResult',
'ExtensionFilterResultMetadata',
'ExtensionPackage',
'ExtensionPayload',
'ExtensionQuery',
'ExtensionQueryResult',
'ExtensionShare',
'ExtensionStatistic',
'ExtensionStatisticUpdate',
'ExtensionVersion',
'FilterCriteria',
'GraphSubjectBase',
'IdentityRef',
'InstallationTarget',
'MetadataItem',
'NotificationsData',
'ProductCategoriesResult',
'ProductCategory',
'PublishedExtension',
'Publisher',
'PublisherBase',
'PublisherFacts',
'PublisherFilterResult',
'PublisherQuery',
'PublisherQueryResult',
'PublisherRoleAssignment',
'PublisherSecurityRole',
'PublisherUserRoleAssignmentRef',
'QnAItem',
'QueryFilter',
'Question',
'QuestionsResult',
'RatingCountPerRating',
'ReferenceLinks',
'Response',
'Review',
'ReviewPatch',
'ReviewReply',
'ReviewsResult',
'ReviewSummary',
'UnpackagedExtensionData',
'UserIdentityRef',
'UserReportedConcern',
'GalleryClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/gallery/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/gallery/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 711
}
| 356 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from .models import *
from .maven_client import MavenClient
__all__ = [
'BatchOperationData',
'JsonPatchOperation',
'MavenDistributionManagement',
'MavenMinimalPackageDetails',
'MavenPackage',
'MavenPackagesBatchRequest',
'MavenPackageVersionDeletionState',
'MavenPomBuild',
'MavenPomCi',
'MavenPomCiNotifier',
'MavenPomDependency',
'MavenPomDependencyManagement',
'MavenPomGav',
'MavenPomIssueManagement',
'MavenPomLicense',
'MavenPomMailingList',
'MavenPomMetadata',
'MavenPomOrganization',
'MavenPomParent',
'MavenPomPerson',
'MavenPomScm',
'MavenRecycleBinPackageVersionDetails',
'MavenRepository',
'MavenSnapshotRepository',
'Package',
'PackageVersionDetails',
'Plugin',
'PluginConfiguration',
'ReferenceLink',
'ReferenceLinks',
'UpstreamingBehavior',
'UpstreamSourceInfo',
'MavenClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/maven/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/maven/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 468
}
| 357 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class OperationReference(Model):
"""
Reference for an async operation.
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None):
super(OperationReference, self).__init__()
self.id = id
self.plugin_id = plugin_id
self.status = status
self.url = url
class OperationResultReference(Model):
"""
:param result_url: URL to the operation result.
:type result_url: str
"""
_attribute_map = {
'result_url': {'key': 'resultUrl', 'type': 'str'}
}
def __init__(self, result_url=None):
super(OperationResultReference, self).__init__()
self.result_url = result_url
class ReferenceLinks(Model):
"""
The class to represent a collection of REST reference links.
:param links: The readonly view of the links. Because Reference links are readonly, we only want to expose them as read only.
:type links: dict
"""
_attribute_map = {
'links': {'key': 'links', 'type': '{object}'}
}
def __init__(self, links=None):
super(ReferenceLinks, self).__init__()
self.links = links
class Operation(OperationReference):
"""
Contains information about the progress or result of an async operation.
:param id: Unique identifier for the operation.
:type id: str
:param plugin_id: Unique identifier for the plugin.
:type plugin_id: str
:param status: The current status of the operation.
:type status: object
:param url: URL to get the full operation object.
:type url: str
:param _links: Links to other related objects.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.operations.models.ReferenceLinks>`
:param detailed_message: Detailed messaged about the status of an operation.
:type detailed_message: str
:param result_message: Result message for an operation.
:type result_message: str
:param result_url: URL to the operation result.
:type result_url: :class:`OperationResultReference <azure.devops.v7_1.operations.models.OperationResultReference>`
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'plugin_id': {'key': 'pluginId', 'type': 'str'},
'status': {'key': 'status', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'},
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'detailed_message': {'key': 'detailedMessage', 'type': 'str'},
'result_message': {'key': 'resultMessage', 'type': 'str'},
'result_url': {'key': 'resultUrl', 'type': 'OperationResultReference'}
}
def __init__(self, id=None, plugin_id=None, status=None, url=None, _links=None, detailed_message=None, result_message=None, result_url=None):
super(Operation, self).__init__(id=id, plugin_id=plugin_id, status=status, url=url)
self._links = _links
self.detailed_message = detailed_message
self.result_message = result_message
self.result_url = result_url
__all__ = [
'OperationReference',
'OperationResultReference',
'ReferenceLinks',
'Operation',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/operations/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/operations/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 1474
}
| 358 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
class SettingsClient(Client):
"""Settings
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(SettingsClient, self).__init__(base_url, creds)
self._serialize = Serializer()
self._deserialize = Deserializer()
resource_area_identifier = None
def get_entries(self, user_scope, key=None):
"""GetEntries.
[Preview API] Get all setting entries for the given user/all-users scope
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param str key: Optional key under which to filter all the entries
:rtype: {object}
"""
route_values = {}
if user_scope is not None:
route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
if key is not None:
route_values['key'] = self._serialize.url('key', key, 'str')
response = self._send(http_method='GET',
location_id='cd006711-163d-4cd4-a597-b05bad2556ff',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('{object}', self._unwrap_collection(response))
def remove_entries(self, user_scope, key):
"""RemoveEntries.
[Preview API] Remove the entry or entries under the specified path
:param str user_scope: User-Scope at which to remove the value. Should be "me" for the current user or "host" for all users.
:param str key: Root key of the entry or entries to remove
"""
route_values = {}
if user_scope is not None:
route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
if key is not None:
route_values['key'] = self._serialize.url('key', key, 'str')
self._send(http_method='DELETE',
location_id='cd006711-163d-4cd4-a597-b05bad2556ff',
version='7.1-preview.1',
route_values=route_values)
def set_entries(self, entries, user_scope):
"""SetEntries.
[Preview API] Set the specified setting entry values for the given user/all-users scope
:param {object} entries: The entries to set
:param str user_scope: User-Scope at which to set the values. Should be "me" for the current user or "host" for all users.
"""
route_values = {}
if user_scope is not None:
route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
content = self._serialize.body(entries, '{object}')
self._send(http_method='PATCH',
location_id='cd006711-163d-4cd4-a597-b05bad2556ff',
version='7.1-preview.1',
route_values=route_values,
content=content)
def get_entries_for_scope(self, user_scope, scope_name, scope_value, key=None):
"""GetEntriesForScope.
[Preview API] Get all setting entries for the given named scope
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param str scope_name: Scope at which to get the setting for (e.g. "project" or "team")
:param str scope_value: Value of the scope (e.g. the project or team id)
:param str key: Optional key under which to filter all the entries
:rtype: {object}
"""
route_values = {}
if user_scope is not None:
route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
if scope_name is not None:
route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
if scope_value is not None:
route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
if key is not None:
route_values['key'] = self._serialize.url('key', key, 'str')
response = self._send(http_method='GET',
location_id='4cbaafaf-e8af-4570-98d1-79ee99c56327',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('{object}', self._unwrap_collection(response))
def remove_entries_for_scope(self, user_scope, scope_name, scope_value, key):
"""RemoveEntriesForScope.
[Preview API] Remove the entry or entries under the specified path
:param str user_scope: User-Scope at which to remove the value. Should be "me" for the current user or "host" for all users.
:param str scope_name: Scope at which to get the setting for (e.g. "project" or "team")
:param str scope_value: Value of the scope (e.g. the project or team id)
:param str key: Root key of the entry or entries to remove
"""
route_values = {}
if user_scope is not None:
route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
if scope_name is not None:
route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
if scope_value is not None:
route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
if key is not None:
route_values['key'] = self._serialize.url('key', key, 'str')
self._send(http_method='DELETE',
location_id='4cbaafaf-e8af-4570-98d1-79ee99c56327',
version='7.1-preview.1',
route_values=route_values)
def set_entries_for_scope(self, entries, user_scope, scope_name, scope_value):
"""SetEntriesForScope.
[Preview API] Set the specified entries for the given named scope
:param {object} entries: The entries to set
:param str user_scope: User-Scope at which to set the values. Should be "me" for the current user or "host" for all users.
:param str scope_name: Scope at which to set the settings on (e.g. "project" or "team")
:param str scope_value: Value of the scope (e.g. the project or team id)
"""
route_values = {}
if user_scope is not None:
route_values['userScope'] = self._serialize.url('user_scope', user_scope, 'str')
if scope_name is not None:
route_values['scopeName'] = self._serialize.url('scope_name', scope_name, 'str')
if scope_value is not None:
route_values['scopeValue'] = self._serialize.url('scope_value', scope_value, 'str')
content = self._serialize.body(entries, '{object}')
self._send(http_method='PATCH',
location_id='4cbaafaf-e8af-4570-98d1-79ee99c56327',
version='7.1-preview.1',
route_values=route_values,
content=content)
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/settings/settings_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/settings/settings_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 3129
}
| 359 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from .models import *
from .test_results_client import TestResultsClient
__all__ = [
'AggregatedDataForResultTrend',
'AggregatedResultDetailsByOutcome',
'AggregatedResultsAnalysis',
'AggregatedResultsByOutcome',
'AggregatedResultsDifference',
'AggregatedRunsByOutcome',
'AggregatedRunsByState',
'BuildConfiguration',
'BuildCoverage',
'BuildReference',
'CodeCoverageData',
'CodeCoverageStatistics',
'CodeCoverageSummary',
'CoverageStatistics',
'CustomTestField',
'DtlEnvironmentDetails',
'FailingSince',
'FieldDetailsForTestResults',
'FileCoverageRequest',
'FlakyDetection',
'FlakyDetectionPipelines',
'FlakySettings',
'FunctionCoverage',
'GraphSubjectBase',
'IdentityRef',
'JobReference',
'ModuleCoverage',
'NewTestResultLoggingSettings',
'PhaseReference',
'PipelineReference',
'PipelineTestMetrics',
'QueryModel',
'ReferenceLinks',
'ReleaseReference',
'ResultsAnalysis',
'ResultsFilter',
'ResultsSummaryByOutcome',
'ResultSummary',
'RunCreateModel',
'RunFilter',
'RunStatistic',
'RunSummary',
'RunSummaryModel',
'RunUpdateModel',
'ShallowReference',
'ShallowTestCaseResult',
'SharedStepModel',
'StageReference',
'TeamProjectReference',
'TestActionResultModel',
'TestAttachment',
'TestAttachmentReference',
'TestAttachmentRequestModel',
'TestCaseResult',
'TestCaseResultAttachmentModel',
'TestCaseResultIdentifier',
'TestEnvironment',
'TestFailureDetails',
'TestFailuresAnalysis',
'TestFailureType',
'TestFlakyIdentifier',
'TestHistoryQuery',
'TestIterationDetailsModel',
'TestLog',
'TestLogReference',
'TestLogStoreAttachment',
'TestLogStoreAttachmentReference',
'TestLogStoreEndpointDetails',
'TestMessageLogDetails',
'TestMethod',
'TestOperationReference',
'TestResolutionState',
'TestResultDocument',
'TestResultFailuresAnalysis',
'TestResultHistory',
'TestResultHistoryDetailsForGroup',
'TestResultHistoryForGroup',
'TestResultMetaData',
'TestResultMetaDataUpdateInput',
'TestResultModelBase',
'TestResultParameterModel',
'TestResultPayload',
'TestResultsContext',
'TestResultsDetails',
'TestResultsDetailsForGroup',
'TestResultsQuery',
'TestResultsSettings',
'TestResultSummary',
'TestResultsUpdateSettings',
'TestResultTrendFilter',
'TestRun',
'TestRunCoverage',
'TestRunStatistic',
'TestSettings',
'TestSubResult',
'TestSummaryForWorkItem',
'TestTag',
'TestTagSummary',
'TestTagsUpdateModel',
'TestToWorkItemLinks',
'WorkItemReference',
'WorkItemToTestLinks',
'TestResultsClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/test_results/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/test_results/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 1116
}
| 360 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class CommentCreateParameters(Model):
"""
Represents a request to create a work item comment.
:param parent_id: Optional CommentId of the parent in order to add a reply for an existing comment
:type parent_id: int
:param text:
:type text: str
"""
_attribute_map = {
'parent_id': {'key': 'parentId', 'type': 'int'},
'text': {'key': 'text', 'type': 'str'}
}
def __init__(self, parent_id=None, text=None):
super(CommentCreateParameters, self).__init__()
self.parent_id = parent_id
self.text = text
class CommentResourceReference(Model):
"""
Base class for comment resource references
:param url:
:type url: str
"""
_attribute_map = {
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, url=None):
super(CommentResourceReference, self).__init__()
self.url = url
class CommentUpdateParameters(Model):
"""
Represents a request to update a comment.
:param state: Set the current state of the comment
:type state: object
:param text: The updated text of the comment
:type text: str
"""
_attribute_map = {
'state': {'key': 'state', 'type': 'object'},
'text': {'key': 'text', 'type': 'str'}
}
def __init__(self, state=None, text=None):
super(CommentUpdateParameters, self).__init__()
self.state = state
self.text = text
class GitRepository(Model):
"""
:param _links:
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._team_foundation._source_control._web_api.models.ReferenceLinks>`
:param default_branch:
:type default_branch: str
:param id:
:type id: str
:param is_disabled: True if the repository is disabled. False otherwise.
:type is_disabled: bool
:param is_fork: True if the repository was created as a fork.
:type is_fork: bool
:param is_in_maintenance: True if the repository is in maintenance. False otherwise.
:type is_in_maintenance: bool
:param name:
:type name: str
:param parent_repository:
:type parent_repository: :class:`GitRepositoryRef <azure.devops.v7_1.microsoft._team_foundation._source_control._web_api.models.GitRepositoryRef>`
:param project:
:type project: :class:`TeamProjectReference <azure.devops.v7_1.microsoft._team_foundation._source_control._web_api.models.TeamProjectReference>`
:param remote_url:
:type remote_url: str
:param size: Compressed size (bytes) of the repository.
:type size: long
:param ssh_url:
:type ssh_url: str
:param url:
:type url: str
:param valid_remote_urls:
:type valid_remote_urls: list of str
:param web_url:
:type web_url: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'default_branch': {'key': 'defaultBranch', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'is_disabled': {'key': 'isDisabled', 'type': 'bool'},
'is_fork': {'key': 'isFork', 'type': 'bool'},
'is_in_maintenance': {'key': 'isInMaintenance', 'type': 'bool'},
'name': {'key': 'name', 'type': 'str'},
'parent_repository': {'key': 'parentRepository', 'type': 'GitRepositoryRef'},
'project': {'key': 'project', 'type': 'TeamProjectReference'},
'remote_url': {'key': 'remoteUrl', 'type': 'str'},
'size': {'key': 'size', 'type': 'long'},
'ssh_url': {'key': 'sshUrl', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'valid_remote_urls': {'key': 'validRemoteUrls', 'type': '[str]'},
'web_url': {'key': 'webUrl', 'type': 'str'}
}
def __init__(self, _links=None, default_branch=None, id=None, is_disabled=None, is_fork=None, is_in_maintenance=None, name=None, parent_repository=None, project=None, remote_url=None, size=None, ssh_url=None, url=None, valid_remote_urls=None, web_url=None):
super(GitRepository, self).__init__()
self._links = _links
self.default_branch = default_branch
self.id = id
self.is_disabled = is_disabled
self.is_fork = is_fork
self.is_in_maintenance = is_in_maintenance
self.name = name
self.parent_repository = parent_repository
self.project = project
self.remote_url = remote_url
self.size = size
self.ssh_url = ssh_url
self.url = url
self.valid_remote_urls = valid_remote_urls
self.web_url = web_url
class GitRepositoryRef(Model):
"""
:param collection: Team Project Collection where this Fork resides
:type collection: :class:`TeamProjectCollectionReference <azure.devops.v7_1.microsoft._team_foundation._source_control._web_api.models.TeamProjectCollectionReference>`
:param id:
:type id: str
:param is_fork: True if the repository was created as a fork
:type is_fork: bool
:param name:
:type name: str
:param project:
:type project: :class:`TeamProjectReference <azure.devops.v7_1.microsoft._team_foundation._source_control._web_api.models.TeamProjectReference>`
:param remote_url:
:type remote_url: str
:param ssh_url:
:type ssh_url: str
:param url:
:type url: str
"""
_attribute_map = {
'collection': {'key': 'collection', 'type': 'TeamProjectCollectionReference'},
'id': {'key': 'id', 'type': 'str'},
'is_fork': {'key': 'isFork', 'type': 'bool'},
'name': {'key': 'name', 'type': 'str'},
'project': {'key': 'project', 'type': 'TeamProjectReference'},
'remote_url': {'key': 'remoteUrl', 'type': 'str'},
'ssh_url': {'key': 'sshUrl', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, collection=None, id=None, is_fork=None, name=None, project=None, remote_url=None, ssh_url=None, url=None):
super(GitRepositoryRef, self).__init__()
self.collection = collection
self.id = id
self.is_fork = is_fork
self.name = name
self.project = project
self.remote_url = remote_url
self.ssh_url = ssh_url
self.url = url
class GitVersionDescriptor(Model):
"""
:param version: Version string identifier (name of tag/branch, SHA1 of commit)
:type version: str
:param version_options: Version options - Specify additional modifiers to version (e.g Previous)
:type version_options: object
:param version_type: Version type (branch, tag, or commit). Determines how Id is interpreted
:type version_type: object
"""
_attribute_map = {
'version': {'key': 'version', 'type': 'str'},
'version_options': {'key': 'versionOptions', 'type': 'object'},
'version_type': {'key': 'versionType', 'type': 'object'}
}
def __init__(self, version=None, version_options=None, version_type=None):
super(GitVersionDescriptor, self).__init__()
self.version = version
self.version_options = version_options
self.version_type = version_type
class GraphSubjectBase(Model):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None):
super(GraphSubjectBase, self).__init__()
self._links = _links
self.descriptor = descriptor
self.display_name = display_name
self.url = url
class IdentityRef(GraphSubjectBase):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param directory_alias: Deprecated - Can be retrieved by querying the Graph user referenced in the "self" entry of the IdentityRef "_links" dictionary
:type directory_alias: str
:param id:
:type id: str
:param image_url: Deprecated - Available in the "avatar" entry of the IdentityRef "_links" dictionary
:type image_url: str
:param inactive: Deprecated - Can be retrieved by querying the Graph membership state referenced in the "membershipState" entry of the GraphUser "_links" dictionary
:type inactive: bool
:param is_aad_identity: Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsAadUserType/Descriptor.IsAadGroupType)
:type is_aad_identity: bool
:param is_container: Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsGroupType)
:type is_container: bool
:param is_deleted_in_origin:
:type is_deleted_in_origin: bool
:param profile_url: Deprecated - not in use in most preexisting implementations of ToIdentityRef
:type profile_url: str
:param unique_name: Deprecated - use Domain+PrincipalName instead
:type unique_name: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'directory_alias': {'key': 'directoryAlias', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'image_url': {'key': 'imageUrl', 'type': 'str'},
'inactive': {'key': 'inactive', 'type': 'bool'},
'is_aad_identity': {'key': 'isAadIdentity', 'type': 'bool'},
'is_container': {'key': 'isContainer', 'type': 'bool'},
'is_deleted_in_origin': {'key': 'isDeletedInOrigin', 'type': 'bool'},
'profile_url': {'key': 'profileUrl', 'type': 'str'},
'unique_name': {'key': 'uniqueName', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, directory_alias=None, id=None, image_url=None, inactive=None, is_aad_identity=None, is_container=None, is_deleted_in_origin=None, profile_url=None, unique_name=None):
super(IdentityRef, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url)
self.directory_alias = directory_alias
self.id = id
self.image_url = image_url
self.inactive = inactive
self.is_aad_identity = is_aad_identity
self.is_container = is_container
self.is_deleted_in_origin = is_deleted_in_origin
self.profile_url = profile_url
self.unique_name = unique_name
class ReferenceLinks(Model):
"""
The class to represent a collection of REST reference links.
:param links: The readonly view of the links. Because Reference links are readonly, we only want to expose them as read only.
:type links: dict
"""
_attribute_map = {
'links': {'key': 'links', 'type': '{object}'}
}
def __init__(self, links=None):
super(ReferenceLinks, self).__init__()
self.links = links
class TeamProjectCollectionReference(Model):
"""
:param avatar_url:
:type avatar_url: str
:param id:
:type id: str
:param name:
:type name: str
:param url:
:type url: str
"""
_attribute_map = {
'avatar_url': {'key': 'avatarUrl', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, avatar_url=None, id=None, name=None, url=None):
super(TeamProjectCollectionReference, self).__init__()
self.avatar_url = avatar_url
self.id = id
self.name = name
self.url = url
class TeamProjectReference(Model):
"""
:param abbreviation:
:type abbreviation: str
:param default_team_image_url:
:type default_team_image_url: str
:param description:
:type description: str
:param id:
:type id: str
:param last_update_time:
:type last_update_time: datetime
:param name:
:type name: str
:param revision:
:type revision: long
:param state:
:type state: object
:param url:
:type url: str
:param visibility:
:type visibility: object
"""
_attribute_map = {
'abbreviation': {'key': 'abbreviation', 'type': 'str'},
'default_team_image_url': {'key': 'defaultTeamImageUrl', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'last_update_time': {'key': 'lastUpdateTime', 'type': 'iso-8601'},
'name': {'key': 'name', 'type': 'str'},
'revision': {'key': 'revision', 'type': 'long'},
'state': {'key': 'state', 'type': 'object'},
'url': {'key': 'url', 'type': 'str'},
'visibility': {'key': 'visibility', 'type': 'object'}
}
def __init__(self, abbreviation=None, default_team_image_url=None, description=None, id=None, last_update_time=None, name=None, revision=None, state=None, url=None, visibility=None):
super(TeamProjectReference, self).__init__()
self.abbreviation = abbreviation
self.default_team_image_url = default_team_image_url
self.description = description
self.id = id
self.last_update_time = last_update_time
self.name = name
self.revision = revision
self.state = state
self.url = url
self.visibility = visibility
class WikiAttachment(Model):
"""
Defines properties for wiki attachment file.
:param name: Name of the wiki attachment file.
:type name: str
:param path: Path of the wiki attachment file.
:type path: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'path': {'key': 'path', 'type': 'str'}
}
def __init__(self, name=None, path=None):
super(WikiAttachment, self).__init__()
self.name = name
self.path = path
class WikiAttachmentResponse(Model):
"""
Response contract for the Wiki Attachments API
:param attachment: Defines properties for wiki attachment file.
:type attachment: :class:`WikiAttachment <azure.devops.v7_1.wiki.models.WikiAttachment>`
:param eTag: Contains the list of ETag values from the response header of the attachments API call. The first item in the list contains the version of the wiki attachment.
:type eTag: list of str
"""
_attribute_map = {
'attachment': {'key': 'attachment', 'type': 'WikiAttachment'},
'eTag': {'key': 'eTag', 'type': '[str]'}
}
def __init__(self, attachment=None, eTag=None):
super(WikiAttachmentResponse, self).__init__()
self.attachment = attachment
self.eTag = eTag
class WikiCreateBaseParameters(Model):
"""
Base wiki creation parameters.
:param mapped_path: Folder path inside repository which is shown as Wiki. Not required for ProjectWiki type.
:type mapped_path: str
:param name: Wiki name.
:type name: str
:param project_id: ID of the project in which the wiki is to be created.
:type project_id: str
:param repository_id: ID of the git repository that backs up the wiki. Not required for ProjectWiki type.
:type repository_id: str
:param type: Type of the wiki.
:type type: object
"""
_attribute_map = {
'mapped_path': {'key': 'mappedPath', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'project_id': {'key': 'projectId', 'type': 'str'},
'repository_id': {'key': 'repositoryId', 'type': 'str'},
'type': {'key': 'type', 'type': 'object'}
}
def __init__(self, mapped_path=None, name=None, project_id=None, repository_id=None, type=None):
super(WikiCreateBaseParameters, self).__init__()
self.mapped_path = mapped_path
self.name = name
self.project_id = project_id
self.repository_id = repository_id
self.type = type
class WikiCreateParametersV2(WikiCreateBaseParameters):
"""
Wiki creation parameters.
:param mapped_path: Folder path inside repository which is shown as Wiki. Not required for ProjectWiki type.
:type mapped_path: str
:param name: Wiki name.
:type name: str
:param project_id: ID of the project in which the wiki is to be created.
:type project_id: str
:param repository_id: ID of the git repository that backs up the wiki. Not required for ProjectWiki type.
:type repository_id: str
:param type: Type of the wiki.
:type type: object
:param version: Version of the wiki. Not required for ProjectWiki type.
:type version: :class:`GitVersionDescriptor <azure.devops.v7_1.wiki.models.GitVersionDescriptor>`
"""
_attribute_map = {
'mapped_path': {'key': 'mappedPath', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'project_id': {'key': 'projectId', 'type': 'str'},
'repository_id': {'key': 'repositoryId', 'type': 'str'},
'type': {'key': 'type', 'type': 'object'},
'version': {'key': 'version', 'type': 'GitVersionDescriptor'}
}
def __init__(self, mapped_path=None, name=None, project_id=None, repository_id=None, type=None, version=None):
super(WikiCreateParametersV2, self).__init__(mapped_path=mapped_path, name=name, project_id=project_id, repository_id=repository_id, type=type)
self.version = version
class WikiPageCreateOrUpdateParameters(Model):
"""
Contract encapsulating parameters for the page create or update operations.
:param content: Content of the wiki page.
:type content: str
"""
_attribute_map = {
'content': {'key': 'content', 'type': 'str'}
}
def __init__(self, content=None):
super(WikiPageCreateOrUpdateParameters, self).__init__()
self.content = content
class WikiPageDetail(Model):
"""
Defines a page with its metedata in a wiki.
:param id: When present, permanent identifier for the wiki page
:type id: int
:param path: Path of the wiki page.
:type path: str
:param view_stats: Path of the wiki page.
:type view_stats: list of :class:`WikiPageStat <azure.devops.v7_1.wiki.models.WikiPageStat>`
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'int'},
'path': {'key': 'path', 'type': 'str'},
'view_stats': {'key': 'viewStats', 'type': '[WikiPageStat]'}
}
def __init__(self, id=None, path=None, view_stats=None):
super(WikiPageDetail, self).__init__()
self.id = id
self.path = path
self.view_stats = view_stats
class WikiPageMoveParameters(Model):
"""
Contract encapsulating parameters for the page move operation.
:param new_order: New order of the wiki page.
:type new_order: int
:param new_path: New path of the wiki page.
:type new_path: str
:param path: Current path of the wiki page.
:type path: str
"""
_attribute_map = {
'new_order': {'key': 'newOrder', 'type': 'int'},
'new_path': {'key': 'newPath', 'type': 'str'},
'path': {'key': 'path', 'type': 'str'}
}
def __init__(self, new_order=None, new_path=None, path=None):
super(WikiPageMoveParameters, self).__init__()
self.new_order = new_order
self.new_path = new_path
self.path = path
class WikiPageMoveResponse(Model):
"""
Response contract for the Wiki Page Move API.
:param eTag: Contains the list of ETag values from the response header of the page move API call. The first item in the list contains the version of the wiki page subject to page move.
:type eTag: list of str
:param page_move: Defines properties for wiki page move.
:type page_move: :class:`WikiPageMove <azure.devops.v7_1.wiki.models.WikiPageMove>`
"""
_attribute_map = {
'eTag': {'key': 'eTag', 'type': '[str]'},
'page_move': {'key': 'pageMove', 'type': 'WikiPageMove'}
}
def __init__(self, eTag=None, page_move=None):
super(WikiPageMoveResponse, self).__init__()
self.eTag = eTag
self.page_move = page_move
class WikiPageResponse(Model):
"""
Response contract for the Wiki Pages PUT, PATCH and DELETE APIs.
:param eTag: Contains the list of ETag values from the response header of the pages API call. The first item in the list contains the version of the wiki page.
:type eTag: list of str
:param page: Defines properties for wiki page.
:type page: :class:`WikiPage <azure.devops.v7_1.wiki.models.WikiPage>`
"""
_attribute_map = {
'eTag': {'key': 'eTag', 'type': '[str]'},
'page': {'key': 'page', 'type': 'WikiPage'}
}
def __init__(self, eTag=None, page=None):
super(WikiPageResponse, self).__init__()
self.eTag = eTag
self.page = page
class WikiPagesBatchRequest(Model):
"""
Contract encapsulating parameters for the pages batch.
:param continuation_token: If the list of page data returned is not complete, a continuation token to query next batch of pages is included in the response header as "x-ms-continuationtoken". Omit this parameter to get the first batch of Wiki Page Data.
:type continuation_token: str
:param page_views_for_days: last N days from the current day for which page views is to be returned. It's inclusive of current day.
:type page_views_for_days: int
:param top: Total count of pages on a wiki to return.
:type top: int
"""
_attribute_map = {
'continuation_token': {'key': 'continuationToken', 'type': 'str'},
'page_views_for_days': {'key': 'pageViewsForDays', 'type': 'int'},
'top': {'key': 'top', 'type': 'int'}
}
def __init__(self, continuation_token=None, page_views_for_days=None, top=None):
super(WikiPagesBatchRequest, self).__init__()
self.continuation_token = continuation_token
self.page_views_for_days = page_views_for_days
self.top = top
class WikiPageStat(Model):
"""
Defines properties for wiki page stat.
:param count: the count of the stat for the Day
:type count: int
:param day: Day of the stat
:type day: datetime
"""
_attribute_map = {
'count': {'key': 'count', 'type': 'int'},
'day': {'key': 'day', 'type': 'iso-8601'}
}
def __init__(self, count=None, day=None):
super(WikiPageStat, self).__init__()
self.count = count
self.day = day
class WikiPageViewStats(Model):
"""
Defines properties for wiki page view stats.
:param count: Wiki page view count.
:type count: int
:param last_viewed_time: Wiki page last viewed time.
:type last_viewed_time: datetime
:param path: Wiki page path.
:type path: str
"""
_attribute_map = {
'count': {'key': 'count', 'type': 'int'},
'last_viewed_time': {'key': 'lastViewedTime', 'type': 'iso-8601'},
'path': {'key': 'path', 'type': 'str'}
}
def __init__(self, count=None, last_viewed_time=None, path=None):
super(WikiPageViewStats, self).__init__()
self.count = count
self.last_viewed_time = last_viewed_time
self.path = path
class WikiUpdateParameters(Model):
"""
Wiki update parameters.
:param name: Name for wiki.
:type name: str
:param versions: Versions of the wiki.
:type versions: list of :class:`GitVersionDescriptor <azure.devops.v7_1.wiki.models.GitVersionDescriptor>`
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'versions': {'key': 'versions', 'type': '[GitVersionDescriptor]'}
}
def __init__(self, name=None, versions=None):
super(WikiUpdateParameters, self).__init__()
self.name = name
self.versions = versions
class WikiV2(WikiCreateBaseParameters):
"""
Defines a wiki resource.
:param mapped_path: Folder path inside repository which is shown as Wiki. Not required for ProjectWiki type.
:type mapped_path: str
:param name: Wiki name.
:type name: str
:param project_id: ID of the project in which the wiki is to be created.
:type project_id: str
:param repository_id: ID of the git repository that backs up the wiki. Not required for ProjectWiki type.
:type repository_id: str
:param type: Type of the wiki.
:type type: object
:param id: ID of the wiki.
:type id: str
:param is_disabled: Is wiki repository disabled
:type is_disabled: bool
:param properties: Properties of the wiki.
:type properties: dict
:param remote_url: Remote web url to the wiki.
:type remote_url: str
:param url: REST url for this wiki.
:type url: str
:param versions: Versions of the wiki.
:type versions: list of :class:`GitVersionDescriptor <azure.devops.v7_1.wiki.models.GitVersionDescriptor>`
"""
_attribute_map = {
'mapped_path': {'key': 'mappedPath', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'project_id': {'key': 'projectId', 'type': 'str'},
'repository_id': {'key': 'repositoryId', 'type': 'str'},
'type': {'key': 'type', 'type': 'object'},
'id': {'key': 'id', 'type': 'str'},
'is_disabled': {'key': 'isDisabled', 'type': 'bool'},
'properties': {'key': 'properties', 'type': '{str}'},
'remote_url': {'key': 'remoteUrl', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'versions': {'key': 'versions', 'type': '[GitVersionDescriptor]'}
}
def __init__(self, mapped_path=None, name=None, project_id=None, repository_id=None, type=None, id=None, is_disabled=None, properties=None, remote_url=None, url=None, versions=None):
super(WikiV2, self).__init__(mapped_path=mapped_path, name=name, project_id=project_id, repository_id=repository_id, type=type)
self.id = id
self.is_disabled = is_disabled
self.properties = properties
self.remote_url = remote_url
self.url = url
self.versions = versions
class Comment(CommentResourceReference):
"""
Comment on an artifact like Work Item or Wiki, etc.
:param url:
:type url: str
:param artifact_id: The id of the artifact this comment belongs to
:type artifact_id: str
:param created_by: IdentityRef of the creator of the comment.
:type created_by: :class:`IdentityRef <azure.devops.v7_1.microsoft._azure._dev_ops._comments._web_api.models.IdentityRef>`
:param created_date: The creation date of the comment.
:type created_date: datetime
:param id: The id assigned to the comment.
:type id: int
:param is_deleted: Indicates if the comment has been deleted.
:type is_deleted: bool
:param mentions: The mentions of the comment.
:type mentions: list of :class:`CommentMention <azure.devops.v7_1.microsoft._azure._dev_ops._comments._web_api.models.CommentMention>`
:param modified_by: IdentityRef of the user who last modified the comment.
:type modified_by: :class:`IdentityRef <azure.devops.v7_1.microsoft._azure._dev_ops._comments._web_api.models.IdentityRef>`
:param modified_date: The last modification date of the comment.
:type modified_date: datetime
:param parent_id: The comment id of the parent comment, if any
:type parent_id: int
:param reactions: The reactions on the comment.
:type reactions: list of :class:`CommentReaction <azure.devops.v7_1.microsoft._azure._dev_ops._comments._web_api.models.CommentReaction>`
:param rendered_text: The rendered text of the comment
:type rendered_text: str
:param replies: Replies for this comment
:type replies: :class:`CommentList <azure.devops.v7_1.microsoft._azure._dev_ops._comments._web_api.models.CommentList>`
:param state: Indicates the current state of the comment
:type state: object
:param text: The plaintext/markdown version of the comment
:type text: str
:param version: The current version of the comment
:type version: int
"""
_attribute_map = {
'url': {'key': 'url', 'type': 'str'},
'artifact_id': {'key': 'artifactId', 'type': 'str'},
'created_by': {'key': 'createdBy', 'type': 'IdentityRef'},
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'int'},
'is_deleted': {'key': 'isDeleted', 'type': 'bool'},
'mentions': {'key': 'mentions', 'type': '[CommentMention]'},
'modified_by': {'key': 'modifiedBy', 'type': 'IdentityRef'},
'modified_date': {'key': 'modifiedDate', 'type': 'iso-8601'},
'parent_id': {'key': 'parentId', 'type': 'int'},
'reactions': {'key': 'reactions', 'type': '[CommentReaction]'},
'rendered_text': {'key': 'renderedText', 'type': 'str'},
'replies': {'key': 'replies', 'type': 'CommentList'},
'state': {'key': 'state', 'type': 'object'},
'text': {'key': 'text', 'type': 'str'},
'version': {'key': 'version', 'type': 'int'}
}
def __init__(self, url=None, artifact_id=None, created_by=None, created_date=None, id=None, is_deleted=None, mentions=None, modified_by=None, modified_date=None, parent_id=None, reactions=None, rendered_text=None, replies=None, state=None, text=None, version=None):
super(Comment, self).__init__(url=url)
self.artifact_id = artifact_id
self.created_by = created_by
self.created_date = created_date
self.id = id
self.is_deleted = is_deleted
self.mentions = mentions
self.modified_by = modified_by
self.modified_date = modified_date
self.parent_id = parent_id
self.reactions = reactions
self.rendered_text = rendered_text
self.replies = replies
self.state = state
self.text = text
self.version = version
class CommentAttachment(CommentResourceReference):
"""
Represents an attachment to a comment.
:param url:
:type url: str
:param created_by: IdentityRef of the creator of the attachment.
:type created_by: :class:`IdentityRef <azure.devops.v7_1.microsoft._azure._dev_ops._comments._web_api.models.IdentityRef>`
:param created_date: The creation date of the attachment.
:type created_date: datetime
:param id: Unique Id of the attachment.
:type id: str
"""
_attribute_map = {
'url': {'key': 'url', 'type': 'str'},
'created_by': {'key': 'createdBy', 'type': 'IdentityRef'},
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'str'}
}
def __init__(self, url=None, created_by=None, created_date=None, id=None):
super(CommentAttachment, self).__init__(url=url)
self.created_by = created_by
self.created_date = created_date
self.id = id
class CommentList(CommentResourceReference):
"""
Represents a list of comments.
:param url:
:type url: str
:param comments: List of comments in the current batch.
:type comments: list of :class:`Comment <azure.devops.v7_1.microsoft._azure._dev_ops._comments._web_api.models.Comment>`
:param continuation_token: A string token that can be used to retrieving next page of comments if available. Otherwise null.
:type continuation_token: str
:param count: The count of comments in the current batch.
:type count: int
:param next_page: Uri to the next page of comments if it is available. Otherwise null.
:type next_page: str
:param total_count: Total count of comments on a work item.
:type total_count: int
"""
_attribute_map = {
'url': {'key': 'url', 'type': 'str'},
'comments': {'key': 'comments', 'type': '[Comment]'},
'continuation_token': {'key': 'continuationToken', 'type': 'str'},
'count': {'key': 'count', 'type': 'int'},
'next_page': {'key': 'nextPage', 'type': 'str'},
'total_count': {'key': 'totalCount', 'type': 'int'}
}
def __init__(self, url=None, comments=None, continuation_token=None, count=None, next_page=None, total_count=None):
super(CommentList, self).__init__(url=url)
self.comments = comments
self.continuation_token = continuation_token
self.count = count
self.next_page = next_page
self.total_count = total_count
class CommentMention(CommentResourceReference):
"""
Contains information about various artifacts mentioned in the comment
:param url:
:type url: str
:param artifact_id: Id of the artifact this mention belongs to
:type artifact_id: str
:param comment_id: Id of the comment associated with this mention. Nullable to support legacy mentions which can potentially have null commentId
:type comment_id: int
:param mentioned_artifact: Value of the mentioned artifact. Expected Value varies by CommentMentionType: Person: VSID associated with the identity Work Item: ID of the work item Pull Request: ID of the Pull Request
:type mentioned_artifact: str
:param type: The context which represent where this mentioned was parsed from
:type type: object
"""
_attribute_map = {
'url': {'key': 'url', 'type': 'str'},
'artifact_id': {'key': 'artifactId', 'type': 'str'},
'comment_id': {'key': 'commentId', 'type': 'int'},
'mentioned_artifact': {'key': 'mentionedArtifact', 'type': 'str'},
'type': {'key': 'type', 'type': 'object'}
}
def __init__(self, url=None, artifact_id=None, comment_id=None, mentioned_artifact=None, type=None):
super(CommentMention, self).__init__(url=url)
self.artifact_id = artifact_id
self.comment_id = comment_id
self.mentioned_artifact = mentioned_artifact
self.type = type
class CommentReaction(CommentResourceReference):
"""
Contains information about comment reaction for a particular reaction type.
:param url:
:type url: str
:param comment_id: The id of the comment this reaction belongs to.
:type comment_id: int
:param count: Total number of reactions for the CommentReactionType.
:type count: int
:param is_current_user_engaged: Flag to indicate if the current user has engaged on this particular EngagementType (e.g. if they liked the associated comment).
:type is_current_user_engaged: bool
:param type: Type of the reaction.
:type type: object
"""
_attribute_map = {
'url': {'key': 'url', 'type': 'str'},
'comment_id': {'key': 'commentId', 'type': 'int'},
'count': {'key': 'count', 'type': 'int'},
'is_current_user_engaged': {'key': 'isCurrentUserEngaged', 'type': 'bool'},
'type': {'key': 'type', 'type': 'object'}
}
def __init__(self, url=None, comment_id=None, count=None, is_current_user_engaged=None, type=None):
super(CommentReaction, self).__init__(url=url)
self.comment_id = comment_id
self.count = count
self.is_current_user_engaged = is_current_user_engaged
self.type = type
class WikiPage(WikiPageCreateOrUpdateParameters):
"""
Defines a page in a wiki.
:param content: Content of the wiki page.
:type content: str
:param git_item_path: Path of the git item corresponding to the wiki page stored in the backing Git repository.
:type git_item_path: str
:param id: When present, permanent identifier for the wiki page
:type id: int
:param is_non_conformant: True if a page is non-conforming, i.e. 1) if the name doesn't match page naming standards. 2) if the page does not have a valid entry in the appropriate order file.
:type is_non_conformant: bool
:param is_parent_page: True if this page has subpages under its path.
:type is_parent_page: bool
:param order: Order of the wiki page, relative to other pages in the same hierarchy level.
:type order: int
:param path: Path of the wiki page.
:type path: str
:param remote_url: Remote web url to the wiki page.
:type remote_url: str
:param sub_pages: List of subpages of the current page.
:type sub_pages: list of :class:`WikiPage <azure.devops.v7_1.wiki.models.WikiPage>`
:param url: REST url for this wiki page.
:type url: str
"""
_attribute_map = {
'content': {'key': 'content', 'type': 'str'},
'git_item_path': {'key': 'gitItemPath', 'type': 'str'},
'id': {'key': 'id', 'type': 'int'},
'is_non_conformant': {'key': 'isNonConformant', 'type': 'bool'},
'is_parent_page': {'key': 'isParentPage', 'type': 'bool'},
'order': {'key': 'order', 'type': 'int'},
'path': {'key': 'path', 'type': 'str'},
'remote_url': {'key': 'remoteUrl', 'type': 'str'},
'sub_pages': {'key': 'subPages', 'type': '[WikiPage]'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, content=None, git_item_path=None, id=None, is_non_conformant=None, is_parent_page=None, order=None, path=None, remote_url=None, sub_pages=None, url=None):
super(WikiPage, self).__init__(content=content)
self.git_item_path = git_item_path
self.id = id
self.is_non_conformant = is_non_conformant
self.is_parent_page = is_parent_page
self.order = order
self.path = path
self.remote_url = remote_url
self.sub_pages = sub_pages
self.url = url
class WikiPageMove(WikiPageMoveParameters):
"""
Request contract for Wiki Page Move.
:param new_order: New order of the wiki page.
:type new_order: int
:param new_path: New path of the wiki page.
:type new_path: str
:param path: Current path of the wiki page.
:type path: str
:param page: Resultant page of this page move operation.
:type page: :class:`WikiPage <azure.devops.v7_1.wiki.models.WikiPage>`
"""
_attribute_map = {
'new_order': {'key': 'newOrder', 'type': 'int'},
'new_path': {'key': 'newPath', 'type': 'str'},
'path': {'key': 'path', 'type': 'str'},
'page': {'key': 'page', 'type': 'WikiPage'}
}
def __init__(self, new_order=None, new_path=None, path=None, page=None):
super(WikiPageMove, self).__init__(new_order=new_order, new_path=new_path, path=path)
self.page = page
__all__ = [
'CommentCreateParameters',
'CommentResourceReference',
'CommentUpdateParameters',
'GitRepository',
'GitRepositoryRef',
'GitVersionDescriptor',
'GraphSubjectBase',
'IdentityRef',
'ReferenceLinks',
'TeamProjectCollectionReference',
'TeamProjectReference',
'WikiAttachment',
'WikiAttachmentResponse',
'WikiCreateBaseParameters',
'WikiCreateParametersV2',
'WikiPageCreateOrUpdateParameters',
'WikiPageDetail',
'WikiPageMoveParameters',
'WikiPageMoveResponse',
'WikiPageResponse',
'WikiPagesBatchRequest',
'WikiPageStat',
'WikiPageViewStats',
'WikiUpdateParameters',
'WikiV2',
'Comment',
'CommentAttachment',
'CommentList',
'CommentMention',
'CommentReaction',
'WikiPage',
'WikiPageMove',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/wiki/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/wiki/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 15889
}
| 361 |
#!/usr/bin/env bash
# Update the version strings in the source code
# Input:
# $1 - the version string, if omitted, use ${BUILD_BUILDID}
version=$1
if [ -z ${version} ]; then
version=`expr match "${BUILD_BUILDID}" '\([0-9]*\)'`
fi
if [ -z ${version} ]; then
echo 'Missing version string'
exit 1
fi
echo "Add dev version suffix: $version"
platform=`uname`
echo "Platform: $platform"
pattern="s/^VERSION = [\"']\(.*\)[\"']/VERSION = \"\1.dev$version\"/"
if [ "${platform}" == "MSYS_NT-10.0" ]; then
# On preview version of sh build task, the script will pick up the wrong version of find.exe
find="C:\Program Files\Git\usr\bin\find.exe"
else
find="find"
fi
for each in $("${find}" . -name setup.py); do
if [ "$platform" == "Darwin" ]; then
sed -i "" "${pattern}" "${each}"
rc=$?; if [[ ${rc} != 0 ]]; then exit ${rc}; fi
else
sed -i "${pattern}" "${each}"
rc=$?; if [[ ${rc} != 0 ]]; then exit ${rc}; fi
fi
done
for each in $("${find}" . -name version.py); do
if [ "$platform" == "Darwin" ]; then
sed -i "" "${pattern}" "${each}"
rc=$?; if [[ ${rc} != 0 ]]; then exit ${rc}; fi
else
sed -i "${pattern}" "${each}"
rc=$?; if [[ ${rc} != 0 ]]; then exit ${rc}; fi
fi
done
|
azure-devops-python-api/scripts/ci/version.sh/0
|
{
"file_path": "azure-devops-python-api/scripts/ci/version.sh",
"repo_id": "azure-devops-python-api",
"token_count": 542
}
| 362 |
# The build-stage image:
FROM continuumio/miniconda3 AS build
# Install the package as normal:
COPY qdk/environment.yml .
RUN conda env create -f environment.yml
# Install conda-pack:
RUN conda install -c conda-forge conda-pack
# Use conda-pack to create a standalone enviornment
# in /venv:
RUN conda-pack -n qdk -o /tmp/env.tar && \
mkdir /venv && cd /venv && tar xf /tmp/env.tar && \
rm /tmp/env.tar
# We've put venv in same path it'll be in final image,
# so now fix up paths:
RUN /venv/bin/conda-unpack
# This uses the latest Docker image built from the samples repository,
# defined by the Dockerfile in the Quantum repository
# (folder: /Build/images/samples).
FROM mcr.microsoft.com/quantum/samples:latest
# Copy /venv from the previous stage:
COPY --from=build /venv /venv
# Mark that this Docker environment is hosted within qdk-python
ENV IQSHARP_HOSTING_ENV=qdk-python
# Make sure the contents of our repo are in ${HOME}.
# These steps are required for use on mybinder.org.
USER root
COPY . /src
COPY examples ${HOME}
# Install qdk-python in development mode
SHELL ["/bin/bash", "-c"]
RUN source /venv/bin/activate && pip install -e /src/qdk
RUN chown -R ${USER} ${HOME}
# Finish by dropping back to the notebook user
USER ${USER}
# When image is run, start jupyter notebook within the environment
ENTRYPOINT source /venv/bin/activate && \
jupyter notebook --ip 0.0.0.0
|
azure-quantum-python/Dockerfile/0
|
{
"file_path": "azure-quantum-python/Dockerfile",
"repo_id": "azure-quantum-python",
"token_count": 491
}
| 363 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from copy import deepcopy
from typing import Any, TYPE_CHECKING
from azure.core import PipelineClient
from azure.core.pipeline import policies
from azure.core.rest import HttpRequest, HttpResponse
from . import models as _models
from ._configuration import QuantumClientConfiguration
from ._serialization import Deserializer, Serializer
from .operations import (
JobsOperations,
ProvidersOperations,
QuotasOperations,
SessionsOperations,
StorageOperations,
TopLevelItemsOperations,
)
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials import TokenCredential
class QuantumClient: # pylint: disable=client-accepts-api-version-keyword
"""Azure Quantum REST API client.
:ivar jobs: JobsOperations operations
:vartype jobs: azure.quantum._client.operations.JobsOperations
:ivar providers: ProvidersOperations operations
:vartype providers: azure.quantum._client.operations.ProvidersOperations
:ivar storage: StorageOperations operations
:vartype storage: azure.quantum._client.operations.StorageOperations
:ivar quotas: QuotasOperations operations
:vartype quotas: azure.quantum._client.operations.QuotasOperations
:ivar sessions: SessionsOperations operations
:vartype sessions: azure.quantum._client.operations.SessionsOperations
:ivar top_level_items: TopLevelItemsOperations operations
:vartype top_level_items: azure.quantum._client.operations.TopLevelItemsOperations
:param azure_region: Supported Azure regions for Azure Quantum Services. For example, "eastus".
Required.
:type azure_region: str
:param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g.
00000000-0000-0000-0000-000000000000). Required.
:type subscription_id: str
:param resource_group_name: Name of an Azure resource group. Required.
:type resource_group_name: str
:param workspace_name: Name of the workspace. Required.
:type workspace_name: str
:param credential: Credential needed for the client to connect to Azure. Required.
:type credential: ~azure.core.credentials.TokenCredential
:keyword api_version: Api Version. Default value is "2023-11-13-preview". Note that overriding
this default value may result in unsupported behavior.
:paramtype api_version: str
"""
def __init__(
self,
azure_region: str,
subscription_id: str,
resource_group_name: str,
workspace_name: str,
credential: "TokenCredential",
**kwargs: Any
) -> None:
_endpoint = kwargs.pop("endpoint", f"https://{azure_region}.quantum.azure.com")
self._config = QuantumClientConfiguration(
azure_region=azure_region,
subscription_id=subscription_id,
resource_group_name=resource_group_name,
workspace_name=workspace_name,
credential=credential,
**kwargs
)
_policies = kwargs.pop("policies", None)
if _policies is None:
_policies = [
policies.RequestIdPolicy(**kwargs),
self._config.headers_policy,
self._config.user_agent_policy,
self._config.proxy_policy,
policies.ContentDecodePolicy(**kwargs),
self._config.redirect_policy,
self._config.retry_policy,
self._config.authentication_policy,
self._config.custom_hook_policy,
self._config.logging_policy,
policies.DistributedTracingPolicy(**kwargs),
policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None,
self._config.http_logging_policy,
]
self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs)
client_models = {k: v for k, v in _models._models.__dict__.items() if isinstance(v, type)}
client_models.update({k: v for k, v in _models.__dict__.items() if isinstance(v, type)})
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self._serialize.client_side_validation = False
self.jobs = JobsOperations(self._client, self._config, self._serialize, self._deserialize)
self.providers = ProvidersOperations(self._client, self._config, self._serialize, self._deserialize)
self.storage = StorageOperations(self._client, self._config, self._serialize, self._deserialize)
self.quotas = QuotasOperations(self._client, self._config, self._serialize, self._deserialize)
self.sessions = SessionsOperations(self._client, self._config, self._serialize, self._deserialize)
self.top_level_items = TopLevelItemsOperations(self._client, self._config, self._serialize, self._deserialize)
def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse:
"""Runs the network request through the client's chained policies.
>>> from azure.core.rest import HttpRequest
>>> request = HttpRequest("GET", "https://www.example.org/")
<HttpRequest [GET], url: 'https://www.example.org/'>
>>> response = client.send_request(request)
<HttpResponse: 200 OK>
For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request
:param request: The network request you want to make. Required.
:type request: ~azure.core.rest.HttpRequest
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
:return: The response of your network call. Does not do error handling on your response.
:rtype: ~azure.core.rest.HttpResponse
"""
request_copy = deepcopy(request)
path_format_arguments = {
"azureRegion": self._serialize.url(
"self._config.azure_region", self._config.azure_region, "str", skip_quote=True
),
}
request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore
def close(self) -> None:
self._client.close()
def __enter__(self) -> "QuantumClient":
self._client.__enter__()
return self
def __exit__(self, *exc_details: Any) -> None:
self._client.__exit__(*exc_details)
|
azure-quantum-python/azure-quantum/azure/quantum/_client/_client.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/_client/_client.py",
"repo_id": "azure-quantum-python",
"token_count": 2581
}
| 364 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
from dataclasses import dataclass
from enum import Enum
from typing import Optional, Type
class Pauli(Enum):
"""Pauli operators"""
I = "PauliI"
X = "PauliX"
Y = "PauliY"
Z = "PauliZ"
class Result(Enum):
"""Result value"""
Zero = False
One = True
@dataclass
class Range:
"""Range value
:param start: Start
:type start: int
:param end: End
:type end: int
:param step: Step
:type step: int
"""
start: int
end: int
step: Optional[int] = None
@property
def value(self):
"""Range value"""
if self.step is None:
return {"start": self.start, "end": self.end}
else:
return {"start": self.start, "end": self.end, "step": self.step}
@dataclass
class EmptyArray:
"""Empty array value"""
element_type: Type
"""Element type"""
|
azure-quantum-python/azure-quantum/azure/quantum/argument_types/types.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/argument_types/types.py",
"repo_id": "azure-quantum-python",
"token_count": 410
}
| 365 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
from typing import TYPE_CHECKING, Union
from azure.quantum._client.models import SessionDetails, JobDetails
from azure.quantum.job.job import Job
from azure.quantum.job.session import Session
if TYPE_CHECKING:
from azure.quantum.workspace import Workspace
__all__ = ["WorkspaceItemFactory"]
class WorkspaceItemFactory():
"""
:param workspace: Workspace instance to submit job to
:type workspace: Workspace
:param item_details: Item details model,
contains item ID, name and other details
:type item_details: ItemDetails
"""
@staticmethod
def __new__(workspace:"Workspace",
item_details:Union[SessionDetails, JobDetails]
) -> Union[Session, Job]:
if isinstance(item_details, JobDetails):
return Job(workspace, job_details=item_details)
elif isinstance(item_details, SessionDetails):
return Session(workspace, details=item_details)
else:
raise TypeError("item_details must be of type `SessionDetails` or `JobDetails`.")
|
azure-quantum-python/azure-quantum/azure/quantum/job/workspace_item_factory.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/job/workspace_item_factory.py",
"repo_id": "azure-quantum-python",
"token_count": 410
}
| 366 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
"""Defines classes for interacting with Microsoft Estimator"""
__all__ = ["ErrorBudgetPartition", "MicrosoftEstimator",
"MicrosoftEstimatorJob", "MicrosoftEstimatorResult",
"MicrosoftEstimatorParams", "QECScheme", "QubitParams"]
from .job import MicrosoftEstimatorJob
from .result import MicrosoftEstimatorResult
from .target import ErrorBudgetPartition, MicrosoftEstimator, \
MicrosoftEstimatorParams, QECScheme, QubitParams
|
azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/__init__.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/__init__.py",
"repo_id": "azure-quantum-python",
"token_count": 174
}
| 367 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
from typing import TYPE_CHECKING, Any, Dict, Optional, Union, Type, Protocol, runtime_checkable
import io
import json
import abc
import warnings
from azure.quantum._client.models import TargetStatus, SessionDetails
from azure.quantum._client.models._enums import SessionJobFailurePolicy
from azure.quantum.job.job import Job, BaseJob
from azure.quantum.job.session import Session, SessionHost
from azure.quantum.job.base_job import ContentType
from azure.quantum.target.params import InputParams
if TYPE_CHECKING:
from azure.quantum import Workspace
@runtime_checkable
class QirRepresentable(Protocol):
_name: str
@abc.abstractmethod
def _repr_qir_(self, **kwargs: Any) -> bytes:
raise NotImplementedError
class Target(abc.ABC, SessionHost):
_QSHARP_USER_AGENT = "azure-quantum-qsharp"
"""Azure Quantum Target."""
# Target IDs that are compatible with this Target class.
# This variable is used by TargetFactory. To set the default
# target class for a given provider, specify the
# default_targets constructor argument.
#
# If you provide a custom job class (derived from
# azurem.quantum.job.job.Job) for this target, you must pass this type to
# __init__ via the job_cls parameter. This is then used by the target's
# submit and get_job method.
target_names = ()
"""Tuple of target names."""
# Name of the provider's input parameter which specifies number of shots for a submitted job.
# If None, target will not pass this input parameter.
_SHOTS_PARAM_NAME = None
def __init__(
self,
workspace: "Workspace",
name: str,
input_data_format: str = "",
output_data_format: str = "",
capability: str = "",
provider_id: str = "",
content_type: ContentType = ContentType.json,
encoding: str = "",
average_queue_time: Union[float, None] = None,
current_availability: str = ""
):
"""
Initializes a new target.
:param workspace: Associated workspace
:type workspace: Workspace
:param name: Target name
:type name: str
:param input_data_format: Format of input data (ex. "qir.v1")
:type input_data_format: str
:param output_data_format: Format of output data (ex. "microsoft.resource-estimates.v1")
:type output_data_format: str
:param capability: QIR capability
:type capability: str
:param provider_id: Id of provider (ex. "microsoft-qc")
:type provider_id: str
:param content_type: "Content-Type" attribute value to set on input blob (ex. "application/json")
:type content_type: azure.quantum.job.ContentType
:param encoding: "Content-Encoding" attribute value to set on input blob (ex. "gzip")
:type encoding: str
:param average_queue_time: Set average queue time (for internal use)
:type average_queue_time: float
:param current_availability: Set current availability (for internal use)
:type current_availability: str
"""
if not provider_id and "." in name:
provider_id = name.split(".")[0]
self.workspace = workspace
self.name = name
self.input_data_format = input_data_format
self.output_data_format = output_data_format
self.capability = capability
self.provider_id = provider_id
self.content_type = content_type
self.encoding = encoding
self._average_queue_time = average_queue_time
self._current_availability = current_availability
def __repr__(self):
return f"<Target name=\"{self.name}\", \
avg. queue time={self._average_queue_time} s, {self._current_availability}>"
@classmethod
def from_target_status(
cls, workspace: "Workspace", status: TargetStatus, **kwargs
):
"""Create a Target instance from a given workspace and target status.
:param workspace: Associated workspace
:type workspace: Workspace
:param status: Target status with availability and current queue time
:type status: TargetStatus
:return: Target instance
:rtype: Target
"""
return cls(
workspace=workspace,
name=status.id,
average_queue_time=status.average_queue_time,
current_availability=status.current_availability,
**kwargs
)
@classmethod
def _get_job_class(cls) -> Type[Job]:
"""
Returns the job class associated to this target.
The job class used by submit and get_job. The default is Job.
"""
return Job
@classmethod
def _can_send_shots_input_param(cls) -> bool:
"""
Tells if provider's target class is able to specify shots number for its jobs.
"""
return cls._SHOTS_PARAM_NAME is not None
def refresh(self):
"""Update the target availability and queue time"""
targets = self.workspace._get_target_status(self.name, self.provider_id)
if len(targets) > 0:
_, target_status = targets[0]
self._current_availability = target_status.current_availability
self._average_queue_time = target_status.average_queue_time
else:
raise ValueError(
f"Cannot refresh the Target status: \
target '{self.name}' of provider '{self.provider_id}' not found."
)
@property
def current_availability(self):
"""
Current availability.
"""
return self._current_availability
@property
def average_queue_time(self):
"""
Average queue time.
"""
return self._average_queue_time
@staticmethod
def _encode_input_data(data: Any) -> bytes:
"""Encode input data to bytes.
If the data is already in bytes format, return it.
:param data: Input data
:type data: Any
:return: Encoded input data
:rtype: bytes
"""
if isinstance(data, bytes):
return data
else:
stream = io.BytesIO()
if isinstance(data, dict):
data = json.dumps(data)
stream.write(data.encode())
return stream.getvalue()
def _qir_output_data_format(self) -> str:
""""Fallback output data format in case of QIR job submission."""
return "microsoft.quantum-results.v1"
def submit(
self,
input_data: Any,
name: str = "azure-quantum-job",
shots: int = None,
input_params: Union[Dict[str, Any], InputParams, None] = None,
**kwargs
) -> Job:
"""Submit input data and return Job.
Provide input_data_format, output_data_format and content_type
keyword arguments to override default values.
:param input_data: Input data
:type input_data: Any
:param name: Job name
:type name: str
:param shots: Number of shots, defaults to None
:type shots: int
:param input_params: Input parameters
:type input_params: Dict[str, Any]
:return: Azure Quantum job
:rtype: azure.quantum.job.Job
"""
if isinstance(input_params, InputParams):
input_params = input_params.as_dict()
else:
input_params = input_params or {}
input_data_format = None
output_data_format = None
content_type = None
# If the input_data is `QirRepresentable`
# we need to convert it to QIR bitcode and set the necessary parameters for a QIR job.
if input_data and isinstance(input_data, QirRepresentable):
input_data_format = kwargs.pop("input_data_format", "qir.v1")
output_data_format = kwargs.pop("output_data_format", self._qir_output_data_format())
content_type = kwargs.pop("content_type", "qir.v1")
# setting UserAgent header to indicate Q# submission
# TODO: this is a temporary solution. We should be setting the User-Agent header
# on per-job basis as targets of different types could be submitted using the same Workspace object
self.workspace.append_user_agent(self._QSHARP_USER_AGENT)
def _get_entrypoint(input_data):
# TODO: this method should be part of QirRepresentable protocol
# and will later move to the QSharpCallable class in the qsharp package
import re
method_name = re.search(r"(?:^|\.)([^.]*)$", input_data._name).group(1)
return f'ENTRYPOINT__{method_name}'
input_params["entryPoint"] = input_params.get("entryPoint", _get_entrypoint(input_data))
input_params["arguments"] = input_params.get("arguments", [])
targetCapability = input_params.get("targetCapability", kwargs.pop("target_capability", self.capability))
if targetCapability:
input_params["targetCapability"] = targetCapability
input_data = input_data._repr_qir_(target=self.name, target_capability=targetCapability)
else:
input_data_format = kwargs.pop("input_data_format", self.input_data_format)
output_data_format = kwargs.pop("output_data_format", self.output_data_format)
content_type = kwargs.pop("content_type", self.content_type)
# re-setting UserAgent header to None for passthrough
self.workspace.append_user_agent(None)
# Set shots number, if possible.
if self._can_send_shots_input_param():
input_params_shots = input_params.pop(self.__class__._SHOTS_PARAM_NAME, None)
# If there is a parameter conflict, choose 'shots'.
if shots is not None and input_params_shots is not None:
warnings.warn(
f"Parameter 'shots' conflicts with the '{self.__class__._SHOTS_PARAM_NAME}' field of the 'input_params' "
"parameter. Please, provide only one option for setting shots. Defaulting to 'shots' parameter."
)
final_shots = shots
# The 'shots' parameter has highest priority.
elif shots is not None:
final_shots = shots
# if 'shots' parameter is not specified, try a provider-specific option.
elif input_params_shots is not None:
warnings.warn(
f"Field '{self.__class__._SHOTS_PARAM_NAME}' from the 'input_params' parameter is subject to change in future versions. "
"Please, use 'shots' parameter instead."
)
final_shots = input_params_shots
else:
final_shots = None
if final_shots is not None:
input_params[self.__class__._SHOTS_PARAM_NAME] = final_shots
encoding = kwargs.pop("encoding", self.encoding)
blob = self._encode_input_data(data=input_data)
job_cls = type(self)._get_job_class()
return job_cls.from_input_data(
workspace=self.workspace,
name=name,
target=self.name,
input_data=blob,
content_type=content_type,
encoding=encoding,
provider_id=self.provider_id,
input_data_format=input_data_format,
output_data_format=output_data_format,
input_params=input_params,
session_id=self.get_latest_session_id(),
**kwargs
)
def make_params(self):
"""
Returns an input parameter object for convenient creation of input
parameters.
"""
return InputParams()
def estimate_cost(
self,
input_data: Any,
input_params: Union[Dict[str, Any], None] = None
):
"""
Estimate the cost for a given circuit.
"""
return NotImplementedError("Price estimation is not implemented yet for this target.")
def _get_azure_workspace(self) -> "Workspace":
return self.workspace
def _get_azure_target_id(self) -> str:
return self.name
def _get_azure_provider_id(self) -> str:
return self.provider_id
def _determine_shots_or_deprecated_num_shots(
shots: int = None,
num_shots: int = None,
) -> int:
"""
This helper function checks if the deprecated 'num_shots' parameter is specified.
In earlier versions it was possible to pass this parameter to specify shots number for a job,
but now we only check for it for compatibility reasons.
"""
final_shots = None
if shots is not None and num_shots is not None:
warnings.warn(
"Both 'shots' and 'num_shots' parameters were specified. Defaulting to 'shots' parameter. "
"Please, use 'shots' since 'num_shots' will be deprecated.",
category=DeprecationWarning,
)
final_shots = shots
elif shots is not None:
final_shots = shots
elif num_shots is not None:
warnings.warn(
"The 'num_shots' parameter will be deprecated. Please, use 'shots' parameter instead.",
category=DeprecationWarning,
)
final_shots = num_shots
return final_shots
|
azure-quantum-python/azure-quantum/azure/quantum/target/target.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/target/target.py",
"repo_id": "azure-quantum-python",
"token_count": 5642
}
| 368 |
[pytest]
markers =
live_test: mark a test as a live test that requires recordings.
ionq: mark a test as requiring access to ionq.
quantinuum: mark a test as requiring access to quantinuum.
rigetti: mark a test as requiring access to Rigetti targets.
qci: mark a test as requiring access to QCI targets.
microsoft_qc: mark a test as requiring access to microsoft-qc targets.
qsharp: mark a test as requiring dependency of the qsharp package.
session: mark a test as requiring access to session feature.
cirq: mark a test as requiring Cirq
qiskit: mark a test as requiring Qiskit
qir: mark a test as requiring QIR
echo_targets: mark a test as requiring access to Microsoft test echo targets.
pasqal: mark a test as requiring access to Pasqal targets.
microsoft_elements_dft: mark a test as requiring access to microsoft.dft targets.
log_cli = True
log_cli_level = ERROR
|
azure-quantum-python/azure-quantum/pytest.ini/0
|
{
"file_path": "azure-quantum-python/azure-quantum/pytest.ini",
"repo_id": "azure-quantum-python",
"token_count": 289
}
| 369 |
interactions:
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_info=1&client_secret=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '144'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1745073439, "ext_expires_in":
1745073439, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000001", "name": "session-00000000-0000-0000-0000-000000000001",
"providerId": "microsoft.test", "target": "echo-quantinuum", "itemType": "Session",
"jobFailurePolicy": "Abort"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '218'
Content-Type:
- application/json
User-Agent:
- testapp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"status": "Waiting", "jobFailurePolicy": "Abort", "name": "session-00000000-0000-0000-0000-000000000001",
"id": "00000000-0000-0000-0000-000000000001", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:20.5914732Z",
"endExecutionTime": null, "costEstimate": null, "itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '332'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_info=1&client_secret=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '144'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1745073441, "ext_expires_in":
1745073441, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000002"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '64'
Content-Type:
- application/json
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl"}'
headers:
connection:
- keep-alive
content-length:
- '174'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:22 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: "\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ContainerNotFound</Code><Message>The
specified container does not exist.\nRequestId:9a9091b6-701e-0006-1267-921f7f000000\nTime:2024-04-19T14:37:23.2397163Z</Message></Error>"
headers:
content-length:
- '223'
content-type:
- application/xml
x-ms-version:
- '2023-11-03'
status:
code: 404
message: The specified container does not exist.
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:23 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:23 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-version:
- '2023-11-03'
status:
code: 200
message: OK
- request:
body: 'b''%Result = type opaque\n%Qubit = type opaque\n\ndefine void @ENTRYPOINT__main()
#0 {\n call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 0 to %Qubit*))\n call
void @__quantum__qis__cx__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Qubit*
inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 2 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 2 to %Qubit*), %Qubit* inttoptr (i64 0 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 2 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 3 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 3 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 3 to %Qubit*))\n call void @__quantum__qis__mz__body(%Qubit*
inttoptr (i64 2 to %Qubit*), %Result* inttoptr (i64 0 to %Result*)) #1\n call
void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 3 to %Qubit*), %Result*
inttoptr (i64 1 to %Result*)) #1\n call void @__quantum__rt__tuple_record_output(i64
2, i8* null)\n call void @__quantum__rt__result_record_output(%Result* inttoptr
(i64 0 to %Result*), i8* null)\n call void @__quantum__rt__result_record_output(%Result*
inttoptr (i64 1 to %Result*), i8* null)\n ret void\n}\n\ndeclare void @__quantum__qis__ccx__body(%Qubit*,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cx__body(%Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__cy__body(%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cz__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__rx__body(double, %Qubit*)\ndeclare void
@__quantum__qis__rxx__body(double, %Qubit*, %Qubit*)\ndeclare void @__quantum__qis__ry__body(double,
%Qubit*)\ndeclare void @__quantum__qis__ryy__body(double, %Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__rz__body(double, %Qubit*)\ndeclare void @__quantum__qis__rzz__body(double,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__h__body(%Qubit*)\ndeclare void
@__quantum__qis__s__body(%Qubit*)\ndeclare void @__quantum__qis__s__adj(%Qubit*)\ndeclare
void @__quantum__qis__t__body(%Qubit*)\ndeclare void @__quantum__qis__t__adj(%Qubit*)\ndeclare
void @__quantum__qis__x__body(%Qubit*)\ndeclare void @__quantum__qis__y__body(%Qubit*)\ndeclare
void @__quantum__qis__z__body(%Qubit*)\ndeclare void @__quantum__qis__swap__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__mz__body(%Qubit*, %Result* writeonly)
#1\ndeclare void @__quantum__rt__result_record_output(%Result*, i8*)\ndeclare
void @__quantum__rt__array_record_output(i64, i8*)\ndeclare void @__quantum__rt__tuple_record_output(i64,
i8*)\n\nattributes #0 = { "entry_point" "output_labeling_schema" "qir_profiles"="base_profile"
"required_num_qubits"="4" "required_num_results"="2" }\nattributes #1 = { "irreversible"
}\n\n; module flags\n\n!llvm.module.flags = !{!0, !1, !2, !3}\n\n!0 = !{i32
1, !"qir_major_version", i32 1}\n!1 = !{i32 7, !"qir_minor_version", i32 0}\n!2
= !{i32 1, !"dynamic_qubit_management", i1 false}\n!3 = !{i32 1, !"dynamic_result_management",
i1 false}\n'''
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '3073'
Content-Type:
- application/octet-stream
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-blob-type:
- BlockBlob
x-ms-date:
- Fri, 19 Apr 2024 14:37:24 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000002", "name": "Bad Job 1",
"providerId": "microsoft.test", "target": "echo-quantinuum", "itemType": "Job",
"sessionId": "00000000-0000-0000-0000-000000000001", "containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "outputDataFormat":
"invalid_output_format"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '676'
Content-Type:
- application/json
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
1", "id": "00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1178'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
1", "id": "00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
1", "id": "00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
1", "id": "00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=4
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
1", "id": "00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=5
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
1", "id": "00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=6
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"Bad Job 1", "id": "00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1421'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=7
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Executing",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": "2024-04-19T14:37:28.634Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Bad Job 1", "id": "00000000-0000-0000-0000-000000000002",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:37:24.5554222+00:00", "endExecutionTime": null, "costEstimate":
null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1445'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=8
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Executing",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": "2024-04-19T14:37:28.634Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Bad Job 1", "id": "00000000-0000-0000-0000-000000000002",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:37:24.5554222+00:00", "endExecutionTime": null, "costEstimate":
null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1445'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=9
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Executing",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": "2024-04-19T14:37:28.634Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Bad Job 1", "id": "00000000-0000-0000-0000-000000000002",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:37:24.5554222+00:00", "endExecutionTime": null, "costEstimate":
null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1445'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=10
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Executing",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": "2024-04-19T14:37:28.634Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Bad Job 1", "id": "00000000-0000-0000-0000-000000000002",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:37:24.5554222+00:00", "endExecutionTime": null, "costEstimate":
null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1445'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000002?api-version=2022-09-12-preview&test-sequence-id=11
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Failed", "jobType":
"QuantumComputing", "outputDataFormat": "invalid_output_format", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B1-00000000-0000-0000-0000-000000000002.output.json",
"beginExecutionTime": "2024-04-19T14:37:28.634Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": {"code": "CannotTranslateOutputData",
"message": "The output returned by ''microsoft.test'' cannot be translated
as specified by ''outputDataFormat''. Please ensure that ''outputDataFormat''
is correct."}, "isCancelling": false, "tags": [], "name": "Bad Job 1", "id":
"00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test", "target":
"echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222+00:00", "endExecutionTime":
"2024-04-19T14:37:47.743Z", "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1658'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- testapp-azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"status": "Failed", "jobFailurePolicy": "Abort", "name": "session-00000000-0000-0000-0000-000000000001",
"id": "00000000-0000-0000-0000-000000000001", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:20.5914732Z",
"endExecutionTime": "2024-04-19T14:37:48.8457092Z", "costEstimate": null,
"itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '357'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_info=1&client_secret=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '144'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1745073470, "ext_expires_in":
1745073470, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000003"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '64'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000003?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl"}'
headers:
connection:
- keep-alive
content-length:
- '174'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:51 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000003?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: "\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ContainerNotFound</Code><Message>The
specified container does not exist.\nRequestId:a6318e86-501e-004c-6a67-92bcf0000000\nTime:2024-04-19T14:37:52.3915610Z</Message></Error>"
headers:
content-length:
- '223'
content-type:
- application/xml
x-ms-version:
- '2023-11-03'
status:
code: 404
message: The specified container does not exist.
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:52 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000003?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:52 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000003?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-version:
- '2023-11-03'
status:
code: 200
message: OK
- request:
body: 'b''%Result = type opaque\n%Qubit = type opaque\n\ndefine void @ENTRYPOINT__main()
#0 {\n call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 0 to %Qubit*))\n call
void @__quantum__qis__cx__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Qubit*
inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 2 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 2 to %Qubit*), %Qubit* inttoptr (i64 0 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 2 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 3 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 3 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 3 to %Qubit*))\n call void @__quantum__qis__mz__body(%Qubit*
inttoptr (i64 2 to %Qubit*), %Result* inttoptr (i64 0 to %Result*)) #1\n call
void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 3 to %Qubit*), %Result*
inttoptr (i64 1 to %Result*)) #1\n call void @__quantum__rt__tuple_record_output(i64
2, i8* null)\n call void @__quantum__rt__result_record_output(%Result* inttoptr
(i64 0 to %Result*), i8* null)\n call void @__quantum__rt__result_record_output(%Result*
inttoptr (i64 1 to %Result*), i8* null)\n ret void\n}\n\ndeclare void @__quantum__qis__ccx__body(%Qubit*,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cx__body(%Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__cy__body(%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cz__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__rx__body(double, %Qubit*)\ndeclare void
@__quantum__qis__rxx__body(double, %Qubit*, %Qubit*)\ndeclare void @__quantum__qis__ry__body(double,
%Qubit*)\ndeclare void @__quantum__qis__ryy__body(double, %Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__rz__body(double, %Qubit*)\ndeclare void @__quantum__qis__rzz__body(double,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__h__body(%Qubit*)\ndeclare void
@__quantum__qis__s__body(%Qubit*)\ndeclare void @__quantum__qis__s__adj(%Qubit*)\ndeclare
void @__quantum__qis__t__body(%Qubit*)\ndeclare void @__quantum__qis__t__adj(%Qubit*)\ndeclare
void @__quantum__qis__x__body(%Qubit*)\ndeclare void @__quantum__qis__y__body(%Qubit*)\ndeclare
void @__quantum__qis__z__body(%Qubit*)\ndeclare void @__quantum__qis__swap__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__mz__body(%Qubit*, %Result* writeonly)
#1\ndeclare void @__quantum__rt__result_record_output(%Result*, i8*)\ndeclare
void @__quantum__rt__array_record_output(i64, i8*)\ndeclare void @__quantum__rt__tuple_record_output(i64,
i8*)\n\nattributes #0 = { "entry_point" "output_labeling_schema" "qir_profiles"="base_profile"
"required_num_qubits"="4" "required_num_results"="2" }\nattributes #1 = { "irreversible"
}\n\n; module flags\n\n!llvm.module.flags = !{!0, !1, !2, !3}\n\n!0 = !{i32
1, !"qir_major_version", i32 1}\n!1 = !{i32 7, !"qir_minor_version", i32 0}\n!2
= !{i32 1, !"dynamic_qubit_management", i1 false}\n!3 = !{i32 1, !"dynamic_result_management",
i1 false}\n'''
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '3073'
Content-Type:
- application/octet-stream
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-blob-type:
- BlockBlob
x-ms-date:
- Fri, 19 Apr 2024 14:37:53 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000003/inputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000003", "name": "Good Job 2",
"providerId": "microsoft.test", "target": "echo-quantinuum", "itemType": "Job",
"sessionId": "00000000-0000-0000-0000-000000000001", "containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000003?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000003/inputData",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "outputDataFormat":
"honeywell.qir.v1"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '672'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000003?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"error": {"code": "InvalidJobDefinition", "message": "Session is already
in a terminal state. This may have been due to failures in prior jobs in the
session."}}'
headers:
connection:
- keep-alive
content-length:
- '162'
content-type:
- application/json; charset=utf-8
status:
code: 400
message: Bad Request
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000001/jobs?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"value": [{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000002/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000001", "status": "Failed", "jobType":
"QuantumComputing", "outputDataFormat": "invalid_output_format", "outputDataUri":
"https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000002/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": "2024-04-19T14:37:28.634Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": {"code": "CannotTranslateOutputData",
"message": "The output returned by ''microsoft.test'' cannot be translated
as specified by ''outputDataFormat''. Please ensure that ''outputDataFormat''
is correct."}, "isCancelling": false, "tags": [], "name": "Bad Job 1", "id":
"00000000-0000-0000-0000-000000000002", "providerId": "microsoft.test", "target":
"echo-quantinuum", "creationTime": "2024-04-19T14:37:24.5554222Z", "endExecutionTime":
"2024-04-19T14:37:47.743Z", "costEstimate": null, "itemType": "Job"}], "nextLink":
null}'
headers:
connection:
- keep-alive
content-length:
- '1520'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"status": "Failed", "jobFailurePolicy": "Abort", "name": "session-00000000-0000-0000-0000-000000000001",
"id": "00000000-0000-0000-0000-000000000001", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:20.5914732Z",
"endExecutionTime": "2024-04-19T14:37:48.8457092Z", "costEstimate": null,
"itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '357'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000001?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"status": "Failed", "jobFailurePolicy": "Abort", "name": "session-00000000-0000-0000-0000-000000000001",
"id": "00000000-0000-0000-0000-000000000001", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:20.5914732Z",
"endExecutionTime": "2024-04-19T14:37:48.8457092Z", "costEstimate": null,
"itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '357'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000004", "name": "session-00000000-0000-0000-0000-000000000004",
"providerId": "microsoft.test", "target": "echo-quantinuum", "itemType": "Session",
"jobFailurePolicy": "Continue"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '221'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000004?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"status": "Waiting", "jobFailurePolicy": "Continue", "name": "session-00000000-0000-0000-0000-000000000004",
"id": "00000000-0000-0000-0000-000000000004", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:54.7630082Z",
"endExecutionTime": null, "costEstimate": null, "itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '335'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_info=1&client_secret=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '144'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1745073475, "ext_expires_in":
1745073475, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000005"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '64'
Content-Type:
- application/json
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl"}'
headers:
connection:
- keep-alive
content-length:
- '174'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:56 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: "\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ContainerNotFound</Code><Message>The
specified container does not exist.\nRequestId:ea96fb79-b01e-006b-6867-92ab34000000\nTime:2024-04-19T14:37:57.3639112Z</Message></Error>"
headers:
content-length:
- '223'
content-type:
- application/xml
x-ms-version:
- '2023-11-03'
status:
code: 404
message: The specified container does not exist.
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:57 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:37:57 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-version:
- '2023-11-03'
status:
code: 200
message: OK
- request:
body: 'b''%Result = type opaque\n%Qubit = type opaque\n\ndefine void @ENTRYPOINT__main()
#0 {\n call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 0 to %Qubit*))\n call
void @__quantum__qis__cx__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Qubit*
inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 2 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 2 to %Qubit*), %Qubit* inttoptr (i64 0 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 2 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 3 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 3 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 3 to %Qubit*))\n call void @__quantum__qis__mz__body(%Qubit*
inttoptr (i64 2 to %Qubit*), %Result* inttoptr (i64 0 to %Result*)) #1\n call
void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 3 to %Qubit*), %Result*
inttoptr (i64 1 to %Result*)) #1\n call void @__quantum__rt__tuple_record_output(i64
2, i8* null)\n call void @__quantum__rt__result_record_output(%Result* inttoptr
(i64 0 to %Result*), i8* null)\n call void @__quantum__rt__result_record_output(%Result*
inttoptr (i64 1 to %Result*), i8* null)\n ret void\n}\n\ndeclare void @__quantum__qis__ccx__body(%Qubit*,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cx__body(%Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__cy__body(%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cz__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__rx__body(double, %Qubit*)\ndeclare void
@__quantum__qis__rxx__body(double, %Qubit*, %Qubit*)\ndeclare void @__quantum__qis__ry__body(double,
%Qubit*)\ndeclare void @__quantum__qis__ryy__body(double, %Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__rz__body(double, %Qubit*)\ndeclare void @__quantum__qis__rzz__body(double,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__h__body(%Qubit*)\ndeclare void
@__quantum__qis__s__body(%Qubit*)\ndeclare void @__quantum__qis__s__adj(%Qubit*)\ndeclare
void @__quantum__qis__t__body(%Qubit*)\ndeclare void @__quantum__qis__t__adj(%Qubit*)\ndeclare
void @__quantum__qis__x__body(%Qubit*)\ndeclare void @__quantum__qis__y__body(%Qubit*)\ndeclare
void @__quantum__qis__z__body(%Qubit*)\ndeclare void @__quantum__qis__swap__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__mz__body(%Qubit*, %Result* writeonly)
#1\ndeclare void @__quantum__rt__result_record_output(%Result*, i8*)\ndeclare
void @__quantum__rt__array_record_output(i64, i8*)\ndeclare void @__quantum__rt__tuple_record_output(i64,
i8*)\n\nattributes #0 = { "entry_point" "output_labeling_schema" "qir_profiles"="base_profile"
"required_num_qubits"="4" "required_num_results"="2" }\nattributes #1 = { "irreversible"
}\n\n; module flags\n\n!llvm.module.flags = !{!0, !1, !2, !3}\n\n!0 = !{i32
1, !"qir_major_version", i32 1}\n!1 = !{i32 7, !"qir_minor_version", i32 0}\n!2
= !{i32 1, !"dynamic_qubit_management", i1 false}\n!3 = !{i32 1, !"dynamic_result_management",
i1 false}\n'''
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '3073'
Content-Type:
- application/octet-stream
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-blob-type:
- BlockBlob
x-ms-date:
- Fri, 19 Apr 2024 14:37:58 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000005", "name": "Good Job 1",
"providerId": "microsoft.test", "target": "echo-quantinuum", "itemType": "Job",
"sessionId": "00000000-0000-0000-0000-000000000004", "containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "outputDataFormat":
"honeywell.qir.v1"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '672'
Content-Type:
- application/json
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000005/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 1", "id": "00000000-0000-0000-0000-000000000005", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:58.7117425+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1245'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 1", "id": "00000000-0000-0000-0000-000000000005", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:58.7117425+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 1", "id": "00000000-0000-0000-0000-000000000005", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:58.7117425+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 1", "id": "00000000-0000-0000-0000-000000000005", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:58.7117425+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=4
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 1", "id": "00000000-0000-0000-0000-000000000005", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:58.7117425+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=5
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"Good Job 1", "id": "00000000-0000-0000-0000-000000000005", "providerId":
"microsoft.test", "target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:58.7117425+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1419'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=6
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"Good Job 1", "id": "00000000-0000-0000-0000-000000000005", "providerId":
"microsoft.test", "target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:58.7117425+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1419'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000005?api-version=2022-09-12-preview&test-sequence-id=7
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Succeeded",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B1-00000000-0000-0000-0000-000000000005.output.json",
"beginExecutionTime": "2024-04-19T14:38:01.92Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Good Job 1", "id": "00000000-0000-0000-0000-000000000005",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:37:58.7117425+00:00", "endExecutionTime": "2024-04-19T14:38:02.522Z",
"costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1467'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000004?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"status": "Executing", "jobFailurePolicy": "Continue", "name": "session-00000000-0000-0000-0000-000000000004",
"id": "00000000-0000-0000-0000-000000000004", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:54.7630082Z",
"endExecutionTime": null, "costEstimate": null, "itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '337'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_info=1&client_secret=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '144'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1745073485, "ext_expires_in":
1745073485, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000006"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '64'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=4
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl"}'
headers:
connection:
- keep-alive
content-length:
- '174'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:38:06 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: "\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ContainerNotFound</Code><Message>The
specified container does not exist.\nRequestId:71d77dfd-101e-003f-4667-92e463000000\nTime:2024-04-19T14:38:07.2050178Z</Message></Error>"
headers:
content-length:
- '223'
content-type:
- application/xml
x-ms-version:
- '2023-11-03'
status:
code: 404
message: The specified container does not exist.
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:38:07 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:38:07 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-version:
- '2023-11-03'
status:
code: 200
message: OK
- request:
body: 'b''%Result = type opaque\n%Qubit = type opaque\n\ndefine void @ENTRYPOINT__main()
#0 {\n call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 0 to %Qubit*))\n call
void @__quantum__qis__cx__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Qubit*
inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 2 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 2 to %Qubit*), %Qubit* inttoptr (i64 0 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 2 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 3 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 3 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 3 to %Qubit*))\n call void @__quantum__qis__mz__body(%Qubit*
inttoptr (i64 2 to %Qubit*), %Result* inttoptr (i64 0 to %Result*)) #1\n call
void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 3 to %Qubit*), %Result*
inttoptr (i64 1 to %Result*)) #1\n call void @__quantum__rt__tuple_record_output(i64
2, i8* null)\n call void @__quantum__rt__result_record_output(%Result* inttoptr
(i64 0 to %Result*), i8* null)\n call void @__quantum__rt__result_record_output(%Result*
inttoptr (i64 1 to %Result*), i8* null)\n ret void\n}\n\ndeclare void @__quantum__qis__ccx__body(%Qubit*,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cx__body(%Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__cy__body(%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cz__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__rx__body(double, %Qubit*)\ndeclare void
@__quantum__qis__rxx__body(double, %Qubit*, %Qubit*)\ndeclare void @__quantum__qis__ry__body(double,
%Qubit*)\ndeclare void @__quantum__qis__ryy__body(double, %Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__rz__body(double, %Qubit*)\ndeclare void @__quantum__qis__rzz__body(double,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__h__body(%Qubit*)\ndeclare void
@__quantum__qis__s__body(%Qubit*)\ndeclare void @__quantum__qis__s__adj(%Qubit*)\ndeclare
void @__quantum__qis__t__body(%Qubit*)\ndeclare void @__quantum__qis__t__adj(%Qubit*)\ndeclare
void @__quantum__qis__x__body(%Qubit*)\ndeclare void @__quantum__qis__y__body(%Qubit*)\ndeclare
void @__quantum__qis__z__body(%Qubit*)\ndeclare void @__quantum__qis__swap__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__mz__body(%Qubit*, %Result* writeonly)
#1\ndeclare void @__quantum__rt__result_record_output(%Result*, i8*)\ndeclare
void @__quantum__rt__array_record_output(i64, i8*)\ndeclare void @__quantum__rt__tuple_record_output(i64,
i8*)\n\nattributes #0 = { "entry_point" "output_labeling_schema" "qir_profiles"="base_profile"
"required_num_qubits"="4" "required_num_results"="2" }\nattributes #1 = { "irreversible"
}\n\n; module flags\n\n!llvm.module.flags = !{!0, !1, !2, !3}\n\n!0 = !{i32
1, !"qir_major_version", i32 1}\n!1 = !{i32 7, !"qir_minor_version", i32 0}\n!2
= !{i32 1, !"dynamic_qubit_management", i1 false}\n!3 = !{i32 1, !"dynamic_result_management",
i1 false}\n'''
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '3073'
Content-Type:
- application/octet-stream
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-blob-type:
- BlockBlob
x-ms-date:
- Fri, 19 Apr 2024 14:38:08 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000006", "name": "Bad Job 2",
"providerId": "microsoft.test", "target": "echo-quantinuum", "itemType": "Job",
"sessionId": "00000000-0000-0000-0000-000000000004", "containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "outputDataFormat":
"invalid_output_format"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '676'
Content-Type:
- application/json
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000006?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
2", "id": "00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1249'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000006?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
2", "id": "00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000006?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
2", "id": "00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000006?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
2", "id": "00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000006?api-version=2022-09-12-preview&test-sequence-id=4
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Bad Job
2", "id": "00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1413'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000006?api-version=2022-09-12-preview&test-sequence-id=5
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "invalid_output_format",
"outputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"Bad Job 2", "id": "00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1421'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000006?api-version=2022-09-12-preview&test-sequence-id=6
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Failed", "jobType":
"QuantumComputing", "outputDataFormat": "invalid_output_format", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DBad%2BJob%2B2-00000000-0000-0000-0000-000000000006.output.json",
"beginExecutionTime": "2024-04-19T14:38:11.997Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": {"code": "CannotTranslateOutputData",
"message": "The output returned by ''microsoft.test'' cannot be translated
as specified by ''outputDataFormat''. Please ensure that ''outputDataFormat''
is correct."}, "isCancelling": false, "tags": [], "name": "Bad Job 2", "id":
"00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test", "target":
"echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259+00:00", "endExecutionTime":
"2024-04-19T14:38:12.565Z", "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1658'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000004?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"status": "Failure(s)", "jobFailurePolicy": "Continue", "name": "session-00000000-0000-0000-0000-000000000004",
"id": "00000000-0000-0000-0000-000000000004", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:54.7630082Z",
"endExecutionTime": null, "costEstimate": null, "itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '338'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: client_id=PLACEHOLDER&grant_type=client_credentials&client_info=1&client_secret=PLACEHOLDER&scope=https%3A%2F%2Fquantum.microsoft.com%2F.default
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '144'
Content-Type:
- application/x-www-form-urlencoded
User-Agent:
- azsdk-python-identity/1.16.0 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-client-current-telemetry:
- 4|730,2|
x-client-os:
- win32
x-client-sku:
- MSAL.Python
x-client-ver:
- 1.28.0
method: POST
uri: https://login.microsoftonline.com/00000000-0000-0000-0000-000000000000/oauth2/v2.0/token
response:
body:
string: '{"token_type": "Bearer", "expires_in": 1745073494, "ext_expires_in":
1745073494, "refresh_in": 31536000, "access_token": "PLACEHOLDER"}'
headers:
content-length:
- '135'
content-type:
- application/json; charset=utf-8
status:
code: 200
message: OK
- request:
body: 'b''{"containerName": "job-00000000-0000-0000-0000-000000000007"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '64'
Content-Type:
- application/json
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/storage/sasUri?api-version=2022-09-12-preview&test-sequence-id=5
response:
body:
string: '{"sasUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl"}'
headers:
connection:
- keep-alive
content-length:
- '174'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:38:15 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: "\uFEFF<?xml version=\"1.0\" encoding=\"utf-8\"?><Error><Code>ContainerNotFound</Code><Message>The
specified container does not exist.\nRequestId:6cef325a-301e-0038-0567-928800000000\nTime:2024-04-19T14:38:16.0080726Z</Message></Error>"
headers:
content-length:
- '223'
content-type:
- application/xml
x-ms-version:
- '2023-11-03'
status:
code: 404
message: The specified container does not exist.
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:38:15 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: null
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-date:
- Fri, 19 Apr 2024 14:38:16 GMT
x-ms-version:
- '2023-11-03'
method: GET
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?restype=container&sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-lease-state:
- available
x-ms-lease-status:
- unlocked
x-ms-version:
- '2023-11-03'
status:
code: 200
message: OK
- request:
body: 'b''%Result = type opaque\n%Qubit = type opaque\n\ndefine void @ENTRYPOINT__main()
#0 {\n call void @__quantum__qis__h__body(%Qubit* inttoptr (i64 0 to %Qubit*))\n call
void @__quantum__qis__cx__body(%Qubit* inttoptr (i64 0 to %Qubit*), %Qubit*
inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 2 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 2 to %Qubit*), %Qubit* inttoptr (i64 0 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 2 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit* inttoptr
(i64 3 to %Qubit*))\n call void @__quantum__qis__cz__body(%Qubit* inttoptr
(i64 3 to %Qubit*), %Qubit* inttoptr (i64 1 to %Qubit*))\n call void @__quantum__qis__h__body(%Qubit*
inttoptr (i64 3 to %Qubit*))\n call void @__quantum__qis__mz__body(%Qubit*
inttoptr (i64 2 to %Qubit*), %Result* inttoptr (i64 0 to %Result*)) #1\n call
void @__quantum__qis__mz__body(%Qubit* inttoptr (i64 3 to %Qubit*), %Result*
inttoptr (i64 1 to %Result*)) #1\n call void @__quantum__rt__tuple_record_output(i64
2, i8* null)\n call void @__quantum__rt__result_record_output(%Result* inttoptr
(i64 0 to %Result*), i8* null)\n call void @__quantum__rt__result_record_output(%Result*
inttoptr (i64 1 to %Result*), i8* null)\n ret void\n}\n\ndeclare void @__quantum__qis__ccx__body(%Qubit*,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cx__body(%Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__cy__body(%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__cz__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__rx__body(double, %Qubit*)\ndeclare void
@__quantum__qis__rxx__body(double, %Qubit*, %Qubit*)\ndeclare void @__quantum__qis__ry__body(double,
%Qubit*)\ndeclare void @__quantum__qis__ryy__body(double, %Qubit*, %Qubit*)\ndeclare
void @__quantum__qis__rz__body(double, %Qubit*)\ndeclare void @__quantum__qis__rzz__body(double,
%Qubit*, %Qubit*)\ndeclare void @__quantum__qis__h__body(%Qubit*)\ndeclare void
@__quantum__qis__s__body(%Qubit*)\ndeclare void @__quantum__qis__s__adj(%Qubit*)\ndeclare
void @__quantum__qis__t__body(%Qubit*)\ndeclare void @__quantum__qis__t__adj(%Qubit*)\ndeclare
void @__quantum__qis__x__body(%Qubit*)\ndeclare void @__quantum__qis__y__body(%Qubit*)\ndeclare
void @__quantum__qis__z__body(%Qubit*)\ndeclare void @__quantum__qis__swap__body(%Qubit*,
%Qubit*)\ndeclare void @__quantum__qis__mz__body(%Qubit*, %Result* writeonly)
#1\ndeclare void @__quantum__rt__result_record_output(%Result*, i8*)\ndeclare
void @__quantum__rt__array_record_output(i64, i8*)\ndeclare void @__quantum__rt__tuple_record_output(i64,
i8*)\n\nattributes #0 = { "entry_point" "output_labeling_schema" "qir_profiles"="base_profile"
"required_num_qubits"="4" "required_num_results"="2" }\nattributes #1 = { "irreversible"
}\n\n; module flags\n\n!llvm.module.flags = !{!0, !1, !2, !3}\n\n!0 = !{i32
1, !"qir_major_version", i32 1}\n!1 = !{i32 7, !"qir_minor_version", i32 0}\n!2
= !{i32 1, !"dynamic_qubit_management", i1 false}\n!3 = !{i32 1, !"dynamic_result_management",
i1 false}\n'''
headers:
Accept:
- application/xml
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '3073'
Content-Type:
- application/octet-stream
User-Agent:
- azsdk-python-storage-blob/12.19.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
x-ms-blob-type:
- BlockBlob
x-ms-date:
- Fri, 19 Apr 2024 14:38:17 GMT
x-ms-version:
- '2023-11-03'
method: PUT
uri: https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl
response:
body:
string: ''
headers:
content-length:
- '0'
x-ms-version:
- '2023-11-03'
status:
code: 201
message: Created
- request:
body: 'b''{"id": "00000000-0000-0000-0000-000000000007", "name": "Good Job 3",
"providerId": "microsoft.test", "target": "echo-quantinuum", "itemType": "Job",
"sessionId": "00000000-0000-0000-0000-000000000004", "containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "outputDataFormat":
"honeywell.qir.v1"}'''
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '672'
Content-Type:
- application/json
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: PUT
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 3", "id": "00000000-0000-0000-0000-000000000007", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:17.5588825+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1245'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 3", "id": "00000000-0000-0000-0000-000000000007", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:17.5588825+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=2
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 3", "id": "00000000-0000-0000-0000-000000000007", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:17.5588825+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 3", "id": "00000000-0000-0000-0000-000000000007", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:17.5588825+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=4
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
null, "errorData": null, "isCancelling": false, "tags": [], "name": "Good
Job 3", "id": "00000000-0000-0000-0000-000000000007", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:17.5588825+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1411'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=5
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Waiting",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": null, "cancellationTime": null, "quantumComputingData":
{"count": 1}, "errorData": null, "isCancelling": false, "tags": [], "name":
"Good Job 3", "id": "00000000-0000-0000-0000-000000000007", "providerId":
"microsoft.test", "target": "echo-quantinuum", "creationTime": "2024-04-19T14:38:17.5588825+00:00",
"endExecutionTime": null, "costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1419'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=6
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Executing",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": "2024-04-19T14:38:21.037Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Good Job 3", "id": "00000000-0000-0000-0000-000000000007",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:38:17.5588825+00:00", "endExecutionTime": null, "costEstimate":
null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1443'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=7
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Executing",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": "2024-04-19T14:38:21.037Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Good Job 3", "id": "00000000-0000-0000-0000-000000000007",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:38:17.5588825+00:00", "endExecutionTime": null, "costEstimate":
null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1443'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=8
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Executing",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/outputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": "2024-04-19T14:38:21.037Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Good Job 3", "id": "00000000-0000-0000-0000-000000000007",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:38:17.5588825+00:00", "endExecutionTime": null, "costEstimate":
null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1443'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/jobs/00000000-0000-0000-0000-000000000007?api-version=2022-09-12-preview&test-sequence-id=9
response:
body:
string: '{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sr=c&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.input.json",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Succeeded",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/rawOutputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=r&rscd=attachment%3B%20filename%3DGood%2BJob%2B3-00000000-0000-0000-0000-000000000007.output.json",
"beginExecutionTime": "2024-04-19T14:38:21.037Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Good Job 3", "id": "00000000-0000-0000-0000-000000000007",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:38:17.5588825+00:00", "endExecutionTime": "2024-04-19T14:38:26.529Z",
"costEstimate": null, "itemType": "Job"}'
headers:
connection:
- keep-alive
content-length:
- '1468'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000004?api-version=2022-09-12-preview&test-sequence-id=3
response:
body:
string: '{"status": "Failure(s)", "jobFailurePolicy": "Continue", "name": "session-00000000-0000-0000-0000-000000000004",
"id": "00000000-0000-0000-0000-000000000004", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:54.7630082Z",
"endExecutionTime": null, "costEstimate": null, "itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '338'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: GET
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000004/jobs?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"value": [{"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000005/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Succeeded",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000005/rawOutputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": "2024-04-19T14:38:01.92Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Good Job 1", "id": "00000000-0000-0000-0000-000000000005",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:37:58.7117425Z", "endExecutionTime": "2024-04-19T14:38:02.522Z",
"costEstimate": null, "itemType": "Job"}, {"containerUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000006/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Failed", "jobType":
"QuantumComputing", "outputDataFormat": "invalid_output_format", "outputDataUri":
"https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000006/outputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": "2024-04-19T14:38:11.997Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": {"code": "CannotTranslateOutputData",
"message": "The output returned by ''microsoft.test'' cannot be translated
as specified by ''outputDataFormat''. Please ensure that ''outputDataFormat''
is correct."}, "isCancelling": false, "tags": [], "name": "Bad Job 2", "id":
"00000000-0000-0000-0000-000000000006", "providerId": "microsoft.test", "target":
"echo-quantinuum", "creationTime": "2024-04-19T14:38:08.7194259Z", "endExecutionTime":
"2024-04-19T14:38:12.565Z", "costEstimate": null, "itemType": "Job"}, {"containerUri":
"https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"inputDataUri": "https://mystorage.blob.core.windows.net/job-00000000-0000-0000-0000-000000000007/inputData?sv=PLACEHOLDER&sr=b&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&sp=rcw",
"inputDataFormat": "qir.v1", "inputParams": {"entryPoint": "ENTRYPOINT__main",
"arguments": [], "targetCapability": "AdaptiveExecution"}, "metadata": null,
"sessionId": "00000000-0000-0000-0000-000000000004", "status": "Succeeded",
"jobType": "QuantumComputing", "outputDataFormat": "honeywell.qir.v1", "outputDataUri":
"https://mystorage.blob.core.windows.net:443/job-00000000-0000-0000-0000-000000000007/rawOutputData?sv=PLACEHOLDER&sig=PLACEHOLDER&se=2050-01-01T00%3A00%3A00Z&srt=co&ss=b&sp=racwl",
"beginExecutionTime": "2024-04-19T14:38:21.037Z", "cancellationTime": null,
"quantumComputingData": {"count": 1}, "errorData": null, "isCancelling": false,
"tags": [], "name": "Good Job 3", "id": "00000000-0000-0000-0000-000000000007",
"providerId": "microsoft.test", "target": "echo-quantinuum", "creationTime":
"2024-04-19T14:38:17.5588825Z", "endExecutionTime": "2024-04-19T14:38:26.529Z",
"costEstimate": null, "itemType": "Job"}], "nextLink": null}'
headers:
connection:
- keep-alive
content-length:
- '4117'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
Content-Length:
- '0'
User-Agent:
- azure-quantum-qsharp azsdk-python-quantum/0.0.1 Python/3.9.19 (Windows-10-10.0.22631-SP0)
method: POST
uri: https://eastus.quantum.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myresourcegroup/providers/Microsoft.Quantum/workspaces/myworkspace/sessions/00000000-0000-0000-0000-000000000004:close?api-version=2022-09-12-preview&test-sequence-id=1
response:
body:
string: '{"status": "Failed", "jobFailurePolicy": "Continue", "name": "session-00000000-0000-0000-0000-000000000004",
"id": "00000000-0000-0000-0000-000000000004", "providerId": "microsoft.test",
"target": "echo-quantinuum", "creationTime": "2024-04-19T14:37:54.7630082Z",
"endExecutionTime": "2024-04-19T14:38:30.1579207Z", "costEstimate": null,
"itemType": "Session"}'
headers:
connection:
- keep-alive
content-length:
- '360'
content-type:
- application/json; charset=utf-8
transfer-encoding:
- chunked
status:
code: 200
message: OK
version: 1
|
azure-quantum-python/azure-quantum/tests/unit/recordings/test_session_job_failure_policies_echo_quantinuum.yaml/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/recordings/test_session_job_failure_policies_echo_quantinuum.yaml",
"repo_id": "azure-quantum-python",
"token_count": 71330
}
| 370 |
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
import pytest
from azure.quantum import JobStatus
from common import QuantumTestBase, DEFAULT_TIMEOUT_SECS
from import_qsharp import skip_if_no_qsharp
from test_job_payload_factory import JobPayloadFactory
@pytest.mark.qsharp
@pytest.mark.live_test
@skip_if_no_qsharp
class TestQSharpQIRJob(QuantumTestBase):
@pytest.mark.rigetti
def test_qsharp_qir_inline_rigetti(self):
self._run_job("rigetti.sim.qvm", inline=True)
@pytest.mark.rigetti
def test_qsharp_qir_file_rigetti(self):
self._run_job("rigetti.sim.qvm", inline=False)
@pytest.mark.quantinuum
def test_qsharp_qir_inline_quantinuum_h2(self):
self._run_job("quantinuum.sim.h2-1e", inline=True)
@pytest.mark.quantinuum
def test_qsharp_qir_inline_quantinuum(self):
self._run_job("quantinuum.sim.h1-1e", inline=True)
@pytest.mark.quantinuum
def test_qsharp_qir_file_quantinuum(self):
self._run_job("quantinuum.sim.h1-1e", inline=False)
@pytest.mark.skip("Modern Q# doesn't currently support QIR format required by \"microsoft.estimator\" target")
@pytest.mark.microsoft_qc
def test_qsharp_qir_inline_microsoft_qc(self):
self._run_job("microsoft.estimator", inline=True)
@pytest.mark.skip("Modern Q# doesn't currently support QIR format required by \"microsoft.estimator\" target")
@pytest.mark.microsoft_qc
def test_qsharp_qir_file_microsoft_qc(self):
self._run_job("microsoft.estimator", inline=False)
def _run_job(self, target_name, inline):
workspace = self.create_workspace()
target = workspace.get_targets(target_name)
input_data = (JobPayloadFactory.get_qsharp_inline_callable_bell_state() if inline
else JobPayloadFactory.get_qsharp_file_callable_bell_state())
job = target.submit(input_data=input_data)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
job.refresh()
self.assertEqual(job.details.status, JobStatus.SUCCEEDED)
results = job.get_results(timeout_secs=DEFAULT_TIMEOUT_SECS)
self.assertIsNotNone(results)
|
azure-quantum-python/azure-quantum/tests/unit/test_qsharp.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/test_qsharp.py",
"repo_id": "azure-quantum-python",
"token_count": 898
}
| 371 |
---
page_type: sample
author: cgranade
description: Find hidden shifts in Boolean functions, using the Azure Quantum service
ms.author: [email protected]
ms.date: 01/25/2021
languages:
- qsharp
- python
products:
- azure-quantum
---
# Finding hidden shift of bent functions using the Azure Quantum service
This sample demonstrates how to use Qiskit and Azure Quantum together to learn the hidden shift of bent functions.
This sample is available as part of the Azure Quantum notebook samples gallery in the Azure Portal. For an example of how to run these notebooks in Azure, see [this getting started guide](https://learn.microsoft.com/azure/quantum/get-started-jupyter-notebook).
## Manifest
- [hidden-shift.ipynb](https://github.com/microsoft/azure-quantum-python/blob/main/samples/hidden-shift/hidden-shift.ipynb): Python + Qiskit notebook demonstrating hidden shift with the Azure Quantum service.
|
azure-quantum-python/samples/hidden-shift/README.md/0
|
{
"file_path": "azure-quantum-python/samples/hidden-shift/README.md",
"repo_id": "azure-quantum-python",
"token_count": 245
}
| 372 |
# Visualization Library Build Process
## Local Dev
Run `build-all-local.sh` script from the build folder.
## ADO pipeline flow for CI/CD
> [_microsoft.visualization_](https://ms-quantum.visualstudio.com/Quantum%20Program/_build?definitionId=789&_a=summary)
The build pipeline is composed of:
- `visualization-lib.yml`
- `build-jslib.sh`
|
azure-quantum-python/visualization/build/Readme.md/0
|
{
"file_path": "azure-quantum-python/visualization/build/Readme.md",
"repo_id": "azure-quantum-python",
"token_count": 115
}
| 373 |
/*------------------------------------
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
All rights reserved.
------------------------------------ */
import * as React from "react";
import * as d3 from "d3";
import * as d3Format from "d3-format";
import * as d3Helper from "./D3HelperFunctions";
import { TextStyle } from "./D3HelperFunctions";
export type LineChartProps = {
chartData: { [key: string]: any };
width: number;
height: number;
};
/* Define Styles */
const runtimeTextStyle: TextStyle = {
fontFamily: "Segoe UI",
fontStyle: "normal",
fontWeight: "600",
fontSize: "14",
lineHeight: "23",
display: "flex",
color: "#323130",
textAlign: null,
textAnchor: null,
alignItems: null,
};
const lineLabelStyle: TextStyle = {
fontFamily: "Segoe UI",
fontStyle: "normal",
fontWeight: "400",
fontSize: "16",
lineHeight: "23",
display: "flex",
color: "#323130",
textAlign: null,
textAnchor: null,
alignItems: null,
};
const titleStyle: TextStyle = {
fontFamily: "Segoe UI",
fontStyle: "normal",
fontWeight: "600",
fontSize: "35",
lineHeight: "47",
display: "flex",
alignItems: "center",
textAlign: "center",
color: "#201f1e",
textAnchor: "middle",
};
/* Helper Functions */
function drawChartVerticalLine(
svg: d3.Selection<d3.BaseType, unknown, HTMLElement, any>,
startX: number,
startY: number,
textStartY: number,
length: number,
lineColor: string,
strokeWidth: string,
id: string,
label: string,
) {
const dashedVerticalLinePoints = [
[startX, startY],
[startX, length],
];
d3Helper.drawCircleMarkers(
svg,
10,
10,
lineColor,
1.5,
5,
5,
5,
5,
"circleMarker",
);
d3Helper.drawLine(
svg,
dashedVerticalLinePoints,
id + "dashedLine",
strokeWidth,
"url(#circleMarker)",
"url(#circleMarker)",
"none",
lineColor,
true,
);
// Append runtime text
d3Helper.drawText(svg, label, startX + 10, textStartY, runtimeTextStyle);
}
function drawChartHorizontalLine(
svg: d3.Selection<d3.BaseType, unknown, HTMLElement, any>,
startX: number,
startY: number,
length: number,
lineColor: string,
strokeWidth: string,
id: string,
label: string,
) {
const linePoints = [
[startX, startY],
[startX + length, startY],
];
// Create start bar
const lineTickId = id + "Tick";
d3Helper.drawLineTick(svg, 1, 10, lineColor, lineTickId);
// Create end arrow
const arrowId = id + "Arrow";
d3Helper.drawArrow(svg, lineColor, arrowId);
// Draw line
d3Helper.drawLine(
svg,
linePoints,
id + "line",
strokeWidth,
"url(#" + lineTickId + ")",
"url(#" + arrowId + ")",
lineColor,
lineColor,
false,
);
// Append text labels to line if applicable.
if (label != null || label != "") {
d3Helper.drawText(svg, label, startX + length + 5, startY, lineLabelStyle);
}
}
function drawTFactoryLines(
svg: d3.Selection<d3.BaseType, unknown, HTMLElement, any>,
numLines: number,
tFactoryXScale: d3.ScaleLinear<number, number, never>,
chartStartX: number,
tFactoryLineY: number,
strokeWidth: string,
tfactoryLineColor: string,
startVal: number,
) {
for (let i = startVal; i < numLines; i++) {
const x1 = tFactoryXScale(i) + chartStartX;
const x2 = tFactoryXScale(i + 1) + chartStartX;
const y = tFactoryLineY;
const points = [
[x1, y],
[x2, y],
];
d3Helper.drawLine(
svg,
points,
"tfactoryLine",
strokeWidth,
"url(#tFactoryTick)",
"url(#arrowTFactory)",
"none",
tfactoryLineColor,
false,
);
}
}
/* Line Chart Component */
function LineChart({ chartData, width, height }: LineChartProps) {
React.useEffect(() => {
/* ------------------------------------------------------------ Set up and define constants ------------------------------------------------------------ */
const svg = d3.select("#linechart");
svg.selectAll("*").remove();
/* ------------------------------ Define chart styling constants ------------------------------ */
const strokeWidth = "2";
const colorArray = ["#1a5d8c", "#8c1a5c", "#aebac0", "#323130"];
/*------------------------------ Define color ranges ------------------------------ */
const algorithmRunTimeColor = colorArray[1];
const tfactoryLineColor = colorArray[0];
const ellipsesColor = colorArray[2];
const timeLineColor = colorArray[3];
/*------------------------------ Define chart data from dictionary ------------------------------ */
const numberTStates: number = chartData["numberTStates"];
const numberTFactoryInvocations: number =
chartData["numberTFactoryInvocations"];
const algorithmRuntime: number = chartData["algorithmRuntime"];
const tFactoryRuntime: number = chartData["tFactoryRuntime"];
const algorithmRuntimeFormatted: string =
chartData["algorithmRuntimeFormatted"];
const tFactoryRuntimeFormatted: string =
chartData["tFactoryRuntimeFormatted"];
/* Define chart constants */
const numTStatesString: string = d3Format.format(",.0f")(numberTStates);
const tfactoryLineLabel: string =
numTStatesString +
(numberTStates == 1
? " T state produced after each invocation's runtime"
: " T states produced after each invocation's runtime");
/* Define legend */
const legendData = [
{
title: "Algorithm",
value: algorithmRuntime,
legendTitle: "runtime",
},
{
title: "Single T factory invocation",
value: tFactoryRuntime,
legendTitle: "runtime",
},
];
/* ------------------------------ Define chart dimensions ------------------------------ */
const chartStartY = 0.6 * height;
const verticalLineSpacingDist = 0.15 * height;
const xAxisLength = 0.85 * width;
const chartStartX = 0.05 * width;
const chartLength = xAxisLength - xAxisLength * 0.15;
const midpoint = xAxisLength / 2;
const algorithmLineY = chartStartY - verticalLineSpacingDist;
const tFactoryLineY = chartStartY - verticalLineSpacingDist * 2;
/* ------------------------------ Define chart length ratios ------------------------------ */
const minAlgorithmLineLength = xAxisLength * 0.05;
const minTFactoryInvocationLength = xAxisLength * 0.015;
let lengthAlgorithmLine = chartLength;
let lengthTFactoryLine = chartLength;
let runtimeRatio = 1;
const totalTFactoryRuntime = numberTFactoryInvocations * tFactoryRuntime;
if (algorithmRuntime > totalTFactoryRuntime) {
// Algorithm is longer.
runtimeRatio = totalTFactoryRuntime / algorithmRuntime;
lengthTFactoryLine = runtimeRatio * chartLength;
} else if (algorithmRuntime < totalTFactoryRuntime) {
// Algorithm shouldn't be shorter, but if it is, handle appropriately.
runtimeRatio = algorithmRuntime / totalTFactoryRuntime;
lengthAlgorithmLine = runtimeRatio * chartLength;
}
if (lengthAlgorithmLine < minAlgorithmLineLength) {
lengthAlgorithmLine = minAlgorithmLineLength;
}
/* ------------------------------------------------------------ Begin draw chart ------------------------------------------------------------ */
/* ------------------------------ Draw Chart Title and Legend ------------------------------ */
// Add chart title
d3Helper.drawText(
svg,
"Time diagram",
midpoint,
chartStartY - verticalLineSpacingDist * 3,
titleStyle,
);
// Create legend
const legendColor = d3
.scaleOrdinal()
.domain(
d3.extent(legendData, (d) => {
return d.title;
}) as unknown as string,
)
.range([algorithmRunTimeColor, tfactoryLineColor]);
d3Helper.drawLegend(
svg,
legendData,
midpoint,
chartStartY,
chartStartX,
legendColor,
false,
true,
);
/* ------------------------------ Draw Timeline ------------------------------ */
drawChartHorizontalLine(
svg,
chartStartX,
chartStartY,
xAxisLength,
timeLineColor,
strokeWidth,
"time",
"Time",
);
/*------------------------------ Draw Algorithm lines------------------------------ */
drawChartHorizontalLine(
svg,
chartStartX,
algorithmLineY,
lengthAlgorithmLine,
algorithmRunTimeColor,
strokeWidth,
"algorithm",
"",
);
const algorithmDashedLineStart = lengthAlgorithmLine + 5 + chartStartX;
const textStartAlgorithmY = chartStartY - 10;
drawChartVerticalLine(
svg,
algorithmDashedLineStart,
chartStartY,
textStartAlgorithmY,
algorithmLineY,
timeLineColor,
strokeWidth,
"algorithm",
algorithmRuntimeFormatted,
);
/* ------------------------------ Draw T factory lines and labels ------------------------------ */
// Define T factory xScale and number of lines
let numLines = numberTFactoryInvocations;
// If more T factory invocations than 50, set showSplit variable to insert ellipses.
const showSplit = numLines > 50;
if (showSplit) {
numLines = 56;
}
if (lengthTFactoryLine / numLines < minTFactoryInvocationLength) {
lengthTFactoryLine = minTFactoryInvocationLength * numLines;
}
// Define the x scaling for T factory invocation length.
const tFactoryXScale = d3
.scaleLinear()
.domain([0, numLines])
.range([0, lengthTFactoryLine]);
// Length of 1 T factory invocation line segement.
const tFactoryRefX = tFactoryXScale(1);
// Create T factory start bar.
d3Helper.drawLineTick(svg, 1, 6, tfactoryLineColor, "tFactoryTick");
// Create tfactory end arrow
d3Helper.drawArrow(svg, tfactoryLineColor, "arrowTFactory");
// Draw dashed line of single T factory invocation runtime.
const tFactoryDashedLineStartX = chartStartX + tFactoryRefX + 5;
const textStartTFactoryY = chartStartY + 20;
drawChartVerticalLine(
svg,
tFactoryDashedLineStartX,
chartStartY,
textStartTFactoryY,
tFactoryLineY,
timeLineColor,
strokeWidth,
"tfactory",
tFactoryRuntimeFormatted,
);
// Append T factory line labels.
d3Helper.drawText(
svg,
tfactoryLineLabel,
tFactoryRefX + chartStartX + 10,
tFactoryLineY + 30,
runtimeTextStyle,
);
const numberTFactoryInvocationsStr: string = d3Format.format(",.0f")(
numberTFactoryInvocations,
);
const numberTFactoryInvocationsText =
numberTFactoryInvocationsStr +
(numberTFactoryInvocations == 1
? " T factory invocation"
: " T factory invocations");
d3Helper.drawText(
svg,
numberTFactoryInvocationsText,
tFactoryRefX + chartStartX + 10,
tFactoryLineY - 20,
runtimeTextStyle,
);
/* ------------------------------ Draw T factory main line ------------------------------ */
// Draw individual invocations lines.
if (!showSplit) {
drawTFactoryLines(
svg,
numLines,
tFactoryXScale,
chartStartX,
tFactoryLineY,
strokeWidth,
tfactoryLineColor,
0,
);
} else {
// Draw first 25 segments.
numLines = 25;
drawTFactoryLines(
svg,
numLines,
tFactoryXScale,
chartStartX,
tFactoryLineY,
strokeWidth,
tfactoryLineColor,
0,
);
// Draw ellipses in middle.
const cx = tFactoryXScale(26) + chartStartX;
const cy = tFactoryLineY;
const radius = tFactoryXScale(1) / 4;
const spaceBetween = tFactoryXScale(1);
d3Helper.drawEllipses(svg, cx, cy, spaceBetween, radius, ellipsesColor);
// Draw last 25 segments.
numLines = 54;
drawTFactoryLines(
svg,
numLines,
tFactoryXScale,
chartStartX,
tFactoryLineY,
strokeWidth,
tfactoryLineColor,
29,
);
}
}, [width, height]);
return (
<div>
<div
style={{
justifyContent: "center",
alignItems: "center",
}}
>
<svg id="linechart" width={width} height={height}></svg>
</div>
</div>
);
}
export default LineChart;
|
azure-quantum-python/visualization/react-lib/src/components/d3-visualization-components/LineChart.tsx/0
|
{
"file_path": "azure-quantum-python/visualization/react-lib/src/components/d3-visualization-components/LineChart.tsx",
"repo_id": "azure-quantum-python",
"token_count": 4710
}
| 374 |
const esModules = ['@table-library/react-table-library/theme', '@table-library/react-table-library/material-ui', '@table-library/react-table-library/table', '@mui/material', '@mui/icons-material/Info'].join('|')
module.exports = {
preset: 'ts-jest',
moduleNameMapper: {
d3: '<rootDir>/node_modules/d3/dist/d3.min.js',
'\\.(css|less)$': '<rootDir>/test-config/mocks/styleMock.js'
},
testEnvironment: 'jsdom',
rootDir: '../',
globals: {
'ts-jest': {
tsConfig: '<rootDir>/test-config/tsconfig.json'
}
},
coveragePathIgnorePatterns: [
'.test.tsx',
'.test.ts',
'models/*'
],
coverageProvider: 'babel',
collectCoverage: true,
coverageReporters: [
'text',
'html',
'cobertura'
],
coverageThreshold: {
'../**/*': {
functions: 50,
lines: 75,
statements: 75
}
},
testMatch: [
'<rootDir>/**/__tests__/**/*.(spec|test).[jt]s?(x)',
'<rootDir>/*.(spec|test).[tj]s?(x)',
'<rootDir>/**/*.(spec|test).[tj]s?(x)'
],
testPathIgnorePatterns: ['/node_modules/'],
collectCoverageFrom: [
'**/*.{ts,tsx}',
'!**/node_modules/**'
],
modulePaths: [
'<rootDir>'
],
transformIgnorePatterns: [`/node_modules/(?!${esModules})`],
reporters: [
'default',
[
'jest-junit',
{
outputDirectory: 'TestResults',
outputName: 'test-results.xml',
suiteName: 'ReactViews.UnitTests'
}
]
]
}
|
azure-quantum-python/visualization/react-lib/test-config/jest.config.js/0
|
{
"file_path": "azure-quantum-python/visualization/react-lib/test-config/jest.config.js",
"repo_id": "azure-quantum-python",
"token_count": 666
}
| 375 |
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= pipenv run sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
deps:
pipenv sync
npm install
.PHONY: help deps Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
|
bistring/docs/Makefile/0
|
{
"file_path": "bistring/docs/Makefile",
"repo_id": "bistring",
"token_count": 273
}
| 376 |
all:
npm run build
deps:
npm install --ignore-scripts
check: all
npm test
clean:
$(RM) -r dist
.PHONY: all deps check clean
|
bistring/js/Makefile/0
|
{
"file_path": "bistring/js/Makefile",
"repo_id": "bistring",
"token_count": 57
}
| 377 |
import { BiString, BiStringBuilder, Alignment } from "..";
test("BiStringBuilder word chunks", () => {
const builder = new BiStringBuilder(" the quick brown fox ");
builder.discard(2);
builder.replace(3, "the");
builder.skip(1);
builder.replace(5, "quick");
builder.replace(2, " ");
builder.replace(5, "brown");
builder.skip(1);
builder.replace(3, "fox");
builder.discard(1);
const bs = builder.build();
expect(bs.original).toBe(" the quick brown fox ");
expect(bs.modified).toBe("the quick brown fox");
expect(bs.slice(0, 1).original).toBe("the");
expect(bs.slice(1, 2).original).toBe("the");
expect(bs.slice(2, 3).original).toBe("the");
expect(bs.slice(0, 3).original).toBe("the");
expect(bs.slice(1, 3).original).toBe("the");
expect(bs.slice(0, 4).original).toBe("the ");
expect(bs.slice(3, 4).original).toBe(" ");
expect(bs.slice(9, 10).original).toBe(" ");
expect(bs.slice(4, 15).original).toBe("quick brown");
expect(bs.slice(5, 14).original).toBe("quick brown");
expect(bs.slice(0, 0).original).toBe("");
expect(bs.slice(10, 10).original).toBe("");
});
test("BiStringBuilder char chunks", () => {
const builder = new BiStringBuilder(" the quick brown fox ");
builder.discardMatch(/\s+/y);
while (!builder.isComplete) {
builder.skipMatch(/\S+/y);
builder.replaceMatch(/\s+(?=\S)/y, " ");
builder.discardMatch(/\s+$/y);
}
const bs = builder.build();
expect(bs.original).toBe(" the quick brown fox ");
expect(bs.modified).toBe("the quick brown fox");
expect(bs.slice(0, 1).original).toBe("t");
expect(bs.slice(1, 2).original).toBe("h");
expect(bs.slice(2, 3).original).toBe("e");
expect(bs.slice(0, 3).original).toBe("the");
expect(bs.slice(1, 3).original).toBe("he");
expect(bs.slice(0, 4).original).toBe("the ");
expect(bs.slice(1, 4).original).toBe("he ");
expect(bs.slice(3, 4).original).toBe(" ");
expect(bs.slice(9, 10).original).toBe(" ");
expect(bs.slice(4, 15).original).toBe("quick brown");
expect(bs.slice(5, 14).original).toBe("uick brow");
expect(bs.slice(0, 0).original).toBe("");
expect(bs.slice(10, 10).original).toBe("");
});
test("BiStringBuilder('')", () => {
const builder = new BiStringBuilder("");
const bs = builder.build();
expect(bs.original).toBe("");
expect(bs.modified).toBe("");
expect(bs.slice(0, 0).original).toBe("");
});
test("BiStringBuilder.rewind", () => {
const builder = new BiStringBuilder("I wish I wouldn't've spent one thousand dollars.");
builder.skipMatch(/[^.]*/y);
builder.discardRest();
builder.rewind();
builder.skipMatch(/I wish I would/y);
builder.replaceMatch(/n't/y, " not");
builder.replaceMatch(/'ve/y, " have");
builder.skipMatch(/ spent /y);
builder.replaceMatch(/one thousand dollars/y, "$1,000");
const bs = builder.build();
expect(bs.original).toBe("I wish I wouldn't've spent one thousand dollars.");
expect(bs.modified).toBe("I wish I would not have spent $1,000");
});
test("BiStringBuilder.replaceAll", () => {
const builder = new BiStringBuilder("the cheese that the mouse that the cat that the dog chased played with ate");
builder.replaceMatch(/that/, "which");
builder.replaceAll(/that/g, "whom");
const bs = builder.build();
expect(bs.original).toBe("the cheese that the mouse that the cat that the dog chased played with ate");
expect(bs.modified).toBe("the cheese which the mouse whom the cat whom the dog chased played with ate");
});
test("BiStringBuilder.replaceAll back-references", () => {
const builder = new BiStringBuilder("it doesn't work and stuff doesn't get replaced");
builder.replaceAll(/\bdoesn't (\S+)/g, "$1s");
const bs = builder.build();
expect(bs.original).toBe("it doesn't work and stuff doesn't get replaced");
expect(bs.modified).toBe("it works and stuff gets replaced");
});
test("BiStringBuilder.append", () => {
const builder = new BiStringBuilder("hello WORLD");
builder.append(new BiString("hello", "HELLO", Alignment.identity(5)));
builder.skip(1)
builder.append(new BiString("WORLD", "world", Alignment.identity(5)));
const bs = builder.build();
expect(bs.slice(1, 4).equals(new BiString("ell", "ELL", Alignment.identity(3)))).toBe(true);
expect(bs.slice(7, 10).equals(new BiString("ORL", "orl", Alignment.identity(3)))).toBe(true);
});
|
bistring/js/tests/builder.test.ts/0
|
{
"file_path": "bistring/js/tests/builder.test.ts",
"repo_id": "bistring",
"token_count": 1708
}
| 378 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from typing import Callable, Match, Pattern, Tuple, Union
BiIndex = Tuple[int, int]
Bounds = Tuple[int, int]
AnyBounds = Union[int, range, slice, Bounds]
Index = Union[int, slice]
Range = Union[range, slice, Bounds]
Regex = Union[str, Pattern[str]]
Replacement = Union[str, Callable[[Match[str]], str]]
|
bistring/python/bistring/_typing.py/0
|
{
"file_path": "bistring/python/bistring/_typing.py",
"repo_id": "bistring",
"token_count": 133
}
| 379 |
[MASTER]
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Clear in-memory caches upon conclusion of linting. Useful if running pylint
# in a server-like mode.
clear-cache-post-run=no
# Load and enable all available extensions. Use --list-extensions to see a list
# all available extensions.
#enable-all-extensions=
# In error mode, messages with a category besides ERROR or FATAL are
# suppressed, and no reports are done by default. Error mode is compatible with
# disabling specific errors.
#errors-only=
# Always return a 0 (non-error) status code, even if lint errors are found.
# This is primarily useful in continuous integration scripts.
#exit-zero=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-allow-list=
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
# for backward compatibility.)
extension-pkg-whitelist=
# Return non-zero exit code if any of these messages/categories are detected,
# even if score is above --fail-under value. Syntax same as enable. Messages
# specified are enabled, while categories only check already-enabled messages.
fail-on=
# Specify a score threshold under which the program will exit with error.
fail-under=10
# Interpret the stdin as a python script, whose filename needs to be passed as
# the module_or_package argument.
#from-stdin=
# Files or directories to be skipped. They should be base names, not paths.
ignore=CVS
# Add files or directories matching the regular expressions patterns to the
# ignore-list. The regex matches against paths and can be in Posix or Windows
# format. Because '\\' represents the directory delimiter on Windows systems,
# it can't be used as an escape character.
ignore-paths=
# Files or directories matching the regular expression patterns are skipped.
# The regex matches against base names, not paths. The default value ignores
# Emacs file locks
ignore-patterns=^\.#
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use, and will cap the count on Windows to
# avoid hangs.
jobs=1
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# Minimum Python version to use for version dependent checks. Will default to
# the version used to run pylint.
py-version=3.8
# Discover python modules and packages in the file system subtree.
recursive=no
# Add paths to the list of the source roots. Supports globbing patterns. The
# source root is an absolute path or a path relative to the current working
# directory used to determine a package namespace for modules located under the
# source root.
source-roots=
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
# In verbose mode, extra non-checker-related info will be displayed.
#verbose=
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style. If left empty, argument names will be checked with the set
# naming style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style. If left empty, attribute names will be checked with the set naming
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style. If left empty, class attribute names will be checked
# with the set naming style.
#class-attribute-rgx=
# Naming style matching correct class constant names.
class-const-naming-style=UPPER_CASE
# Regular expression matching correct class constant names. Overrides class-
# const-naming-style. If left empty, class constant names will be checked with
# the set naming style.
#class-const-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style. If left empty, class names will be checked with the set naming style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style. If left empty, constant names will be checked with the set naming
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style. If left empty, function names will be checked with the set
# naming style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style. If left empty, inline iteration names will be checked
# with the set naming style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style. If left empty, method names will be checked with the set naming style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style. If left empty, module names will be checked with the set naming style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Regular expression matching correct type alias names. If left empty, type
# alias names will be checked with the set naming style.
#typealias-rgx=
# Regular expression matching correct type variable names. If left empty, type
# variable names will be checked with the set naming style.
#typevar-rgx=
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style. If left empty, variable names will be checked with the set
# naming style.
#variable-rgx=
[CLASSES]
# Warn about protected attribute access inside special methods
check-protected-access-in-special-methods=no
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
__post_init__
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,_fields,_replace,_source,_make,os._exit
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=mcs,cls
[DESIGN]
# List of regular expressions of class ancestor names to ignore when counting
# public methods (see R0903)
exclude-too-few-public-methods=
# List of qualified class names to ignore when counting class parents (see
# R0901)
ignored-parents=
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branch for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[EXCEPTIONS]
# Exceptions that will emit a warning when caught.
overgeneral-exceptions=builtins.BaseException,builtins.Exception
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=120
# Maximum number of lines in a module.
max-module-lines=1000
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow explicit reexports by alias from a package __init__.
allow-reexport-from-package=no
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=
# Output a graph (.gv or any supported image format) of external dependencies
# to the given file (report RP0402 must not be disabled).
ext-import-graph=
# Output a graph (.gv or any supported image format) of all (i.e. internal and
# external) dependencies to the given file (report RP0402 must not be
# disabled).
import-graph=
# Output a graph (.gv or any supported image format) of internal dependencies
# to the given file (report RP0402 must not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
# UNDEFINED.
confidence=HIGH,
CONTROL_FLOW,
INFERENCE,
INFERENCE_FAILURE,
UNDEFINED
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
duplicate-code,
redefined-outer-name,
missing-docstring,
too-many-instance-attributes,
too-few-public-methods,
redefined-builtin,
too-many-arguments,
fixme,
broad-except,
bare-except,
too-many-public-methods,
cyclic-import,
too-many-locals,
too-many-function-args,
too-many-return-statements,
import-error,
no-name-in-module,
too-many-branches,
too-many-ancestors,
too-many-nested-blocks,
attribute-defined-outside-init,
super-with-arguments,
missing-timeout,
broad-exception-raised,
exec-used,
unspecified-encoding,
unused-variable,
consider-using-f-string,
raise-missing-from,
invalid-name,
useless-object-inheritance,
no-else-raise,
implicit-str-concat,
use-dict-literal,
use-list-literal,
unnecessary-dunder-call,
consider-using-in,
consider-using-with,
useless-parent-delegation,
f-string-without-interpolation,
global-variable-not-assigned,
dangerous-default-value,
wrong-import-order,
wrong-import-position,
ungrouped-imports,
import-outside-toplevel,
consider-using-from-import,
reimported,
unused-import,
unused-argument,
arguments-renamed,
unused-private-member,
unidiomatic-typecheck,
protected-access,
used-before-assignment,
invalid-overridden-method,
no-member,
deprecated-module,
too-many-lines,
c-extension-no-member,
unsubscriptable-object
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=
[METHOD_ARGS]
# List of qualified names (i.e., library.method) which require a timeout
# parameter e.g. 'requests.api.get,requests.api.post'
timeout-methods=requests.api.delete,requests.api.get,requests.api.head,requests.api.options,requests.api.patch,requests.api.post,requests.api.put,requests.api.request
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
notes-rgx=
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit,argparse.parse_error
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'fatal', 'error', 'warning', 'refactor',
# 'convention', and 'info' which contain the number of messages in each
# category, as well as 'statement' which is the total number of statements
# analyzed. This score is used by the global evaluation report (RP0004).
evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
#output-format=
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[SIMILARITIES]
# Comments are removed from the similarity computation
ignore-comments=yes
# Docstrings are removed from the similarity computation
ignore-docstrings=yes
# Imports are removed from the similarity computation
ignore-imports=yes
# Signatures are removed from the similarity computation
ignore-signatures=yes
# Minimum lines number of a similarity.
min-similarity-lines=4
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. No available dictionaries : You need to install
# both the python package and the system dependency for enchant to work..
spelling-dict=
# List of comma separated words that should be considered directives if they
# appear at the beginning of a comment and should not be checked.
spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of symbolic message names to ignore for Mixin members.
ignored-checks-for-mixins=no-member,
not-async-context-manager,
not-context-manager,
attribute-defined-outside-init
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# Regex pattern to define which classes are considered mixins.
mixin-class-rgx=.*[Mm]ixin
# List of decorators that change the signature of a decorated function.
signature-mutators=
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of names allowed to shadow builtins
allowed-redefined-builtins=
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
|
botbuilder-python/.pylintrc/0
|
{
"file_path": "botbuilder-python/.pylintrc",
"repo_id": "botbuilder-python",
"token_count": 6837
}
| 380 |
# {{cookiecutter.bot_name}}
{{cookiecutter.bot_description}}
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a simple bot that accepts input from the user and echoes it back.
## Prerequisites
This sample **requires** prerequisites in order to run.
### Install Python 3.6
## Running the sample
- Run `pip install -r requirements.txt` to install all dependencies
- Run `python app.py`
## Testing the bot using Bot Framework Emulator
[Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
- Install the Bot Framework Emulator version 4.3.0 or greater from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
### Connect to the bot using Bot Framework Emulator
- Launch Bot Framework Emulator
- Enter a Bot URL of `http://localhost:3978/api/messages`
## Further reading
- [Bot Framework Documentation](https://docs.botframework.com)
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
- [Dialogs](https://docs.microsoft.com/azure/bot-service/bot-builder-concept-dialog?view=azure-bot-service-4.0)
- [Gathering Input Using Prompts](https://docs.microsoft.com/azure/bot-service/bot-builder-prompts?view=azure-bot-service-4.0&tabs=csharp)
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
- [Azure Bot Service Introduction](https://docs.microsoft.com/azure/bot-service/bot-service-overview-introduction?view=azure-bot-service-4.0)
- [Azure Bot Service Documentation](https://docs.microsoft.com/azure/bot-service/?view=azure-bot-service-4.0)
- [Azure CLI](https://docs.microsoft.com/cli/azure/?view=azure-cli-latest)
- [Azure Portal](https://portal.azure.com)
- [Language Understanding using LUIS](https://docs.microsoft.com/azure/cognitive-services/luis/)
- [Channels and Bot Connector Service](https://docs.microsoft.com/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
|
botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/README.md/0
|
{
"file_path": "botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/README.md",
"repo_id": "botbuilder-python",
"token_count": 664
}
| 381 |
[bdist_wheel]
universal=0
|
botbuilder-python/libraries/botbuilder-adapters-slack/setup.cfg/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-adapters-slack/setup.cfg",
"repo_id": "botbuilder-python",
"token_count": 10
}
| 382 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import re
from typing import Dict
import aiohttp
from botbuilder.ai.luis.activity_util import ActivityUtil
from botbuilder.ai.luis.luis_util import LuisUtil
from botbuilder.core import (
IntentScore,
RecognizerResult,
TurnContext,
)
from .luis_recognizer_internal import LuisRecognizerInternal
from .luis_recognizer_options_v3 import LuisRecognizerOptionsV3
from .luis_application import LuisApplication
# from .activity_util import ActivityUtil
class LuisRecognizerV3(LuisRecognizerInternal):
_dateSubtypes = [
"date",
"daterange",
"datetime",
"datetimerange",
"duration",
"set",
"time",
"timerange",
]
_geographySubtypes = ["poi", "city", "countryRegion", "continent", "state"]
_metadata_key = "$instance"
# The value type for a LUIS trace activity.
luis_trace_type: str = "https://www.luis.ai/schemas/trace"
# The context label for a LUIS trace activity.
luis_trace_label: str = "Luis Trace"
def __init__(
self,
luis_application: LuisApplication,
luis_recognizer_options_v3: LuisRecognizerOptionsV3 = None,
):
super().__init__(luis_application)
self.luis_recognizer_options_v3 = (
luis_recognizer_options_v3 or LuisRecognizerOptionsV3()
)
self._application = luis_application
async def recognizer_internal(self, turn_context: TurnContext):
recognizer_result: RecognizerResult = None
utterance: str = (
turn_context.activity.text if turn_context.activity is not None else None
)
url = self._build_url()
body = self._build_request(utterance)
headers = {
"Ocp-Apim-Subscription-Key": self.luis_application.endpoint_key,
"Content-Type": "application/json",
}
async with aiohttp.ClientSession() as session:
async with session.post(
url, json=body, headers=headers, ssl=False
) as result:
luis_result = await result.json()
recognizer_result = RecognizerResult(
text=utterance,
intents=self._get_intents(luis_result["prediction"]),
entities=self._extract_entities_and_metadata(
luis_result["prediction"]
),
)
if self.luis_recognizer_options_v3.include_instance_data:
recognizer_result.entities[self._metadata_key] = (
recognizer_result.entities[self._metadata_key]
if self._metadata_key in recognizer_result.entities
else {}
)
if "sentiment" in luis_result["prediction"]:
recognizer_result.properties["sentiment"] = self._get_sentiment(
luis_result["prediction"]
)
await self._emit_trace_info(
turn_context,
luis_result,
recognizer_result,
self.luis_recognizer_options_v3,
)
return recognizer_result
def _build_url(self):
base_uri = (
self._application.endpoint or "https://westus.api.cognitive.microsoft.com"
)
uri = "%s/luis/prediction/v3.0/apps/%s" % (
base_uri,
self._application.application_id,
)
if self.luis_recognizer_options_v3.version:
uri += "/versions/%s/predict" % (self.luis_recognizer_options_v3.version)
else:
uri += "/slots/%s/predict" % (self.luis_recognizer_options_v3.slot)
params = "?verbose=%s&show-all-intents=%s&log=%s" % (
"true"
if self.luis_recognizer_options_v3.include_instance_data
else "false",
"true" if self.luis_recognizer_options_v3.include_all_intents else "false",
"true" if self.luis_recognizer_options_v3.log else "false",
)
return uri + params
def _build_request(self, utterance: str):
body = {
"query": utterance,
"options": {
"preferExternalEntities": self.luis_recognizer_options_v3.prefer_external_entities,
},
}
if self.luis_recognizer_options_v3.datetime_reference:
body["options"][
"datetimeReference"
] = self.luis_recognizer_options_v3.datetime_reference
if self.luis_recognizer_options_v3.dynamic_lists:
body["dynamicLists"] = self.luis_recognizer_options_v3.dynamic_lists
if self.luis_recognizer_options_v3.external_entities:
body["externalEntities"] = self.luis_recognizer_options_v3.external_entities
return body
def _get_intents(self, luis_result):
intents = {}
if not luis_result["intents"]:
return intents
for intent in luis_result["intents"]:
intents[self._normalize_name(intent)] = IntentScore(
luis_result["intents"][intent]["score"]
)
return intents
def _normalize_name(self, name):
return re.sub(r"\.", "_", name)
def _normalize(self, entity):
split_entity = entity.split(":")
entity_name = split_entity[-1]
return self._normalize_name(entity_name)
def _extract_entities_and_metadata(self, luis_result):
entities = luis_result["entities"]
return self._map_properties(entities, False)
def _map_properties(self, source, in_instance):
if isinstance(source, (int, float, bool, str)):
return source
result = source
if isinstance(source, list):
narr = []
for item in source:
is_geography_v2 = ""
if (
isinstance(item, dict)
and "type" in item
and item["type"] in self._geographySubtypes
):
is_geography_v2 = item["type"]
if not in_instance and is_geography_v2:
geo_entity = {}
for item_props in item:
if item_props == "value":
geo_entity["location"] = item[item_props]
geo_entity["type"] = is_geography_v2
narr.append(geo_entity)
else:
narr.append(self._map_properties(item, in_instance))
result = narr
elif not isinstance(source, str):
nobj = {}
if (
not in_instance
and isinstance(source, dict)
and "type" in source
and isinstance(source["type"], str)
and source["type"] in self._dateSubtypes
):
timexs = source["values"]
arr = []
if timexs:
unique = []
for elt in timexs:
if elt["timex"] and elt["timex"] not in unique:
unique.append(elt["timex"])
for timex in unique:
arr.append(timex)
nobj["timex"] = arr
nobj["type"] = source["type"]
else:
for property in source:
name = self._normalize(property)
is_array = isinstance(source[property], list)
is_string = isinstance(source[property], str)
is_int = isinstance(source[property], (int, float))
val = self._map_properties(
source[property], in_instance or property == self._metadata_key
)
if name == "datetime" and is_array:
nobj["datetimeV1"] = val
elif name == "datetimeV2" and is_array:
nobj["datetime"] = val
elif in_instance:
if name == "length" and is_int:
nobj["endIndex"] = source[name] + source["startIndex"]
elif not (
(is_int and name == "modelTypeId")
or (is_string and name == "role")
):
nobj[name] = val
else:
if name == "unit" and is_string:
nobj["units"] = val
else:
nobj[name] = val
result = nobj
return result
def _get_sentiment(self, luis_result):
return {
"label": luis_result["sentiment"]["label"],
"score": luis_result["sentiment"]["score"],
}
async def _emit_trace_info(
self,
turn_context: TurnContext,
luis_result,
recognizer_result: RecognizerResult,
options: LuisRecognizerOptionsV3,
) -> None:
trace_info: Dict[str, object] = {
"recognizerResult": LuisUtil.recognizer_result_as_dict(recognizer_result),
"luisModel": {"ModelID": self._application.application_id},
"luisOptions": {"Slot": options.slot},
"luisResult": luis_result,
}
trace_activity = ActivityUtil.create_trace(
turn_context.activity,
"LuisRecognizer",
trace_info,
LuisRecognizerV3.luis_trace_type,
LuisRecognizerV3.luis_trace_label,
)
await turn_context.send_activity(trace_activity)
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v3.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer_v3.py",
"repo_id": "botbuilder-python",
"token_count": 5115
}
| 383 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from botbuilder.schema import Activity
from .metadata import Metadata
from .query_result import QueryResult
from .qna_request_context import QnARequestContext
from .ranker_types import RankerTypes
class QnAMakerTraceInfo:
"""Represents all the trace info that we collect from the QnAMaker Middleware."""
def __init__(
self,
message: Activity,
query_results: List[QueryResult],
knowledge_base_id: str,
score_threshold: float,
top: int,
strict_filters: List[Metadata],
context: QnARequestContext = None,
qna_id: int = None,
is_test: bool = False,
ranker_type: str = RankerTypes.DEFAULT,
):
"""
Parameters:
-----------
message: Message which instigated the query to QnA Maker.
query_results: Results that QnA Maker returned.
knowledge_base_id: ID of the knowledge base that is being queried.
score_threshold: The minimum score threshold, used to filter returned results.
top: Number of ranked results that are asked to be returned.
strict_filters: Filters used on query.
context: (Optional) The context from which the QnA was extracted.
qna_id: (Optional) Id of the current question asked.
is_test: (Optional) A value indicating whether to call test or prod environment of knowledgebase.
ranker_types: (Optional) Ranker types.
"""
self.message = message
self.query_results = query_results
self.knowledge_base_id = knowledge_base_id
self.score_threshold = score_threshold
self.top = top
self.strict_filters = strict_filters
self.context = context
self.qna_id = qna_id
self.is_test = is_test
self.ranker_type = ranker_type
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/qnamaker_trace_info.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/qnamaker_trace_info.py",
"repo_id": "botbuilder-python",
"token_count": 739
}
| 384 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from aiohttp import ClientSession
from ..qnamaker_endpoint import QnAMakerEndpoint
from ..models import FeedbackRecord, TrainRequestBody
from .http_request_utils import HttpRequestUtils
class TrainUtils:
"""Class for Train API, used in active learning to add suggestions to the knowledge base"""
def __init__(self, endpoint: QnAMakerEndpoint, http_client: ClientSession):
"""
Initializes a new instance for active learning train utils.
Parameters:
-----------
endpoint: QnA Maker Endpoint of the knowledge base to query.
http_client: Http client.
"""
self._endpoint = endpoint
self._http_client = http_client
async def call_train(self, feedback_records: List[FeedbackRecord]):
"""
Train API to provide feedback.
Parameter:
-------------
feedback_records: Feedback record list.
"""
if not feedback_records:
raise TypeError("TrainUtils.call_train(): feedback_records cannot be None.")
if not feedback_records:
return
await self._query_train(feedback_records)
async def _query_train(self, feedback_records: List[FeedbackRecord]):
url: str = f"{ self._endpoint.host }/knowledgebases/{ self._endpoint.knowledge_base_id }/train"
payload_body = TrainRequestBody(feedback_records=feedback_records)
http_request_helper = HttpRequestUtils(self._http_client)
await http_request_helper.execute_http_request(
url, payload_body, self._endpoint
)
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/utils/train_utils.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/utils/train_utils.py",
"repo_id": "botbuilder-python",
"token_count": 627
}
| 385 |
{
"text": "Deliver from 12345 VA to 12346 WA",
"intents": {
"Cancel": {
"score": 1.01764708e-9
},
"Delivery": {
"score": 0.00238572317
},
"EntityTests": {
"score": 4.757576e-10
},
"Greeting": {
"score": 1.0875e-9
},
"Help": {
"score": 1.01764708e-9
},
"None": {
"score": 0.00000117844979
},
"Roles": {
"score": 0.999911964
},
"search": {
"score": 0.000009494859
},
"SpecifyName": {
"score": 3.0666667e-9
},
"Travel": {
"score": 0.00000309763345
},
"Weather_GetForecast": {
"score": 0.00000102792524
}
},
"entities": {
"$instance": {
"Destination": [
{
"endIndex": 33,
"modelType": "Composite Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.9818366,
"startIndex": 25,
"text": "12346 WA",
"type": "Address"
}
],
"Source": [
{
"endIndex": 21,
"modelType": "Composite Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.9345161,
"startIndex": 13,
"text": "12345 VA",
"type": "Address"
}
]
},
"Destination": [
{
"$instance": {
"number": [
{
"endIndex": 30,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 25,
"text": "12346",
"type": "builtin.number"
}
],
"State": [
{
"endIndex": 33,
"modelType": "Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.9893861,
"startIndex": 31,
"text": "WA",
"type": "State"
}
]
},
"number": [
12346
],
"State": [
"WA"
]
}
],
"Source": [
{
"$instance": {
"number": [
{
"endIndex": 18,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 13,
"text": "12345",
"type": "builtin.number"
}
],
"State": [
{
"endIndex": 21,
"modelType": "Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.941649556,
"startIndex": 19,
"text": "VA",
"type": "State"
}
]
},
"number": [
12345
],
"State": [
"VA"
]
}
]
},
"sentiment": {
"label": "neutral",
"score": 0.5
},
"v3": {
"response": {
"prediction": {
"entities": {
"$instance": {
"Destination": [
{
"length": 8,
"modelType": "Composite Entity Extractor",
"modelTypeId": 4,
"recognitionSources": [
"model"
],
"role": "Destination",
"score": 0.9818366,
"startIndex": 25,
"text": "12346 WA",
"type": "Address"
}
],
"Source": [
{
"length": 8,
"modelType": "Composite Entity Extractor",
"modelTypeId": 4,
"recognitionSources": [
"model"
],
"role": "Source",
"score": 0.9345161,
"startIndex": 13,
"text": "12345 VA",
"type": "Address"
}
]
},
"Destination": [
{
"$instance": {
"number": [
{
"length": 5,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 25,
"text": "12346",
"type": "builtin.number"
}
],
"State": [
{
"length": 2,
"modelType": "Entity Extractor",
"modelTypeId": 1,
"recognitionSources": [
"model"
],
"score": 0.9893861,
"startIndex": 31,
"text": "WA",
"type": "State"
}
]
},
"number": [
12346
],
"State": [
"WA"
]
}
],
"Source": [
{
"$instance": {
"number": [
{
"length": 5,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 13,
"text": "12345",
"type": "builtin.number"
}
],
"State": [
{
"length": 2,
"modelType": "Entity Extractor",
"modelTypeId": 1,
"recognitionSources": [
"model"
],
"score": 0.941649556,
"startIndex": 19,
"text": "VA",
"type": "State"
}
]
},
"number": [
12345
],
"State": [
"VA"
]
}
]
},
"intents": {
"Cancel": {
"score": 1.01764708e-9
},
"Delivery": {
"score": 0.00238572317
},
"EntityTests": {
"score": 4.757576e-10
},
"Greeting": {
"score": 1.0875e-9
},
"Help": {
"score": 1.01764708e-9
},
"None": {
"score": 0.00000117844979
},
"Roles": {
"score": 0.999911964
},
"search": {
"score": 0.000009494859
},
"SpecifyName": {
"score": 3.0666667e-9
},
"Travel": {
"score": 0.00000309763345
},
"Weather_GetForecast": {
"score": 0.00000102792524
}
},
"normalizedQuery": "deliver from 12345 va to 12346 wa",
"sentiment": {
"label": "neutral",
"score": 0.5
},
"topIntent": "Roles"
},
"query": "Deliver from 12345 VA to 12346 WA"
},
"options": {
"includeAllIntents": true,
"includeAPIResults": true,
"includeInstanceData": true,
"log": true,
"preferExternalEntities": true,
"slot": "production",
"version": "GeoPeople"
}
}
}
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Composite3_v3.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Composite3_v3.json",
"repo_id": "botbuilder-python",
"token_count": 5054
}
| 386 |
{
"text": "email about something wicked this way comes from bart simpson and also kb435",
"intents": {
"search": {
"score": 0.999999
},
"None": {
"score": 7.91005E-06
},
"EntityTests": {
"score": 5.412342E-06
},
"Weather_GetForecast": {
"score": 3.7898792E-06
},
"Delivery": {
"score": 2.06122013E-06
},
"SpecifyName": {
"score": 1.76767367E-06
},
"Travel": {
"score": 1.76767367E-06
},
"Greeting": {
"score": 5.9375E-10
},
"Cancel": {
"score": 5.529412E-10
},
"Help": {
"score": 5.529412E-10
}
},
"entities": {
"$instance": {
"Part": [
{
"startIndex": 71,
"endIndex": 76,
"text": "kb435",
"type": "Part"
}
],
"subject": [
{
"startIndex": 12,
"endIndex": 43,
"text": "something wicked this way comes",
"type": "subject"
}
],
"person": [
{
"startIndex": 49,
"endIndex": 61,
"text": "bart simpson",
"type": "person"
}
],
"extra": [
{
"startIndex": 71,
"endIndex": 76,
"text": "kb435",
"type": "subject"
}
]
},
"Part": [
"kb435"
],
"subject": [
"something wicked this way comes"
],
"person": [
"bart simpson"
],
"extra": [
"kb435"
]
},
"sentiment": {
"label": "negative",
"score": 0.210341513
},
"luisResult": {
"query": "email about something wicked this way comes from bart simpson and also kb435",
"topScoringIntent": {
"intent": "search",
"score": 0.999999
},
"intents": [
{
"intent": "search",
"score": 0.999999
},
{
"intent": "None",
"score": 7.91005E-06
},
{
"intent": "EntityTests",
"score": 5.412342E-06
},
{
"intent": "Weather.GetForecast",
"score": 3.7898792E-06
},
{
"intent": "Delivery",
"score": 2.06122013E-06
},
{
"intent": "SpecifyName",
"score": 1.76767367E-06
},
{
"intent": "Travel",
"score": 1.76767367E-06
},
{
"intent": "Greeting",
"score": 5.9375E-10
},
{
"intent": "Cancel",
"score": 5.529412E-10
},
{
"intent": "Help",
"score": 5.529412E-10
}
],
"entities": [
{
"entity": "kb435",
"type": "Part",
"startIndex": 71,
"endIndex": 75
},
{
"entity": "something wicked this way comes",
"type": "subject",
"startIndex": 12,
"endIndex": 42,
"role": ""
},
{
"entity": "bart simpson",
"type": "person",
"startIndex": 49,
"endIndex": 60,
"role": ""
},
{
"entity": "kb435",
"type": "subject",
"startIndex": 71,
"endIndex": 75,
"role": "extra"
}
],
"sentimentAnalysis": {
"label": "negative",
"score": 0.210341513
}
}
}
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Patterns.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Patterns.json",
"repo_id": "botbuilder-python",
"token_count": 1843
}
| 387 |
{
"answers": [
{
"questions": [
"Tell me about birds",
"What do you know about birds"
],
"answer": "Choose one of the following birds to get more info",
"score": 100.0,
"id": 37,
"source": "Editorial",
"isDocumentText": false,
"metadata": [],
"context": {
"isContextOnly": false,
"prompts": [
{
"displayOrder": 1,
"qnaId": 38,
"displayText": "Bald Eagle"
},
{
"displayOrder": 2,
"qnaId": 39,
"displayText": "Hummingbird"
}
]
}
}
],
"activeLearningEnabled": true
}
|
botbuilder-python/libraries/botbuilder-ai/tests/qna/test_data/QnAMakerDialog_MultiTurn_Answer1.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/qna/test_data/QnAMakerDialog_MultiTurn_Answer1.json",
"repo_id": "botbuilder-python",
"token_count": 601
}
| 388 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Application Insights Telemetry Client for Bots."""
import traceback
from typing import Dict, Callable
from applicationinsights import TelemetryClient # pylint: disable=no-name-in-module
from botbuilder.core.bot_telemetry_client import (
BotTelemetryClient,
Severity,
TelemetryDataPointType,
)
from .bot_telemetry_processor import BotTelemetryProcessor
def bot_telemetry_processor(data, context) -> bool:
"""Bot Telemetry Processor as a method for backward compatibility. Refer to
callable object :class:`BotTelemetryProcessor` for details.
:param data: Data from Application Insights
:type data: telemetry item
:param context: Context from Application Insights
:type context: context object
:return: determines if the event is passed to the server (False = Filtered).
:rtype: bool
"""
processor = BotTelemetryProcessor()
return processor(data, context)
class ApplicationInsightsTelemetryClient(BotTelemetryClient):
"""Application Insights Telemetry Client."""
def __init__(
self,
instrumentation_key: str,
telemetry_client: TelemetryClient = None,
telemetry_processor: Callable[[object, object], bool] = None,
client_queue_size: int = None,
):
self._instrumentation_key = instrumentation_key
self._client = (
telemetry_client
if telemetry_client is not None
else TelemetryClient(self._instrumentation_key)
)
if client_queue_size:
self._client.channel.queue.max_queue_length = client_queue_size
# Telemetry Processor
processor = (
telemetry_processor
if telemetry_processor is not None
else bot_telemetry_processor
)
self._client.add_telemetry_processor(processor)
def track_pageview(
self,
name: str,
url: str,
duration: int = 0,
properties: Dict[str, object] = None,
measurements: Dict[str, object] = None,
) -> None:
"""
Send information about the page viewed in the application (a web page for instance).
:param name: the name of the page that was viewed.
:type name: str
:param url: the URL of the page that was viewed.
:type url: str
:param duration: the duration of the page view in milliseconds. (defaults to: 0)
:duration: int
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:type properties: :class:`typing.Dict[str, object]`
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to:
None)
:type measurements: :class:`typing.Dict[str, object]`
"""
self._client.track_pageview(name, url, duration, properties, measurements)
def track_exception(
self,
exception_type: type = None,
value: Exception = None,
trace: traceback = None,
properties: Dict[str, object] = None,
measurements: Dict[str, object] = None,
) -> None:
"""
Send information about a single exception that occurred in the application.
:param exception_type: the type of the exception that was thrown.
:param value: the exception that the client wants to send.
:param trace: the traceback information as returned by :func:`sys.exc_info`.
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:type properties: :class:`typing.Dict[str, object]`
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to:
None)
:type measurements: :class:`typing.Dict[str, object]`
"""
self._client.track_exception(
exception_type, value, trace, properties, measurements
)
def track_event(
self,
name: str,
properties: Dict[str, object] = None,
measurements: Dict[str, object] = None,
) -> None:
"""
Send information about a single event that has occurred in the context of the application.
:param name: the data to associate to this event.
:type name: str
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:type properties: :class:`typing.Dict[str, object]`
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to:
None)
:type measurements: :class:`typing.Dict[str, object]`
"""
self._client.track_event(name, properties=properties, measurements=measurements)
def track_metric(
self,
name: str,
value: float,
tel_type: TelemetryDataPointType = None,
count: int = None,
min_val: float = None,
max_val: float = None,
std_dev: float = None,
properties: Dict[str, object] = None,
) -> NotImplemented:
"""
Send information about a single metric data point that was captured for the application.
:param name: The name of the metric that was captured.
:type name: str
:param value: The value of the metric that was captured.
:type value: float
:param tel_type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`)
:param count: the number of metrics that were aggregated into this data point. (defaults to: None)
:type count: int
:param min_val: the minimum of all metrics collected that were aggregated into this data point. (defaults to:
None)
:type min_val: float
:param max_val: the maximum of all metrics collected that were aggregated into this data point. (defaults to:
None)
:type max_val: float
:param std_dev: the standard deviation of all metrics collected that were aggregated into this data point.
(defaults to: None)
:type std_dev: float
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:type properties: :class:`typing.Dict[str, object]`
"""
self._client.track_metric(
name, value, tel_type, count, min_val, max_val, std_dev, properties
)
def track_trace(
self, name: str, properties: Dict[str, object] = None, severity: Severity = None
):
"""
Sends a single trace statement.
:param name: the trace statement.
:type name: str
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:type properties: :class:`typing.Dict[str, object]`
:param severity: the severity level of this trace, one of DEBUG, INFO, WARNING, ERROR, CRITICAL
"""
self._client.track_trace(name, properties, severity)
def track_request(
self,
name: str,
url: str,
success: bool,
start_time: str = None,
duration: int = None,
response_code: str = None,
http_method: str = None,
properties: Dict[str, object] = None,
measurements: Dict[str, object] = None,
request_id: str = None,
):
"""
Sends a single request that was captured for the application.
:param name: The name for this request. All requests with the same name will be grouped together.
:type name: str
:param url: The actual URL for this request (to show in individual request instances).
:type url: str
:param success: True if the request ended in success, False otherwise.
:type success: bool
:param start_time: the start time of the request. The value should look the same as the one returned by
:func:`datetime.isoformat`. (defaults to: None)
:type start_time: str
:param duration: the number of milliseconds that this request lasted. (defaults to: None)
:type duration: int
:param response_code: the response code that this request returned. (defaults to: None)
:type response_code: str
:param http_method: the HTTP method that triggered this request. (defaults to: None)
:type http_method: str
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)
:type properties: :class:`typing.Dict[str, object]`
:param measurements: the set of custom measurements the client wants to attach to this data item. (defaults to:
None)
:type measurements: :class:`typing.Dict[str, object]`
:param request_id: the id for this request. If None, a new uuid will be generated. (defaults to: None)
:type request_id: str
"""
self._client.track_request(
name,
url,
success,
start_time,
duration,
response_code,
http_method,
properties,
measurements,
request_id,
)
def track_dependency(
self,
name: str,
data: str,
type_name: str = None,
target: str = None,
duration: int = None,
success: bool = None,
result_code: str = None,
properties: Dict[str, object] = None,
measurements: Dict[str, object] = None,
dependency_id: str = None,
):
"""
Sends a single dependency telemetry that was captured for the application.
:param name: the name of the command initiated with this dependency call. Low cardinality value.
Examples are stored procedure name and URL path template.
:type name: str
:param data: the command initiated by this dependency call. Examples are SQL statement and HTTP URL with all
query parameters.
:type data: str
:param type_name: the dependency type name. Low cardinality value for logical grouping of dependencies and
interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP.
(default to: None)
:type type_name: str
:param target: the target site of a dependency call. Examples are server name, host address. (default to: None)
:type target: str
:param duration: the number of milliseconds that this dependency call lasted. (defaults to: None)
:type duration: int
:param success: true if the dependency call ended in success, false otherwise. (defaults to: None)
:type success: bool
:param result_code: the result code of a dependency call. Examples are SQL error code and HTTP status code.
(defaults to: None)
:type result_code: str
:param properties: the set of custom properties the client wants attached to this data item.
(defaults to: None)
:type properties: :class:`typing.Dict[str, object]`
:param measurements: the set of custom measurements the client wants to attach to this data item.
(defaults to: None)
:type measurements: :class:`typing.Dict[str, object]`
:param dependency_id: the id for this dependency call. If None, a new uuid will be generated.
(defaults to: None)
:type dependency_id: str
"""
self._client.track_dependency(
name,
data,
type_name,
target,
duration,
success,
result_code,
properties,
measurements,
dependency_id,
)
def flush(self):
"""Flushes data in the queue. Data in the queue will be sent either immediately irrespective of what sender is
being used.
"""
self._client.flush()
|
botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/application_insights_telemetry_client.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/application_insights_telemetry_client.py",
"repo_id": "botbuilder-python",
"token_count": 4633
}
| 389 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import unittest
import aiounittest
from jsonpickle import decode
from botbuilder.azure import AzureQueueStorage
EMULATOR_RUNNING = False
# This connection string is to connect to local Azure Storage Emulator.
CONNECTION_STRING = (
"AccountName=devstoreaccount1;"
"AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr"
"/KBHBeksoGMGw==;DefaultEndpointsProtocol=http;"
"BlobEndpoint=http://127.0.0.1:10000/devstoreaccount1;"
"QueueEndpoint=http://127.0.0.1:10001/devstoreaccount1;"
"TableEndpoint=http://127.0.0.1:10002/devstoreaccount1;"
)
QUEUE_NAME = "queue"
class TestAzureQueueStorageConstructor:
def test_queue_storage_init_should_error_without_connection_string(self):
try:
# pylint: disable=no-value-for-parameter
AzureQueueStorage()
except Exception as error:
assert error
def test_queue_storage_init_should_error_without_queue_name(self):
try:
# pylint: disable=no-value-for-parameter
AzureQueueStorage(queues_storage_connection_string="somestring")
except Exception as error:
assert error
class TestAzureQueueStorage(aiounittest.AsyncTestCase):
@unittest.skipIf(not EMULATOR_RUNNING, reason="Needs the emulator to run.")
async def test_returns_read_receipt(self):
message = {"string": "test", "object": {"string2": "test2"}, "number": 99}
queue = AzureQueueStorage(CONNECTION_STRING, QUEUE_NAME)
receipt = await queue.queue_activity(message)
decoded = decode(receipt)
assert decoded.id is not None
assert decode(decoded.content) == message
|
botbuilder-python/libraries/botbuilder-azure/tests/test_queue_storage.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-azure/tests/test_queue_storage.py",
"repo_id": "botbuilder-python",
"token_count": 712
}
| 390 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.schema import (
AnimationCard,
Attachment,
AudioCard,
HeroCard,
OAuthCard,
ReceiptCard,
SigninCard,
ThumbnailCard,
VideoCard,
)
class ContentTypes:
adaptive_card = "application/vnd.microsoft.card.adaptive"
animation_card = "application/vnd.microsoft.card.animation"
audio_card = "application/vnd.microsoft.card.audio"
hero_card = "application/vnd.microsoft.card.hero"
receipt_card = "application/vnd.microsoft.card.receipt"
oauth_card = "application/vnd.microsoft.card.oauth"
signin_card = "application/vnd.microsoft.card.signin"
thumbnail_card = "application/vnd.microsoft.card.thumbnail"
video_card = "application/vnd.microsoft.card.video"
class CardFactory:
content_types = ContentTypes
@staticmethod
def adaptive_card(card: dict) -> Attachment:
"""
Returns an attachment for an adaptive card. The attachment will contain the card and the
appropriate 'contentType'. Will raise a TypeError if the 'card' argument is not an
dict.
:param card:
:return:
"""
if not isinstance(card, dict):
raise TypeError(
"CardFactory.adaptive_card(): `card` argument is not of type dict, unable to prepare "
"attachment."
)
return Attachment(
content_type=CardFactory.content_types.adaptive_card, content=card
)
@staticmethod
def animation_card(card: AnimationCard) -> Attachment:
"""
Returns an attachment for an animation card. Will raise a TypeError if the 'card' argument is not an
AnimationCard.
:param card:
:return:
"""
if not isinstance(card, AnimationCard):
raise TypeError(
"CardFactory.animation_card(): `card` argument is not an instance of an AnimationCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.animation_card, content=card
)
@staticmethod
def audio_card(card: AudioCard) -> Attachment:
"""
Returns an attachment for an audio card. Will raise a TypeError if 'card' argument is not an AudioCard.
:param card:
:return:
"""
if not isinstance(card, AudioCard):
raise TypeError(
"CardFactory.audio_card(): `card` argument is not an instance of an AudioCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.audio_card, content=card
)
@staticmethod
def hero_card(card: HeroCard) -> Attachment:
"""
Returns an attachment for a hero card. Will raise a TypeError if 'card' argument is not a HeroCard.
Hero cards tend to have one dominant full width image and the cards text & buttons can
usually be found below the image.
:return:
"""
if not isinstance(card, HeroCard):
raise TypeError(
"CardFactory.hero_card(): `card` argument is not an instance of an HeroCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.hero_card, content=card
)
@staticmethod
def oauth_card(card: OAuthCard) -> Attachment:
"""
Returns an attachment for an OAuth card used by the Bot Frameworks Single Sign On (SSO) service. Will raise a
TypeError if 'card' argument is not a OAuthCard.
:param card:
:return:
"""
if not isinstance(card, OAuthCard):
raise TypeError(
"CardFactory.oauth_card(): `card` argument is not an instance of an OAuthCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.oauth_card, content=card
)
@staticmethod
def receipt_card(card: ReceiptCard) -> Attachment:
"""
Returns an attachment for a receipt card. Will raise a TypeError if 'card' argument is not a ReceiptCard.
:param card:
:return:
"""
if not isinstance(card, ReceiptCard):
raise TypeError(
"CardFactory.receipt_card(): `card` argument is not an instance of an ReceiptCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.receipt_card, content=card
)
@staticmethod
def signin_card(card: SigninCard) -> Attachment:
"""
Returns an attachment for a signin card. For channels that don't natively support signin cards an alternative
message will be rendered. Will raise a TypeError if 'card' argument is not a SigninCard.
:param card:
:return:
"""
if not isinstance(card, SigninCard):
raise TypeError(
"CardFactory.signin_card(): `card` argument is not an instance of an SigninCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.signin_card, content=card
)
@staticmethod
def thumbnail_card(card: ThumbnailCard) -> Attachment:
"""
Returns an attachment for a thumbnail card. Thumbnail cards are similar to
but instead of a full width image, they're typically rendered with a smaller thumbnail version of
the image on either side and the text will be rendered in column next to the image. Any buttons
will typically show up under the card. Will raise a TypeError if 'card' argument is not a ThumbnailCard.
:param card:
:return:
"""
if not isinstance(card, ThumbnailCard):
raise TypeError(
"CardFactory.thumbnail_card(): `card` argument is not an instance of an ThumbnailCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.thumbnail_card, content=card
)
@staticmethod
def video_card(card: VideoCard) -> Attachment:
"""
Returns an attachment for a video card. Will raise a TypeError if 'card' argument is not a VideoCard.
:param card:
:return:
"""
if not isinstance(card, VideoCard):
raise TypeError(
"CardFactory.video_card(): `card` argument is not an instance of an VideoCard, "
"unable to prepare attachment."
)
return Attachment(
content_type=CardFactory.content_types.video_card, content=card
)
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/card_factory.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/card_factory.py",
"repo_id": "botbuilder-python",
"token_count": 2843
}
| 391 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import traceback
from aiohttp.web import (
middleware,
HTTPException,
HTTPNotImplemented,
HTTPUnauthorized,
HTTPNotFound,
HTTPInternalServerError,
)
from botbuilder.core import BotActionNotImplementedError
@middleware
async def aiohttp_error_middleware(request, handler):
try:
response = await handler(request)
return response
except BotActionNotImplementedError:
raise HTTPNotImplemented()
except NotImplementedError:
raise HTTPNotImplemented()
except PermissionError:
raise HTTPUnauthorized()
except KeyError:
raise HTTPNotFound()
except HTTPException:
raise
except Exception:
traceback.print_exc()
raise HTTPInternalServerError()
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/integration/aiohttp_channel_service_exception_middleware.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/integration/aiohttp_channel_service_exception_middleware.py",
"repo_id": "botbuilder-python",
"token_count": 311
}
| 392 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC, abstractmethod
from .turn_context import TurnContext
from .recognizer_result import RecognizerResult
class Recognizer(ABC):
@abstractmethod
async def recognize(self, turn_context: TurnContext) -> RecognizerResult:
raise NotImplementedError()
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/recognizer.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/recognizer.py",
"repo_id": "botbuilder-python",
"token_count": 104
}
| 393 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
class StatePropertyInfo(ABC):
@property
def name(self):
raise NotImplementedError()
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/state_property_info.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/state_property_info.py",
"repo_id": "botbuilder-python",
"token_count": 67
}
| 394 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Middleware Component for logging Activity messages."""
from typing import Awaitable, Callable, List, Dict
from jsonpickle import encode
from botbuilder.schema import Activity, ConversationReference, ActivityTypes
from botbuilder.schema.teams import TeamsChannelData, TeamInfo
from botframework.connector import Channels
from .bot_telemetry_client import BotTelemetryClient
from .bot_assert import BotAssert
from .middleware_set import Middleware
from .null_telemetry_client import NullTelemetryClient
from .turn_context import TurnContext
from .telemetry_constants import TelemetryConstants
from .telemetry_logger_constants import TelemetryLoggerConstants
# pylint: disable=line-too-long
class TelemetryLoggerMiddleware(Middleware):
"""Middleware for logging incoming, outgoing, updated or deleted Activity messages."""
def __init__(
self, telemetry_client: BotTelemetryClient, log_personal_information: bool
) -> None:
super(TelemetryLoggerMiddleware, self).__init__()
self._telemetry_client = telemetry_client or NullTelemetryClient()
self._log_personal_information = log_personal_information
@property
def telemetry_client(self) -> BotTelemetryClient:
"""Gets the currently configured BotTelemetryClient."""
return self._telemetry_client
@property
def log_personal_information(self) -> bool:
"""Gets a value indicating whether determines whether to log personal
information that came from the user."""
return self._log_personal_information
# pylint: disable=arguments-differ
async def on_turn(
self, context: TurnContext, logic_fn: Callable[[TurnContext], Awaitable]
) -> None:
"""Logs events based on incoming and outgoing activities using
BotTelemetryClient base class
:param turn_context: The context object for this turn.
:param logic: Callable to continue the bot middleware pipeline
:return: None
"""
BotAssert.context_not_none(context)
# Log incoming activity at beginning of turn
if context.activity:
activity = context.activity
# Log Bot Message Received
await self.on_receive_activity(activity)
# hook up onSend pipeline
# pylint: disable=unused-argument
async def send_activities_handler(
ctx: TurnContext,
activities: List[Activity],
next_send: Callable[[], Awaitable[None]],
):
# Run full pipeline
responses = await next_send()
for activity in activities:
await self.on_send_activity(activity)
return responses
context.on_send_activities(send_activities_handler)
# hook up update activity pipeline
async def update_activity_handler(
ctx: TurnContext, activity: Activity, next_update: Callable[[], Awaitable]
):
# Run full pipeline
response = await next_update()
await self.on_update_activity(activity)
return response
context.on_update_activity(update_activity_handler)
# hook up delete activity pipeline
async def delete_activity_handler(
ctx: TurnContext,
reference: ConversationReference,
next_delete: Callable[[], Awaitable],
):
# Run full pipeline
await next_delete()
delete_msg = Activity(
type=ActivityTypes.message_delete, id=reference.activity_id
)
deleted_activity: Activity = TurnContext.apply_conversation_reference(
delete_msg, reference, False
)
await self.on_delete_activity(deleted_activity)
context.on_delete_activity(delete_activity_handler)
if logic_fn:
await logic_fn()
async def on_receive_activity(self, activity: Activity) -> None:
"""Invoked when a message is received from the user.
Performs logging of telemetry data using the BotTelemetryClient.track_event() method.
This event name used is "BotMessageReceived".
:param activity: Current activity sent from user.
"""
self.telemetry_client.track_event(
TelemetryLoggerConstants.BOT_MSG_RECEIVE_EVENT,
await self.fill_receive_event_properties(activity),
)
async def on_send_activity(self, activity: Activity) -> None:
"""Invoked when the bot sends a message to the user.
Performs logging of telemetry data using the BotTelemetryClient.track_event() method.
This event name used is "BotMessageSend".
:param activity: Current activity sent from bot.
"""
self.telemetry_client.track_event(
TelemetryLoggerConstants.BOT_MSG_SEND_EVENT,
await self.fill_send_event_properties(activity),
)
async def on_update_activity(self, activity: Activity) -> None:
"""Invoked when the bot updates a message.
Performs logging of telemetry data using the BotTelemetryClient.track_event() method.
This event name used is "BotMessageUpdate".
:param activity: Current activity sent from user.
"""
self.telemetry_client.track_event(
TelemetryLoggerConstants.BOT_MSG_UPDATE_EVENT,
await self.fill_update_event_properties(activity),
)
async def on_delete_activity(self, activity: Activity) -> None:
"""Invoked when the bot deletes a message.
Performs logging of telemetry data using the BotTelemetryClient.track_event() method.
This event name used is "BotMessageDelete".
:param activity: Current activity sent from user.
"""
self.telemetry_client.track_event(
TelemetryLoggerConstants.BOT_MSG_DELETE_EVENT,
await self.fill_delete_event_properties(activity),
)
async def fill_receive_event_properties(
self, activity: Activity, additional_properties: Dict[str, str] = None
) -> Dict[str, str]:
"""Fills the event properties for the BotMessageReceived.
Adheres to the LogPersonalInformation flag to filter Name, Text and Speak properties.
:param activity: activity sent from user.
:param additional_properties: Additional properties to add to the event.
Additional properties can override "stock" properties.
:return: A dictionary that is sent as "Properties" to
BotTelemetryClient.track_event method for the BotMessageReceived event.
"""
properties = {
TelemetryConstants.FROM_ID_PROPERTY: activity.from_property.id
if activity.from_property
else None,
TelemetryConstants.CONVERSATION_NAME_PROPERTY: activity.conversation.name,
TelemetryConstants.LOCALE_PROPERTY: activity.locale,
TelemetryConstants.RECIPIENT_ID_PROPERTY: activity.recipient.id,
TelemetryConstants.RECIPIENT_NAME_PROPERTY: activity.recipient.name,
}
if self.log_personal_information:
if (
activity.from_property
and activity.from_property.name
and activity.from_property.name.strip()
):
properties[
TelemetryConstants.FROM_NAME_PROPERTY
] = activity.from_property.name
if activity.text and activity.text.strip():
properties[TelemetryConstants.TEXT_PROPERTY] = activity.text
if activity.speak and activity.speak.strip():
properties[TelemetryConstants.SPEAK_PROPERTY] = activity.speak
TelemetryLoggerMiddleware.__populate_additional_channel_properties(
activity, properties
)
# Additional properties can override "stock" properties
if additional_properties:
for prop in additional_properties:
properties[prop.key] = prop.value
return properties
async def fill_send_event_properties(
self, activity: Activity, additional_properties: Dict[str, str] = None
) -> Dict[str, str]:
"""Fills the event properties for the BotMessageSend.
These properties are logged when an activity message is sent by the Bot to the user.
:param activity: activity sent from user.
:param additional_properties: Additional properties to add to the event.
Additional properties can override "stock" properties.
:return: A dictionary that is sent as "Properties" to the
BotTelemetryClient.track_event method for the BotMessageSend event.
"""
properties = {
TelemetryConstants.REPLY_ACTIVITY_ID_PROPERTY: activity.reply_to_id,
TelemetryConstants.RECIPIENT_ID_PROPERTY: activity.recipient.id,
TelemetryConstants.CONVERSATION_NAME_PROPERTY: activity.conversation.name,
TelemetryConstants.LOCALE_PROPERTY: activity.locale,
}
# Use the LogPersonalInformation flag to toggle logging PII data, text and user name are common examples
if self.log_personal_information:
if activity.attachments and len(activity.attachments) > 0:
properties[TelemetryConstants.ATTACHMENTS_PROPERTY] = encode(
activity.attachments
)
if activity.from_property.name and activity.from_property.name.strip():
properties[
TelemetryConstants.FROM_NAME_PROPERTY
] = activity.from_property.name
if activity.text and activity.text.strip():
properties[TelemetryConstants.TEXT_PROPERTY] = activity.text
if activity.speak and activity.speak.strip():
properties[TelemetryConstants.SPEAK_PROPERTY] = activity.speak
# Additional properties can override "stock" properties
if additional_properties:
for prop in additional_properties:
properties[prop.key] = prop.value
return properties
async def fill_update_event_properties(
self, activity: Activity, additional_properties: Dict[str, str] = None
) -> Dict[str, str]:
"""Fills the event properties for the BotMessageUpdate.
These properties are logged when an activity message is updated by the Bot.
For example, if a card is interacted with by the use, and the card needs
to be updated to reflect some interaction.
:param activity: activity sent from user.
:param additional_properties: Additional properties to add to the event.
Additional properties can override "stock" properties.
:return: A dictionary that is sent as "Properties" to the
BotTelemetryClient.track_event method for the BotMessageUpdate event.
"""
properties = {
TelemetryConstants.RECIPIENT_ID_PROPERTY: activity.recipient.id,
TelemetryConstants.CONVERSATION_ID_PROPERTY: activity.conversation.id,
TelemetryConstants.CONVERSATION_NAME_PROPERTY: activity.conversation.name,
TelemetryConstants.LOCALE_PROPERTY: activity.locale,
}
# Use the LogPersonalInformation flag to toggle logging PII data, text is a common examples
if self.log_personal_information:
if activity.text and activity.text.strip():
properties[TelemetryConstants.TEXT_PROPERTY] = activity.text
# Additional properties can override "stock" properties
if additional_properties:
for prop in additional_properties:
properties[prop.key] = prop.value
return properties
async def fill_delete_event_properties(
self, activity: Activity, additional_properties: Dict[str, str] = None
) -> Dict[str, str]:
"""Fills the event properties for the BotMessageDelete.
These properties are logged when an activity message is deleted by the Bot.
:param activity: activity sent from user.
:param additional_properties: Additional properties to add to the event.
Additional properties can override "stock" properties.
:return: A dictionary that is sent as "Properties" to the
BotTelemetryClient.track_event method for the BotMessageUpdate event.
"""
properties = {
TelemetryConstants.RECIPIENT_ID_PROPERTY: activity.recipient.id,
TelemetryConstants.CONVERSATION_ID_PROPERTY: activity.conversation.id,
TelemetryConstants.CONVERSATION_NAME_PROPERTY: activity.conversation.name,
}
# Additional properties can override "stock" properties
if additional_properties:
for prop in additional_properties:
properties[prop.key] = prop.value
return properties
@staticmethod
def __populate_additional_channel_properties(
activity: Activity,
properties: dict,
):
if activity.channel_id == Channels.ms_teams:
teams_channel_data: TeamsChannelData = TeamsChannelData().deserialize(
activity.channel_data
)
properties["TeamsTenantId"] = (
teams_channel_data.tenant.id
if teams_channel_data and teams_channel_data.tenant
else ""
)
properties["TeamsUserAadObjectId"] = (
activity.from_property.aad_object_id if activity.from_property else ""
)
if teams_channel_data and teams_channel_data.team:
properties["TeamsTeamInfo"] = TeamInfo.serialize(
teams_channel_data.team
)
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/telemetry_logger_middleware.py",
"repo_id": "botbuilder-python",
"token_count": 5404
}
| 395 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import aiounittest
from botbuilder.schema import Activity
from botbuilder.schema.teams import TeamInfo
from botbuilder.core.teams import (
teams_get_channel_id,
teams_get_team_info,
teams_notify_user,
)
from botbuilder.core.teams.teams_activity_extensions import teams_get_meeting_info
class TestTeamsActivityHandler(aiounittest.AsyncTestCase):
def test_teams_get_channel_id(self):
# Arrange
activity = Activity(
channel_data={"channel": {"id": "id123", "name": "channel_name"}}
)
# Act
result = teams_get_channel_id(activity)
# Assert
assert result == "id123"
def test_teams_get_channel_id_with_no_channel(self):
# Arrange
activity = Activity(
channel_data={"team": {"id": "id123", "name": "channel_name"}}
)
# Act
result = teams_get_channel_id(activity)
# Assert
assert result is None
def test_teams_get_channel_id_with_no_channel_id(self):
# Arrange
activity = Activity(channel_data={"team": {"name": "channel_name"}})
# Act
result = teams_get_channel_id(activity)
# Assert
assert result is None
def test_teams_get_channel_id_with_no_channel_data(self):
# Arrange
activity = Activity(type="type")
# Act
result = teams_get_channel_id(activity)
# Assert
assert result is None
def test_teams_get_channel_id_with_none_activity(self):
# Arrange
activity = None
# Act
result = teams_get_channel_id(activity)
# Assert
assert result is None
def test_teams_get_team_info(self):
# Arrange
activity = Activity(
channel_data={"team": {"id": "id123", "name": "channel_name"}}
)
# Act
result = teams_get_team_info(activity)
# Assert
assert result == TeamInfo(id="id123", name="channel_name")
def test_teams_get_team_info_with_no_channel_data(self):
# Arrange
activity = Activity(type="type")
# Act
result = teams_get_team_info(activity)
# Assert
assert result is None
def test_teams_get_team_info_with_no_team_info(self):
# Arrange
activity = Activity(channel_data={"eventType": "eventType"})
# Act
result = teams_get_team_info(activity)
# Assert
assert result is None
def test_teams_get_team_info_with_none_activity(self):
# Arrange
activity = None
# Act
result = teams_get_team_info(activity)
# Assert
assert result is None
def test_teams_notify_user(self):
# Arrange
activity = Activity(channel_data={"eventType": "eventType"})
# Act
teams_notify_user(activity)
# Assert
assert activity.channel_data.notification.alert
def test_teams_notify_user_with_no_activity(self):
# Arrange
activity = None
# Act
teams_notify_user(activity)
# Assert
assert activity is None
def test_teams_notify_user_with_preexisting_notification(self):
# Arrange
activity = Activity(channel_data={"notification": {"alert": False}})
# Act
teams_notify_user(activity)
# Assert
assert activity.channel_data.notification.alert
def test_teams_notify_user_with_no_channel_data(self):
# Arrange
activity = Activity(id="id123")
# Act
teams_notify_user(activity)
# Assert
assert activity.channel_data.notification.alert
assert activity.id == "id123"
def test_teams_meeting_info(self):
# Arrange
activity = Activity(channel_data={"meeting": {"id": "meeting123"}})
# Act
meeting_id = teams_get_meeting_info(activity).id
# Assert
assert meeting_id == "meeting123"
|
botbuilder-python/libraries/botbuilder-core/tests/teams/test_teams_extension.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/teams/test_teams_extension.py",
"repo_id": "botbuilder-python",
"token_count": 1798
}
| 396 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Awaitable, Callable
import aiounittest
from botbuilder.core import (
AnonymousReceiveMiddleware,
MiddlewareSet,
Middleware,
TurnContext,
)
class TestMiddlewareSet(aiounittest.AsyncTestCase):
# pylint: disable=unused-argument
async def test_no_middleware(self):
middleware_set = MiddlewareSet()
# This shouldn't explode.
await middleware_set.receive_activity(None)
async def test_no_middleware_with_callback(self):
callback_complete = False
middleware_set = MiddlewareSet()
async def runs_after_pipeline(context):
nonlocal callback_complete
callback_complete = True
await middleware_set.receive_activity_with_status(None, runs_after_pipeline)
assert callback_complete
async def test_middleware_set_receive_activity_internal(self):
class PrintMiddleware:
async def on_turn(self, context_or_string, next_middleware):
print("PrintMiddleware says: %s." % context_or_string)
return next_middleware
class ModifyInputMiddleware(Middleware):
async def on_turn(
self, context: TurnContext, logic: Callable[[TurnContext], Awaitable]
):
context = "Hello"
print(context)
print("Here is the current context_or_string: %s" % context)
return logic
async def request_handler(context_or_string):
assert context_or_string == "Hello"
middleware_set = MiddlewareSet().use(PrintMiddleware())
middleware_set.use(ModifyInputMiddleware())
await middleware_set.receive_activity_internal("Bye", request_handler)
async def test_middleware_run_in_order(self):
called_first = False
called_second = False
class FirstMiddleware(Middleware):
async def on_turn(self, context, logic):
nonlocal called_first, called_second
assert called_second is False
called_first = True
return await logic()
class SecondMiddleware(Middleware):
async def on_turn(self, context, logic):
nonlocal called_first, called_second
assert called_first
called_second = True
return await logic()
middleware_set = MiddlewareSet().use(FirstMiddleware()).use(SecondMiddleware())
await middleware_set.receive_activity(None)
assert called_first
assert called_second
async def test_run_one_middleware(self):
called_first = False
finished_pipeline = False
class FirstMiddleware(Middleware):
async def on_turn(self, context, logic):
nonlocal called_first
called_first = True
return await logic()
middleware_set = MiddlewareSet().use(FirstMiddleware())
async def runs_after_pipeline(context):
nonlocal finished_pipeline
finished_pipeline = True
await middleware_set.receive_activity_with_status(None, runs_after_pipeline)
assert called_first
assert finished_pipeline
async def test_run_empty_pipeline(self):
ran_empty_pipeline = False
middleware_set = MiddlewareSet()
async def runs_after_pipeline(context):
nonlocal ran_empty_pipeline
ran_empty_pipeline = True
await middleware_set.receive_activity_with_status(None, runs_after_pipeline)
assert ran_empty_pipeline
async def test_two_middleware_one_does_not_call_next(self):
called_first = False
called_second = False
called_all_middleware = False
class FirstMiddleware(Middleware):
"""First Middleware, does not call next."""
async def on_turn(self, context, logic):
nonlocal called_first, called_second
assert called_second is False
called_first = True
return
class SecondMiddleware(Middleware):
async def on_turn(self, context, logic):
nonlocal called_all_middleware
called_all_middleware = True
return await logic()
middleware_set = MiddlewareSet().use(FirstMiddleware()).use(SecondMiddleware())
await middleware_set.receive_activity(None)
assert called_first
assert not called_second
assert not called_all_middleware
async def test_one_middleware_does_not_call_next(self):
called_first = False
finished_pipeline = False
class FirstMiddleware(Middleware):
async def on_turn(self, context, logic):
nonlocal called_first
called_first = True
return
middleware_set = MiddlewareSet().use(FirstMiddleware())
async def runs_after_pipeline(context):
nonlocal finished_pipeline
finished_pipeline = True
await middleware_set.receive_activity_with_status(None, runs_after_pipeline)
assert called_first
assert not finished_pipeline
async def test_anonymous_middleware(self):
did_run = False
middleware_set = MiddlewareSet()
async def processor(context, logic):
nonlocal did_run
did_run = True
return await logic()
middleware_set.use(AnonymousReceiveMiddleware(processor))
assert not did_run
await middleware_set.receive_activity(None)
assert did_run
async def test_anonymous_two_middleware_and_in_order(self):
called_first = False
called_second = False
middleware_set = MiddlewareSet()
async def processor_one(context, logic):
nonlocal called_first, called_second
called_first = True
assert not called_second
return await logic()
async def processor_two(context, logic):
nonlocal called_first, called_second
called_second = True
return await logic()
middleware_set.use(AnonymousReceiveMiddleware(processor_one))
middleware_set.use(AnonymousReceiveMiddleware(processor_two))
await middleware_set.receive_activity(None)
assert called_first
assert called_second
async def test_mixed_middleware_anonymous_first(self):
called_regular_middleware = False
called_anonymous_middleware = False
middleware_set = MiddlewareSet()
class MyFirstMiddleware(Middleware):
async def on_turn(self, context, logic):
nonlocal called_regular_middleware, called_anonymous_middleware
assert called_anonymous_middleware
called_regular_middleware = True
return await logic()
async def anonymous_method(context, logic):
nonlocal called_regular_middleware, called_anonymous_middleware
assert not called_regular_middleware
called_anonymous_middleware = True
return await logic()
middleware_set.use(AnonymousReceiveMiddleware(anonymous_method))
middleware_set.use(MyFirstMiddleware())
await middleware_set.receive_activity(None)
assert called_regular_middleware
assert called_anonymous_middleware
async def test_mixed_middleware_anonymous_last(self):
called_regular_middleware = False
called_anonymous_middleware = False
middleware_set = MiddlewareSet()
class MyFirstMiddleware(Middleware):
async def on_turn(self, context, logic):
nonlocal called_regular_middleware, called_anonymous_middleware
assert not called_anonymous_middleware
called_regular_middleware = True
return await logic()
async def anonymous_method(context, logic):
nonlocal called_regular_middleware, called_anonymous_middleware
assert called_regular_middleware
called_anonymous_middleware = True
return await logic()
middleware_set.use(MyFirstMiddleware())
middleware_set.use(AnonymousReceiveMiddleware(anonymous_method))
await middleware_set.receive_activity(None)
assert called_regular_middleware
assert called_anonymous_middleware
def test_invalid_middleware_should_not_be_added_to_middleware_set(self):
middleware_set = MiddlewareSet()
try:
middleware_set.use(2)
except TypeError:
pass
except Exception as error:
raise error
else:
raise AssertionError(
"MiddlewareSet.use(): should not have added an invalid middleware."
)
|
botbuilder-python/libraries/botbuilder-core/tests/test_middleware_set.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_middleware_set.py",
"repo_id": "botbuilder-python",
"token_count": 3803
}
| 397 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Union
from botbuilder.core import CardFactory, MessageFactory
from botbuilder.schema import ActionTypes, Activity, CardAction, HeroCard, InputHints
from . import Channel, Choice, ChoiceFactoryOptions
class ChoiceFactory:
"""
Assists with formatting a message activity that contains a list of choices.
"""
@staticmethod
def for_channel(
channel_id: str,
choices: List[Union[str, Choice]],
text: str = None,
speak: str = None,
options: ChoiceFactoryOptions = None,
) -> Activity:
"""
Creates a message activity that includes a list of choices formatted based on the
capabilities of a given channel.
Parameters:
----------
channel_id: A channel ID.
choices: List of choices to render
text: (Optional) Text of the message to send.
speak (Optional) SSML. Text to be spoken by your bot on a speech-enabled channel.
"""
if channel_id is None:
channel_id = ""
choices = ChoiceFactory._to_choices(choices)
# Find maximum title length
max_title_length = 0
for choice in choices:
if choice.action is not None and choice.action.title not in (None, ""):
size = len(choice.action.title)
else:
size = len(choice.value)
if size > max_title_length:
max_title_length = size
# Determine list style
supports_suggested_actions = Channel.supports_suggested_actions(
channel_id, len(choices)
)
supports_card_actions = Channel.supports_card_actions(channel_id, len(choices))
max_action_title_length = Channel.max_action_title_length(channel_id)
long_titles = max_title_length > max_action_title_length
if not long_titles and not supports_suggested_actions and supports_card_actions:
# SuggestedActions is the preferred approach, but for channels that don't
# support them (e.g. Teams, Cortana) we should use a HeroCard with CardActions
return ChoiceFactory.hero_card(choices, text, speak)
if not long_titles and supports_suggested_actions:
# We always prefer showing choices using suggested actions. If the titles are too long, however,
# we'll have to show them as a text list.
return ChoiceFactory.suggested_action(choices, text, speak)
if not long_titles and len(choices) <= 3:
# If the titles are short and there are 3 or less choices we'll use an inline list.
return ChoiceFactory.inline(choices, text, speak, options)
# Show a numbered list.
return ChoiceFactory.list_style(choices, text, speak, options)
@staticmethod
def inline(
choices: List[Union[str, Choice]],
text: str = None,
speak: str = None,
options: ChoiceFactoryOptions = None,
) -> Activity:
"""
Creates a message activity that includes a list of choices formatted as an inline list.
Parameters:
----------
choices: The list of choices to render.
text: (Optional) The text of the message to send.
speak: (Optional) SSML. Text to be spoken by your bot on a speech-enabled channel.
options: (Optional) The formatting options to use to tweak rendering of list.
"""
choices = ChoiceFactory._to_choices(choices)
if options is None:
options = ChoiceFactoryOptions()
opt = ChoiceFactoryOptions(
inline_separator=options.inline_separator or ", ",
inline_or=options.inline_or or " or ",
inline_or_more=options.inline_or_more or ", or ",
include_numbers=(
options.include_numbers if options.include_numbers is not None else True
),
)
# Format list of choices
connector = ""
txt_builder: List[str] = [text]
txt_builder.append(" ")
for index, choice in enumerate(choices):
title = (
choice.action.title
if (choice.action is not None and choice.action.title is not None)
else choice.value
)
txt_builder.append(connector)
if opt.include_numbers is True:
txt_builder.append("(")
txt_builder.append(f"{index + 1}")
txt_builder.append(") ")
txt_builder.append(title)
if index == (len(choices) - 2):
connector = opt.inline_or if index == 0 else opt.inline_or_more
connector = connector or ""
else:
connector = opt.inline_separator or ""
# Return activity with choices as an inline list.
return MessageFactory.text(
"".join(txt_builder), speak, InputHints.expecting_input
)
@staticmethod
def list_style(
choices: List[Union[str, Choice]],
text: str = None,
speak: str = None,
options: ChoiceFactoryOptions = None,
):
"""
Creates a message activity that includes a list of choices formatted as a numbered or bulleted list.
Parameters:
----------
choices: The list of choices to render.
text: (Optional) The text of the message to send.
speak: (Optional) SSML. Text to be spoken by your bot on a speech-enabled channel.
options: (Optional) The formatting options to use to tweak rendering of list.
"""
choices = ChoiceFactory._to_choices(choices)
if options is None:
options = ChoiceFactoryOptions()
if options.include_numbers is None:
include_numbers = True
else:
include_numbers = options.include_numbers
# Format list of choices
connector = ""
txt_builder = [text]
txt_builder.append("\n\n ")
for index, choice in enumerate(choices):
title = (
choice.action.title
if choice.action is not None and choice.action.title is not None
else choice.value
)
txt_builder.append(connector)
if include_numbers:
txt_builder.append(f"{index + 1}")
txt_builder.append(". ")
else:
txt_builder.append("- ")
txt_builder.append(title)
connector = "\n "
# Return activity with choices as a numbered list.
txt = "".join(txt_builder)
return MessageFactory.text(txt, speak, InputHints.expecting_input)
@staticmethod
def suggested_action(
choices: List[Choice], text: str = None, speak: str = None
) -> Activity:
"""
Creates a message activity that includes a list of choices that have been added as suggested actions.
"""
# Return activity with choices as suggested actions
return MessageFactory.suggested_actions(
ChoiceFactory._extract_actions(choices),
text,
speak,
InputHints.expecting_input,
)
@staticmethod
def hero_card(
choices: List[Union[Choice, str]], text: str = None, speak: str = None
) -> Activity:
"""
Creates a message activity that includes a lsit of coices that have been added as `HeroCard`'s
"""
attachment = CardFactory.hero_card(
HeroCard(text=text, buttons=ChoiceFactory._extract_actions(choices))
)
# Return activity with choices as HeroCard with buttons
return MessageFactory.attachment(
attachment, None, speak, InputHints.expecting_input
)
@staticmethod
def _to_choices(choices: List[Union[str, Choice]]) -> List[Choice]:
"""
Takes a list of strings and returns them as [`Choice`].
"""
if choices is None:
return []
return [
Choice(value=choice) if isinstance(choice, str) else choice
for choice in choices
]
@staticmethod
def _extract_actions(choices: List[Union[str, Choice]]) -> List[CardAction]:
if choices is None:
choices = []
choices = ChoiceFactory._to_choices(choices)
card_actions: List[CardAction] = []
for choice in choices:
if choice.action is not None:
card_action = choice.action
else:
card_action = CardAction(
type=ActionTypes.im_back, value=choice.value, title=choice.value
)
card_actions.append(card_action)
return card_actions
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_factory.py",
"repo_id": "botbuilder-python",
"token_count": 3760
}
| 398 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Optional
from botbuilder.core.turn_context import TurnContext
from botbuilder.dialogs.memory import DialogStateManager
from .dialog_event import DialogEvent
from .dialog_events import DialogEvents
from .dialog_set import DialogSet
from .dialog_state import DialogState
from .dialog_turn_status import DialogTurnStatus
from .dialog_turn_result import DialogTurnResult
from .dialog_reason import DialogReason
from .dialog_instance import DialogInstance
from .dialog import Dialog
class DialogContext:
def __init__(
self, dialog_set: DialogSet, turn_context: TurnContext, state: DialogState
):
if dialog_set is None:
raise TypeError("DialogContext(): dialog_set cannot be None.")
# TODO: Circular dependency with dialog_set: Check type.
if turn_context is None:
raise TypeError("DialogContext(): turn_context cannot be None.")
self._turn_context = turn_context
self._dialogs = dialog_set
self._stack = state.dialog_stack
self.services = {}
self.parent: DialogContext = None
self.state = DialogStateManager(self)
@property
def dialogs(self) -> DialogSet:
"""Gets the set of dialogs that can be called from this context.
:param:
:return DialogSet:
"""
return self._dialogs
@property
def context(self) -> TurnContext:
"""Gets the context for the current turn of conversation.
:param:
:return TurnContext:
"""
return self._turn_context
@property
def stack(self) -> List:
"""Gets the current dialog stack.
:param:
:return list:
"""
return self._stack
@property
def active_dialog(self):
"""Return the container link in the database.
:param:
:return:
"""
if self._stack:
return self._stack[0]
return None
@property
def child(self) -> Optional["DialogContext"]:
"""Return the container link in the database.
:param:
:return DialogContext:
"""
# pylint: disable=import-outside-toplevel
instance = self.active_dialog
if instance:
dialog = self.find_dialog_sync(instance.id)
# This import prevents circular dependency issues
from .dialog_container import DialogContainer
if isinstance(dialog, DialogContainer):
return dialog.create_child_context(self)
return None
async def begin_dialog(self, dialog_id: str, options: object = None):
"""
Pushes a new dialog onto the dialog stack.
:param dialog_id: ID of the dialog to start
:param options: (Optional) additional argument(s) to pass to the dialog being started.
"""
try:
if not dialog_id:
raise TypeError("Dialog(): dialog_id cannot be None.")
# Look up dialog
dialog = await self.find_dialog(dialog_id)
if dialog is None:
raise Exception(
"'DialogContext.begin_dialog(): A dialog with an id of '%s' wasn't found."
" The dialog must be included in the current or parent DialogSet."
" For example, if subclassing a ComponentDialog you can call add_dialog() within your constructor."
% dialog_id
)
# Push new instance onto stack
instance = DialogInstance()
instance.id = dialog_id
instance.state = {}
self._stack.insert(0, (instance))
# Call dialog's begin_dialog() method
return await dialog.begin_dialog(self, options)
except Exception as err:
self.__set_exception_context_data(err)
raise
# TODO: Fix options: PromptOptions instead of object
async def prompt(self, dialog_id: str, options) -> DialogTurnResult:
"""
Helper function to simplify formatting the options for calling a prompt dialog. This helper will
take a `PromptOptions` argument and then call.
:param dialog_id: ID of the prompt to start.
:param options: Contains a Prompt, potentially a RetryPrompt and if using ChoicePrompt, Choices.
:return:
"""
try:
if not dialog_id:
raise TypeError("DialogContext.prompt(): dialogId cannot be None.")
if not options:
raise TypeError("DialogContext.prompt(): options cannot be None.")
return await self.begin_dialog(dialog_id, options)
except Exception as err:
self.__set_exception_context_data(err)
raise
async def continue_dialog(self):
"""
Continues execution of the active dialog, if there is one, by passing the context object to
its `Dialog.continue_dialog()` method. You can check `turn_context.responded` after the call completes
to determine if a dialog was run and a reply was sent to the user.
:return:
"""
try:
# Check for a dialog on the stack
if self.active_dialog is not None:
# Look up dialog
dialog = await self.find_dialog(self.active_dialog.id)
if not dialog:
raise Exception(
"DialogContext.continue_dialog(): Can't continue dialog. "
"A dialog with an id of '%s' wasn't found."
% self.active_dialog.id
)
# Continue execution of dialog
return await dialog.continue_dialog(self)
return DialogTurnResult(DialogTurnStatus.Empty)
except Exception as err:
self.__set_exception_context_data(err)
raise
# TODO: instance is DialogInstance
async def end_dialog(self, result: object = None):
"""
Ends a dialog by popping it off the stack and returns an optional result to the dialog's
parent. The parent dialog is the dialog that started the dialog being ended via a call to
either "begin_dialog" or "prompt".
The parent dialog will have its `Dialog.resume_dialog()` method invoked with any returned
result. If the parent dialog hasn't implemented a `resume_dialog()` method then it will be
automatically ended as well and the result passed to its parent. If there are no more
parent dialogs on the stack then processing of the turn will end.
:param result: (Optional) result to pass to the parent dialogs.
:return:
"""
try:
await self.end_active_dialog(DialogReason.EndCalled)
# Resume previous dialog
if self.active_dialog is not None:
# Look up dialog
dialog = await self.find_dialog(self.active_dialog.id)
if not dialog:
raise Exception(
"DialogContext.EndDialogAsync(): Can't resume previous dialog."
" A dialog with an id of '%s' wasn't found."
% self.active_dialog.id
)
# Return result to previous dialog
return await dialog.resume_dialog(self, DialogReason.EndCalled, result)
return DialogTurnResult(DialogTurnStatus.Complete, result)
except Exception as err:
self.__set_exception_context_data(err)
raise
async def cancel_all_dialogs(
self,
cancel_parents: bool = None,
event_name: str = None,
event_value: object = None,
):
"""
Deletes any existing dialog stack thus cancelling all dialogs on the stack.
:param cancel_parents:
:param event_name:
:param event_value:
:return:
"""
try:
event_name = event_name or DialogEvents.cancel_dialog
if self.stack or self.parent:
# Cancel all local and parent dialogs while checking for interception
notify = False
dialog_context = self
while dialog_context:
if dialog_context.stack:
# Check to see if the dialog wants to handle the event
if notify:
event_handled = await dialog_context.emit_event(
event_name,
event_value,
bubble=False,
from_leaf=False,
)
if event_handled:
break
# End the active dialog
await dialog_context.end_active_dialog(
DialogReason.CancelCalled
)
else:
dialog_context = (
dialog_context.parent if cancel_parents else None
)
notify = True
return DialogTurnResult(DialogTurnStatus.Cancelled)
# Stack was empty and no parent
return DialogTurnResult(DialogTurnStatus.Empty)
except Exception as err:
self.__set_exception_context_data(err)
raise
async def find_dialog(self, dialog_id: str) -> Dialog:
"""
If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext`
will be searched if there is one.
:param dialog_id: ID of the dialog to search for.
:return:
"""
try:
dialog = await self.dialogs.find(dialog_id)
if dialog is None and self.parent is not None:
dialog = await self.parent.find_dialog(dialog_id)
return dialog
except Exception as err:
self.__set_exception_context_data(err)
raise
def find_dialog_sync(self, dialog_id: str) -> Dialog:
"""
If the dialog cannot be found within the current `DialogSet`, the parent `DialogContext`
will be searched if there is one.
:param dialog_id: ID of the dialog to search for.
:return:
"""
dialog = self.dialogs.find_dialog(dialog_id)
if dialog is None and self.parent is not None:
dialog = self.parent.find_dialog_sync(dialog_id)
return dialog
async def replace_dialog(
self, dialog_id: str, options: object = None
) -> DialogTurnResult:
"""
Ends the active dialog and starts a new dialog in its place. This is particularly useful
for creating loops or redirecting to another dialog.
:param dialog_id: ID of the dialog to search for.
:param options: (Optional) additional argument(s) to pass to the new dialog.
:return:
"""
try:
# End the current dialog and giving the reason.
await self.end_active_dialog(DialogReason.ReplaceCalled)
# Start replacement dialog
return await self.begin_dialog(dialog_id, options)
except Exception as err:
self.__set_exception_context_data(err)
raise
async def reprompt_dialog(self):
"""
Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior.
:return:
"""
try:
# Check for a dialog on the stack
if self.active_dialog is not None:
# Look up dialog
dialog = await self.find_dialog(self.active_dialog.id)
if not dialog:
raise Exception(
"DialogSet.reprompt_dialog(): Can't find A dialog with an id of '%s'."
% self.active_dialog.id
)
# Ask dialog to re-prompt if supported
await dialog.reprompt_dialog(self.context, self.active_dialog)
except Exception as err:
self.__set_exception_context_data(err)
raise
async def end_active_dialog(self, reason: DialogReason):
instance = self.active_dialog
if instance is not None:
# Look up dialog
dialog = await self.find_dialog(instance.id)
if dialog is not None:
# Notify dialog of end
await dialog.end_dialog(self.context, instance, reason)
# Pop dialog off stack
self._stack.pop(0)
async def emit_event(
self,
name: str,
value: object = None,
bubble: bool = True,
from_leaf: bool = False,
) -> bool:
"""
Searches for a dialog with a given ID.
Emits a named event for the current dialog, or someone who started it, to handle.
:param name: Name of the event to raise.
:param value: Value to send along with the event.
:param bubble: Flag to control whether the event should be bubbled to its parent if not handled locally.
Defaults to a value of `True`.
:param from_leaf: Whether the event is emitted from a leaf node.
:param cancellationToken: The cancellation token.
:return: True if the event was handled.
"""
try:
# Initialize event
dialog_event = DialogEvent(
bubble=bubble,
name=name,
value=value,
)
dialog_context = self
# Find starting dialog
if from_leaf:
while True:
child_dc = dialog_context.child
if child_dc:
dialog_context = child_dc
else:
break
# Dispatch to active dialog first
instance = dialog_context.active_dialog
if instance:
dialog = await dialog_context.find_dialog(instance.id)
if dialog:
return await dialog.on_dialog_event(dialog_context, dialog_event)
return False
except Exception as err:
self.__set_exception_context_data(err)
raise
def __set_exception_context_data(self, exception: Exception):
if not hasattr(exception, "data"):
exception.data = {}
if not type(self).__name__ in exception.data:
stack = []
current_dc = self
while current_dc is not None:
stack = stack + [x.id for x in current_dc.stack]
current_dc = current_dc.parent
exception.data[type(self).__name__] = {
"active_dialog": None
if self.active_dialog is None
else self.active_dialog.id,
"parent": None if self.parent is None else self.parent.active_dialog.id,
"stack": self.stack,
}
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py",
"repo_id": "botbuilder-python",
"token_count": 6946
}
| 399 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class DialogPath:
# Counter of emitted events.
EVENT_COUNTER = "dialog.eventCounter"
# Currently expected properties.
EXPECTED_PROPERTIES = "dialog.expectedProperties"
# Default operation to use for entities where there is no identified operation entity.
DEFAULT_OPERATION = "dialog.defaultOperation"
# Last surfaced entity ambiguity event.
LAST_EVENT = "dialog.lastEvent"
# Currently required properties.
REQUIRED_PROPERTIES = "dialog.requiredProperties"
# Number of retries for the current Ask.
RETRIES = "dialog.retries"
# Last intent.
LAST_INTENT = "dialog.lastIntent"
# Last trigger event: defined in FormEvent, ask, clarifyEntity etc..
LAST_TRIGGER_EVENT = "dialog.lastTriggerEvent"
@staticmethod
def get_property_name(prop: str) -> str:
return prop.replace("dialog.", "")
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_path.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_path.py",
"repo_id": "botbuilder-python",
"token_count": 316
}
| 400 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from copy import deepcopy
from botbuilder.dialogs.memory import scope_path
from .memory_scope import MemoryScope
class DialogClassMemoryScope(MemoryScope):
def __init__(self):
# pylint: disable=import-outside-toplevel
super().__init__(scope_path.DIALOG_CLASS, include_in_snapshot=False)
# This import is to avoid circular dependency issues
from botbuilder.dialogs import DialogContainer
self._dialog_container_cls = DialogContainer
def get_memory(self, dialog_context: "DialogContext") -> object:
if not dialog_context:
raise TypeError(f"Expecting: DialogContext, but received None")
# if active dialog is a container dialog then "dialogclass" binds to it.
if dialog_context.active_dialog:
dialog = dialog_context.find_dialog_sync(dialog_context.active_dialog.id)
if isinstance(dialog, self._dialog_container_cls):
return deepcopy(dialog)
# Otherwise we always bind to parent, or if there is no parent the active dialog
parent_id = (
dialog_context.parent.active_dialog.id
if dialog_context.parent and dialog_context.parent.active_dialog
else None
)
active_id = (
dialog_context.active_dialog.id if dialog_context.active_dialog else None
)
return deepcopy(dialog_context.find_dialog_sync(parent_id or active_id))
def set_memory(self, dialog_context: "DialogContext", memory: object):
raise Exception(
f"{self.__class__.__name__}.set_memory not supported (read only)"
)
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/dialog_class_memory_scope.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/dialog_class_memory_scope.py",
"repo_id": "botbuilder-python",
"token_count": 662
}
| 401 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Dict
from recognizers_date_time import recognize_datetime
from botbuilder.core.turn_context import TurnContext
from botbuilder.schema import ActivityTypes
from .datetime_resolution import DateTimeResolution
from .prompt import Prompt
from .prompt_options import PromptOptions
from .prompt_recognizer_result import PromptRecognizerResult
class DateTimePrompt(Prompt):
def __init__(
self, dialog_id: str, validator: object = None, default_locale: str = None
):
super(DateTimePrompt, self).__init__(dialog_id, validator)
self.default_locale = default_locale
async def on_prompt(
self,
turn_context: TurnContext,
state: Dict[str, object],
options: PromptOptions,
is_retry: bool,
):
if not turn_context:
raise TypeError("DateTimePrompt.on_prompt(): turn_context cannot be None.")
if not options:
raise TypeError("DateTimePrompt.on_prompt(): options cannot be None.")
if is_retry and options.retry_prompt is not None:
await turn_context.send_activity(options.retry_prompt)
else:
if options.prompt is not None:
await turn_context.send_activity(options.prompt)
async def on_recognize(
self,
turn_context: TurnContext,
state: Dict[str, object],
options: PromptOptions,
) -> PromptRecognizerResult:
if not turn_context:
raise TypeError(
"DateTimePrompt.on_recognize(): turn_context cannot be None."
)
result = PromptRecognizerResult()
if turn_context.activity.type == ActivityTypes.message:
# Recognize utterance
utterance = turn_context.activity.text
if not utterance:
return result
# TODO: English constant needs to be ported.
culture = (
turn_context.activity.locale
if turn_context.activity.locale is not None
else "English"
)
results = recognize_datetime(utterance, culture)
if results:
result.succeeded = True
result.value = []
values = results[0].resolution["values"]
for value in values:
result.value.append(self.read_resolution(value))
return result
def read_resolution(self, resolution: Dict[str, str]) -> DateTimeResolution:
result = DateTimeResolution()
if "timex" in resolution:
result.timex = resolution["timex"]
if "value" in resolution:
result.value = resolution["value"]
if "start" in resolution:
result.start = resolution["start"]
if "end" in resolution:
result.end = resolution["end"]
return result
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/datetime_prompt.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/datetime_prompt.py",
"repo_id": "botbuilder-python",
"token_count": 1263
}
| 402 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import uuid
from typing import Coroutine
from botbuilder.core import TurnContext
from botbuilder.schema import ActivityTypes
from .dialog_reason import DialogReason
from .dialog import Dialog
from .dialog_turn_result import DialogTurnResult
from .dialog_context import DialogContext
from .dialog_instance import DialogInstance
from .waterfall_step_context import WaterfallStepContext
class WaterfallDialog(Dialog):
PersistedOptions = "options"
StepIndex = "stepIndex"
PersistedValues = "values"
PersistedInstanceId = "instanceId"
def __init__(self, dialog_id: str, steps: [Coroutine] = None):
super(WaterfallDialog, self).__init__(dialog_id)
if not steps:
self._steps = []
else:
if not isinstance(steps, list):
raise TypeError("WaterfallDialog(): steps must be list of steps")
self._steps = steps
def add_step(self, step):
"""
Adds a new step to the waterfall.
:param step: Step to add
:return: Waterfall dialog for fluent calls to `add_step()`.
"""
if not step:
raise TypeError("WaterfallDialog.add_step(): step cannot be None.")
self._steps.append(step)
return self
async def begin_dialog(
self, dialog_context: DialogContext, options: object = None
) -> DialogTurnResult:
if not dialog_context:
raise TypeError("WaterfallDialog.begin_dialog(): dc cannot be None.")
# Initialize waterfall state
state = dialog_context.active_dialog.state
instance_id = uuid.uuid1().__str__()
state[self.PersistedOptions] = options
state[self.PersistedValues] = {}
state[self.PersistedInstanceId] = instance_id
properties = {}
properties["DialogId"] = self.id
properties["InstanceId"] = instance_id
self.telemetry_client.track_event("WaterfallStart", properties)
# Run first stepkinds
return await self.run_step(dialog_context, 0, DialogReason.BeginCalled, None)
async def continue_dialog( # pylint: disable=unused-argument,arguments-differ
self,
dialog_context: DialogContext = None,
reason: DialogReason = None,
result: object = NotImplementedError(),
) -> DialogTurnResult:
if not dialog_context:
raise TypeError("WaterfallDialog.continue_dialog(): dc cannot be None.")
if dialog_context.context.activity.type != ActivityTypes.message:
return Dialog.end_of_turn
return await self.resume_dialog(
dialog_context,
DialogReason.ContinueCalled,
dialog_context.context.activity.text,
)
async def resume_dialog(
self, dialog_context: DialogContext, reason: DialogReason, result: object
):
if dialog_context is None:
raise TypeError("WaterfallDialog.resume_dialog(): dc cannot be None.")
# Increment step index and run step
state = dialog_context.active_dialog.state
# Future Me:
# If issues with CosmosDB, see https://github.com/Microsoft/botbuilder-dotnet/issues/871
# for hints.
return await self.run_step(
dialog_context, state[self.StepIndex] + 1, reason, result
)
async def end_dialog( # pylint: disable=unused-argument
self, context: TurnContext, instance: DialogInstance, reason: DialogReason
) -> None:
if reason is DialogReason.CancelCalled:
index = instance.state[self.StepIndex]
step_name = self.get_step_name(index)
instance_id = str(instance.state[self.PersistedInstanceId])
properties = {
"DialogId": self.id,
"StepName": step_name,
"InstanceId": instance_id,
}
self.telemetry_client.track_event("WaterfallCancel", properties)
else:
if reason is DialogReason.EndCalled:
instance_id = str(instance.state[self.PersistedInstanceId])
properties = {"DialogId": self.id, "InstanceId": instance_id}
self.telemetry_client.track_event("WaterfallComplete", properties)
return
async def on_step(self, step_context: WaterfallStepContext) -> DialogTurnResult:
step_name = self.get_step_name(step_context.index)
instance_id = str(step_context.active_dialog.state[self.PersistedInstanceId])
properties = {
"DialogId": self.id,
"StepName": step_name,
"InstanceId": instance_id,
}
self.telemetry_client.track_event("WaterfallStep", properties)
return await self._steps[step_context.index](step_context)
async def run_step(
self,
dialog_context: DialogContext,
index: int,
reason: DialogReason,
result: object,
) -> DialogTurnResult:
if not dialog_context:
raise TypeError(
"WaterfallDialog.run_steps(): dialog_context cannot be None."
)
if index < len(self._steps):
# Update persisted step index
state = dialog_context.active_dialog.state
state[self.StepIndex] = index
# Create step context
options = state[self.PersistedOptions]
values = state[self.PersistedValues]
step_context = WaterfallStepContext(
self, dialog_context, options, values, index, reason, result
)
return await self.on_step(step_context)
# End of waterfall so just return any result to parent
return await dialog_context.end_dialog(result)
def get_step_name(self, index: int) -> str:
"""
Give the waterfall step a unique name
"""
step_name = self._steps[index].__qualname__
if not step_name or step_name.endswith("<lambda>"):
step_name = f"Step{index + 1}of{len(self._steps)}"
return step_name
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_dialog.py",
"repo_id": "botbuilder-python",
"token_count": 2534
}
| 403 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
import aiounittest
from recognizers_text import Culture
from botbuilder.core import CardFactory, ConversationState, MemoryStorage, TurnContext
from botbuilder.core.adapters import TestAdapter
from botbuilder.dialogs import (
DialogSet,
DialogTurnResult,
DialogTurnStatus,
ChoiceRecognizers,
FindChoicesOptions,
)
from botbuilder.dialogs.choices import Choice, ChoiceFactoryOptions, ListStyle
from botbuilder.dialogs.prompts import (
ChoicePrompt,
PromptCultureModel,
PromptOptions,
PromptValidatorContext,
)
from botbuilder.schema import Activity, ActivityTypes
_color_choices: List[Choice] = [
Choice(value="red"),
Choice(value="green"),
Choice(value="blue"),
]
_answer_message: Activity = Activity(text="red", type=ActivityTypes.message)
_invalid_message: Activity = Activity(text="purple", type=ActivityTypes.message)
class ChoicePromptTest(aiounittest.AsyncTestCase):
def test_choice_prompt_with_empty_id_should_fail(self):
empty_id = ""
with self.assertRaises(TypeError):
ChoicePrompt(empty_id)
def test_choice_prompt_with_none_id_should_fail(self):
none_id = None
with self.assertRaises(TypeError):
ChoicePrompt(none_id)
async def test_should_call_choice_prompt_using_dc_prompt(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("ChoicePrompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
# Initialize TestAdapter.
adapter = TestAdapter(exec_test)
# Create new ConversationState with MemoryStorage and register the state as middleware.
convo_state = ConversationState(MemoryStorage())
# Create a DialogState property, DialogSet, and ChoicePrompt.
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("ChoicePrompt")
dialogs.add(choice_prompt)
step1 = await adapter.send("hello")
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_call_choice_prompt_with_custom_validator(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
return prompt.recognized.succeeded
choice_prompt = ChoicePrompt("prompt", validator)
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_invalid_message)
step4 = await step3.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step5 = await step4.send(_answer_message)
await step5.assert_reply("red")
async def test_should_send_custom_retry_prompt(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
retry_prompt=Activity(
type=ActivityTypes.message,
text="Please choose red, blue, or green.",
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_invalid_message)
step4 = await step3.assert_reply(
"Please choose red, blue, or green. (1) red, (2) green, or (3) blue"
)
step5 = await step4.send(_answer_message)
await step5.assert_reply("red")
async def test_should_send_ignore_retry_prompt_if_validator_replies(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
retry_prompt=Activity(
type=ActivityTypes.message,
text="Please choose red, blue, or green.",
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
if not prompt.recognized.succeeded:
await prompt.context.send_activity("Bad input.")
return prompt.recognized.succeeded
choice_prompt = ChoicePrompt("prompt", validator)
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_invalid_message)
step4 = await step3.assert_reply("Bad input.")
step5 = await step4.send(_answer_message)
await step5.assert_reply("red")
async def test_should_use_default_locale_when_rendering_choices(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
if not prompt.recognized.succeeded:
await prompt.context.send_activity("Bad input.")
return prompt.recognized.succeeded
choice_prompt = ChoicePrompt(
"prompt", validator, default_locale=Culture.Spanish
)
dialogs.add(choice_prompt)
step1 = await adapter.send(Activity(type=ActivityTypes.message, text="Hello"))
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, o (3) blue"
)
step3 = await step2.send(_invalid_message)
step4 = await step3.assert_reply("Bad input.")
step5 = await step4.send(Activity(type=ActivityTypes.message, text="red"))
await step5.assert_reply("red")
async def test_should_use_context_activity_locale_when_rendering_choices(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
if not prompt.recognized.succeeded:
await prompt.context.send_activity("Bad input.")
return prompt.recognized.succeeded
choice_prompt = ChoicePrompt("prompt", validator)
dialogs.add(choice_prompt)
step1 = await adapter.send(
Activity(type=ActivityTypes.message, text="Hello", locale=Culture.Spanish)
)
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, o (3) blue"
)
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_use_context_activity_locale_over_default_locale_when_rendering_choices(
self,
):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
if not prompt.recognized.succeeded:
await prompt.context.send_activity("Bad input.")
return prompt.recognized.succeeded
choice_prompt = ChoicePrompt(
"prompt", validator, default_locale=Culture.Spanish
)
dialogs.add(choice_prompt)
step1 = await adapter.send(
Activity(type=ActivityTypes.message, text="Hello", locale=Culture.English)
)
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_default_to_english_locale(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
if not prompt.recognized.succeeded:
await prompt.context.send_activity("Bad input.")
return prompt.recognized.succeeded
locales = [None, "", "not-supported"]
for locale in locales:
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt", validator)
dialogs.add(choice_prompt)
step1 = await adapter.send(
Activity(type=ActivityTypes.message, text="Hello", locale=locale)
)
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_recognize_locale_variations_of_correct_locales(self):
def cap_ending(locale: str) -> str:
return f"{locale.split('-')[0]}-{locale.split('-')[1].upper()}"
def title_ending(locale: str) -> str:
return locale[:3] + locale[3].upper() + locale[4:]
def cap_two_letter(locale: str) -> str:
return locale.split("-")[0].upper()
def lower_two_letter(locale: str) -> str:
return locale.split("-")[0].upper()
async def exec_test_for_locale(valid_locale: str, locale_variations: List):
# Hold the correct answer from when a valid locale is used
expected_answer = None
def inspector(activity: Activity, description: str):
nonlocal expected_answer
assert not description
if valid_locale == test_locale:
expected_answer = activity.text
else:
# Ensure we're actually testing a variation.
assert activity.locale != valid_locale
assert activity.text == expected_answer
return True
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
if not prompt.recognized.succeeded:
await prompt.context.send_activity("Bad input.")
return prompt.recognized.succeeded
test_locale = None
for test_locale in locale_variations:
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt", validator)
dialogs.add(choice_prompt)
step1 = await adapter.send(
Activity(
type=ActivityTypes.message, text="Hello", locale=test_locale
)
)
await step1.assert_reply(inspector)
locales = [
"zh-cn",
"nl-nl",
"en-us",
"fr-fr",
"de-de",
"it-it",
"ja-jp",
"ko-kr",
"pt-br",
"es-es",
"tr-tr",
"de-de",
]
locale_tests = []
for locale in locales:
locale_tests.append(
[
locale,
cap_ending(locale),
title_ending(locale),
cap_two_letter(locale),
lower_two_letter(locale),
]
)
# Test each valid locale
for locale_tests in locale_tests:
await exec_test_for_locale(locale_tests[0], locale_tests)
async def test_should_recognize_and_use_custom_locale_dict(
self,
):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
async def validator(prompt: PromptValidatorContext) -> bool:
assert prompt
if not prompt.recognized.succeeded:
await prompt.context.send_activity("Bad input.")
return prompt.recognized.succeeded
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
culture = PromptCultureModel(
locale="custom-locale",
no_in_language="customNo",
yes_in_language="customYes",
separator="customSeparator",
inline_or="customInlineOr",
inline_or_more="customInlineOrMore",
)
custom_dict = {
culture.locale: ChoiceFactoryOptions(
inline_or=culture.inline_or,
inline_or_more=culture.inline_or_more,
inline_separator=culture.separator,
include_numbers=True,
)
}
choice_prompt = ChoicePrompt("prompt", validator, choice_defaults=custom_dict)
dialogs.add(choice_prompt)
step1 = await adapter.send(
Activity(type=ActivityTypes.message, text="Hello", locale=culture.locale)
)
await step1.assert_reply(
"Please choose a color. (1) redcustomSeparator(2) greencustomInlineOrMore(3) blue"
)
async def test_should_not_render_choices_if_list_style_none_is_specified(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
style=ListStyle.none,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply("Please choose a color.")
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_create_prompt_with_inline_choices_when_specified(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
choice_prompt.style = ListStyle.in_line
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_create_prompt_with_list_choices_when_specified(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
choice_prompt.style = ListStyle.list_style
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(
"Please choose a color.\n\n 1. red\n 2. green\n 3. blue"
)
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_create_prompt_with_suggested_action_style_when_specified(
self,
):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
style=ListStyle.suggested_action,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply("Please choose a color.")
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_create_prompt_with_auto_style_when_specified(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
style=ListStyle.auto,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send(_answer_message)
await step3.assert_reply("red")
async def test_should_recognize_valid_number_choice(self):
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a color."
),
choices=_color_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(
"Please choose a color. (1) red, (2) green, or (3) blue"
)
step3 = await step2.send("1")
await step3.assert_reply("red")
async def test_should_display_choices_on_hero_card(self):
size_choices = ["large", "medium", "small"]
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(
prompt=Activity(
type=ActivityTypes.message, text="Please choose a size."
),
choices=size_choices,
)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
def assert_expected_activity(
activity: Activity, description
): # pylint: disable=unused-argument
assert len(activity.attachments) == 1
assert (
activity.attachments[0].content_type
== CardFactory.content_types.hero_card
)
assert activity.attachments[0].content.text == "Please choose a size."
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
# Change the ListStyle of the prompt to ListStyle.none.
choice_prompt.style = ListStyle.hero_card
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
step2 = await step1.assert_reply(assert_expected_activity)
step3 = await step2.send("1")
await step3.assert_reply(size_choices[0])
async def test_should_display_choices_on_hero_card_with_additional_attachment(self):
size_choices = ["large", "medium", "small"]
card = CardFactory.adaptive_card(
{
"type": "AdaptiveCard",
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.2",
"body": [],
}
)
card_activity = Activity(attachments=[card])
async def exec_test(turn_context: TurnContext):
dialog_context = await dialogs.create_context(turn_context)
results: DialogTurnResult = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(prompt=card_activity, choices=size_choices)
await dialog_context.prompt("prompt", options)
elif results.status == DialogTurnStatus.Complete:
selected_choice = results.result
await turn_context.send_activity(selected_choice.value)
await convo_state.save_changes(turn_context)
def assert_expected_activity(
activity: Activity, description
): # pylint: disable=unused-argument
assert len(activity.attachments) == 2
assert (
activity.attachments[0].content_type
== CardFactory.content_types.adaptive_card
)
assert (
activity.attachments[1].content_type
== CardFactory.content_types.hero_card
)
adapter = TestAdapter(exec_test)
convo_state = ConversationState(MemoryStorage())
dialog_state = convo_state.create_property("dialogState")
dialogs = DialogSet(dialog_state)
choice_prompt = ChoicePrompt("prompt")
# Change the ListStyle of the prompt to ListStyle.none.
choice_prompt.style = ListStyle.hero_card
dialogs.add(choice_prompt)
step1 = await adapter.send("Hello")
await step1.assert_reply(assert_expected_activity)
async def test_should_not_find_a_choice_in_an_utterance_by_ordinal(self):
found = ChoiceRecognizers.recognize_choices(
"the first one please",
_color_choices,
FindChoicesOptions(recognize_numbers=False, recognize_ordinals=False),
)
assert not found
async def test_should_not_find_a_choice_in_an_utterance_by_numerical_index(self):
found = ChoiceRecognizers.recognize_choices(
"one",
_color_choices,
FindChoicesOptions(recognize_numbers=False, recognize_ordinals=False),
)
assert not found
|
botbuilder-python/libraries/botbuilder-dialogs/tests/test_choice_prompt.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/test_choice_prompt.py",
"repo_id": "botbuilder-python",
"token_count": 16319
}
| 404 |
from unittest.mock import Mock
import aiounittest
from botbuilder.schema import ConversationAccount, ChannelAccount, RoleTypes
from botbuilder.integration.aiohttp import BotFrameworkHttpClient
from botframework.connector.auth import CredentialProvider, Activity
class TestBotFrameworkHttpClient(aiounittest.AsyncTestCase):
async def test_should_create_connector_client(self):
with self.assertRaises(TypeError):
BotFrameworkHttpClient(None)
async def test_adds_recipient_and_sets_it_back_to_null(self):
mock_credential_provider = Mock(spec=CredentialProvider)
# pylint: disable=unused-argument
async def _mock_post_content(
to_url: str, token: str, activity: Activity
) -> (int, object):
nonlocal self
self.assertIsNotNone(activity.recipient)
return 200, None
client = BotFrameworkHttpClient(credential_provider=mock_credential_provider)
client._post_content = _mock_post_content # pylint: disable=protected-access
activity = Activity(conversation=ConversationAccount())
await client.post_activity(
None,
None,
"https://skillbot.com/api/messages",
"https://parentbot.com/api/messages",
"NewConversationId",
activity,
)
assert activity.recipient is None
async def test_does_not_overwrite_non_null_recipient_values(self):
skill_recipient_id = "skillBot"
mock_credential_provider = Mock(spec=CredentialProvider)
# pylint: disable=unused-argument
async def _mock_post_content(
to_url: str, token: str, activity: Activity
) -> (int, object):
nonlocal self
self.assertIsNotNone(activity.recipient)
self.assertEqual(skill_recipient_id, activity.recipient.id)
return 200, None
client = BotFrameworkHttpClient(credential_provider=mock_credential_provider)
client._post_content = _mock_post_content # pylint: disable=protected-access
activity = Activity(
conversation=ConversationAccount(),
recipient=ChannelAccount(id=skill_recipient_id),
)
await client.post_activity(
None,
None,
"https://skillbot.com/api/messages",
"https://parentbot.com/api/messages",
"NewConversationId",
activity,
)
assert activity.recipient.id == skill_recipient_id
assert activity.recipient.role is RoleTypes.skill
|
botbuilder-python/libraries/botbuilder-integration-aiohttp/tests/test_bot_framework_http_client.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-integration-aiohttp/tests/test_bot_framework_http_client.py",
"repo_id": "botbuilder-python",
"token_count": 1108
}
| 405 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class SpeechConstants:
"""
Defines constants that can be used in the processing of speech interactions.
"""
EMPTY_SPEAK_TAG = '<speak version="1.0" xmlns="https://www.w3.org/2001/10/synthesis" xml:lang="en-US" />'
"""
The xml tag structure to indicate an empty speak tag, to be used in the 'speak' property of an Activity.
When set this indicates to the channel that speech should not be generated.
"""
|
botbuilder-python/libraries/botbuilder-schema/botbuilder/schema/speech_constants.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-schema/botbuilder/schema/speech_constants.py",
"repo_id": "botbuilder-python",
"token_count": 164
}
| 406 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
from setuptools import setup
REQUIRES = [
"botbuilder-schema==4.16.0",
"botbuilder-core==4.16.0",
"botbuilder-dialogs==4.16.0",
"botbuilder-azure==4.16.0",
"pytest~=7.3.1",
]
TESTS_REQUIRES = ["aiounittest==1.3.0"]
root = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(root, "botbuilder", "testing", "about.py")) as f:
package_info = {}
info = f.read()
exec(info, package_info)
with open(os.path.join(root, "README.rst"), encoding="utf-8") as f:
long_description = f.read()
setup(
name=package_info["__title__"],
version=package_info["__version__"],
url=package_info["__uri__"],
author=package_info["__author__"],
description=package_info["__description__"],
keywords="botbuilder-testing bots ai testing botframework botbuilder",
long_description=long_description,
long_description_content_type="text/x-rst",
license=package_info["__license__"],
packages=["botbuilder.testing"],
install_requires=REQUIRES + TESTS_REQUIRES,
tests_require=TESTS_REQUIRES,
include_package_data=True,
classifiers=[
"Programming Language :: Python :: 3.7",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 5 - Production/Stable",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
)
|
botbuilder-python/libraries/botbuilder-testing/setup.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-testing/setup.py",
"repo_id": "botbuilder-python",
"token_count": 593
}
| 407 |
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# --------------------------------------------------------------------------
import asyncio
from collections.abc import AsyncIterator
import functools
import logging
from oauthlib import oauth2
import requests
from msrest.exceptions import (
TokenExpiredError,
ClientRequestError,
raise_with_traceback,
)
_LOGGER = logging.getLogger(__name__)
class AsyncServiceClientMixin:
async def async_send_formdata(self, request, headers=None, content=None, **config):
"""Send data as a multipart form-data request.
We only deal with file-like objects or strings at this point.
The requests is not yet streamed.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param dict content: Dictionary of the fields of the formdata.
:param config: Any specific config overrides.
"""
files = self._prepare_send_formdata(request, headers, content)
return await self.async_send(request, headers, files=files, **config)
async def async_send(self, request, headers=None, content=None, **config):
"""Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add to the request.
:param config: Any specific config overrides
"""
loop = asyncio.get_event_loop()
if self.config.keep_alive and self._session is None:
self._session = requests.Session()
try:
session = self.creds.signed_session(self._session)
except TypeError: # Credentials does not support session injection
session = self.creds.signed_session()
if self._session is not None:
_LOGGER.warning(
"Your credentials class does not support session injection. Performance will not be at the maximum."
)
kwargs = self._configure_session(session, **config)
if headers:
request.headers.update(headers)
if not kwargs.get("files"):
request.add_content(content)
if request.data:
kwargs["data"] = request.data
kwargs["headers"].update(request.headers)
response = None
try:
try:
future = loop.run_in_executor(
None,
functools.partial(
session.request, request.method, request.url, **kwargs
),
)
return await future
except (
oauth2.rfc6749.errors.InvalidGrantError,
oauth2.rfc6749.errors.TokenExpiredError,
) as err:
error = "Token expired or is invalid. Attempting to refresh."
_LOGGER.warning(error)
try:
session = self.creds.refresh_session()
kwargs = self._configure_session(session)
if request.data:
kwargs["data"] = request.data
kwargs["headers"].update(request.headers)
future = loop.run_in_executor(
None,
functools.partial(
session.request, request.method, request.url, **kwargs
),
)
return await future
except (
oauth2.rfc6749.errors.InvalidGrantError,
oauth2.rfc6749.errors.TokenExpiredError,
) as err:
msg = "Token expired or is invalid."
raise_with_traceback(TokenExpiredError, msg, err)
except (requests.RequestException, oauth2.rfc6749.errors.OAuth2Error) as err:
msg = "Error occurred in request."
raise_with_traceback(ClientRequestError, msg, err)
finally:
self._close_local_session_if_necessary(response, session, kwargs["stream"])
def stream_download_async(self, response, user_callback):
"""Async Generator for streaming request body data.
:param response: The initial response
:param user_callback: Custom callback for monitoring progress.
"""
block = self.config.connection.data_block_size
return StreamDownloadGenerator(response, user_callback, block)
class _MsrestStopIteration(Exception):
pass
def _msrest_next(iterator):
""" "To avoid:
TypeError: StopIteration interacts badly with generators and cannot be raised into a Future
"""
try:
return next(iterator)
except StopIteration:
raise _MsrestStopIteration()
class StreamDownloadGenerator(AsyncIterator):
def __init__(self, response, user_callback, block):
self.response = response
self.block = block
self.user_callback = user_callback
self.iter_content_func = self.response.iter_content(self.block)
async def __anext__(self):
loop = asyncio.get_event_loop()
try:
chunk = await loop.run_in_executor(
None, _msrest_next, self.iter_content_func
)
if not chunk:
raise _MsrestStopIteration()
if self.user_callback and callable(self.user_callback):
self.user_callback(chunk, self.response)
return chunk
except _MsrestStopIteration:
self.response.close()
raise StopAsyncIteration()
except Exception as err:
_LOGGER.warning("Unable to stream download: %s", err)
self.response.close()
raise
|
botbuilder-python/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/async_mixin/async_mixin.py",
"repo_id": "botbuilder-python",
"token_count": 2797
}
| 408 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC, abstractmethod
class ChannelProvider(ABC):
"""
ChannelProvider interface. This interface allows Bots to provide their own
implementation for the configuration parameters to connect to a Bot.
Framework channel service.
"""
@abstractmethod
async def get_channel_service(self) -> str:
raise NotImplementedError()
@abstractmethod
def is_government(self) -> bool:
raise NotImplementedError()
@abstractmethod
def is_public_azure(self) -> bool:
raise NotImplementedError()
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/channel_provider.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/channel_provider.py",
"repo_id": "botbuilder-python",
"token_count": 205
}
| 409 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .channel_provider import ChannelProvider
from .government_constants import GovernmentConstants
class SimpleChannelProvider(ChannelProvider):
"""
ChannelProvider interface. This interface allows Bots to provide their own
implementation for the configuration parameters to connect to a Bot.
Framework channel service.
"""
def __init__(self, channel_service: str = None):
self.channel_service = channel_service
async def get_channel_service(self) -> str:
return self.channel_service
def is_government(self) -> bool:
return self.channel_service == GovernmentConstants.CHANNEL_SERVICE
def is_public_azure(self) -> bool:
return not self.channel_service
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/simple_channel_provider.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/simple_channel_provider.py",
"repo_id": "botbuilder-python",
"token_count": 240
}
| 410 |
from .bot_framework_client import BotFrameworkClient
__all__ = ["BotFrameworkClient"]
|
botbuilder-python/libraries/botframework-connector/botframework/connector/skills/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/skills/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 25
}
| 411 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from msrest.serialization import Model
from msrest.exceptions import HttpOperationError
# pylint: disable=invalid-name
class AadResourceUrls(Model):
"""AadResourceUrls.
:param resource_urls:
:type resource_urls: list[str]
"""
_attribute_map = {"resource_urls": {"key": "resourceUrls", "type": "[str]"}}
def __init__(self, **kwargs):
super(AadResourceUrls, self).__init__(**kwargs)
self.resource_urls = kwargs.get("resource_urls", None)
class Error(Model):
"""Error.
:param code:
:type code: str
:param message:
:type message: str
:param inner_http_error:
:type inner_http_error: ~botframework.tokenapi.models.InnerHttpError
"""
_attribute_map = {
"code": {"key": "code", "type": "str"},
"message": {"key": "message", "type": "str"},
"inner_http_error": {"key": "innerHttpError", "type": "InnerHttpError"},
}
def __init__(self, **kwargs):
super(Error, self).__init__(**kwargs)
self.code = kwargs.get("code", None)
self.message = kwargs.get("message", None)
self.inner_http_error = kwargs.get("inner_http_error", None)
class ErrorResponse(Model):
"""ErrorResponse.
:param error:
:type error: ~botframework.tokenapi.models.Error
"""
_attribute_map = {"error": {"key": "error", "type": "Error"}}
def __init__(self, **kwargs):
super(ErrorResponse, self).__init__(**kwargs)
self.error = kwargs.get("error", None)
class ErrorResponseException(HttpOperationError):
"""Server responsed with exception of type: 'ErrorResponse'.
:param deserialize: A deserializer
:param response: Server response to be deserialized.
"""
def __init__(self, deserialize, response, *args):
super(ErrorResponseException, self).__init__(
deserialize, response, "ErrorResponse", *args
)
class InnerHttpError(Model):
"""InnerHttpError.
:param status_code:
:type status_code: int
:param body:
:type body: object
"""
_attribute_map = {
"status_code": {"key": "statusCode", "type": "int"},
"body": {"key": "body", "type": "object"},
}
def __init__(self, **kwargs):
super(InnerHttpError, self).__init__(**kwargs)
self.status_code = kwargs.get("status_code", None)
self.body = kwargs.get("body", None)
class SignInUrlResponse(Model):
"""SignInUrlResponse.
:param sign_in_link:
:type sign_in_link: str
:param token_exchange_resource:
:type token_exchange_resource:
~botframework.tokenapi.models.TokenExchangeResource
"""
_attribute_map = {
"sign_in_link": {"key": "signInLink", "type": "str"},
"token_exchange_resource": {
"key": "tokenExchangeResource",
"type": "TokenExchangeResource",
},
}
def __init__(self, **kwargs):
super(SignInUrlResponse, self).__init__(**kwargs)
self.sign_in_link = kwargs.get("sign_in_link", None)
self.token_exchange_resource = kwargs.get("token_exchange_resource", None)
class TokenExchangeRequest(Model):
"""TokenExchangeRequest.
:param uri:
:type uri: str
:param token:
:type token: str
"""
_attribute_map = {
"uri": {"key": "uri", "type": "str"},
"token": {"key": "token", "type": "str"},
}
def __init__(self, **kwargs):
super(TokenExchangeRequest, self).__init__(**kwargs)
self.uri = kwargs.get("uri", None)
self.token = kwargs.get("token", None)
class TokenExchangeResource(Model):
"""TokenExchangeResource.
:param id:
:type id: str
:param uri:
:type uri: str
:param provider_id:
:type provider_id: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"uri": {"key": "uri", "type": "str"},
"provider_id": {"key": "providerId", "type": "str"},
}
def __init__(self, **kwargs):
super(TokenExchangeResource, self).__init__(**kwargs)
self.id = kwargs.get("id", None)
self.uri = kwargs.get("uri", None)
self.provider_id = kwargs.get("provider_id", None)
class TokenResponse(Model):
"""TokenResponse.
:param channel_id:
:type channel_id: str
:param connection_name:
:type connection_name: str
:param token:
:type token: str
:param expiration:
:type expiration: str
"""
_attribute_map = {
"channel_id": {"key": "channelId", "type": "str"},
"connection_name": {"key": "connectionName", "type": "str"},
"token": {"key": "token", "type": "str"},
"expiration": {"key": "expiration", "type": "str"},
}
def __init__(self, **kwargs):
super(TokenResponse, self).__init__(**kwargs)
self.channel_id = kwargs.get("channel_id", None)
self.connection_name = kwargs.get("connection_name", None)
self.token = kwargs.get("token", None)
self.expiration = kwargs.get("expiration", None)
class TokenStatus(Model):
"""The status of a particular token.
:param channel_id: The channelId of the token status pertains to
:type channel_id: str
:param connection_name: The name of the connection the token status
pertains to
:type connection_name: str
:param has_token: True if a token is stored for this ConnectionName
:type has_token: bool
:param service_provider_display_name: The display name of the service
provider for which this Token belongs to
:type service_provider_display_name: str
"""
_attribute_map = {
"channel_id": {"key": "channelId", "type": "str"},
"connection_name": {"key": "connectionName", "type": "str"},
"has_token": {"key": "hasToken", "type": "bool"},
"service_provider_display_name": {
"key": "serviceProviderDisplayName",
"type": "str",
},
}
def __init__(self, **kwargs):
super(TokenStatus, self).__init__(**kwargs)
self.channel_id = kwargs.get("channel_id", None)
self.connection_name = kwargs.get("connection_name", None)
self.has_token = kwargs.get("has_token", None)
self.service_provider_display_name = kwargs.get(
"service_provider_display_name", None
)
|
botbuilder-python/libraries/botframework-connector/botframework/connector/token_api/models/_models.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/token_api/models/_models.py",
"repo_id": "botbuilder-python",
"token_count": 2663
}
| 412 |
interactions:
- request:
body: '{"recipient": {"id": "U19KH8EHJ:T03CWQ0QB"}, "channelId": "slack", "text":
"Hello again!", "from": {"id": "B21UTEF8S:T03CWQ0QB"}, "type": "message"}'
headers:
Accept: [application/json]
Accept-Encoding: ['gzip, deflate']
Connection: [keep-alive]
Content-Length: ['148']
Content-Type: [application/json; charset=utf-8]
User-Agent: [python/3.5.3 (Linux-4.11.0-041100-generic-x86_64-with-Ubuntu-17.04-zesty)
requests/2.18.1 msrest/0.4.23 azure-botframework-connector/v3.0]
method: POST
uri: https://slack.botframework.com/v3/conversations/B21UTEF8S%3AT03CWQ0QB%3AD2369CT7C/activities
response:
body: {string: "{\r\n \"id\": \"1514296291.000146\"\r\n}"}
headers:
cache-control: [no-cache]
content-length: ['33']
content-type: [application/json; charset=utf-8]
date: ['Tue, 26 Dec 2017 13:51:30 GMT']
expires: ['-1']
pragma: [no-cache]
request-context: ['appId=cid-v1:6814484e-c0d5-40ea-9dba-74ff29ca4f62']
server: [Microsoft-IIS/10.0]
strict-transport-security: [max-age=31536000]
vary: [Accept-Encoding]
x-powered-by: [ASP.NET]
status: {code: 200, message: OK}
version: 1
|
botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_send_to_conversation.yaml/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_send_to_conversation.yaml",
"repo_id": "botbuilder-python",
"token_count": 593
}
| 413 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from uuid import UUID
from botframework.streaming.payloads.assemblers import PayloadStreamAssembler
class ContentStream:
def __init__(self, identifier: UUID, assembler: PayloadStreamAssembler):
if not assembler:
raise TypeError(
f"'assembler: {assembler.__class__.__name__}' argument can't be None"
)
self.identifier = identifier
self._assembler = assembler
self.stream = self._assembler.get_payload_as_stream()
self.content_type: str = None
self.length: int = None
def cancel(self):
self._assembler.close()
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/content_stream.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/content_stream.py",
"repo_id": "botbuilder-python",
"token_count": 275
}
| 414 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from asyncio import Future, shield
from uuid import UUID
from typing import Dict
import botframework.streaming as streaming
class RequestManager:
def __init__(
self,
*,
pending_requests: Dict[UUID, "Future[streaming.ReceiveResponse]"] = None
):
self._pending_requests = pending_requests or {}
async def signal_response(
self, request_id: UUID, response: "streaming.ReceiveResponse"
) -> bool:
# TODO: dive more into this logic
signal: Future = self._pending_requests.get(request_id)
if signal:
signal.set_result(response)
# TODO: double check this
# del self._pending_requests[request_id]
return True
return False
async def get_response(self, request_id: UUID) -> "streaming.ReceiveResponse":
if request_id in self._pending_requests:
return None
pending_request = Future()
self._pending_requests[request_id] = pending_request
try:
response: streaming.ReceiveResponse = await shield(pending_request)
return response
finally:
del self._pending_requests[request_id]
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/request_manager.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/request_manager.py",
"repo_id": "botbuilder-python",
"token_count": 523
}
| 415 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
from .transport_base import TransportBase
class TransportSenderBase(ABC, TransportBase):
async def send(self, buffer: object, offset: int, count: int) -> int:
raise NotImplementedError()
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/transport_sender_base.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/transport_sender_base.py",
"repo_id": "botbuilder-python",
"token_count": 92
}
| 416 |
import asyncio
from asyncio import Future, ensure_future
from typing import Dict
from uuid import UUID, uuid4
import aiounittest
from botframework.streaming import ReceiveResponse
from botframework.streaming.payloads import RequestManager
class TestRequestManager(aiounittest.AsyncTestCase):
def test_ctor_empty_dictionary(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
_ = RequestManager(pending_requests=pending_requests)
self.assertEqual(0, len(pending_requests))
async def test_signal_response_returns_false_when_no_uuid(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
manager = RequestManager(pending_requests=pending_requests)
request_id: UUID = uuid4()
response = ReceiveResponse()
signal = await manager.signal_response(request_id=request_id, response=response)
self.assertFalse(signal)
async def test_signal_response_returns_true_when_uuid(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
request_id: UUID = uuid4()
pending_requests[request_id] = Future()
manager = RequestManager(pending_requests=pending_requests)
response = ReceiveResponse()
signal = await manager.signal_response(request_id=request_id, response=response)
self.assertTrue(signal)
async def test_signal_response_null_response_is_ok(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
request_id: UUID = uuid4()
pending_requests[request_id] = Future()
manager = RequestManager(pending_requests=pending_requests)
# noinspection PyTypeChecker
_ = await manager.signal_response(request_id=request_id, response=None)
self.assertIsNone(pending_requests[request_id].result())
async def test_signal_response_response(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
request_id: UUID = uuid4()
pending_requests[request_id] = Future()
manager = RequestManager(pending_requests=pending_requests)
response = ReceiveResponse()
_ = await manager.signal_response(request_id=request_id, response=response)
self.assertEqual(response, pending_requests[request_id].result())
async def test_get_response_returns_null_on_duplicate_call(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
request_id: UUID = uuid4()
pending_requests[request_id] = Future()
manager = RequestManager(pending_requests=pending_requests)
response = await manager.get_response(request_id)
self.assertIsNone(response)
async def test_get_response_returns_response(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
request_id: UUID = uuid4()
manager = RequestManager(pending_requests=pending_requests)
test_response = ReceiveResponse()
async def set_response():
nonlocal manager
nonlocal request_id
nonlocal test_response
while True:
signal = await manager.signal_response(
request_id, response=test_response
)
if signal:
break
await asyncio.sleep(2)
ensure_future(set_response())
response = await manager.get_response(request_id)
self.assertEqual(test_response, response)
async def test_get_response_returns_null_response(self):
pending_requests: Dict[UUID, Future[ReceiveResponse]] = {}
request_id: UUID = uuid4()
manager = RequestManager(pending_requests=pending_requests)
async def set_response():
nonlocal manager
nonlocal request_id
while True:
# noinspection PyTypeChecker
signal = await manager.signal_response(request_id, response=None)
if signal:
break
await asyncio.sleep(2)
ensure_future(set_response())
response = await manager.get_response(request_id)
self.assertIsNone(response)
|
botbuilder-python/libraries/botframework-streaming/tests/test_request_manager.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/tests/test_request_manager.py",
"repo_id": "botbuilder-python",
"token_count": 1730
}
| 417 |
{
"name": "generateclient",
"version": "1.0.0",
"description": "",
"private": true,
"author": "",
"devDependencies": {
"@microsoft.azure/autorest.python": "^4.0.67",
"autorest": "^3.0.5165",
"replace": "^1.2.2"
},
"dependencies": {}
}
|
botbuilder-python/swagger/package.json/0
|
{
"file_path": "botbuilder-python/swagger/package.json",
"repo_id": "botbuilder-python",
"token_count": 149
}
| 418 |
from .main_dialog import MainDialog
__all__ = [
"MainDialog"
]
|
botbuilder-python/tests/experimental/sso/parent/dialogs/__init__.py/0
|
{
"file_path": "botbuilder-python/tests/experimental/sso/parent/dialogs/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 27
}
| 419 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import ActivityHandler, TurnContext
from botbuilder.schema import ChannelAccount
class MyBot(ActivityHandler):
"""See https://aka.ms/about-bot-activity-message to learn more about the message and other activity types."""
async def on_message_activity(self, turn_context: TurnContext):
await turn_context.send_activity(f"You said '{ turn_context.activity.text }'")
async def on_members_added_activity(
self, members_added: ChannelAccount, turn_context: TurnContext
):
for member_added in members_added:
if member_added.id != turn_context.activity.recipient.id:
await turn_context.send_activity("Hello and welcome!")
|
botbuilder-python/tests/functional-tests/functionaltestbot/flask_bot_app/my_bot.py/0
|
{
"file_path": "botbuilder-python/tests/functional-tests/functionaltestbot/flask_bot_app/my_bot.py",
"repo_id": "botbuilder-python",
"token_count": 257
}
| 420 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
from unittest import TestCase
from direct_line_client import DirectLineClient
class PyBotTest(TestCase):
def test_deployed_bot_answer(self):
direct_line_secret = os.environ.get("DIRECT_LINE_KEY", "")
if direct_line_secret == "":
return
client = DirectLineClient(direct_line_secret)
user_message: str = "Contoso"
send_result = client.send_message(user_message)
self.assertIsNotNone(send_result)
self.assertEqual(200, send_result.status_code)
response, text = client.get_message()
self.assertIsNotNone(response)
self.assertEqual(200, response.status_code)
self.assertEqual(f"You said '{user_message}'", text)
|
botbuilder-python/tests/functional-tests/tests/test_py_bot.py/0
|
{
"file_path": "botbuilder-python/tests/functional-tests/tests/test_py_bot.py",
"repo_id": "botbuilder-python",
"token_count": 320
}
| 421 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import ActivityHandler, ConversationState, UserState, TurnContext
from botbuilder.dialogs import Dialog
from helpers.dialog_helper import DialogHelper
class DialogBot(ActivityHandler):
def __init__(self, conversation_state: ConversationState, user_state: UserState, dialog: Dialog):
self.conversation_state = conversation_state
self._user_state = user_state
self.dialog = dialog
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)
await self.conversation_state.save_changes(turn_context, False)
await self._user_state.save_changes(turn_context, False)
async def on_message_activity(self, turn_context: TurnContext):
print("on message: Running dialog with Message Activity.")
return await DialogHelper.run_dialog(
self.dialog,
turn_context,
self.conversation_state.create_property("DialogState")
)
|
botbuilder-python/tests/skills/skills-prototypes/dialog-to-dialog/authentication-bot/bots/dialog_bot.py/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-prototypes/dialog-to-dialog/authentication-bot/bots/dialog_bot.py",
"repo_id": "botbuilder-python",
"token_count": 372
}
| 422 |
from typing import List
from botbuilder.core import (
ActivityHandler,
ConversationState,
MessageFactory,
TurnContext,
)
from botbuilder.core.skills import SkillConversationIdFactory
from botbuilder.integration.aiohttp import BotFrameworkHttpClient
from botbuilder.schema import ActivityTypes, ChannelAccount
from config import DefaultConfig, SkillConfiguration
class RootBot(ActivityHandler):
def __init__(
self,
conversation_state: ConversationState,
skills_config: SkillConfiguration,
conversation_id_factory: SkillConversationIdFactory,
skill_client: BotFrameworkHttpClient,
config: DefaultConfig,
):
self._conversation_id_factory = conversation_id_factory
self._bot_id = config.APP_ID
self._skill_client = skill_client
self._skills_config = skills_config
self._conversation_state = conversation_state
self._active_skill_property = conversation_state.create_property(
"activeSkillProperty"
)
async def on_turn(self, turn_context: TurnContext):
if turn_context.activity.type == ActivityTypes.end_of_conversation:
# Handle end of conversation back from the skill
# forget skill invocation
await self._active_skill_property.delete(turn_context)
await self._conversation_state.save_changes(turn_context, force=True)
# We are back
await turn_context.send_activity(
MessageFactory.text(
'Back in the root bot. Say "skill" and I\'ll patch you through'
)
)
else:
await super().on_turn(turn_context)
async def on_message_activity(self, turn_context: TurnContext):
# If there is an active skill
active_skill_id: str = await self._active_skill_property.get(turn_context)
skill_conversation_id = await self._conversation_id_factory.create_skill_conversation_id(
TurnContext.get_conversation_reference(turn_context.activity)
)
if active_skill_id:
# NOTE: Always SaveChanges() before calling a skill so that any activity generated by the skill
# will have access to current accurate state.
await self._conversation_state.save_changes(turn_context, force=True)
# route activity to the skill
await self._skill_client.post_activity(
self._bot_id,
self._skills_config.SKILLS[active_skill_id].app_id,
self._skills_config.SKILLS[active_skill_id].skill_endpoint,
self._skills_config.SKILL_HOST_ENDPOINT,
skill_conversation_id,
turn_context.activity,
)
else:
if "skill" in turn_context.activity.text:
await turn_context.send_activity(
MessageFactory.text("Got it, connecting you to the skill...")
)
# save ConversationReferene for skill
await self._active_skill_property.set(turn_context, "SkillBot")
# NOTE: Always SaveChanges() before calling a skill so that any activity generated by the
# skill will have access to current accurate state.
await self._conversation_state.save_changes(turn_context, force=True)
await self._skill_client.post_activity(
self._bot_id,
self._skills_config.SKILLS["SkillBot"].app_id,
self._skills_config.SKILLS["SkillBot"].skill_endpoint,
self._skills_config.SKILL_HOST_ENDPOINT,
skill_conversation_id,
turn_context.activity,
)
else:
# just respond
await turn_context.send_activity(
MessageFactory.text(
"Me no nothin'. Say \"skill\" and I'll patch you through"
)
)
async def on_members_added_activity(
self, members_added: List[ChannelAccount], turn_context: TurnContext
):
for member in members_added:
if member.id != turn_context.activity.recipient.id:
await turn_context.send_activity(
MessageFactory.text("Hello and welcome!")
)
|
botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-root-bot/bots/root_bot.py/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-root-bot/bots/root_bot.py",
"repo_id": "botbuilder-python",
"token_count": 1973
}
| 423 |
# Cascadia Code Contributor's Guide
Below is our guidance for how to report issues, propose new features, and submit contributions via Pull Requests (PRs).
## Before you start, file an issue
Please follow this simple rule to help us eliminate any unnecessary wasted effort & frustration, and ensure an efficient and effective use of everyone's time - yours, ours, and other community members':
> 👉 If you have a question, think you've discovered an issue, would like to propose a new feature, etc., then find/file an issue **BEFORE** starting work to fix/implement it.
### Search existing issues first
Before filing a new issue, search existing open and closed issues first: It is likely someone else has found the problem you're seeing, and someone may be working on or have already contributed a fix!
If no existing item describes your issue/feature, great - please file a new issue:
### File a new issue
* Don't know whether you're reporting an issue or requesting a feature? File an issue
* Have a question that you don't see answered in docs, videos, etc.? File an issue
* Want to know if we're planning on building a particular feature? File an issue
* Got a great idea for a new feature? File an issue/request/idea
* Don't understand how to do something? File an issue
* Found an existing issue that describes yours? Great - upvote and add additional commentary / info / repro-steps / etc.
When you hit "New Issue", select the type of issue closest to what you want to report/ask/request:

### Complete the template
**Complete the information requested in the issue template, providing as much information as possible**. The more information you provide, the more likely your issue/ask will be understood and implemented. Helpful information includes:
* What version of Cascadia Code you have?
* What application you are using to view the font?
* What is your screen resolution?
* Don't assume we're experts in setting up YOUR environment. Teach us to help you!
* **We LOVE detailed repro steps!** What steps do we need to take to reproduce the issue? Assume we love to read repro steps. As much detail as you can stand is probably _barely_ enough detail for us!
* Please try to provide the exact Unicode codepoint for the glyphs you're talking about. (e.g. U+1F4AF, U+4382)
* **If you intend to implement the fix/feature yourself then say so!** If you do not indicate otherwise we will assume that the issue is our to solve, or may label the issue as `Help-Wanted`.
### DO NOT post "+1" comments
> ⚠ DO NOT post "+1", "me too", or similar comments - they just add noise to an issue.
If you don't have any additional info/context to add but would like to indicate that you're affected by the issue, upvote the original issue by clicking its [+😊] button and hitting 👍 (+1) icon. This way we can actually measure how impactful an issue is.
---
## Contributing fixes / features
For those able & willing to help fix issues and/or implement features ...
### To Spec or not to Spec
Some issues/features may be quick and simple to describe and understand. For such scenarios, once a team member has agreed with your approach, skip ahead to the section headed "Fork, Branch, and Create your PR", below.
Small issues that do not require a spec will be labelled Issue-Bug or Issue-Task.
However, some issues/features will require careful thought & formal design before implementation. For these scenarios, we'll request that a spec is written and the associated issue will be labeled Issue-Feature.
Specs help collaborators discuss different approaches to solve a problem, describe how the feature will behave, how the feature will impact the user, what happens if something goes wrong, etc. Driving towards agreement in a spec, before any code is written, often results in less wasted effort in the long run.
Specs will be managed in a very similar manner as code contributions so please follow the "Fork, Branch and Create your PR" below.
### Writing / Contributing-to a Spec
To write/contribute to a spec: fork, branch and commit via PRs, as you would with any code changes.
Specs are written in markdown, stored under the `\doc\spec` folder and named `[issue id] - [spec description].md`.
Team members will be happy to help review specs and guide them to completion.
### Help Wanted
Once the team have approved an issue/spec, development can proceed. If no developers are immediately available, the spec can be parked ready for a developer to get started. Parked specs' issues will be labeled "Help Wanted". To find a list of development opportunities waiting for developer involvement, visit the Issues and filter on [the Help-Wanted label](https://github.com/microsoft/terminal/labels/Help-Wanted).
---
## Development
### Fork, Clone, Branch and Create your PR
Once you've discussed your proposed feature/fix/etc. with a team member, and you've agreed an approach or a spec has been written and approved, it's time to start development:
1. Fork the repo if you haven't already
1. Clone your fork locally
1. Create & push a feature branch
1. Create a [Draft Pull Request (PR)](https://github.blog/2019-02-14-introducing-draft-pull-requests/)
1. Work on your changes
### Code Review
When you'd like the team to take a look, (even if the work is not yet fully-complete), mark the PR as 'Ready For Review' so that the team can review your work and provide comments, suggestions, and request changes. It may take several cycles, but the end result will be solid, testable, conformant code that is safe for us to merge.
### Merge
Once your code has been reviewed and approved by the requisite number of team members, it will be merged into the main branch. Once merged, your PR will be automatically closed.
---
## Thank you
Thank you in advance for your contribution! Now, [what's next on the list](https://github.com/microsoft/cascadia-code/labels/Help-Wanted)? 😜
|
cascadia-code/doc/CONTRIBUTING.md/0
|
{
"file_path": "cascadia-code/doc/CONTRIBUTING.md",
"repo_id": "cascadia-code",
"token_count": 1444
}
| 424 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Abrevedotbelow" format="2">
<advance width="1200"/>
<unicode hex="1EB6"/>
<outline>
<component base="A"/>
<component base="dotbelowcomb"/>
<component base="brevecomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_brevedotbelow.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_brevedotbelow.glif",
"repo_id": "cascadia-code",
"token_count": 105
}
| 425 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="acircumflexhookabove" format="2">
<advance width="1200"/>
<unicode hex="1EA9"/>
<outline>
<component base="a"/>
<component base="circumflexcomb" xOffset="-20"/>
<component base="hookabovecomb" xOffset="358" yOffset="340"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top_viet</string>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>hookabovecomb</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/acircumflexhookabove.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/acircumflexhookabove.glif",
"repo_id": "cascadia-code",
"token_count": 320
}
| 426 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="afghani-ar" format="2">
<advance width="1200"/>
<unicode hex="060B"/>
<outline>
<component base="fehDotless-ar.init"/>
<component base="dotabove-ar" xOffset="65" yOffset="460"/>
<component base="alefbelow-ar" xOffset="3" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>dotabove-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/afghani-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/afghani-ar.glif",
"repo_id": "cascadia-code",
"token_count": 374
}
| 427 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ainTwodotshorizontalabove-ar" format="2">
<advance width="1200"/>
<unicode hex="075D"/>
<outline>
<component base="ain-ar"/>
<component base="twodotshorizontalabove-ar" xOffset="-93" yOffset="466"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_wodotshorizontalabove-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_wodotshorizontalabove-ar.glif",
"repo_id": "cascadia-code",
"token_count": 179
}
| 428 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefFathatan-ar.fina" format="2">
<advance width="1200"/>
<unicode hex="FD3C"/>
<outline>
<component base="alef-ar.fina"/>
<component base="fathatan-ar" xOffset="309" yOffset="-252"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>fathatan-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefF_athatan-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefF_athatan-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 355
}
| 429 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefWasla-ar.fina.alt" format="2">
<anchor x="0" y="0" name="_overlap"/>
<anchor x="319" y="-141" name="bottom"/>
<anchor x="253" y="1660" name="top"/>
<outline>
<component base="alef-ar.fina.short.alt" xOffset="6"/>
<component base="wasla-ar" xOffset="-372" yOffset="78"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>alef-ar.fina.short.alt</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefW_asla-ar.fina.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefW_asla-ar.fina.alt.glif",
"repo_id": "cascadia-code",
"token_count": 405
}
| 430 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefpatah-hb" format="2">
<advance width="1200"/>
<unicode hex="FB2E"/>
<outline>
<component base="alef-hb"/>
<component base="patah-hb" xOffset="-15"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.97,1,0,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefpatah-hb.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefpatah-hb.glif",
"repo_id": "cascadia-code",
"token_count": 166
}
| 431 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behThreedotshorizontalbelow-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.fina"/>
<component base="_dots.horz.below" xOffset="-18" yOffset="-18"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>_dots.horz.below</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotshorizontalbelow-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotshorizontalbelow-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 357
}
| 432 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behThreedotsupbelow-ar.init.alt" format="2">
<advance width="1200"/>
<anchor x="0" y="0" name="overlap"/>
<outline>
<component base="behDotless-ar.init.alt"/>
<component base="threedotsupbelow-ar" xOffset="210" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotsupbelow-ar.init.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotsupbelow-ar.init.alt.glif",
"repo_id": "cascadia-code",
"token_count": 194
}
| 433 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behVabove-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.medi"/>
<component base="vabove-ar" xOffset="30" yOffset="223"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>vabove-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_above-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_above-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 340
}
| 434 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="beheh-ar.fina.alt" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.fina.alt"/>
<component base="fourdotsbelow-ar" xOffset="-710" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>fourdotsbelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beheh-ar.fina.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beheh-ar.fina.alt.glif",
"repo_id": "cascadia-code",
"token_count": 352
}
| 435 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="betdagesh-hb" format="2">
<advance width="1200"/>
<unicode hex="FB31"/>
<outline>
<component base="bet-hb"/>
<component base="dagesh-hb" xOffset="-208" yOffset="63"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.97,1,0,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/betdagesh-hb.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/betdagesh-hb.glif",
"repo_id": "cascadia-code",
"token_count": 170
}
| 436 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="colon_equal_middle.seq" format="2">
<advance width="1200"/>
<outline>
<contour>
<point x="983" y="835" type="line"/>
<point x="1250" y="835" type="line"/>
<point x="1250" y="1085" type="line"/>
<point x="983" y="1085" type="line"/>
</contour>
<contour>
<point x="983" y="333" type="line"/>
<point x="1250" y="333" type="line"/>
<point x="1250" y="583" type="line"/>
<point x="983" y="583" type="line"/>
</contour>
<contour>
<point x="-50" y="835" type="line"/>
<point x="217" y="835" type="line"/>
<point x="217" y="1085" type="line"/>
<point x="-50" y="1085" type="line"/>
</contour>
<contour>
<point x="-50" y="333" type="line"/>
<point x="217" y="333" type="line"/>
<point x="217" y="583" type="line"/>
<point x="-50" y="583" type="line"/>
</contour>
<component base="colon.center"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/colon_equal_middle.seq.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/colon_equal_middle.seq.glif",
"repo_id": "cascadia-code",
"token_count": 478
}
| 437 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dahal-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="dal-ar.fina"/>
<component base="twodotshorizontalabove-ar" xOffset="36" yOffset="492"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dahal-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dahal-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 169
}
| 438 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dalTwodotsverticalbelowTahabove-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="dal-ar.fina"/>
<component base="twodotsverticalbelow-ar" xOffset="-40" yOffset="-24"/>
<component base="_tahabove" xOffset="71" yOffset="613"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>twodotsverticalbelow-ar</string>
</dict>
<dict>
<key>anchor</key>
<string>top</string>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>_tahabove</string>
</dict>
</array>
<key>com.schriftgestaltung.Glyphs.glyph.leftMetricsKey</key>
<string>dal-ar</string>
<key>com.schriftgestaltung.Glyphs.glyph.rightMetricsKey</key>
<string>dal-ar</string>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalT_wodotsverticalbelowT_ahabove-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalT_wodotsverticalbelowT_ahabove-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 601
}
| 439 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dcroat" format="2">
<advance width="1200"/>
<unicode hex="0111"/>
<outline>
<contour>
<point x="462" y="1168" type="line"/>
<point x="1155" y="1168" type="line"/>
<point x="1155" y="1392" type="line"/>
<point x="462" y="1392" type="line"/>
</contour>
<component base="d"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>d</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dcroat.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dcroat.glif",
"repo_id": "cascadia-code",
"token_count": 373
}
| 440 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dotaccentcomb.case" format="2">
<anchor x="600" y="1420" name="_top"/>
<anchor x="600" y="1850" name="top"/>
<outline>
<contour>
<point x="600" y="1572" type="curve" smooth="yes"/>
<point x="694" y="1572"/>
<point x="771" y="1648"/>
<point x="771" y="1742" type="curve" smooth="yes"/>
<point x="771" y="1838"/>
<point x="694" y="1913"/>
<point x="600" y="1913" type="curve" smooth="yes"/>
<point x="506" y="1913"/>
<point x="429" y="1838"/>
<point x="429" y="1742" type="curve" smooth="yes"/>
<point x="429" y="1648"/>
<point x="506" y="1572"/>
</contour>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.originalWidth</key>
<integer>1200</integer>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dotaccentcomb.case.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dotaccentcomb.case.glif",
"repo_id": "cascadia-code",
"token_count": 407
}
| 441 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dul-ar" format="2">
<advance width="1200"/>
<unicode hex="068E"/>
<outline>
<component base="dal-ar"/>
<component base="threedotsupabove-ar" xOffset="16" yOffset="492"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dul-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dul-ar.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 442 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.